繁体   English   中英

Cakephp 3.x检查用户是否存在于数据库中的方法

[英]Cakephp 3.x way to check if a user exists in the database

我想创建一个简单的检查,即用户刚登录后是否在我的数据库中存在(LDAP认证)。 如果他不存在,则应在数据库中创建一条记录。 是否有任何标准的CakePHP 3.x这样的方式? 还是我可以在“用户”控制器中创建一个函数,该函数检查数据库中是否存在用户,并在login()函数末尾调用它(如果已成功创建用户会话)?

public function login(){
        if ($this->request->is('post')){
            $user = $this->Auth->identify();
            if ($user) {
                $this->Auth->setUser($user);
                $this->createStudent($user);
                return $this->redirect($this->Auth->redirectUrl());
            }

            // user is not identified
            $this->Flash->error('Your username or password is not correct');
        }
    }

public function createStudent($user){
        $studExists = $this->Students->find('isExists', ['uid' => $user['uid']]);

    if (!$studExists) {
        $student = $this->Students->newEntity();
        $data = ['id' => $user['uid']];
        $student = $this->Students->patchEntity($student, $data);
        if ($this->Students->save($student)) {
            $this->Flash->success(__('It is your first logon. You have been added to our database!'));
            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error(__('You could not be saved in our database. Please, try again.'));
        }
    }
}

先感谢您。

您显示的内容有效,但更好的方法是使用LDAP Authenticate类中的事件来通知需要在应用程序中创建新的用户记录。 可以将表的createStudent()设置为该事件的侦听器回调。 另外,如果在datbase表中找到匹配的记录,则LDAP authenticate类也应该仅返回信息,我认为目前不是这种情况。

您可以参考与此类似的HybridAuthAuthenticate 插件的自述文件显示了如何设置事件的侦听器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM