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 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化