2011-08-28 135 views
2

如何檢查當前登錄的用戶是否屬於管理員角色。CakePHP檢查用戶角色

我有兩個表,一個用戶和角色表。在用戶表中,我有一個名爲role_id的外鍵。管理員的角色在角色表中的ID爲1。

1)我怎麼會做這種檢查在視圖中顯示的管理員聯繫

2)我怎麼會做這種檢查在app_controller阻止訪問具有管理員前綴的所有動作?

我已經試過類似:

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; 
    } 
} 

,然後我嘗試使用is_admin變量來檢查周圍的應用

感謝

回答

1

這樣做的一個方法是在設置變量您的控制器功能

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 

} 

    } 

在您的查看您測試像下面

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

} 
?> 

你的第二個答案...你可以做同樣的這個變量...

 function beforeFilter() 
    { 
    if($this->Auth->user('role_id')==1){ 
    $this->Auth->allow('admin_view','admin_controls');//put your all admin actions separated by comma 

    } 


    }