Skip to content
Advertisement

Middleware auth keep logging me out? Edit: RedirectIfAuthenticated logging me out?

Fairly new to Laravel and tried to make a Login page.

Edit 2:

Tried to use Guard and when I’m redirected to RedirectIfAuthenticated it seems somehow the auth()->check() or Auth::check() return false at handle function

here’s my RedirectIfAuthenticated.php

class RedirectIfAuthenticated
{
    /**
     * Handle an incoming request.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  Closure  $next
     * @param  string|null  ...$guards
     * @return mixed
     */

    public function handle($request, Closure $next, $guard = null)
    {
        //dd(Auth::check());
        if ($guard == "admin" && Auth::guard($guard)->check()) {
            return redirect('/home');
        }
        if ($guard == "management" && Auth::guard($guard)->check()) {
            return redirect('/home');
        }
        if ($guard == "member" && Auth::guard($guard)->check()) {
            return redirect('/home');
        }
        if (Auth::guard($guard)->check()) {
            return redirect('/home');
        }

        return $next($request);
    }
}

The Auth was able to store the user, but it keeps logging me out when I’m going to HomeController where it had ‘auth’ middleware

web.php

Route::get('/login', [LoginController::class, 'login'])->name('login');
Route::post('/check_user', [LoginController::class, 'check_user'])->name('check_user');
Route::get('/home', [HomeController::class, 'index'])->name('home');

It going fairly well and using dd() I can still see that the auth()->check() is still returning true after login in LoginController

LoginController.php

<?php

namespace AppHttpControllersAuth;

use AppHttpControllersController;
use AppModelsGrantAccess;
// use AppModelsMember;
use AppProvidersRouteServiceProvider;
use IlluminateFoundationAuthAuthenticatesUsers;
use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;

class LoginController extends Controller
{
    public function login(){
        return view('auth.login');
    }

    public function check_user(Request $request){
        $email = $request->email;
        $password = $request->password;
        $auth = Auth::attempt(['email' => $email, 'password' => $password]);

        if($auth){
            $ga = auth()->user()->access_grant;
            $uga = GrantAccess::where('grant_id', $ga)->get();
            $ugd = $uga[0]->grant_desc;
            $uemail = auth()->user()->email;
            $umcard = auth()->user()->matrix_card;

            $request->session()->put('user_access', $ugd);
            $request->session()->put('user_email', $uemail);
            $request->session()->put('user_matric', $umcard);

            return redirect('home');
        }else{
            return redirect('login');
        }
    }
    use AuthenticatesUsers;
    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;

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

When redirecting it doesn’t even reach the HomeController. So, I suspect it’s because the $this->middleware('auth');

HomeController.php

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;

class HomeController extends Controller
{
    public function index(Request $r)
    {
        $role = $r->session()->get('user_access');

        if($role == "admin"){
            return redirect('admin');
        } else if($role == "management"){
            return redirect('management');
        } else if($role == "member"){
            return redirect('member');
        } else {
            return redirect('logout');
        }

        return view('home');
    }

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

    /**
     * Show the application dashboard.
     *
     * @return IlluminateContractsSupportRenderable
     */
}

Then the auth()->check() somehow return false here

Authenticate.php (Middleware)

<?php

namespace AppHttpMiddleware;

use IlluminateAuthMiddlewareAuthenticate as Middleware;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  IlluminateHttpRequest  $request
     * @return string|null
     */
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            return route('login');
        }
    }
}

So… yeah any suggestion?

Edit:

Add some problems that I got before. So it may be connected? I got a 419 error, looked it up they say it mostly because of csrf, already add @csrf after the form but nothing happen

<form class="user" method="POST" action="{{ route('check_user') }}">
@csrf
  <div class="form-group"><input
  class="form-control form-control-user @error('email') is-invalid @enderror" type="email" value="{{ old('email') }}" id="exampleInputEmail" aria-describedby="emailHelp" placeholder="Enter Email Address..." name="email">
    @error('email')
      <span class="invalid-feedback" role="alert">
        <strong>{{ $message }}</strong>
      </span>
    @enderror
  </div>
  <div class="form-group"><input class="form-control form-control-user @error('password') is-invalid @enderror" type="password" id="exampleInputPassword" placeholder="Password" name="password">
    @error('password')
      <span class="invalid-feedback" role="alert">
        <strong>{{ $message }}</strong>
      </span>
    @enderror
  </div>
  <button class="btn btn-primary btn-block text-white btn-user" type="submit" data-toggle="modal" data-target="#myModal" style="background: rgb(230,32,43);">Log in</button>
<hr>
</form>

so I just put “*” on VerifyCrsfToken

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        //
        '*'
    ];
}

Advertisement

Answer

Already Solved I a mistake in my “Member” Model which is the primary key. I use $primary_key instead of $primaryKey

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement