代码实现:
修改表结构,增加 auth_c 和 auth_a 两列,权限控制实际操控的是一个访问的地址,权限名称只是一个中文描述,要实现权限控制,其真谛就在于控制住访问的请求地址即可。
步骤一:先根据登录的用户ID查询出权限
控制器:
/**
* 登录接口
* @param Request $request
* @return \think\response\Json|void
* @throws \think\Exception
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
*/
public function login(Request $request){
try {
# 根据用户ID 查权限 controller action
$data = $request->all();
# 验证参数
validate(\app\api\validate\Login::class)->check($data);
$adminInfo = Db::table('admin')->where('username',$data['username'])->find();
if ($adminInfo) {
if ($adminInfo['password'] == $data['password']) {
# 根据用户id 查询当前用户对应的角色
#以及对应的权限
$adminInfo = \app\api\model\Admin::with(['role','role.auth'])->find($adminInfo['id'])->toArray();
# 处理数据
$authList = $adminInfo['role'][0]['auth'];
$authArr = [];
foreach ($authList as $value) {
$authArr[] = $value['auth_c'].'/'.$value['auth_a'];
}
# 把权限存入缓存
cache('auth_list',$authArr);
$data = [
'token' => Token::getToken($adminInfo['id'])
];
return success($data);
} else {
return fail('','密码错误',2001);
}
} else {
# 手动抛出异常
return fail('','用户名不存在',2001);
}
}catch (ValidateException $exception){
return fail('',$exception->getError(),2001);
}
}
Log::info($adminInfo['username'].'登录成功'.date('Y-m-d H:i:s'));
模型关联
Admin