如何仅在 Laravel 8 Jetstream 中验证用户的状态是活动的?

How do I authenticate a user in Laravel 8 Jetstream only if his status is active?

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

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

我正在使用 JetStreamFortify

谢谢

您可以通过 app\Providers\JetStreamServiceProvider.php,在 boot 方法上自定义用户身份验证:

use App\Models\User;
use Illuminate\Http\Request;
use Laravel\Fortify\Fortify;

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;
            }
       }

    });
}

参见Customizing User Authentication

的官方Jetstream文档

你应该添加到:使用 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 Illuminate\Validation\ValidationException;

您也可以直接发送客户 403 消息

abort(403,'Your Message Here!')