如何检查当前登录的用户是否属于管理员角色。
我有两个表,一个是用户和角色表。在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
变量来检查应用程序
感谢
一种方法是在控制器函数中设置一个变量
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
}
}