Auth::attempt validate user login correctly but does not save user session so user still appear not login
public function handle()
{
// try {
// $user = \App\User::where('email', trim($this->email))->firstOrFail();
// } catch (\Exception $e) {
// throw new \Exception('User not registered.');
// }
// //compare password
// if (! Hash::check(trim($this->password), $user->password) ) {
// throw new \Exception('Sorry, your email and/or password is incorrect.');
// }
if(!Auth::attempt(['email' => $this->email, 'password' => $this->password])) {
throw new \Exception('Sorry, your email and/or password is incorrect.');
}
$user = \App\User::where('email', trim($this->email))->firstOrFail();
if (empty($user->email_verified_at)) {
throw new \Exception('Email not yet verified.');
}
$user->update([
'auth_token' => custom_unique('AUTH_TOKEN'),
]);
return $user;
}
When I redirected the user to the dashboard route which is protected with an auth middleware, it bounces me back. I also noticed the session stored in the database has user_id set to NULL.
I refectored the code to this based on the documentation link from @jlrdw
if(!Auth::attempt(['email' => $this->email, 'password' => $this->password])) {
throw new \Exception('Sorry, your email and/or password is incorrect.');
}
$user = auth()->user();
if (empty($user->email_verified_at)) {
throw new \Exception('Email not yet verified.');
}
$this->session()->regenerate();
$user->update([
'auth_token' => custom_unique('AUTH_TOKEN'),
]);
I noticed I was missing this $this->session()->regenerate() from the documentation but now I get a seperate error message:
[2021-02-03 21:18:10] local.ERROR: Session store not set on request. {"userId":1,"exception":"[object] (RuntimeException(code: 0): Session store not set on request. at /Users/agoiabel/code/hirefreehands_api/vendor/laravel/framework/src/Illuminate/Http/Request.php:487)
[stacktrace]
I missed the first time you had token. What are you using here for the API. API Authentication is going to be different from session-based Authentication.
So I am not exactly sure what you are trying to do.
I would suggest you have a look at the passport and or Sanctum documentation, whichever you use.