user1104854
user1104854

Reputation: 2167

Accessing admin auth component from view in cakephp

I'd like to display a link on my default.ctp page to an admin panel but only if the user is an admin.

I'm attempting to do something like this but nothing appears to be happening

//default.ctp
if (!empty($role) && ($role == 'admin')) { 
   link here
} 

In my beforeFilter funciton in the appcontroller I have the following

$role = $this->Auth->user('role'); 
    if ($role == 'author' || $role == 'admin') { 
        $this->set('role', $role); 
    } 

When I try print_r($admin) the admin role is displayed, but for whatever reason the if statement isn't working.

Upvotes: 0

Views: 157

Answers (2)

Arun Jain
Arun Jain

Reputation: 5464

You could try to use the following code snippet in your AppController's beforeFilter() method:

function beforeFilter()
{
     $role = $this->Auth->user('role'); 
     if ($role == 'author' || $role == 'admin') { 
         $this->set('role', $role); 
     } 

     if($role == 'admin')
     {
         $this->set('is_admin', true);
     }
     else
     {
         $this->set('is_admin', false);
     }
    /***** your remaining code *******/

}

And in your view just use the following:

 if($is_admin)
 {
      $this->Html->link('Admin Link', 'controllers/view');
 } 

Upvotes: 0

Hugo Dozois
Hugo Dozois

Reputation: 8420

Try using:

$this->Session->read('Auth.User.role');

In the view file instead.

You will just read the value directly from the session instead of setting a new variable.

Upvotes: 1

Related Questions