使用 AuthComponent
如果您使用内置的AuthComponent,CakePHP 将在会话中存储当前登录用户的详细信息。
获取当前登录用户的属性
登录后,您可以通过AuthComponent 访问Used 的信息(例如role_id)。这可以在任何地方完成(如果需要,也可以在您的视图或模型中);
例如;
if (123 === AuthComponent::user('role_id')) {
debug('hello admin user');
}
或者,在控制器内部:
if (123 === $this->Auth->user('role_id')) {
debug('hello admin user');
}
访问已登录的用户
但是,为了不必在任何地方重复 group-id,最好为此创建一个方法(例如在您的 AppController 中);
/**
* Checks if the currently logged in user is an admin
*
* @return bool true if the current user is an admin
*/
protected function isAdmin()
{
// probably best to make the id configurable (Configure::write())?
return (123 === $this->Auth->user('role_id'));
}
访问控制
要使用“简单”授权,您可以在控制器中创建自己的isAuthorized()
操作,这将允许您根据当前登录用户的属性阻止对特定操作的访问;
使用控制器授权