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.
Related
I have an issue with user authentication. I can create a new user and use laravel's Hash::make command to encrypt the password which all appears to be working correctly see database record below :
Now for the login script. I did a dump die on the $input and confirmed it has the post data from the login form inside it.
Code :
public function CheckLogin()
{
$input = Request::all();
// create our user data for the authentication
$userdata = array(
'Email' => $input['email'],
'Password' => $input['password']
);
// attempt to do the login
if (Auth::attempt($userdata)) {
// if(Auth::attempt(['Email' => $input['email'], 'Password' =>$input['password'], 'ArchivedOn' => null])){
//return redirect()->intended('devices');
return redirect()->intended('devices');
} else {
$err = 'Login Failed Please check credentials and try again.';
return view('welcome', compact('err'));
}
}
The Auth::attempt appears to always return false as it always re-directs to the welcome page with the error message I specified.
I expectect I am missing something obvious but I thought I would ask for a fresh pair of eyes on this as I can't see the problem.
Your userdata should be:-
$userdata = array(
'Email' => $input['email'],
'password' => $input['password']
);
Note: You need to write Password 's p character in small letter. You can change email with Email or Username whatever name you want but password must be 'password'.
Check this link for more detail.
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');
}
}
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']).
I'm logging in with the HybridAuth plug-in at the address = /cake/hybridauth/auth/google, then I use these details to look up the user on the database and log them in to the default CakePHP Auth like so:
$hybridauth = new Hybrid_Auth($hybridauth_config);
$adapter = $hybridauth->authenticate($provider);
$userprofile = $adapter->getUserProfile();
//look up user + register if not found
$this->loadModel('User');
$isUser = $this->User->find('first', array(
'conditions' => array(
'User.provider' => strtolower($provider),
'User.identifier' => $userprofile->identifier
),
'callbacks' => true
));
if(!$isUser){
//register the user
} else {
//update user with new credentials
$this->Auth->login($isUser["User"]);
//this doesn't work across the whole site,
//only this controller's "action" page
}
This all works fine, until I go back to my homepage at /cake/, where there seems to be no recognition of me having logged in - although on the controller's action page (cake/hybridauth/auth/google) I have the user logged into the Auth component and the above code seemed to work...
Any ideas what I'm missing please?
Many thanks.
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.