401 response at first login attempt after password reset
I'm using Sanctum in a Laravel 9 SPA. After resetting the password, the user is redirected to the login page, but at the first login attempt the API return a 401 response. The next try is successful. I'm trying to logout the user and/or invalidate the session from sessions table but nothing is working (more info in the code below). The session ID is being regenerated but the user_id column is not being removed from the session's table (as it does when the user simply logout). I also get 401 when trying the logout route after a successful password update response (because the session cookie does not match, I guess).
How can I make this work?
This is the reset password method:
public function updatePassword(Request $request)
{
if (Auth::guard('web')->attempt(['email' => request('email'), 'password' => request('password_current')])) {
$this->validate($request, [
'password_confirmation' => 'required',
'password' => ['required', 'confirmed', Password::min(8)],
]);
try {
DB::beginTransaction();
$user = Auth::guard('web')->user();
if (empty($user)) {
return response()->json([
'status' => false,
'message' => 'User not found!'
]);
}
$hashPassword = Hash::make(request('password'));
$user->password = $hashPassword;
$user->update();
//Auth::guard('web')->login($user);
// destroying the session not working
//$session_id = $request->session()->getId();
//Session::getHandler()->destroy($session_id);
// logging out allow will allow login at first attempt but will return 401 in the next request from a route in 'web' middleware
//Auth::guard('web')->logout();
//$request->session()->invalidate();
//$request->session()->regenerateToken();
//$request->session()->flush();
$user_logged = Auth::guard('web')->check();
DB::commit();
return response()->json([
'status' => true,
//'userData' => $user,
'logged' => $user_logged
//'request' => request()->all()
], 200);
} catch (\Exception $e) {
DB::rollBack();
return response()->json([
'status' => false,
'message' => $e->getMessage(),
], 403);
}
} else {
return response()->json([
'error' => 'Unauthorised',
'message' => __('auth.wrong_current_password'),
//'request' => request()->all(),
], 403);
}
}
Please or to participate in this conversation.