我正在构建一个 Laravel 8 应用程序并已成功实现身份验证。现在我想在登录之前检查用户的状态是否处于活动状态。我在用户表中添加了一个字段
username varchar
password varchar
....
status tinyint(1)
...
我正在使用JetStream和Fortify
谢谢你
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
文档
这是带有自定义错误消息的。
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!')
您也应该添加:使用 Illuminate\Support\Facades\Hash;