2009-08-07 120 views
0

在CakePHP中,我們可以使用$this->Auth->allow('someMethod');使頁面無需登錄即可查看。如何讓某些用戶登錄時看不到相同的頁面?一個例子是我們希望可以在沒有用戶登錄的情況下訪問的註冊頁面,但是一旦用戶登錄後就不能訪問。如何在用戶登錄時使某些頁面不可用

我把$this->Auth->deny('someMethod')寫入isAuthorized()但在我看來,如果該方法是在允許列表中,當我們嘗試運行該頁面時,不會調用isAuthorized

任何輸入?謝謝

回答

3

有沒有像蛋糕認證內置的複雜規則。你必須手動檢查這樣的條件。這很簡單,但:

// Controller 
function register() { 
    if ($this->Auth->user()) { 
     $this->redirect(/* somewhere else */); 
    } 
} 

相反mlevits答案,你不需要任何存儲在會議上,信息是很容易從AuthComponent本身。 http://book.cakephp.org/view/387/user

還有一個例子,如何通過動態使用deny()來做到這一點,但這不像在這個簡單的例子這樣恕我直言。 http://book.cakephp.org/view/383/deny
此外,deny()會產生一條錯誤消息(「您無權訪問此位置」),這可能不是您想要的用戶體驗。

+0

事情是......我發現在查看允許列表中的頁面時,甚至沒有調用isAuthorized()。 但是,無論如何要確認它可能無法通過蛋糕Auth進行操作。 – user152235 2009-08-07 05:00:38

+0

'isAuthorized()'計算用戶是否被您指定爲拒絕或允許的內容授權,所以您已將其取消。 'deny()'拒絕所有人的動作,所以動態使用它是有意義的。你想要的是拒絕(或重定向)用戶是否簡單登錄。要做到這一點,請使用我上面的代碼。 – deceze 2009-08-07 05:05:51

+0

閱讀「isAuthorized()」的描述,它與「已登錄」非常不同:http://api.cakephp.org/class/auth-component#method-AuthComponentisAuthorized – deceze 2009-08-07 05:07:18

0

編輯:

不知道CakePHP使用不同的語法。

然後,您可以使用以下方法來設置會話變量:

$this->Session->write('user_id', '<some_user_name>'); 

然後用它來重定向用戶,如果他們登錄:

if ($this->Session->check('user_id')) 
{ 
    $this->redirect('http://google.com'); 
} 

然後摧毀一個會話使用:

$this->Session->destroy() 

More information about CakePHP Sessions

謝謝

+2

這個問題是關於CakePHP不是PHP的一般。 – linead 2009-08-07 04:16:28

+0

嗨mlevit謝謝你的回覆......是的,我當然可以使用會話來實現我想要做的事......但我只是認爲CakePHP Auth中必須有一些東西可以讓我做到這一點...就像我可以用Auth-> allow()做什麼。 – user152235 2009-08-07 04:17:25

+0

修復了CakePHP的語法。你可以使用'$ this-> Auth-> deny()'和你使用'allow'相同的方式,我相當確定。 – mlevit 2009-08-07 04:34:36

0

您可以在AppController的beforeFilter方法中檢查它,以允許在應用程序範圍內進行檢查。例如:

<?php 
class AppContoller extends Controller { 
    var $components = array('Session', 'Auth'); 

    function beforeFilter(){ 
     $this->Auth->allow('register', 'home'); 
     // Check if current action allowed to access without authorization and User has login 
     if(array_key_exists($this->params['action'], $this->Auth->allowedActions) && $this->Auth->user()){ 
      $this->redirect(/* somewhere else */); 
     } 
    } 
} 
?> 

當然你也可以在一些控制器而不是AppController中實現它。

相關問題