Hi there,
I've created a middleware to check if a user has been banned. If so, the user is being logged out and redirected to login with an error message.
This is my middleware (CheckBanned)
public function handle(Request $request, Closure $next): Response|RedirectResponse|JsonResponse
{
if (Auth::check() && ! Auth::user()->active){
Auth::logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect()
->route('login')
->with('modalMessage', [
__('auth.suspended.msg.information.headline'),
__('auth.suspended.msg.information.body'),
'error'
]);
}
return $next($request);
}
In kernel.php I've added CheckBanned::class to $middlewareGroups['web'].
This works perfectly. However, my tests which are using actingAs are now broken.
my user model (minimum example)
class User extends Authenticatable implements MustVerifyEmail
{
use HasApiTokens, HasFactory, Notifiable, CanResetPassword;
public static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->uuid = Str::uuid();
});
}
}
An example for a test
public function test_email_verification_screen_can_be_rendered()
{
$this->refreshApplicationWithLocale('en');
$user = User::factory()->create([
'email_verified_at' => null,
]);
$response = $this->actingAs($user)->get(route('verification.notice'));
$response->assertStatus(200);
}
This one failes. After debugging I found out, that $response->showContent is showing redirecting to login....
Debugging further I found the problem:
dd($user) is showing that $user->active == true.
However, Auth::user()->active inside CheckBanned is false.
Because of that the user gets logged out and I see the redirect inside my test (!).
Can anyone point me to the right direction how to solve this problem and explain to me please, why Auth::user()->active == false when my dd($user) tells me it is not?
Thanks in advance