Laravel 在使用Spatial';登录用户之前,如何检查用户角色;拉威尔允许吗?

Laravel 在使用Spatial';登录用户之前,如何检查用户角色;拉威尔允许吗?,laravel,spatie,laravel-authentication,Laravel,Spatie,Laravel Authentication,我正在使用Spatial的“Laravel许可”包进行ACL。一切都很顺利。我现在只想允许用户角色2和3登录 以前,在使用“laravelpermission”包之前,我的表上只有这个“role”列,我可以使用Login Controller的credentials方法上的这行代码轻松地登录用户 protected function credentials(Request $request) { $credentials = $request->only($this->usernam

我正在使用Spatial的“Laravel许可”包进行ACL。一切都很顺利。我现在只想允许用户角色2和3登录

以前,在使用“laravelpermission”包之前,我的表上只有这个“role”列,我可以使用Login Controller的credentials方法上的这行代码轻松地登录用户

protected function credentials(Request $request)
{
$credentials = $request->only($this->username(), 'password');
//$credentials['role'] = '1';
return $credentials;
}

如何仅允许2个和3个用户角色登录?

您可以使用以下解决方法:

如果您使用的是
App\Http\Controllers\Auth
文件夹中的默认
LoginController
,则覆盖来自所用特征的
attemptLogin()
方法

受保护的函数尝试登录(请求$Request)
{
如果($this->guard()->尝试(
$this->credentials($request),$request->filled('记住')
)){//凭证身份验证成功
//获取用户模型
$user=Auth::user();
返回$user->hasRole([2,3]);//检查用户是否有角色ID 2或3
}
返回false;
}

hasRoles()
方法来自
hasRoles
特性,该特性用于
用户
模型。

或者您可以在登录期间覆盖Laravel凭据。在
App\Http\Controllers\Auth
文件夹中的默认
LoginController
,然后覆盖来自所用特征的凭据(
Request$Request
)方法

覆盖它,使其看起来与此类似

protected function credentials(Request $request)
{

 return [ 'email' => $request-> { this-> username() }, 'password' -> $request -> password, 'role_id'  => [ '1', '2' ] ];

这是假定您的用户模型中有一个
role\u id
。为我工作。返回

您可以覆盖LoginController中的authenticated(),并检查用户角色。很简单

protected function authenticated(Request $request, $user)
{
    //Check user role, if it is not admin then logout
    if(!$user->hasRole(['Admin', 'Super-Admin']))
    {
        $this->guard()->logout();
        $request->session()->invalidate();
        return redirect('/login')->withErrors('You are unauthorized to login');
    }
}

你试过中间件吗?谢谢☺, 这同样适用于角色名
return$user->hasRole(['admin','stack overflower'])
protected function authenticated(Request $request, $user)
{
    //Check user role, if it is not admin then logout
    if(!$user->hasRole(['Admin', 'Super-Admin']))
    {
        $this->guard()->logout();
        $request->session()->invalidate();
        return redirect('/login')->withErrors('You are unauthorized to login');
    }
}