CakePHP 2.0 Automatic Login after Account Activation

我只是一个虾纸丫 提交于 2020-01-01 10:44:49

问题


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?


回答1:


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.




回答2:


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!



来源:https://stackoverflow.com/questions/9650605/cakephp-2-0-automatic-login-after-account-activation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!