【问题标题】:Cakephp 3.x way to check if a user exists in the databaseCakephp 3.x 检查数据库中是否存在用户的方法
【发布时间】:2015-11-22 19:00:40
【问题描述】:

我想创建一个简单的检查,即用户在登录后是否存在于我的数据库中(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.'));
        }
    }
}

提前谢谢你。

【问题讨论】:

    标签: php cakephp cakephp-3.0


    【解决方案1】:

    您所展示的内容有效,但更好的方法是使用 LDAP 身份验证类中的事件来通知需要在您的应用中创建新的用户记录。您的表的createStudent() 可以设置为该事件的侦听器回调。此外,如果在您的数据库表中找到匹配的记录,您的 LDAP 身份验证类也应该只返回信息,我认为目前不是这种情况。

    你可以参考这个类似的HybridAuthAuthenticate。插件的自述文件显示了如何为事件设置监听器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-31
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 2021-12-19
      • 2016-09-04
      相关资源
      最近更新 更多