vendredi 11 octobre 2019

Laravel loggin user out immediately after login

My Code

I have the following routes in Laravel 5.8.

The only public accessible routes, must be /login.

//web.php

Route::get('/login', function() {
    return view('auth.login', ['loginRequested' => false]);
})->name('login');
Route::post('/login', 'Auth\LoginController@login')->name('process-login');
Route::get('/login/{loginKey}/{loginHash}', 'Auth\LoginController@authenticate');

Route::group(['middleware' => ['auth']], function() {
    Route::get('/', function () {
        return view('welcome');
    });
    Route::get('/logout', 'Auth\LoginController@logout');
});

I then have the following authentication code:

// LoginController.php
/**
 * @param string $loginKey
 * @param string $loginHash
 * @param UsersRepository $usersRepository
 * @param ThirdPartyConnect $thirdParty
 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
 */
public function authenticate(string $loginKey, string $loginHash, UsersRepository $usersRepository, ThirdPartyConnect $thirdParty)
{
    try {
        $user = $usersRepository->findUserByHash($loginKey);
        if (md5($user->user_email) !== $loginHash) {
            throw new \Exception('Invalid login hash', 403);
        }

        Auth::login($user);
        $user->details = $thirdParty->getUserDetails($user->user_email);
        Auth::setUser($user);
        return \redirect($this->redirectTo);
    } catch (\Exception $e) {
        return \redirect('login');
    }
}

What do I expect

When I log in, it should redirect to my $this->redirectTo where I should have access to the user object via Auth::user().

What does it do

When I log in, it redirects to /login. If I dump user after the $user->details call, it has all the info I want on the user. It does not throw an Exception (I've added a dd($e) in the catch part of authenticate.

It also seems to not set the session time correctly. If I inspect the cookie in chrome, the expiration date is the current date/time and not current date/time + 30mins as per the config file.

Question

How do I fix this? Is there something I'm missing, is something set up wrong? Why does it redirect back to /login and not $this->redirectTo as expected?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire