Why in lumen in oauth_access_tokens.expires_at field does not work? - lumen

In lumen app with dusterio/lumen-passport when new user is logged into the system
request like:
"token_type": "Bearer",
"expires_in": 31536000,
"access_token": "ey...",
"refresh_token": "de...5f0"
is returned and new row in “oauth_access_tokens” table is added with expires_at field and
also 1 more row in “oauth_refresh_tokens”
But when I tried to change manually value in oauth_access_tokens.expires_at field (I set prior date)
I expected that user will not have access ander this token, but it has access anyway...
Also checking sql tracing :
SELECT *
FROM `oauth_access_tokens`
WHERE `id` = '336283f12e8c41d6c84a0f304191e93047ff5f6b349ad0e80c634460efb1e1d516d3e50f2d227f03' limit 1
in sql statements I do not see any checks on expires_at field...
Looks like that work a bit different I expected...
Also what for is “oauth_refresh_tokens” table and how can I use it ?
Making login I set days_to_expire parameter in LumenPassport before token creation:
$days_to_expire = 30;
$tokens_expire_in = Carbon::now()->addDays($days_to_expire);
LumenPassport::tokensExpireIn($tokens_expire_in, $client_id);
$tokenRequest = $request->create('api/oauth/token'), 'POST');
$tokenRequest->request->add([
"grant_type" => "password",
"username" => $email,
"password" => $password,
"client_id" => $client_id,
"client_secret" => $client_secret,
]);
$response = app()->handle($tokenRequest);
and tokens_expire_in that is the value I see in oauth_access_tokens.expires_at field...
"dusterio/lumen-passport": "^0.3.4",
"laravel/lumen-framework": "^8.3.1",
Thanks!

Related

Magento 2 Rest API Order edit

I'm trying to figure out how to edit an order after I requested it.
I made a custom attribute whether an order is exported or not.
I first get all orders with status not exported and after I exported them, I want to change the custom attribute to exported.
What is the REST request to edit/update an order? I keep getting error messages like:
{"message":"%fieldName is a required field.","parameters":
{"fieldName":"entity"}
This is my code:
$json = array(
"entity_id" => $id,
"extension_attributes" => array(
"custom_export_attribute" => "exported",
)
);
$webapi = new ApiClient('https://dev.local.nl', self::$username, self::$password);
$response = $webapi->getClient()->request('PUT', '/rest/V1/orders/create', [
'headers' => [
'Authorization' => "Bearer " . $webapi->getToken(),
'Content-Type' => "application/json"
],
'body' => json_encode($json)
]);
return json_decode($response->getBody(), true);
I also tried:
$webapi->getClient()->request('PUT', '/rest/V1/orders/'.$id,
To edit / update order details, the Magento 2 /V1/orders accepts POST request method. As per Magento 2 Dev Doc, it accepts the request body in below format (You can find whole JSON request in documentation page):
{
"entity": {
"entity_id": 0,
"extension_attributes": {
}
}
}
So, you just need to update the $json variable as:
$json = [
"entity"=> [
"entity_id" => $id,
"extension_attributes" => [
"custom_export_attribute" => "exported"
]
]
]
And than invoke with POST request method instead of PUT. In my suggestion prefer to use Create API for new order creation.

Error pulling companies user is admin of in LinkedIn

I'm currently trying to pull the list of company pages a user is the admin of with the LinkedIn API and am getting the following response:
Array
(
[response] => {
"errorCode": 0,
"message": "Member does not have permission to get companies as admin.",
"requestId": "R1LHP32UKD",
"status": 403,
"timestamp": 1482357250945
}
[http_code] => 403
)
The call works perfectly when authenticated as the same user in the LinkedIn API Console.
Has anyone else come across this?
I figured out the problem.
Even though I had made sure the app had the rw_company_admin permission checked off, I wasn't passing that in the scope when requesting oath2 authorization.
My fixed code below:
The call:
return $linkedin->getAuthorizationUrl("r_basicprofile w_share rw_company_admin", $thisurl);
The function:
public function getAuthorizationUrl($scope, $callback)
{
$params = array('response_type' => 'code',
'client_id' => $this->api_key,
'scope' => $scope,
'state' => uniqid('', true), // unique long string
'redirect_uri' => $callback,
);
// Authentication request
$url = 'https://www.linkedin.com/uas/oauth2/authorization?' . http_build_query($params);
// Needed to identify request when it returns to us
$_SESSION['Linkedin_state'] = $params['state'];
$_SESSION['Linkedin_callback'] = $callback;
// this is where to send the user
return $url;
}
First you have to get user token of linkedin user
Use Socialite or REST API package for oauth.
Once you having user token it is pretty simple to fetch Company list under admin user
$token = 'uflefjefheilhfbwrfliehbwfeklfw'; // user token
$api_url = "https://api.linkedin.com/v1/companies?oauth2_access_token=".$token."&format=json&is-company-admin=true";
$pages = json_decode(file_get_contents($api_url));
You have get $pages json array of list of company profile.

How to get email from facebook through Guzzle in laravel?

I am using below code to login via facebook in laravel.
Referring https://scotch.io/tutorials/token-based-authentication-for-angularjs-and-laravel-apps for token based authentication and using https://github.com/sahat/satellizer for social media integration.
$params = [
'code' => $request->input('code'),
'client_id' => $request->input('clientId'),
'redirect_uri' => $request->input('redirectUri'),
'client_secret' => 'XXXXXXXXXXXXXXXXXXX'
/*'client_secret' => Config::get('app.facebook_secret')*/
];
// Step 1. Exchange authorization code for access token.
$accessTokenResponse = $client->request('GET', 'https://graph.facebook.com/v2.5/oauth/access_token', [
'query' => $params
]);
$accessToken = json_decode($accessTokenResponse->getBody(), true);
// Step 2. Retrieve profile information about the current user.
$profileResponse = $client->request('GET', 'https://graph.facebook.com/v2.5/me', [
'query' => $accessToken
]);
$profile = json_decode($profileResponse->getBody(), true);
$profile returning only fb id and user name.
What changes should I do to get email from facebook.
Use below code in your step 2.
$fields = 'id,email,first_name,last_name,link,name';
$profileResponse = $client->request('GET', 'https://graph.facebook.com/v2.5/me', [
'query' => [
'access_token' => $accessToken['access_token'],
'fields' => $fields
]
]);
Replace this:
'https://graph.facebook.com/v2.5/me'
with this:
'https://graph.facebook.com/v2.5/me?fields=name,email'
It´s called "Declarative Fields", see changelog.
Also, you need to authorize with the email permission, of course. And the email has to be confirmed. You can´t be 100% sure to get an email, some users use their phone number to login.
You should also check this out: https://github.com/sahat/satellizer/issues/615

How to programmatically add an event to a page using Graph API?

Is it possible to programmatically add an event to a page using Facebook Graph API?
If yes, what HTTP request shall be made?
For example, Startup Weekend has events on its Facebook page.
These events can be added using Graph API Event object?
UPDATE
Creating event with the API is no longer possible in v2.0+. Check: https://developers.facebook.com/docs/apps/changelog#v2_0
Yes it's possible.
Permissions:
create_event
manage_pages
So first you get the page id and its access token, through:
$facebook->api("/me/accounts");
The Result will be something like:
Array
(
[data] => Array
(
[0] => Array
(
[name] => Page Name
[category] => Website
[id] => XXXXXX
[access_token] => XXXXX
)
[1] => Array
(
[name] => Page Name 2
[category] => Company
[id] => XXXXXXX
[access_token] => XXXXXXXX
)
)
)
UPDATE: To retrieve the page's access_token you could now call the page object directly like:
$page_info = $facebook->api("/PAGE_ID?fields=access_token");
The access token, if successful call, should be accessible: $page_info['access_token']
Now you get the Page ID and access token and use the events connection:
$nextWeek = time() + (7 * 24 * 60 * 60);
$event_param = array(
"access_token" => "XXXXXXXX",
"name" => "My Page Event",
"start_time" => $nextWeek,
"location" => "Beirut"
);
$event_id = $facebook->api("/PAGE_ID/events", "POST", $event_param);
And you are done! :-)

Converting Facebook session keys to access tokens

I have a web app that allows users to connect Facebook account with their account on my site. When the user decides to connect with Facebook, the app requests publish_stream and offline_access permissions, and then stores the Facebook uid and session_key for each user. All this works fine right now.
My problem is migrating to Facebook's new OAuth 2.0 system. I'd like to transform the session keys I have into access tokens. I followed these instructions and everything seemed to work fine; Facebook returned a bunch of access tokens. However, none of them work. When I try to go to a URL such as https://graph.facebook.com/me?access_token=TOKEN-HERE, I get an error that says "Error validating client".
What am I doing wrong?
Also, I'm under the impression that access tokens work just like session keys in that once I have one, I can use it forever (since I request offline_access permissions). Is that correct?
Update:
Below are the exact steps I took to convert a session key into an access token, along with the output I got. Hopefully that will help bring my problem to light.
Step 1: Convert Session Key to Access Token
Code:
$session_key = '87ebbedf29cc2000a28603e8-100000652996522';
$app = sfConfig::get('app_facebook_prod_api'); // I happen to use Symfony. This gets an array with my Facebook app ID and secret.
$post = array(
'type' => 'client_cred',
'client_id' => $app['app_id'],
'client_secret' => $app['secret'],
'sessions' => $session_key
);
$options = array(
CURLOPT_POST => 1,
CURLOPT_HEADER => 0,
CURLOPT_URL => 'https://graph.facebook.com/oauth/exchange_sessions',
CURLOPT_FRESH_CONNECT => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POSTFIELDS => http_build_query($post)
);
$ch = curl_init();
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
curl_close($ch);
var_export(json_decode($result));
Output:
array (
0 =>
stdClass::__set_state(array(
'access_token' => '251128963105|87ebbedf29cc2000a28603e8-100000652996522|Dy8CcJzEX8lYRrJE9Xk1EoW-BW0.',
)),
)
Step 2: Test Access Token
Code:
$access_token = '251128963105|87ebbedf29cc2000a28603e8-100000652996522|Dy8CcJzEX8lYRrJE9Xk1EoW-BW0.';
$options = array(
CURLOPT_HEADER => 0,
CURLOPT_URL => 'https://graph.facebook.com/me?access_token=' . $access_token,
CURLOPT_FRESH_CONNECT => 1,
CURLOPT_RETURNTRANSFER => 1,
);
$ch = curl_init();
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
curl_close($ch);
var_export(json_decode($result));
Output:
stdClass::__set_state(array(
'error' =>
stdClass::__set_state(array(
'type' => 'OAuthException',
'message' => 'Error validating client.',
)),
))
From reading your post here is my understanding -
You are tranforming session keys into access keys for each user in your system and storing these keys.
You then test the key using your own page. (Graph.facebook.com/me etc...)
If this is the case
A) You cannot use another users key with your own key. Going to graph.facebook.com would only be valid for the user that the key belongs to and if they were logged in. So for example, if you have my access key you could visit http://graph.facebook.com/YOURID....) but for graph.facebook.com/me to work you would have to be logged in as me.
B) These keys expire every 3 hours (Or there abouts) so it may no longer be valid.
The Platform Upgrade Guide has a section about OAuth 2.0 which includes the instructions for exchanging a session_key for an access_token. You should use this if you already have stored session keys.
For new users, you should use one of the new SDKs or the OAuth2 flow directly which will give you an access token to begin with.