C层
步骤一:先根据登录的用户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);
}
}
步骤二:实现控制
通过TP6中间间实现权限检测
/**
* 中间件验证token以及权限检测
* @param $request
* @param \Closure $next
* @return mixed|\think\response\Json|void
* @throws \Exception
*/
public function handle($request, \Closure $next)
{
try {
# 判断token是否存在、并且保证token是有效的才能访问
# 获取token
$token = Token::getRequestToken();
if (!$token) {
return fail('','请先登录');
}
# 验证token
$user_id = Token::getUserId($token);
if (!$user_id) {
return fail('','token失效');
}
# 权限检测
# controller()获取当前访问的控制器名a
# action()获取当前访问的方法名
$current = $request->controller().'/'.$request->action();
$authList = cache('auth_list');# 获取缓存中的权限列表
if (!in_array($current,$authList) && $user_id != 1) {
return fail('','无权限访问');
}
# token 认证成功、并且有权限访问
return $next($request);
}catch (RuntimeException $exception){
return fail('','token 无效');
}
}