houze\Auth 是基于 Redis 的角色权限(RBAC):用户挂角色,角色挂权限,判断「某人有没有某项权限」。数据存 Redis,不建表。
基本概念
用户 ──多个──▶ 角色 ──多个──▶ 权限
user:3 admin article.delete
常用方法
| 方法 | 作用 |
|---|---|
addRoleForUser($user, $role) | 给用户加角色 |
delRoleForUser($user, $role) | 移除角色 |
clearRoleForUser($user) | 清空该用户所有角色 |
getRoleForUser($user) | 查用户有哪些角色 |
getUserForRole($role) | 查某角色下有哪些用户 |
isRoleForUser($user, $role) | 判断用户是否属于某角色 |
delUser / delRole / delAuth | 删除用户 / 角色 / 权限 |
用法
$auth = new \houze\Auth();
// 授权
$auth->addRoleForUser('3', 'editor');
// 判断
if (!$auth->isRoleForUser('3', 'editor')) {
return $this->api(403, '没有权限');
}
放在中间件里
class Admin extends \houze\Middleware
{
public function handle()
{
$user = \houze\Session::get('admin');
if (!$user) return $this->error('请先登录');
$auth = new \houze\Auth();
if (!$auth->isRoleForUser((string)$user['id'], 'admin')) {
return $this->error('需要管理员权限');
}
return true;
}
}
注意
- 数据在 Redis,清库即清权限,重要环境要备份;
- 用户标识统一用字符串,传 int 可能因为序列化差异查不到;
- 它只管「角色归属」,具体的权限点校验还要自己写一层。