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?
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.