george1
3 months ago
110
3
Laravel

Laravel 5.7 Login session expires right after redirect but register doesn't?

Posted 3 months ago by george1

Hi,

I have been working on my Laravel project for a while and suddenly, the login authentication functionality doesn't work at all. I have tested it by dumping the session just before the redirect function is called and the session looks like to have been created (by the instant started = true). However, as soon as the redirect function is called, Laravel seems to kill the session but doesn't for register?

The register function uses the same login() function which can be found in the AuthenticateUsers.php, and hence the same process is being applied after the validation is done.

Logout also works fine.

Below, is my code. I haven't touched anything on the AuthenticateUsers.php, other than using the die and dump function (dd()) to view the session. Auth::check() was also returning true before redirecting.

AuthenticateUsers.php

<?php

namespace Illuminate\Foundation\Auth;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;

trait AuthenticatesUsers
{
    use RedirectsUsers, ThrottlesLogins;

    /**
     * Show the application's login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function showLoginForm()
    {
        return view('auth.login');
    }

    /**
     * Handle a login request to the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function login(Request $request)
    {
        
        $this->validateLogin($request);

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.

        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        if ($this->attemptLogin($request)) {
            // dd($this->sendLoginResponse($request));

            return $this->sendLoginResponse($request);


        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }

    /**
     * Validate the user login request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return void
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    protected function validateLogin(Request $request)
    {
        $request->validate([
            $this->username() => 'required|string',
            'password' => 'required|string',
        ]);
    }

    /**
     * Attempt to log the user into the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    protected function attemptLogin(Request $request)
    {
        return $this->guard()->attempt(
            $this->credentials($request), $request->filled('remember')
        );
    }

    /**
     * Get the needed authorization credentials from the request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    protected function credentials(Request $request)
    {
        return $request->only($this->username(), 'password');
    }

    /**
     * Send the response after the user was authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    protected function sendLoginResponse(Request $request)
    {
        $request->session()->regenerate();

        $this->clearLoginAttempts($request);

        // dd($this->guard()->user(), $this->redirectPath(), Auth::check());

        return $this->authenticated($request, $this->guard()->user())
                ?: redirect()->intended($this->redirectPath());
    }

    /**
     * The user has been authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  mixed  $user
     * @return mixed
     */
    protected function authenticated(Request $request, $user)
    {
        //
    }

    /**
     * Get the failed login response instance.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Symfony\Component\HttpFoundation\Response
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    protected function sendFailedLoginResponse(Request $request)
    {
        throw ValidationException::withMessages([
            $this->username() => [trans('auth.failed')],
        ]);
    }

    /**
     * Get the login username to be used by the controller.
     *
     * @return string
     */
    public function username()
    {
        return 'email';
    }

    /**
     * Log the user out of the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function logout(Request $request)
    {
        $this->guard()->logout();

        $request->session()->invalidate();

        return $this->loggedOut($request) ?: redirect('/');
    }

    /**
     * The user has logged out of the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return mixed
     */
    protected function loggedOut(Request $request)
    {
        //
    }

    /**
     * Get the guard to be used during authentication.
     *
     * @return \Illuminate\Contracts\Auth\StatefulGuard
     */
    protected function guard()
    {
        return Auth::guard();
    }
}

RegistersUsers.php

<?php

namespace Illuminate\Foundation\Auth;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Auth\Events\Registered;

trait RegistersUsers
{
    use RedirectsUsers;

    /**
     * Show the application registration form.
     *
     * @return \Illuminate\Http\Response
     */
    public function showRegistrationForm()
    {
        return view('auth.register');
    }

    /**
     * Handle a registration request for the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function register(Request $request)
    {
        $this->validator($request->all())->validate();

        event(new Registered($user = $this->create($request->all())));

        $this->guard()->login($user);

        return $this->registered($request, $user)
                        ?: redirect($this->redirectPath());
    }

    /**
     * Get the guard to be used during registration.
     *
     * @return \Illuminate\Contracts\Auth\StatefulGuard
     */
    protected function guard()
    {
        return Auth::guard();
    }

    /**
     * The user has been registered.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  mixed  $user
     * @return mixed
     */
    protected function registered(Request $request, $user)
    {
        //
    }
}

LoginController.php

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Valiator;
use Auth;
use Illuminate\Http\Request;
use Session;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */
    use AuthenticatesUsers;
    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/';
    /**
     * Create a new controller instance.
     *
     * @return void
     */

    public function logout(){
        Auth::logout();
        return redirect('/');
    }

    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }
}

RegisterController

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'firstname' => ['required', 'string', 'max:255'],
            'lastname' => ['required', 'string', 'max:255'],
            'username' => ['required', 'string', 'max:255', 'unique:users'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'confirmed', 'between:8,255'],
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        return User::create([
            'firstname' => $data['firstname'],
            'lastname' => $data['lastname'],
            'username' => $data['username'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);
    }
}

login.blade.php

@extends("main")

@section("title", "Support")

@section("stylesheets")
    <link href="{{ asset('css/register.css') }}" rel="stylesheet">
@endsection

@section("content")
<div class="login-form">
        <div class="vertical">
          <div class="login_wrapper">
            <h1 class="title">Welcome back, user</h1>
            <div class="fields_wrapper">

                <div class="table-wrapper">
                    <form method="POST" action="{{ route('login') }}">
                        @csrf
                        
                                <div class="class-form-wrapper">
                                  <div class="social_login fields">
                                    <a type="text" class="facebook_login">
                                      <span class="facebook-icon"></span>
                                      Facebook Sign Up
                                    </a>
                                    <a type="text" class="twitter_login">
                                      <span class="twitter-icon"></span>
                                      Twitter Sign Up
                                    </a>
                                    <a type="text" class="google_login">
                                      <span class="google-icon"></span>
                                      Google Sign Up
                                    </a>
                                  </div>
                                  <div class="seperator">
                                    <span class="line"></span>
                                    <p>or</p>
                                  </div>
                                  <div class="login fields">
                    
                                    <!--
                                      Below we include the Login Button social plugin. This button uses
                                      the JavaScript SDK to present a graphical Login button that triggers
                                      the FB.login() function when clicked.
                                    -->
                    
                                    <!-- <fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
                                    </fb:login-button> -->
                                    <input type="email" placeholder="[email protected]" class="email form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="email" value="" required autofocus>
                                    @if ($errors->has('email'))
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $errors->first('email') }}</strong>
                                        </span>
                                    @endif
                                    <input type="password" placeholder="Password" class="pwd form-control{{ $errors->has('password') ? ' is-invalid' : '' }}" name="password" value="" required>
                                    @if ($errors->has('password'))
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $errors->first('password') }}</strong>
                                        </span>
                                    @endif
                                    @if (Route::has('password.request'))
                                        <a class="btn btn-link" href="{{ route('password.request') }}">
                                            {{ __('Forgot Your Password?') }}
                                        </a>
                                    @endif
                                    <div class="remember_me_wrapper input">
                                      <input type="checkbox" id="remember_me" class="checkbox" name="remember_me" value="scales" />
                                      <label class="remember_me_label" for="remember_me" {{ old('remember') ? 'checked' : '' }}>
                                        <span></span>
                                        Remember Me
                                      </label>
                                    </div>
                                  </div>
                                </div>
                                <input type="submit" name="submit" class="submit" value="Log in">
                              </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@section("scripts")
    <script src="{{ asset('js/register.js') }}"></script>
@endsection

register.blade.php

@extends("main")

@section("title", "Support")

@section("stylesheets")
    <link href="{{ asset('css/register.css') }}" rel="stylesheet">
@endsection

@section("content")
    <div class="login-form">
        <div class="vertical">
            <div class="login_wrapper">
                <h1 class="title">Sign in</h1>
                <div class="card fields_wrapper">
    
                    <div class="card-body">
                        <form method="POST" action="{{ route('register') }}" class="form">
                            @csrf
                            <div class="table-wrapper">
                                    <div class="class-form-wrapper">
                                      <div class="social_login fields">
                                        <a type="text" class="facebook_login">
                                          <span class="facebook-icon"></span>
                                          Facebook Sign Up
                                        </a>
                                        <a type="text" class="twitter_login">
                                          <span class="twitter-icon"></span>
                                          Twitter Sign Up
                                        </a>
                                        <a type="text" class="google_login">
                                          <span class="google-icon"></span>
                                          Google Sign Up
                                        </a>
                                      </div>
                                      <div class="seperator">
                                        <span class="line"></span>
                                        <p>or</p>
                                      </div>
                                      <div class="login fields">
                                        <input id="name" placeholder="First Name" type="text" class="form-control first-name{{ $errors->has('firstname') ? ' is-invalid' : '' }}" name="firstname" value="{{ old('firstname') }}" required autofocus>
                                        <input id="name" placeholder="Last Name" type="text" class="form-control last-name{{ $errors->has('name') ? ' is-invalid' : '' }}" name="lastname" value="{{ old('last-name') }}" required autofocus>
                                        <input id="name" placeholder="Username" type="text" class="form-control username{{ $errors->has('username') ? ' is-invalid' : '' }}" name="username" value="{{ old('username') }}" required autofocus>
                                        <input id="email" placeholder="[email protected]" type="email" class="email form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="email" value="{{ old('email') }}" required>
                                        <input type="password" placeholder="New Password" name="password" class="pwd">
                                        <input type="password" placeholder="Verify Password" name="password_confirmation" class="ver-pwd">
                                        <div class="remember_me_wrapper input">
                                          <input type="checkbox" id="remember_me" class="checkbox" name="remember_me" />
                                          <label class="remember_me_label" for="remember_me">
                                            <span></span>
                                            Remember Me
                                          </label>
                                        </div>
                                      </div>
                                    </div>
                                  </div>
                                  <div class="input">
                                    <input type="checkbox" id="terms_of_service" class="checkbox" name="terms_of_service" checked />
                                    <label class="terms_of_service_label" for="terms_of_service">
                                      <span></span>
                                      I understand the terms of service and I accept
                                    </label>
                                  </div>
                                  <div class="input">
                                    <input type="checkbox" id="email_not" class="checkbox" name="email_not" checked />
                                    <label class="email_not_label" for="email_not">
                                      <span></span>
                                      I want to receive email notifications
                                    </label>
                                  </div>
                                  <input type="submit" name="submit" class="submit" value="{{ __('Register') }}">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

@section("scripts")
    <script src="{{ asset('js/register.js') }}"></script>
@endsection

Your help will be much appreciated!

Please sign in or create an account to participate in this conversation.