Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP 2.0 Automatic Login after Account Activation

I'm just working on the user management-component of our new project. The plan is:

  1. User registers on the page with minimal amount of account data (username, pass, email)
  2. User gets an email with an activation link to activate the account
  3. User clicks on the link and activates his account
  4. The system logs in the user after automatically after activation and redirects him to kind of a dashboard with account information (last login, hi "username", etc.)

But there are some problems with the auto login. this is the part of the code i use:

<?php
...
// set userstatus to "active" and delete meta information "activation_key"
// then automatically login
$this->User->id = $id;
$this->User->saveField('modified', date('Y-m-d H:i:s') );
$this->User->saveField('status', 1 );

// $this->User->deleteActivationKey ....

$this->Auth->login($this->User->read());
$this->Session->setFlash(__('Successfully activated account. You are now logged in.'));

$this->User->saveField('last_login', date('Y-m-d H:i:s') );

$this->redirect(array('controller' => 'pages'));
...

This works so far, until you want to get information about the logged in user with the user() function of the Auth Component.

We're using this in AppController->beforeRender, to have user information application wide:

$this->set('auth', $this->Auth->user());

but after that auto login action, i'm getting undefined index notices. (e.g. by accessing $auth['id'] in a view). print_r() shows me only the username and hashed password of the current user. If you login manually, everything works fine. it must be something with the automatic login after the account activation.

Seems to be a problem with the session? What am i doing wrong?

like image 821
rookian Avatar asked Mar 10 '12 22:03

rookian


2 Answers

Have you tried this? (CakePHP 2.x)

public function signup() {   
  if (!empty($this->request->data)) {
    // Registration stuff

    // Auto login
    if ($this->Auth->login()) {
      $this->redirect('/');
    }
  }
}

That simple!

like image 33
vinzcelavi Avatar answered Oct 23 '22 20:10

vinzcelavi


Found a solution after testing many variations.

Works now with:

$user = $this->User->findById($id);
$user = $user['User'];
$this->Auth->login($user);

Don't know why, i thought i tried this way already and that did not work.

like image 174
rookian Avatar answered Oct 23 '22 20:10

rookian