CakePHP - Auth to save user's last login time - cakephp

Where is the best place to insert the code to save the user's last login? I am using the CakePHP Auth login system in almost the standard implementation in the manual.
Where can I insert the code so that it will save to the User record just before Auth redirects after login?

You need to disable AuthComponent::autoRedirect if you wish for the code in your UsersController::login() method to execute:
public $components = array(
'Auth' => array(
// ...
'autoRedirect' => false,
),
);
You can then do this in your login action, but you will still need to perform the redirect manually:
public function login() {
if ($this->Auth->user()) { // check user is logged in
$this->User->id = $this->Auth->user('id'); // target correct record
$this->User->saveField('last_login', date(DATE_ATOM)); // save login time
$this->redirect($this->Auth->redirect()); // redirect to default place
}
}

Related

cakephp referrer after auth deny

How do I get the page that was denied access by the Auth component using CakePHP 2.x? If I use the referer() function, it gives me the page that linked to the denied action. Here's my code:
public function login() {
//get the current url of the login page (or current controller+action)
$currentLoginUrl = "/login";
if ($this->request->is('post')) {
$this->User->recursive = -1;
$user = $this->User->find(
'first',
array(
'conditions' => array(
'User.username' => $this->request->data['User']['username'],
'User.password' => AuthComponent::password($this->request->data['User']['password'])
)
)
);
if ($user && $this->Auth->login($user['User'])) {
//if the referer page is not from login page,
if( $this->referer() != $currentLoginUrl )
//use $this->referer() right away
$this->redirect($this->referer('/admin', true)); //if referer can't be read, or if its not from local server, use $this->Auth->rediret() instead
else
//if the user lands on login page first, rely on our session
$this->redirect( $this->Session->read('beforeLogin_referer') );
}
else
$this->Session->setFlash('Username or password is incorrect', 'default', array('class' => 'alert-danger'));
}
if( $this->referer() != $currentLoginUrl )
//store this value to use once user is succussfully logged in
$this->Session->write('beforeLogin_referer', $this->referer('/admin', true) ) ; //if referer can't be read, or if its not from local server, use $this->Auth->rediret() instead
}
So basically what happens is I'm not logged in, and I'm at this url:
'http://localhost/hotelguide/hotels/view/17/'
and I click on a link that would take me to
'http://localhost/hotelguide/hotels/review/17/'
but that requires a user to be logged in, so it redirects me to the login page, which, when I debug referrer(), it gives me this:
'http://localhost/hotelguide/hotels/view/17/'
What am I doing wrong?
When you use Auth component in CakePHP and try to access a restricted site, it redirects you to login page and saves the referring page in session. Session key Auth.redirect holds the value you're looking for - the page that you were trying to access.
Look at the __unauthenticated() method of AuthComponent. It includes the code responsible for writing session value to Auth.redirect. If you don't want to use AuthComponent, you can check how it is implemented in the component and write your own solution based on the method I have mentioned.
$this->referer() will not provide you the correct referrer url for you. If you want to get referrer url just use $this->Session->read('Auth.redirect');
You can find exact url you are looking for by $this->Session->read('Auth.redirect');
$this->referer() value update every time when you reload the page.

Cakephp 2.x does not login manually

I am trying to integrate facebook authentication to my Cakephp 2.2.4 app and once the facebook authentication is done, I am trying to create the user and login the user manually, I see that though the below code is creating a auth session, i.e., $this->Auth->user() contains all the data , it is not logging the user into the app, i.e, I am not able to access other functions of the app
$user = $this->User->findById($user_id);
$this->Auth->login($user);
this is what I am using to manually login and the user saved does not contain a username and password
this is in my AppController.php
class AppController extends Controller {
public $components = array(
'Session',
'Auth'=>array(
'loginRedirect'=>array('controller'=>'Users','action'=>'dashboard'),
'logoutRedirect'=>array('controller'=>'Users','action'=>'login'),
'authError'=>'You can\'t access that page',
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'email')
),'Basic'),
'authorize'=>array('controller')
),
'RequestHandler'
);
public $helpers = array('Js' => array('Jquery'),'Html','Form');
public function isAuthorized($user){
return TRUE ;
}
public function beforeFilter(){
// $this->Auth->allow('index','view');
// $this->set('logged_in',$this->Auth->loggedIn());
// $this->set('current_user',$this->Auth->user());
}
}
Try:
$this->Auth->login($user['User']);
This was nothing to do with the cakephp app but the plugin which i was using for facebook, which did not post data
Maybe the Auth component still refer to username field for authentication instead of email. You can try change to username.
I am developing a Plugin that uses Facebook oAuth as an authentication object for Auth Component. If you want an already-built solution that uses server-side Facebook login, please check my website: http://marianofino.github.com/Facebook-Plugin-for-CakePHP/

$this-Session->destroy() is not destroying the session? v. cakephp 2.0

my UserController.php has logout function that looks like this
function logout()
{
$this->Session->destroy('User');
$this->Session->setFlash('You\'ve successfully logged out.');
var_export($this->Session->read('User'));
//$this->redirect('login');
}
my view Users/index.ctp
<?php echo $this->Html->link('Logout', array('controller' => 'users', 'action' => 'logout')); ?>
When I click "log out" the var_export still displays all the User data and if I go back to Users/index.ctp it still shows me that page even though in my my UserController.php I am checking if User is set
function beforeFilter()
{
$this->__validateLoginStatus();
}
function __validateLoginStatus()
{
if($this->action != 'login' && $this->action != 'logout')
{
if($this->Session->check('User') == false)
{
$this->redirect('login');
}
}
It does not redirect to login page and just brings me to index page.
}
$this->Session->destroy();
The destroy method will delete the session cookie and all session data stored in the temporary file system.
User to remove, use better delete.
$this->Session->delete('User');
If you use the AuthComponent to authenticate the users, you can log them out by using the logout() method.
$this->Auth->logout();
See http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#logging-users-out for Cake 2 or http://book.cakephp.org/1.3/en/view/1262/logout for Cake 1.3
And if you don't use the AuthComponent at all, you should maybe have a look at it as it contains out of the box many functionalities that you have already or will likely implement yourself.

CakePHP + Facebook

I am trying to implement facebook Connect to my cakephp Application. i am using Nick's Facebook Plugin.
I wanna implement it this way
When a user Visits the Site he should be able to login via Registration on the site or Facebook Connect
Existing users should be able to connect their account to their FB account
People who first time login to the site using FB Connect and dont have an account on the site. should be redirected to a page where they have to enter details to complete the profile.
What i have done -
I have followed the instruction of Nick to implement it and when i click Login - it connects to my app. but i dont understand how to create a username and password associated with the Fb Connect Id. and user it against the FB token.
Apparently I'm doing the same thing a little before you... ;-)
Here's a method for Facebook login I'm using (slightly redacted and annotated):
public function facebook($authorize = null) {
App::import('Lib', 'Facebook.FB');
$Fb = new FB();
$session = $Fb->getSession();
// not logged into Facebook and not a callback either,
// sending user over to Facebook to log in
if (!$session && !$authorize) {
$params = array(
'req_perms' => /* the permissions you require */,
'next' => Router::url(array('action' => 'facebook', 'authorize'), true),
'cancel_url' => Router::url(array('action' => 'login'), true)
);
$this->redirect($Fb->getLoginUrl($params));
}
// user is coming back from Facebook login,
// assume we have a valid Facebook session
$userInfo = $Fb->api('/me');
if (!$userInfo) {
// nope, login failed or something went wrong, aborting
$this->Session->setFlash('Facebook login failed');
$this->redirect(array('action' => 'login'));
}
$user = array(
'User' => array(
'firstname' => $userInfo['first_name'],
'lastname' => $userInfo['last_name'],
'username' => trim(parse_url($userInfo['link'], PHP_URL_PATH), '/'),
'email' => $userInfo['email'],
'email_validated' => $userInfo['verified']
),
'Oauth' => array(
'provider' => 'facebook',
'provider_uid' => $userInfo['id']
)
);
$this->oauthLogin($user);
}
This gives me an array with all the user details I could grab from Facebook and invokes ::oauthLogin, which either logs the user in with the given information or asks the user to fill in missing details and/or creates a new user record in the database. The most important part you get from the Facebook API is the $userInfo['id'] and/or email address, either of which you can use to identify the user in your database. If you're using the AuthComponent, you can "manually" log in the user using $this->Auth->login($user_id), where $user_id is the id of the user in your own database.
private function oauthLogin($data) {
$this->User->create();
// do we already know about these credentials?
$oauth = $this->User->Oauth->find('first', array('conditions' => $data['Oauth']));
if ($oauth) {
// yes we do, let's try to log this user in
if (empty($oauth['User']['id']) || !$this->Auth->login($oauth['User']['id'])) {
$this->Session->setFlash('Login failed');
}
$this->redirect('/');
}
// no we don't, let's see if we know this email address already
if (!empty($data['User']['email'])) {
$user = $this->User->find('first', array('conditions' => array('email' => $data['User']['email'])));
if ($user) {
// yes we do! let's store all data in the session
// and ask the user to associate his accounts
$data['User'] = array_merge($data['User'], $user['User']);
$data['Oauth']['user_id'] = $user['User']['id'];
$this->Session->write('Oauth.associate_accounts', $data);
$this->redirect(array('action' => 'oauth_associate_accounts'));
}
}
// no, this is a new user, let's ask him to register
$this->Session->write('Oauth.register', $data);
$this->redirect(array('action' => 'oauth_register'));
}
Look no further. Here is an excellent article that'll guide you all the way through (minus any readymade plugins):
Integrating Facebook Connect with CakePHP's Auth component
Simply follow the approach described in there.
Cheers,
m^e

Auto login in CakePHP

I am using the registration form for different users? After a new user logs in, the registered users should redirect to an after-login page. We are using Auth component for the authentication.
How do I do this?
If you want the user to auto-login after registering, you can use the AuthComponent's login() method.
if ($this->User->save($this->data)) {
$this->Auth->login($this->data);
}
On newer Cakes, you only need to add
$this->Auth->login();
after you add the user into the database.
I'm not sure what the question is, but it sounds like you're wondering how to send a user somewhere after a successful login. If that's correct, try this:
$this->Auth->loginAction = array (
'controller' => 'whichever_controller',
'action' => 'desired_action',
'admin' => true
);
The admin key may not be necessary if you're not accessing /admin/whichever_controller/desired_action.
You will have to call the login method manually from your register action.
Save the username + unhashed password in an array then call it from the method after the save like this:
$data = array('username' => 'user', 'password' => $unhashedPw);
$this->User->login($data);

Resources