AuthComponent不返回用户ID

时间:2014-04-05 16:27:35

标签: authentication cakephp-2.4

我已多次这样做,这个问题从未发生过。

$this->Auth->user()仅返回包含usernamepassword字段

的数组

$this->Auth->user('id')返回null。

任何?

修改

AppController中的AuthComponent定义:

public $components = array(
    'Session',
    'Cookie',
    'Auth' => array(
        'authorize' => 'Controller',
        'loginError' => 'Invalid account specified',
        'authError' => 'No Permission',
        'logoutRedirect' => array('controller' => 'users', 'action' => 'login'),
    ),
);

编辑2

用户模型:

<?php

class User extends AppModel {

public $validate = array(
    '_password' => array(
        'equaltofield' => array(
            'rule' => array('equaltofield', 'password'),
            'message' => 'Require the same value to password.',
        )
    )
);

public function beforeValidate ($options = array()) {
    $this->data[$this->alias]['password'] = AuthComponent :: password($this->data[$this->alias]['password']);
    $this->data[$this->alias]['_password'] = AuthComponent :: password($this->data[$this->alias]['_password']);
}

function equaltofield($check,$otherfield) {
    $fname = '';
    foreach ($check as $key => $value){
        $fname = $key;
        break;
    }
    return $this->data[$this->name][$otherfield] === $this->data[$this->name][$fname];
} 

}

?>

UsersController登录/注销功能:

public function login () {
    if($this->request->is('post')) {
        if($this->Auth->login($this->request->data)) {
            if($this->Auth->user('role' == 'administrator')) {
                return $this->redirect(array('controller' => 'brands', 'action' => 'index'));   
            }
            else {
                return $this->redirect(array('controller' => 'visits', 'action' => 'index'));   
            }
        }
        else {
            $this->Session->setFlash('Login incorrect');    
        }
    }
}

public function logout () {
    $this->Auth->logout();
    return $this->redirect(array('action' => 'login')); 
}

1 个答案:

答案 0 :(得分:1)

登录操作存在问题 -

$this->request->data

中删除$this->Auth->login();

必须是 -

public function login () {
    if($this->request->is('post')) {
        if($this->Auth->login()) {
            if($this->Auth->user('role' == 'administrator')) {
                return $this->redirect(array('controller' => 'brands', 'action' => 'index'));   
            }
            else {
                return $this->redirect(array('controller' => 'visits', 'action' => 'index'));   
            }
        }
        else {
            $this->Session->setFlash('Login incorrect');    
        }
    }
}