dsrruefh12970 2016-04-23 08:20
浏览 36
已采纳

包含Auth info CakePHP 3中的组

I'm looking for a CakePHP 3.x update for this question. Basically, I am authenticating users using the Auth component in CakePHP 3 and need to include groups.

My model relations are as follows:

User hasMany Groups
Group hasMany Users

So basically it's a many-to-many relationship.

Currently, my login function looks like this:

public function login()
{
    if ($this->request->is('post')) {
        $user = $this->Auth->identify();
        if ($user) {
            $this->Auth->setUser($user);
            return $this->redirect($this->Auth->redirectUrl());
        }
        $this->Flash->error(__('Invalid username or password, try again'));
    }
    $this->viewBuilder()->layout('login');
}

Is there a way to do this with the Auth component?

  • 写回答

1条回答 默认 最新

  • dongxu7121 2016-04-23 08:41
    关注

    So it was pretty easy:

    I changed my login function to this:

    public function login()
    {
        if ($this->request->is('post')) {
            $user = $this->Auth->identify();
            if ($user) {
                $user = $this->setUserGroups($user);
                $this->Auth->setUser($user);
                die(debug($this->Auth->user()));
                return $this->redirect($this->Auth->redirectUrl());
            }
            $this->Flash->error(__('Invalid username or password, try again'),['params'=>['class'=>'test']]);
        }
        $this->viewBuilder()->layout('login');
    }
    

    Then I created the setUserGroups($user) function

    /**
     * @param AuthComponent $user
     * @return TableRegistry $this
     */
    private function getUserGroups($user)
    {
        $users = TableRegistry::get('Users');
    
        $query = $users->find()
            ->contain(['Groups'])
            ->where(['users.id' => $user['id']])
            ->limit(1);
        return $query;
    }
    
    /**
     * @param AuthComponent $user
     * @return AuthComponent mixed
     */
    private function setUserGroups($user)
    {
        $results = $this->getUserGroups($user);
        $user['groups'] = [];
        foreach ($results as $row) {
            foreach ($row->groups as $group) {
                $user['groups'][] = $group['id'];
            }
        }
    
        return $user;
    }
    

    Now it returns my user object with an array of group id's.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 WPF动态创建页面内容
  • ¥15 如何对TBSS的结果进行统计学的分析已完成置换检验,如何在最终的TBSS输出结果提取除具体值及如何做进一步相关性分析
  • ¥15 SQL数据库操作问题
  • ¥100 关于lm339比较电路出现的问题
  • ¥15 Matlab安装yalmip和cplex功能安装失败
  • ¥15 加装宝马安卓中控改变开机画面
  • ¥15 STK安装问题问问大家,这种情况应该怎么办
  • ¥15 关于罗技鼠标宏lua文件的问题
  • ¥15 halcon ocr mlp 识别问题
  • ¥15 已知曲线满足正余弦函数,根据其峰值,还原出整条曲线