我的网站上有几个不同的'项目',我正在使用cakePHP构建,例如Recipe和ShoppingList。
我希望我的视图中的某些项目(例如更新和删除功能链接)仅对上传该项目的人可见。
我想添加一个函数,将任何给定的id与当前登录用户的id进行比较。它看起来像这样:
public function compareUser($id){
if(!empty($this->userInfo) && $this->userInfo['User']['id'] == $id){
return true;
}
}
$ this-> userInfo在beforeFilter中设置:
$this->userInfo = $this->User->find('first', array('conditions' => array('id' => $this->Auth->user('id'))));
我已经尝试将它放在我的appController中,但这似乎不起作用。
如何正确实施?谢谢!
答案 0 :(得分:1)
最好使用isAuthorized($ user)方法。
有关您当前用户的所有信息都存储在$ this-> Session-> read('Auth.User')中(这会检索完整数组,如果您只想获取他们的'id',则使用$这个> Auth->用户('id')就像你已经做过的那样)。 从上面可以看出,通常您不需要通过额外的查询来检索用户的详细信息,因为它们已经存储在会话的Auth组件中:)
请确保您的Auth组件的设置中包含'authorize'=> 'controller'并将以下内容添加到AppController:
public function isAuthorized($user) {
//I want the default to be allow the user access so I will return true
return TRUE;
}
然后将以下内容添加到RecipesController(和ShoppingListsController,如果你想要相同的东西):
public function isAuthorized($user) {
if ($this->action === 'update' || $this->action === 'delete') {
$recipe = $this->Recipe->find(
'first',
'conditions' => array(
'id' => $this->params['pass'][0]
)
'fields' => array(
'user_id'
)
);
if ($this->Auth->user('id') == $recipe['Recipe']['user_id']) {
return TRUE;
}
else {
return FALSE;
}
}
return parent::isAuthorized($user);
}
现在,如果有人试图访问www.yourDomain.com/recipes/update/2或www.yourDomain.com/recipes/delete/2,它会检查当前用户的ID是否为2,如果你是好的话去,如果没有,那么它会阻止他们离开那个页面。
编辑:
让所有地方都可以访问方法的最简单方法我建议将它放在AppModel中,这样所有模型都会继承它:
//inside AppModel
public function isOwnedBy($id) {
if (AuthComponent::user('id) == $id) {
return TRUE;
}
return FALSE;
}