Reputation: 28783
How do I check if the currently logged in user belongs to the admin role.
I have two tables, a users and roles table. In the users table I have a foreign key called role_id
. And a role of admin is ID of 1 in the roles table.
1.) How would I do this check in the view to show an admin link
2.) How would I do this check in the app_controller to prevent access to all actions that have the admin prefix?
I have tried something like:
public function beforeRender()
{
$user = $this->Auth->user();
if (!empty($user))
{
$user = $user[$this->Auth->getModel()->alias];
}
$this->set(compact('user'));
if($user['Role']['id'] == 1)
{
$is_admin = true;
}
}
and then I try and use the is_admin
variable to check around the app
Thanks
Upvotes: 2
Views: 7326
Reputation: 1015
one way of doing this is setting a variable in your controller functions
function beforeFilter()
{
if($this->Auth->user('role_id')==1){
$this->set("role",$this->Auth->user('role_id'));//it will set a variable role for your view
}
else
{
$this->set("role",2);//2 is the role of normal users
}
}
in your view you test this variable like below
<?php if($role==1){ ?>
echo $html->link('view registered users',array('controller'=>'users','action'=>'admin_check_users'),array('title'=>'Users'));/provide a link for admin using html helper; }
else{
echo $html->link('logout',array('controller'=>'users','action'=>'logout'),array('title'=>'Logout...'));//provide a link for normal users using html helper;
}
?>
for your 2nd answer... you can do the same...
function beforeFilter()
{
if($this->Auth->user('role_id')==1){
$this->Auth->allow('admin_view','admin_controls');//put your all admin actions separated by comma
}
}
Upvotes: 1