如何检查当前登录的用户是否属于admin角色。
我有两个表,一个是用户和角色表。在users表中,我有一个名为role_id
的外键。 admin的角色是角色表中的ID为1。
1。)如何在视图中执行此检查以显示管理链接
2.。)如何在app_controller中执行此检查以阻止访问具有admin前缀的所有操作?
我尝试过类似的事情:
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
变量来检查应用
由于
答案 0 :(得分: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
}
}