在我的 Laravel 应用程序中,用户可以禁用(而不是删除)他们的帐户以从网站上消失。但是,如果他们再次尝试登录,他们的帐户应该会自动激活并且他们应该能够成功登录。
这是通过用户表中的“事件”列和用户模型中的全局范围完成的:
protected static function boot() {
parent::boot();
static::addGlobalScope('active', function(Builder $builder) {
$builder->where('active', 1);
});
}
现在的问题是那些非事件帐户无法再次登录,因为 AuthController 找不到它们(超出范围)。
我需要达到的目标:
我现在的想法是使用 withoutGlobalScope 定位用户,手动验证密码,将“active”列更改为 1,然后继续常规登录。
在我的 AuthController postLogin 方法中:
$user = User::withoutGlobalScope('active')
->where('username', $request->username)
->first();
if($user != null) {
if (Hash::check($request->username, $user->password))
{
// Set active column to 1
}
}
return $this->login($request);
所以问题是如何让 AuthController 忽略全局范围而不改变 Laravel 主代码,这样它就会保持更新?
谢谢。
最佳答案
创建类(class) GlobalUserProvider
扩展 EloquentUserProvider
像下面
class GlobalUserProvider extends EloquentUserProvider {
public function createModel() {
$model = parent::createModel();
return $model->withoutGlobalScope('active');
}
}
在
AuthServiceProvider
中注册您的新用户提供商:Auth::provider('globalUserProvider', function ($app, array $config) {
return new GlobalUserProvider($this->app->make('hash'), $config['model']);
});
最后,您应该在
auth.php
中将您的用户提供程序驱动程序更改为 globalUserProvider配置文件。 'providers' => [
'users' => [
'driver' => 'globalUserProvider',
'model' => App\Models\User::class
]
]
关于没有全局范围的 Laravel 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38266296/