【问题标题】:CakePHP: calling function in the AppController but not effect some exceptionCakePHP:在 AppController 中调用函数但不影响某些异常
【发布时间】:2017-05-31 08:30:28
【问题描述】:

通常,cakephp 中有 Auth 组件来帮助用户登录,并且有 Auth->Allow() 函数可以使访客用户仍然可以访问某些页面,例如索引。但现在我希望只有激活的帐户才能访问网络的几乎所有功能,但仍然除了一些正常的页面,如索引、视图等。 我在 Appcontroller 中有一个功能

public function is_activated(){
    $userId = $this->Auth->user('id');
    $user = $this->Users->find('all', [
            'conditions' => ['id' => $userId],
            'fields' => ['id', 'email', 'activated']
        ])->first();
    $activated = $user->activated;
    if($activated !== 1){
            $this->Flash->error(__('Your account is not yet activated'));
            return $this->redirect('/users/activate');
    }
}

我在 BeforeFilter 和 ProjectsController 中的 Auth->allow() 中调用它:

public function beforeFilter(Event $event) {
    parent::beforeFilter($event);
    $this->Auth->allow(['index', 'getMyProjects']);
    $this->is_activated();
}

但是通过这种方式,每个页面都会受到影响,并且 Auth->allow() 不再起作用。任何人都可以向我展示我的 is_activated() 函数的更好方法,我想这种方式我重定向网络不是一个好方法。

【问题讨论】:

    标签: php cakephp


    【解决方案1】:

    你要找的是 isAuthorized() 函数:

    public function isAuthorized($user){
        if($user->activated){
            return true;
        }
        return false;
    }
    

    把它放在你的 AppController 中,你也可以在你的其他控制器中覆盖它。如果存在,它将被自动调用。

    延伸阅读:

    https://book.cakephp.org/3.0/en/tutorials-and-examples/blog-auth-example/auth.html#authorization-who-s-allowed-to-access-what

    https://book.cakephp.org/3.0/en/controllers/components/authentication.html#authorization

    【讨论】:

    • 那个函数默认注释了吗?
    • 我可以在我想要限制的任何操作之前调用 is_activated 函数吗?
    • 请先阅读文档。在 isAuthorized() 方法中,您可以编写您的授权代码,如果用户被授权,它应该返回 true,如果用户不是,它应该返回 false。我发布的只是一个例子。您可以通过添加更多特定于您的控制器的代码来扩展它。例如,您可以使用条件语句和 $this->request->getParam('action') 授权所有用户查看 index() 操作,并仅授权激活的用户查看() 操作。它只会影响登录用户,因此使用 Auth::allow() 您仍然可以管理未登录访问者可用的操作。
    • 如果我有 3 个级别,访客、未激活成员和已激活一个?
    • 访客(如果您指的是未登录的访客)由 Auth::allow() 处理。已登录的用户由 isAuthorized 处理。如果用户未授权,您可以在 Auth 选项中设置未授权的重定向 url,他们将被重定向到。请检查 AuthComponent 的所有可用选项:book.cakephp.org/3.0/en/controllers/components/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多