Menu options authorization

Hi. I’m trying to validate the auth rights a user have to access a specific option of the app menu.
I Have my app’s menu in /template/element/menu.ctp. from here, if I evaluate $this->Aut->user (set in /Controller/UsersController login method, I get a null value. So, I wonder if there is a way to evaluate, in menu.ctp element, the Auth info.

Hi,

if you call

$user = $this->Auth->user();
$this->set(‘currentUser’, $user);

inside your controller method

you can access the variable inside the ctp by using

$currentUser

so for example

<?php if ($currentUser != null): ?>

<span>A user is logged in</span>

<?php endif; ?>

If this does not help, please show your code :wink:

Hi, dmuenstermann, Thanks for your help.
Unfortunately didn’t work. When I evaluate $currentUser in menu.ctp it shows as null…

This is my UsersController login method:
public function login()
{
if($this->request->is(‘post’))
{
$user = $this->Auth->identify();
if($user)
{
$user1 = $this->Auth->user(); // added from dmuenstermann help
$this->set(‘currentUser’, $user1); // added from dmuenstermannhelp
debug($currentUser); ****** THIS RETURN NULL AS WELL *******
debug($user1); ****** THIS RETURN NULL AS WELL *******
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}else {
$this->Flash->error(‘Datos son invalidos, por favor intente nuevamente’, [‘key’ => ‘auth’]);
}
}
if ($this->Auth->user())
{
return $this->redirect([‘controller’ => ‘Users’, ‘action’ => ‘home’]);
}
}

This is an extract of menu.ctp where i do the user evaluation in order to allow or deny menu options access:

<?php
    if($currentUser != null){
     $name = $currentuser['name'];
     $UserType = $currentUser['user_type']; ;
     $UserRol = $currentUser['access_level']; ?>
     <span>A user is logged in</span>
<?php } debug($currentUser); ?>
<nav class="navbar navbar-expand-lg navbar-light bg-light">

.
.
.
.

Do you have AuthComponent loaded in AppController and configured (e.g.)Form Authentication? If so, what are the fields named/configured that you use to submit the login?

(this link contains more info on how to configure the AuthComponent)

Yes, Take a look of my appController auth setting:
.
.
.
namespace App\Controller;

use Cake\Controller\Controller;
use Cake\Event\Event;
class AppController extends Controller
{

public function initialize()
{
    parent::initialize();
    $this->loadComponent('RequestHandler');
    $this->loadComponent('Flash');
    $this->loadComponent('Auth', [
        'authorize' => ['Controller'],
        'authenticate' => [
            'Form' => [
                'fields' => [
                    'username' => 'email',
                    'password' => 'password'
                ],
                'finder' => 'auth'
    ]
],
        'loginAction' => [
            'controller' => 'Users',
            'action' => 'login'
        ],
        'authError' => 'No Autorizado para esta acción',
        'loginRedirect' => '',
        'logoutRedirect' => [
            'controller' => 'Users',
            'action' => 'login'
        ],
        'storage' => 'Session',
        'unauthorizedRedirect' => $this->referer()
    ]);

    // Allow the display action so our PagesController
    // continues to work. Also enable the read only actions.
    $this->Auth->allow(['display', 'view', 'index']);
}

My UsersTable find auth method:

public function findAuth(\Cake\ORM\Query $query, array $options)
{
    $query
        ->select(['id', 'name', 'email', 'password', 'access_level', 'user_type', 'company_code'])
        ->where(['Users.status' => 'Activo']);
    return $query;
}

the following is the content of debugkit session input:

Config (array)
Auth (array)
User (array)
id 1
name XXXXXXXXXXXXXXXXX
email xxxxxxxxxxxxxx@gmail.com (values overriden by myself)
access_level admin
user_type XXXXXXXXXX
company_code 999
Flash (empty)

I think there is a problem with my components loading because my Flash messages don’t work neither.

Ok, I’m running out of ideas at the moment.

But there’s one thing left that comes in my mind when I see your code :wink:
Do you have an initialize()-function/beforeFilter()-function at the usersController and is it calling parent::intialize()/parent::beforeFilter()?
So, as you set the authorization to ‘Controller’ is it possible that you are “not allowed” to access the login-function?
With the unauth-redirect set to $this->referer() it may happen that you get to see pages you shouldn’t be able to see (though the content you see depends on proper ‘user-is-logged-in-testing’ in the ctp-files)

well my friend, we are now two running out of ideas…

Actualiy, I did had a beforeFilter at my UserController. I commented it out and try again, but is still the same.
As you have realized, I’m a real novice in cakePHP, so I don’t even know how to set the authorization, other than ‘Controller’. Is there any else?

The following is my whole UserController definitions:

<?php namespace App\Controller; use App\Controller\AppController; /** * Users Controller * * @property \App\Model\Table\UsersTable $Users * * @method \App\Model\Entity\User[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = []) */ class UsersController extends AppController { /** * Index method * * @return \Cake\Http\Response|void */ /* public function beforeFilter(\Cake\Event\Event $event) { parent::beforeFilter($event); $this->Auth->allow(['add']); } */ t public function isAuthorized($user) { if(isset($user['access_level']) and $user['access_level'] == 'admin') { if($user['user_type']== 'TheRightOne') { if(in_array($this->request->action, ['add', 'delete', 'edit', 'index', 'view', 'logout'])) { return true; } } }else{ if(in_array($this->request->action, ['index', 'view', 'logout'])) { return true; } } return parent::isAuthorized($user); } public function logout() { $this->Flash->success('Has salido del sistema.'); return $this->redirect($this->Auth->logout()); } public function login() { if($this->request->is('post')) { $user = $this->Auth->identify(); if($user) { $user1 = $this->Auth->user(); // added from dmuenstermann help $this->set('currentUser', $user1); // added from dmuenstermannhelp //debug($currentUser); // this return null as well //debug($user1); // this return null as well $this->Auth->setUser($user); return $this->redirect($this->Auth->redirectUrl()); }else { $this->Flash->error('Datos son invalidos, por favor intente nuevamente', ['key' => 'auth']); } } if ($this->Auth->user()) { return $this->redirect(['controller' => 'Users', 'action' => 'home']); } } //****************************************************************************************/ public function home() { $this->render(); } public function index() { $users = $this->paginate($this->Users); $this->set('users', $users); } /** * View method * * @param string|null $id User id. * @return \Cake\Http\Response|void * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found. */ public function view($id) { $user = $this->Users->get($id); $this->set('user', $user); } /** * Add method * * @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise. */ public function add() { $user = $this->Users->newEntity(); if($this->request->is('post')) { $user = $this->Users->patchEntity($user, $this->request->data); $user->role = 'user'; $user->active = 1; if($this->Users->save($user)) { $this->Flash->success('El usuario ha sido creado correctamente.'); } else { $this->Flash->error('El usuario no pudo ser creado. Por favor, intente nuevamente.'); } } $this->set(compact('user')); } /** * Edit method * * @param string|null $id User id. * @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise. * @throws \Cake\Network\Exception\NotFoundException When record not found. */ public function edit($id = null) { $user = $this->Users->get($id); if ($this->request->is(['patch', 'post', 'put'])) { $user = $this->Users->patchEntity($user, $this->request->data); if ($this->Users->save($user)) { $this->Flash->success('El usuario ha sido modificado'); return $this->redirect(['action' => 'index']); } else { $this->Flash->error('El usuario no pudo ser modificado. Por favor, intente nuevamente.'); } } $this->set(compact('user')); } /** * Delete method * * @param string|null $id User id. * @return \Cake\Http\Response|null Redirects to index. * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found. */ public function delete($id = null) { $this->request->allowMethod(['post', 'delete']); $user = $this->Users->get($id); if ($this->Users->delete($user)) { $this->Flash->success('El usuario ha sido eliminado.'); } else { $this->Flash->error('El usuario no pudo ser eliminado. Por favor, intente nuevamente.'); } return $this->redirect(['action' => 'index']); } }

Sorry by the mess

<?php namespace App\Controller; use App\Controller\AppController; /** * Users Controller * * @property \App\Model\Table\UsersTable $Users * * @method \App\Model\Entity\User[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = []) */ class UsersController extends AppController { /** * Index method * * @return \Cake\Http\Response|void */ /* public function beforeFilter(\Cake\Event\Event $event) { parent::beforeFilter($event); $this->Auth->allow(['add']); } */ public function isAuthorized($user) { if(isset($user['access_level']) and $user['access_level'] == 'admin') { if($user['user_type']== 'Pacplus') { if(in_array($this->request->action, ['add', 'delete', 'edit', 'index', 'view', 'logout'])) { return true; } } }else{ if(in_array($this->request->action, ['index', 'view', 'logout'])) { return true; } } return parent::isAuthorized($user); } public function logout() { $this->Flash->success('Has salido de Pacplus system.'); return $this->redirect($this->Auth->logout()); } public function login() { if($this->request->is('post')) { $user = $this->Auth->identify(); if($user) { $user1 = $this->Auth->user(); // added from dmuenstermann help $this->set('currentUser', $user1); // added from dmuenstermannhelp //debug($currentUser); // this return null as well //debug($user1); // this return null as well $this->Auth->setUser($user); return $this->redirect($this->Auth->redirectUrl()); }else { $this->Flash->error('Datos son invalidos, por favor intente nuevamente', ['key' => 'auth']); } } if ($this->Auth->user()) { return $this->redirect(['controller' => 'Users', 'action' => 'home']); } } //****************************************************************************************/ public function home() { $this->render(); } public function index() { $users = $this->paginate($this->Users); $this->set('users', $users); } /** * View method * * @param string|null $id User id. * @return \Cake\Http\Response|void * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found. */ public function view($id) { $user = $this->Users->get($id); $this->set('user', $user); } /** * Add method * * @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise. */ public function add() { $user = $this->Users->newEntity(); if($this->request->is('post')) { $user = $this->Users->patchEntity($user, $this->request->data); $user->role = 'user'; $user->active = 1; if($this->Users->save($user)) { $this->Flash->success('El usuario ha sido creado correctamente.'); } else { $this->Flash->error('El usuario no pudo ser creado. Por favor, intente nuevamente.'); } } $this->set(compact('user')); } /** * Edit method * * @param string|null $id User id. * @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise. * @throws \Cake\Network\Exception\NotFoundException When record not found. */ public function edit($id = null) { $user = $this->Users->get($id); if ($this->request->is(['patch', 'post', 'put'])) { $user = $this->Users->patchEntity($user, $this->request->data); if ($this->Users->save($user)) { $this->Flash->success('El usuario ha sido modificado'); return $this->redirect(['action' => 'index']); } else { $this->Flash->error('El usuario no pudo ser modificado. Por favor, intente nuevamente.'); } } $this->set(compact('user')); } /** * Delete method * * @param string|null $id User id. * @return \Cake\Http\Response|null Redirects to index. * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found. */ public function delete($id = null) { $this->request->allowMethod(['post', 'delete']); $user = $this->Users->get($id); if ($this->Users->delete($user)) { $this->Flash->success('El usuario ha sido eliminado.'); } else { $this->Flash->error('El usuario no pudo ser eliminado. Por favor, intente nuevamente.'); } return $this->redirect(['action' => 'index']); } }

you are first trying to get user

$user1 = $this->Auth->user();

and then set it

$this->Auth->setUser($user);

you will get null because you are getting user that is not yet set : )
just ->setUser($user) before you ->user()

1 Like

ok. Graziel, you’re right. I already solve my problem. Thanks a lot.