How can I update user records when they log into CakePHP?

I'm new to CakePHP and frameworks and I tried googling the answer with no luck.

I am using an empty login () function and I want to be able to change the user records on login (like last_login). How can i do this?

0


source to share


4 answers


If you are using the Cake Auth component, you first need to insert the following line into your beforeFilter function:

$this->Auth->autoRedirect = false;

      

Setting this value 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 have the last_login field in your users table and its value is datetime.

+1


source


Assuming you are using an embedded application AuthComponent

in your application, you need to set the following property in your controller:

$this->Auth->autoRedirect = false;

      

This will allow you to use your function login()

(s logout()

) to do something. Information about the user who is currently logged in is available through



$this->Auth->user()

      

Then you can use this data to accomplish what you want with that user.

As a shameless self-definition, I suggest you take a look at my open source project where I use this technique to create a remember me cookie.

0


source


I believe you can add stuff to the login () function even if autoRedirect is set to true. I was having some problems with implicit redirection (resource limited user request, must log in and then redirected), so I added code to my login function. Everything seems to be fine, and the login autostart function is called additionally.

I would say just go ahead and add your login logic, see if it works for you.

0


source


The pattern I like is to create an afterLogin () hook on the user model. So in your UserController, 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
}

      

0


source







All Articles