2013-04-25 83 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('/'); 
    } 
相關問題