adding log in using facebook option in registration form - php

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');
}
}

Related

force user to fill the form after obtaining the info using laravel and socialite

How to force the user to fill the form after login with google or facebook. I ma using laravel 5.4 with socials. In my app i want to allow google and facebook login but user can create a standard user too. When login with one of the social providers (facebook or google) i want the user to fill other fields in the form to complete the registration.
The handleProviderCallback:
public function handleProviderCallback($provider)
{
try{
$socialUser = Socialite::driver($provider)->stateless()->user();
}catch (Exception $e){
return redirect('/');
}
// check if we have logged PROVIDER
$socialProvider = Social::where('provider_id', $socialUser->getId())->first();
// if we don`t have a provider create a user and provider
if(!$socialProvider){
// i want the user to go back in the form and finish the registration
return view('auth.socials')->with('socialUser', $socialUser)->with('provider', $provider);
}
else{
// return the user
$user = $socialProvider->user;
}
// log the user in our app :)
auth()->login($user);
return redirect('/home');
the problem is when submiting the form i get an exception:
Client error: `POST https://accounts.google.com/o/oauth2/token` resulted in
a `400 Bad Request` response:
{
"error" : "invalid_grant",
"error_description" : "Invalid code."
}
If i use the method handleProviderCallback like this:
public function handleProviderCallback($provider)
{
try{
$socialUser = Socialite::driver($provider)->stateless()->user();
}catch (Exception $e){
return redirect('/');
}
// check if we have logged PROVIDER
$socialProvider = Social::where('provider_id', $socialUser->getId())->first();
// if we don`t have a provider create a user and provider
if(!$socialProvider){
$user = User::firstOrCreate(
['email' => $socialUser->getEmail()],
// i have to manualy add the missing fields
['name' => $socialUser->getName(), 'forename' => 'test', 'password' => '' ,'address' => 'adasda', 'country' => 'asasfasf', 'town' => 'asfasfsfsfs', 'legal_person' => '0', 'newsletter' => '1', 'phone' => '1235241521']
);
// add provider for this user
$user->socials()->create(
['provider_id' => $socialUser->getId(), 'provider' => $provider]
);
}
else{
// return the user
$user = $socialProvider->user;
}
// log the user in our app :)
auth()->login($user);
return redirect('/home');
}
the user get logged in, but as you can see i have to manually insert the missing fields in the firstOrCreate method (which are required in the users table)
Any suggestion how to do this?

How to validate session with rest api post

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.

CakePHP Auth Facebook Connect not working (no plugin)

I have a strange situation and I don't know how to debug it.
One client requested to make a facebook login for a website that is on CakePHP version 1.2.12.
So i used Facebook PHP SDK and followed standard procedure. If the user is not registered then register with the data from Facebook generate a password and so on.
Then if the user is registered and he gets connected with his facebook account I want to use the CakePHP Auth Component to log him in.
Problem is that it kicks me out as cannot authenticate.
Here's what I did:
public function facebook_login_register() {
$fbUser = $this->Facebook->getUser();
if ($fbUser) {
//gets FB details about my profile
$fbUser = $this->Facebook->api('/me');
$registeredUser = $this->UserProfile->find('first', array('conditions' => array('UserProfile.email' => $fbUser['email']),
'fields' => array('UserProfile.email')));
if (!$registeredUser) {
... registration ...
}
else{
$usernameDisplay = $this->User->find('first', array('conditions' => array('User.username' => $fbUser['username']),
'fields' => array('User.username_display')));
}
$fb['username'] = $fbUser['username'];
$fb['password'] = $usernameDisplay['User']['username_display'];
$this->Auth->fields = array(
'username' => 'username',
'password' => 'username_display_encoded' //the encoded display_name (encoded with $this->Auth->password() or Security::hash(...). The result is correct when testing it for hashing)
);
if ($this->Auth->login($fb)) {
echo 'ok';
}
else{
echo 'not ok';
}
....
}
So when i am doing this it just kicks me out on the else branch.
Thanks in advance for your help!
Cheers.
I think your login is failing because you have an incorrect field mapped to password - the username_display_encoded field doesn't even exist in the array $fb which you're passing for the login. The array you intend to pass into $this->Auth->login() needs to match the users model's fields for username and password, since it's going to check what you've passed against the database.
$user = $this->User->find('first', array('conditions' => array('User.username' => $fbUser['username'])));
$this->Auth->fields = array(
'username' => 'username',
'password' => 'username_display'
);
if ($this->Auth->login($user['User'])) {
echo 'ok';
}
else{
echo 'not ok';
}
Also, take a look at How do I integrate Facebook SDK login with cakephp 2.x? which seems like it might be useful, though it's for a newer version of Cake.

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']).

Facebook function does not return user when using getUser()

I am using the Facebook files to login to an app I have created just so people can login through Facebook on the site I am working on. I am working in Code Igniter and I was able to return the users info and everything. I had it working no problem.
But when I went on to the developer side because I wanted to test it locally and changed the site url I got an error about something I can't remember I think the error code was 191 I could be wrong.
I then figured ok well that didn't work so I changed it back and now I am unable to retrieve any of the user data when logging in. There is no errors being thrown. The functions from the Facebook file work fine but I can't seem to get the user info again.
I have a model that I use to grab the info from login.
class Facebook_model extends CI_Model {
function __construct() {
parent::__construct();
$config = array(
'appId' => 'XXXX',
'secret' => 'XXXXX',
'fileUpload' => true
);
$this->load->library('facebook', $config);
$user = $this->facebook->getUser();
$profile = null;
if($user)
{
try {
// Proceed knowing you have a logged in user who's authenticated.
$profile = $this->facebook->api('/me?fields=id,name,link,email');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
$login_params = array(
'redirect_uri' => (base_url() . 'test'),
'scope' => 'email'
);
$fb_data = array(
'me' => $profile,
'uid' => $user,
'loginUrl' => $this->facebook->getLoginUrl($login_params),
'logoutUrl' => $this->facebook->getLogoutUrl()
);
$this->session->set_userdata('fb_data', $fb_data);
}
}
So right after the ($user = $this->facebook->getUser();) I did a test and echoed $user and got 0. Where before I didn't.
The one change I made was in the $login_params var. I changed the redirect_uri to localhost which did not work for obvious reasons and then I changed it back to what I have displayed now.
Thanks
getUser only returns the user info if the user is logged in your application/web (http://developers.facebook.com/docs/reference/php/facebook-getUser/)
So you should deal in the model with the posibility that the user is not logged in (is 0) and show him the login buttom. Besides you should reset the session info in case the user is 0.

Categories