如何解决如何使用 Laravel 在登录中添加 Spatie 角色条件
我正在使用 Laravel-8、laravel-passport 和 spatie-permission 来创建restful api。我已经在控制器中有这个代码了。
我为管理员设置了这个控制器:
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']);
}
}
我只希望“超级管理员”能够使用管理员控制器登录。如果不是“超级管理员”,则应表示未经授权。
如何将下面的代码包含在我上面已有的代码中或其他任何最佳方式中?
if($user->hasRole('Super Admin'))
$res = User::with(['roles','employee','company'])->find($user->id);
else
$res = User::with('roles')->find($user->id);
解决方法
您可以在尝试身份验证后检查用户的角色。
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']);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。