Cakephp auth登录问题。我可以使用ClientController进行登录吗?

时间:2017-06-08 07:01:35

标签: php cakephp

我目前正在网站中设置一个登录模块,它有两个角色,如admin,普通用户。 UsersController已经为后端登录创建并且它正在工作。 我创建了另一个控制器ClientController并在数据库中创建了新的表客户端。

但是登录不起作用并且提供错误用户名和密码不正确。 我必须使用UsersController进行登录。 这是我正在使用的代码。

提前感谢您的帮助!

AppController.php:

public $components = array(
'Acl',
'Auth' => array(
    'authorize' => array(
    'Actions' => array(
        'actionPath' => 'controllers',
        'userModel' => 'Clients '
        )
    ),
    'authError' => 'Sorry, you are not authorised to do that.',
),
'Session'
);

ClientController.php:

public function login() {
    if ($this->request->is('post')) {
        if ($this->Auth->login() {
        $this->Session->setFlash('Your login was successful.');
        return $this->redirect(array('action' => 'dashboard'));
        }

        $this->Session->setFlash('Your username or password was incorrect. Please, try again.');
        return $this->redirect('/login');
    }
    }

Client.php 模型

    class Client extends AppModel {

    public $useTable = 'clients';
    public $validate = array(
    'username' => array(
        'required' => array(
        'rule' => array('notEmpty'),
        'message' => 'A username is required'
        )
    ),
    'password' => array(
        'required' => array(
        'rule' => array('notEmpty'),
        'message' => 'A password is required'
        )
    ),
    'email' => array(
        'email' => array(
        'rule' => array('email', true),
        'message' => 'Please supply a valid email address.'
        ),
        'required' => array(
        'rule' => array('notEmpty'),
        'message' => 'A email is required'
        )
    )
    );
    public $belongsTo = array(
    'Group' => array(
        'className' => 'Group',
        'foreignKey' => 'group_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    )
    );

    public function beforeSave($options = array()) {

    if (empty($this->data[$this->alias]['password'])) {
        unset($this->data[$this->alias]['password']);
    } else {
        $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
    }
    return true;

    }

}

1 个答案:

答案 0 :(得分:0)

您可能需要在ClientController中再次设置auth组件,还需要使用userModel指定Authentication方法。

例如在你的情况下:

$this->Auth->authenticate = array(
            'Form' => array('userModel' => 'Client')
        );

将上面的代码放在 ClientController beforeFilter 方法中。