2012-03-27 42 views
0

所以我想隐藏那些没有登录的人一定的看法,并希望允许某个用户角色编辑/删除等限制索引视图,但允许在CakePHP中编辑?

但使用Auth->允许和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; 
} 
+0

ACL可能是要走的路:http://book.cakephp.org/2.0/en/tutorials-and-examples/simple-acl-controlled-application /simple-acl-controlled-application.html – nIcO 2012-03-27 06:39:28

回答

0
$this->Auth->allow('index', 'view'); 
在beforeFilter

()告诉蛋糕是任何人允许查看索引&查看操作,而不管它们是否已登录或未登录。

您必须在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更多细节

0

您可以从会议

获取当前用户

渲染某些局部元素在你的视图(* .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 
} 
?>