How to validate session with rest api post - php

I have API login using session, when mobile apps use login feature actually they hit the API. In API login, i made session login so when the user login it give response session. check my code below:
public function user_post()
{
$data = array (
'username' => $this->input->get_post('username'),
'password' => sha1($this->input->get_post('password'))
);
$result = $this->login_m->user_check($data);
if ($result ) {
foreach ($result as $row ) {
$sess_array = array(
'username' => $row->username,
'email' => $row->email
);
$this->session->set_userdata('logged', $sess_array);
$this->response(array('success' => $this->session->userdata('logged') ));
}
} else {
$this->response(array(404 => 'missing parameter'));
}
}
and the response will be like this below:
* {
* "success":
* {
* "username": "johndoe123",
* "email": "myemail#my.com"
* }
* }
my question is, how to get the session to validate API post? example:
i have post API to store new data. i've imagine this way would be good, set the param to catch the session name 'logged' using codeigniter , in session 'logged' is already has email and username, so will use it as condition to check to table is the email and username is in the table.
$this->session->has_userdata('logged')
so the mobile apps need to save the session in their apps to send again as params. and the code would be like this below:
$data = array(
'idcardno' => $this->input->get_post('idcardno'),
'dateofbirth' => $this->input->get_post('dateofbirth')
);
$addnewpolis = $this->modelname->modelmethod($data2);
thank you guys,
CMIIW

You cannot use sessions like you want in your code with external api calls. You may generate a token from the login and return it. Then on next api calls from your mobile, send this token in order to know the user identity.
Why: Is it good to implement REST api using Sessions?
To generate a token:
https://www.google.com/search?q=generate%20token%20php&rct=j
Then return it in your response and save it somewhere in order to retrieve it on next calls.

Related

Finding User with Auth - Laravel

I am trying to find the logged in user in my application using Auth but i get trying to get property of non-object which i understand clearly that it is returning null.
In my code below, an event triggers my webhook and post is sent to the address below. The function orderCreateWebhook triggers but that is where the error comes from..
The line $get_template = Order::where('id', Auth::user()->id);. Why is Auth returning null please? I am logged as well because i use auth in this same controller for another function which works fine.
Is it because it a webhook ?
Controller
public function registerOrderCreateWebhook(Request $request)
{
$shop = "feas.myshopify.com";
$token = "8f43d89a64e922d7d343c1173f6d";
$shopify = Shopify::setShopUrl($shop)->setAccessToken($token);
Shopify::setShopUrl($shop)->setAccessToken($token)->post("admin/webhooks.json", ['webhook' =>
['topic' => 'orders/create',
'address' => 'https://larashop.domain.com/order-create-webhook',
'format' => 'json'
]
]);
}
public function orderCreateWebhook(Request $request)
{
$get_template = Order::where('id', Auth::user()->id);
$baseurl = "https://apps.domain.net/smsapi";
$query = "?key=7e3e4d4a6cfebc08eadc&to=number&msg=message&sender_id=Shopify";
$final_uri = $baseurl.$query;
$response = file_get_contents($final_uri);
header ("Content-Type:text/xml");
}
In your function registerOrderCreateWebhook you appear to be making a request to shopify api and providing your webhook as the address which shopify will redirect the user to upon success. If this is correct, that request does not know about the user who generated the original request that made the api request since the request is coming from a completely different origin.
You would need to pass some key along with the url and then obtain the user within orderCreateWebhook. Something like:
Shopify::setShopUrl($shop)->setAccessToken($token)->post("admin/webhooks.json",
['webhook' =>
['topic' => 'orders/create',
'address' => 'https://larashop.domain.com/order-create-webhook/some-unique-key',
'format' => 'json'
]
]);
My suggestion would be to have a unique hash stored somewhere that relates back to the user in your system, perhaps a column in your users table. I wouldn't use the user_id for security reasons. So you would end up with something like:
//route
Route::get('/order-create-webhook/{uniqueKey}', 'YourController#orderCreateWebhook');
//or
Route::post('/order-create-webhook/{uniqueKey}', 'YourController#orderCreateWebhook');
// depending on the request type used by api which calls this endpoint
// controller function
public function orderCreateWebhook($uniqueKey, Request $request)
{
$user = User::where('unique_key', $uniqueKey)->first();
$get_template = Order::where('id', Auth::user()->id);
$baseurl = "https://apps.domain.net/smsapi";
$query = "?key=7e3e4d4a6cfebc08eadc&to=number&msg=message&sender_id=Shopify";
$final_uri = $baseurl.$query;
$response = file_get_contents($final_uri);
header ("Content-Type:text/xml");
}
Is it because it a webhook ?
Yes, you can't use sessions in a webhook. It's the shopify server which is making the call. You should read the doc, it may exist a way to give an unique identifier in your call to shopify api and get it back in the webhook to find your user associated.
just use this to get authenticated user
use the facade in your class/Controller
use Illuminate\Support\Facades\Auth
public function getAuthUser(){
$user = Auth::user()
if(!is_null($user)
{
//user is authenticated
}
else
{
// no user
}
}

adding log in using facebook option in registration form

I have a registration form in my site,where the users submits their personal details such as name,email id,dob,and mobile number to be stored in my database. Now I am in the idea to include the connect with facebook button,,by using that link,the user can provide their details by logging into their account. those details can be stored in my database. my expectation looks like this image..help me to implement this
First, you need to decide whether you want to use PHP or JavaScript for Facebook's SDK. Then, download the SDK from:
https://developers.facebook.com/docs/facebook-login/login-flow-for-web/v2.2
Here's a "Getting started" guide for PHP:
https://developers.facebook.com/docs/php/gettingstarted/4.0.0
And here's the same kind of guide for JavaScript:
https://developers.facebook.com/docs/javascript
Here's a part of my code for Facebook Login written with PHP. Note that I'm using CodeIgniter as a framwork for my project:
public function registerWithFacebook()
{
try {
// Proceed knowing you have a logged in user who's authenticated
$facebook_user_data = $this->facebook->get_user();
} catch (FacebookApiException $e) {
$user = null;
print_r($e);
return false;
}
// if we don't have the facebook-user array variable, leave the method
if (!$facebook_user_data) {
return false;
}
// If we can't get the email, leave the method
if(!$facebook_user_data['email']) {
return false;
}
// If user is already registered with Facebook, start sessions and redirect user to app home page (exit the method at this point)
if ($this->facebook_model->facebookUserIdExistsAlreadyInDatabase($facebook_user_data)) {
$session = $this->user_model->getUserInfo($facebook_user_data['id']);
$data = array(
'user_id' => $session['user_id'],
'name' => $session['name'],
'email' => $session['email'],
'profilepic' => $session['profilepic'],
'loggedin' => true,
);
$this->session->set_userdata($data);
redirect(base_url().'home');
exit();
}
// Generate password for new user since you can't get the password from Facebook (obviously)
$generated_password = random_string('alnum', 8);
$data = [
'email' => $facebook_user_data['email'],
'name' => $facebook_user_data['name'],
'password' => $this->phpass->hash($generated_password),
'profilepic' => 'https://graph.facebook.com/'.$facebook_user_data['id'].'/picture?width=160&height=160',
'user_facebook_id' => $facebook_user_data['id'],
];
// Insert data to your database
$new_user = $this->facebook_model->add_facebook_user($data);
// If new user's data was saved successfully to database, start sessions and redirect user
if($new_user) {
$session = $this->user_model->getUserInfo($facebook_user_data['id']);
$data = array(
'user_id' => $session['user_id'],
'name' => $session['name'],
'email' => $session['email'],
'profilepic' => 'https://graph.facebook.com/'.$facebook_user_data['id'].'/picture?width=160&height=160',
'loggedin' => true,
);
$this->session->set_userdata($data);
redirect(base_url().'home');
}
}

How to get google contact list using artdarek-oauth-4-laravel?

I am using artdarek-oauth-4-laravel for the Login to my website via Facebook, twitter and google.
Login part is working fine. But I want to get some more data from these api, like if user is registering through the google then I am looking for their general info as well as google contact list, or if the user is registering from Facebook then I am trying to get the /me and /friend-list etc.
Here, I am just taking the case of google.
I have set the config like this
'Google' => array(
'client_id' => '***********************************',
'client_secret' => '***********************************',
'scope' => array('userinfo_email', 'userinfo_profile', 'https://www.google.com/m8/feeds/'),
),
My Controller Function is this:-
public function loginWithGoogle()
{
$code = Input::get( 'code' );
$googleService = OAuth::consumer( 'Google' );
if ( !empty( $code ) )
{
$token = $googleService->requestAccessToken( $code );
// $result = json_decode( $googleService->request( 'https://www.googleapis.com/oauth2/v1/userinfo' ), true );
$result = json_decode( $googleService->request( 'https://www.google.com/m8/feeds/contacts/default/full' ), true );
echo json_encode($result);
}
else {
// get googleService authorization
$url = $googleService->getAuthorizationUri();
// return to google login url
return Redirect::to( (string)$url );
}
}
This code leads me to the google api and asks for all the permission that I have set in the scope of the service. Here once I got the access token after exchanging the code parameter with the api, I am calling the url to return me the contact list but it fails. And I am getting this message from the laravel :-Failed to request resource.
If I call the commented $result request, it returns me the result.
So, I wanted to know how can we use this library for the data other than login and register. In case of retrieving facebook friendlist the same thing happens but the login works. (My Facebook App has the permission to get friendlist).
Any help is appreciated.
Check this response, https://stackoverflow.com/a/26488136/434790.
It worked for me. The culprit: alt=json to be added to https://www.google.com/m8/feeds/contacts/default/full

Facebook - get profile picture php sdk

Until few months ago I was using this method to get the user's facebook profile picture and was working fine.
public function getUserProfilePic(){
$access_token = $this->facebook_obj->getAccessToken();
$user_id = $this->facebook_obj->getUser();
$response = $this->facebook_obj->api(
"/me/picture",
"GET",
array (
'redirect' => false,
'type' => 'large'
)
);
return (!empty($response['data']['url'])) ? $response['data']['url'] : 'images/default_profile.jpg';
}
But since the new PHP SDK I have some problems with this method. If I afk for 5 minutes on the main menu on my app and than go on the click to go the page where it calls this method I get
"OAuthException : An active access token must be used to query information about the current user" error.
Any thoughts?
Nothing to do with new/old SDK I guess. The user is logged-out, or access token is expired or your handling of the user in session is flawed.
This error is occurred whenever you try to make calls with /me but no user is logged-in to the app.
So, before making the calls, you should always validate the current user and then proceed, something like that-
$user_id = $this->facebook_obj->getUser();
if ($user_id) {
try {
$response = $this->facebook_obj->api(
"/me/picture",
"GET",
array (
'redirect' => false,
'type' => 'large'
)
);
} catch (FacebookApiException $e) {
error_log($e);
}
}else {
// redirect to Facebook login to get a fresh user access_token
$loginUrl = $this->facebook_obj->getLoginUrl();
header('Location: ' . $loginUrl);
}
Edit:
You dont need to do redirect: false and fetching the url from the json. You can directly use the url as the image source:
https://graph.facebook.com/{user-id}/picture?type=large
That's it!

Cakephp 2.2.4 does not save Auth User Info after using a alternative authenication

I am trying to create an authentication for facebook users. Right now I check to see if a fb user id exist in my database, if it does then it authenicates, if not, then it data mines the users facebook info and creates a user and then authenicates. It works successfully, the problem is, if I use something like $this->Auth->user('id'); the values return back null. I am curious on what I maybe doing wrong. below is my code
public function fb_authenticate($data) {
$this->Auth->fields = array('username' => 'fbid', 'password' => 'fbpassword');
$this->loadModel('User');
$user_record = $this->User->find('first', array(
'conditions' => array('fbid' => $data['user_id'])
));
if(empty($user_record)) {
$fbu = $this->Facebook->getUserInfo($data['user_id']);
$user_record = array(
'User'=>array(
'username'=>$fbu->username,
'fbid'=>$data['user_id'],
'oauth_token'=>$data['oauth_token'],
'access_token'=>$data['access_token'],
'firstname'=>$fbu->first_name,
'lastname'=>$fbu->last_name,
'fbpassword'=>$this->Auth->password($data['user_id']),
'role'=>'user'
));
$this->User->create();
$this->User->save($user_record,null);
}
if (!$this->Auth->login($user_record)) {
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
It authenicates and lets the user in, but it does not store the users info in the Auth component session. what could be the problem ??
if I debug debug($this->Auth->user()) I can see the data but if I pull a field individually debug($this->Auth->user('id')); it returns null.
Change $this->Auth->login($user_record)
to $this->Auth->login($user_record['User']).

Categories