Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

StackOverflow Point

StackOverflow Point Navigation

  • Web Stories
  • Badges
  • Tags
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Web Stories
  • Badges
  • Tags
Home/ Questions/Q 1768
Alex Hales
  • 0
Alex HalesTeacher
Asked: May 31, 20222022-05-31T01:57:28+00:00 2022-05-31T01:57:28+00:00

php – How to redirect if session not set in middleware

  • 0

[ad_1]

I am trying to redirect the user to login page if it tries to access dashboard or other user page if they haven’t logged in yet.

here is my web.php

Route::group(['middleware'=>'UserAuthChk'], function(){
    Route::get("https://stackoverflow.com/",[HomeController::class, 'index']) -> name('home.index');
    // User Controller
    Route::get('/user/dashboard', [UserController::class, 'dashboard']) -> name('user.dashboard');
    
    // User Authentication Controller
    Route::get('/auth/user/login', [UserAuthController::class, 'login']) -> name('auth.user.login');
    Route::get('/auth/user/signup', [UserAuthController::class, 'signup']) -> name('auth.user.signup');
    Route::get('/auth/user/forgotpassword', [UserAuthController::class, 'forgotpass']) -> name('auth.user.forgotpass');
    // User Authentication POST
    Route::post('/auth/user/registeruser', [UserAuthController::class, 'registerUser']) -> name('auth.user.reguser');
    Route::post('/auth/user/loginuser', [UserAuthController::class, 'loginUser']) -> name('auth.user.loginuser');
    Route::get('/auth/user/logoutuser', [UserAuthController::class, 'logoutUser']) -> name('auth.user.logoutuser');
});

Here is my middleware UserAuthChk.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class UserAuthChk
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        if (session()->has('userID') && ($request->path()==route('auth.user.login') || $request->path()==route('auth.user.signup') || $request->path()==route('auth.user.forgotpass'))) {
            return back();
        }
        if(!session()->has('userID') && ($request->path()!=route('auth.user.login') || $request->path()!=route('auth.user.signup') || $request->path()!=route('auth.user.forgotpass') || $request->path()!=route('home.index'))) {
            return redirect()->route('auth.user.login');
        }
        
        return $next($request)->header('Cache-Control','no-cache, no-store, max-age=0, must-revalidate')
                              ->header('Pragma','no-cache')
                              ->header('Expires', 'Sat 01 Jan 1990 00:00:00 GMT');
    }
}

Here is my kernel.php

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'UserAuthChk' => \App\Http\Middleware\UserAuthChk::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];

If I haven’t logged in and I try to access the login page, signup page, home page, it just keeps loading and then errors saying that it redirected too many times.

When I removed the whole !session() part and I loggedd in then try to access the login or signup page, it works fine. Any solutions?

[ad_2]

  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report
Leave an answer

Leave an answer
Cancel reply

Browse

Sidebar

Ask A Question

Related Questions

  • xcode - Can you build dynamic libraries for iOS and ...

    • 0 Answers
  • bash - How to check if a process id (PID) ...

    • 5380 Answers
  • database - Oracle: Changing VARCHAR2 column to CLOB

    • 1169 Answers
  • What's the difference between HEAD, working tree and index, in ...

    • 1111 Answers
  • Amazon EC2 Free tier - how many instances can I ...

    • 0 Answers

Stats

  • Questions : 43k

Subscribe

Login

Forgot Password?

Footer

Follow

© 2022 Stackoverflow Point. All Rights Reserved.

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.