2009-08-07 99 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中实现它。