3

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

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

我正在使用JetStreamFortify

谢谢你

4

3 回答 3

2

app\Providers\JetStreamServiceProvider.php您可以从, onboot方法自定义用户身份验证:

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文档

于 2020-11-14T15:56:48.690 回答
0

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

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!')
于 2022-01-21T22:50:59.880 回答
-2

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

于 2021-05-06T22:04:33.520 回答