Question

I'm new to CakePHP and frameworks and I've tried to google in search of an answer without any luck.

I'm using the blank login() function and want to be able to change user records on login (like last_login). How can I do that?

Was it helpful?

Solution

If you're using Cake's Auth component, first you'll have to insert the following line into your beforeFilter function:

$this->Auth->autoRedirect = false;

Setting this to false will allow the following code to execute after CakePHP's login function has done its magic.

In your login function add:

if ($this->Auth->User()) {
$this->User->id = $this->Auth->user('id');
$this->User->saveField('last_login', date('Y-m-d H:i:s'));
}

Note: Make sure you've got the last_login field in your users table and its set to datetime.

OTHER TIPS

Assuming you're using the built in AuthComponent in you app, you need to set the following property in your controller:

$this->Auth->autoRedirect = false;

This will enable you to use your login() function (and logout()) to do stuff. Information about the currently logged in user is available via

$this->Auth->user()

You can then use this data to do whatever you want with that user.

As a shameless self promotion, I suggest you take a look at my open source project, where I'm using this technique to create a "remember me" cookie.

I believe you can add stuff to the login() function, even with autoRedirect set to true. I have had some issues with the implicit redirect (user requests restricted resource, has to login, then gets redirected), so I added some code in my login function. Seems to work fine, and the automagic login function gets called in addition.

I'd say just go ahead and add some logic to login, see if it works for you.

A pattern that I like is to create an afterLogin() hook in the User model. So in your UsersController create something like:

function beforeFilter() {
    $this->Auth->autoRedirect = false;
    parent::beforeFilter();
}

function login() {
    if($this->Auth->User()) {
        if(!$this->User->afterLogin($this->Auth->User())) {
            return $this->logout();
        }

        $this->redirect($this->Auth->redirect());
    }
}

Then in the User model create:

function afterLogin($User) {
    // perform actions on $User here

    return true; // return false to halt login
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top