【问题标题】:Limiting view of index, but allowing edit in CakePHP?限制索引视图,但允许在 CakePHP 中进行编辑?
【发布时间】:2012-04-10 14:32:20
【问题描述】:

所以我想对未登录的人隐藏某个视图,并希望允许某个用户角色编辑/删除等。

但是使用 Auth->allow 和 isAuthorized 有点令人困惑。有没有办法简化以下内容?

我想允许某些角色(教练和管理员)查看索引和视图,并完全对其他人隐藏。

public function beforeFilter() {
    parent::beforeFilter();
    $this->Auth->allow('index', 'view');
}

public function isAuthorized($user) {
    if (in_array($this->action, array('edit', 'delete'))) {
        if ($user['id'] != $this->request->params['pass'][0]) {
            return false;
        }
    }
    return true;
}

【问题讨论】:

标签: cakephp authorization cakephp-2.0


【解决方案1】:
$this->Auth->allow('index', 'view');

在 beforeFilter() 中告诉 cake 任何人都可以查看索引和查看操作,无论他们是否登录。

您必须在 isAuthorized() 中执行测试并在那里测试该操作是否可以由用户执行。如果当前用户可以执行操作 ($this->action),则返回 true,如果不能,则返回 false。

public isAuthorized($user = null) {

  switch($this->action) {

    case "index":
    case "view":

      if ($user['role'] == 'admin') {

        return true;

      }

      break;

    case "edit":
    case "delete":

      if ($user['id'] == $this->request->params['pass'][0]) {
        return true;
      }   

      break;

   }

   return false;

}

详情请见http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#using-controllerauthorize

【讨论】:

    【解决方案2】:

    你可以从Session中获取当前用户

    在你的视图中渲染一些部分元素 (*.ctp)

    <?php
    $user = $this->session->read('Auth.User')
    
    if(!$user){
        echo $this->element('logmein');
    }else{
        echo $this->element('logmeout')
    ?>
    <h2>Here is member section</h2>
    <?php
    //... do some thing for member
    }
    ?>
    

    【讨论】:

      猜你喜欢
      • 2021-07-29
      • 2021-05-07
      • 1970-01-01
      • 2014-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-20
      相关资源
      最近更新 更多