仅当用户状态为活动时,如何在 Laravel 8 Jetstream 中对用户进行身份验证?

我正在构建一个 Laravel 8 应用程序并已成功实现身份验证。现在我想在登录之前检查用户的状态是否处于活动状态。我在用户表中添加了一个字段

username varchar
password varchar
....
status tinyint(1)
...

我正在使用 JetStreamFortify

谢谢你

stack overflow How do I authenticate a user in Laravel 8 Jetstream only if his status is active?
原文答案
author avatar

接受的答案

您可以在 appProvidersJetStreamServiceProvider.php 方法上从 boot 自定义用户身份验证:

use AppModelsUser;
use IlluminateHttpRequest;
use LaravelFortifyFortify;

public function boot()
{
    $this->configurePermissions();

    Jetstream::createTeamsUsing(CreateTeam::class);
    Jetstream::updateTeamNamesUsing(UpdateTeamName::class);
    Jetstream::addTeamMembersUsing(AddTeamMember::class);
    Jetstream::deleteTeamsUsing(DeleteTeam::class);
    Jetstream::deleteUsersUsing(DeleteUser::class);
    // Below code is for your customization
    Fortify::authenticateUsing(function (Request $request) {
        $user = User::where('email', $request->email)->first();

       if ($user && Hash::check($request->password, $user->password)) {
            if ($user->status == 1) {  // it will return if status == 1
                 return $user;
            }
       }

    });
}

请参阅 Jetstream 的官方 Customizing User Authentication 文档


答案:

作者头像

您应该添加:使用 Illuminate Support Facades Hash;

作者头像

这是带有自定义错误消息的。

Fortify::authenticateUsing(function (Request $request) {
    $user = User::where('email', $request->email)->first();

    if ($user && Hash::check($request->password, $user->password)) {
        if ($user->active == 1) { 
            return $user;
        }
        throw ValidationException::withMessages(['Your Message Here!']);        
    }

});

确保您导入 ValidationException

use IlluminateValidationValidationException;

您也可以只发送一条客户 403 消息

abort(403,'Your Message Here!')