我使用的是restful api的Laravel-8、laravel-passport和spatie permission。我已经在Controller中有了这段代码。
我有这个Admin的控制器:
public function adminLogin(Request $request)
{
if(Auth::attempt(['email' => $request->email, 'password' => $request->password])){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')-> accessToken;
$success['name'] = $user->name;
return $this->sendResponse($success, 'User login successfully.');
}
else{
return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
}
}我只希望‘超级管理员’能够使用管理员控制器登录。如果不是'Super Admin',它应该指示unathorized。
我如何将下面的代码包含到上面已经有的代码中,或者以任何其他最好的方式?
if($user->hasRole('Super Admin'))
$res = User::with(['roles', 'employee', 'company'])->find($user->id);
else
$res = User::with('roles')->find($user->id);发布于 2021-04-05 22:03:33
您可以在尝试身份验证后检查用户的角色。
public function adminLogin(Request $request)
{
if (Auth::attempt($request->only('email', 'password'))) {
$user = Auth::user();
if (!$user->hasRole('Super Admin') {
Auth::logout();
return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
}
$success['token'] = $user->createToken('MyApp')-> accessToken;
$success['name'] = $user->name;
return $this->sendResponse($success, 'User login successfully.');
}
return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
}https://stackoverflow.com/questions/66954243
复制相似问题