简单ACL -重定向用户,如果他们有不正确的权限


Simple ACL - Redirect user if they have incorrect permissions

我遵循这个'简单ACL控制应用程序' CakePHP教程:http://book.cakephp.org/2.0/en/tutorials-and-examples/simple-acl-controlled-application/simple-acl-controlled-application.html

一切正常,但应用程序有一个怪癖,我不喜欢。

示例中有三个角色:admin、manager和user。我用一个具有用户角色的帐户登录。当我点击一个我没有权限访问的链接时,我被重定向到当前的url,所以本质上,什么都没有发生。我不喜欢这样,因为它看起来像应用程序没有响应。

如何将用户重定向到"拒绝许可"页面而不是重定向到推荐人?我已经在UsersController中创建了一个名为permissionDenied的新操作和相应的视图。我还为动作创建了aco,并允许所有组访问它。

没有发生任何事情的原因是因为您没有显示Acl组件在视图中生成的flash消息(正如Dave在评论中已经提到的那样)。您必须将其添加到您的布局或视图:

echo $this->Session->flash('auth');

这样用户就可以在你的AuthComponent属性中看到你设置为authError的任何消息。

另一种方法是在AppController的beforeFilter方法中运行Acl检查,如果Acl检查失败,则重定向用户,如下所示:

/**
 * ACL Check (CakeError controller is exempt from this example,
 * so errors are always "allowed" to be shown).
 */
if (!is_null($this->Auth->User()) && $this->name != 'CakeError'
    && !$this->Acl->check(array(
        'model' => 'User',
        'foreign_key' => AuthComponent::user('id')),
        $this->name . '/' . $this->request->params['action']
)) {
    // Optionally log an ACL deny message in auth.log
    CakeLog::write('auth', 'ACL DENY: ' . AuthComponent::user('username') .
        ' tried to access ' . $this->name . '/' .
        $this->request->params['action'] . '.'
    );
    // Render the forbidden page instead of the current requested page
    echo $this->render('/Pages/forbidden');
    /**
     * Make sure we halt here, otherwise the forbidden message
     * is just shown above the content.
     */
    exit;
}

这样,app/View/Pages/forbidden.ctp文件将被呈现,exit语句将阻止重定向发生。