2013-04-25 88 views
0

我们使用的是Auth组件。我们目前能够阻止未登录的用户访问我们的“管理员”页面(adminhome.ctp)。但我们无法弄清楚如何让isAuthorized()阻止非管理员访问该页面。CakePHP:如何为特定页面要求管理员角色?

的AppController的内部:

public function beforeFilter() { 
    $this->Auth->allow('index', 'view', 'login', 'logout', 'display'); 
    $this->Auth->authorize = array('Controller'); 
    //$this->Auth->autoRedirect = false; 
} 

public function isAuthorized($user_id) { 
    $this->loadModel('User'); 
    $user = $this->User->findById($this->Auth->user()); 
    if ($user['User']['role'] === 'admin') { 
     $this->Session->setFlash('isAuthorized'); 
     return true; 
    } 
    $this->Session->setFlash('!isAuthorized'); 
    return false; 
} 

这里beforeFilter()在PagesController:

function beforeFilter() { 
    $this->Auth->deny('adminhome'); 
} 

什么是我们做错了什么?

回答

1

我相信你的方式不起作用,因为你应该使用Auth-> deny()来限制对方法的访问,而adminhome不是PagesController中的方法。试试这个:

# in app/controller/PagesController.php 
public function display() { 
    $page = empty($this->request->params['pass'][0]) ? null : $this->request->params['pass'][0]; 
    if($page == 'adminhome' || $this->User->isAuthorized()) { 
    $this->render($page); 
    } else { 
    # redirect the user somewhere else 
    } 
} 

我希望这有助于

+0

我们使用管理路由。它在所有控制器上都能很好地工作,但它似乎不适用于页面,因为正如您所指出的那样,'adminhome'不是一种方法。我会尝试你的版本,但我很困惑它将如何解决我的特定问题,这涉及到由PagesController呈现的特定页面。换句话说'$ this-> Auth-> deny()'不能引用特定的页面,可以吗? – emersonthis 2013-04-26 00:23:59

+0

我想我很困惑你的答案,因为第一个块(使用管理员前缀,因为我们想)似乎并没有参考网页。 – emersonthis 2013-04-26 00:26:03

+0

如果您已经使用管理路由,那么不要考虑答案的第一部分。是的,$ this-> Auth-> deny()可能不能引用特定的页面,这就是为什么你必须在你的情况下使用display()和isAuthorized()方法,就像我在第二部分中指出的那样。 – vcanales 2013-04-26 00:33:05

0

你必须在user表中的作用领域。在特定的操作。如果你想只有管理员可以看到像admincontroller

在某些控制器每个动作,你可以在控制器beforeRender行动

if($this->Session->read('Auth.User.role') != 'admin') 
      { 
       $this->Session->setFlash(You are not authorized to visit this page,'flash',array('alert'=>'info')); 
       $this->redirect('/'); 
      } 
2

我添加此代码中加入这一行

if($this->Session->read('Auht.User.role') != 'admin') { 
     ............................... 
} 

刚刚使用雅利安的答案,但我已经做了一些小的变化,这可能会对其他人有所帮助:

if($this->Session->read('Auth.User.role') != 'admin') 
    { 
     $this->Session->setFlash('You are not authorized to visit this page'); 
     $this->redirect('/'); 
    } 
相关问题