PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, January 24, 2022

[FIXED] Laravel Redirect If Authenticated middleware

 January 24, 2022     laravel, laravel-5, laravel-request, php, redirect     No comments   

Issue

I have three type of users for the application, Each one have its own dashboard. I need a check that adminor any other user cannot see another user dashboard.

There is a middleware RedirectIfAuthenticated :

public function handle($request, Closure $next, $guard = null){

    if (Auth::guard($guard)->check() && auth()->user()->type == 'admin'){
        return redirect('/admin');
    }

    if (Auth::guard($guard)->check() && auth()->user()->type == 'author'){
        return redirect('/author');
    }

    if (Auth::guard($guard)->check() && auth()->user()->type == 'client'){
        return redirect('/client');
    }
}

Its under guest middleware.

The above code seems good to me but when i tests it, The browser says Too many redirects.

What am i doing wrong, What will be the best way to handle it.


Solution

You may have misunderstood the purpose of that middleware. The purpose of RedirectIfAuthenticated is to redirect a user to their default authenticated page. It is not meant to block unauthenticated/unauthorised users from accessing specific areas.

What you need to do is redirect if not authorised. Since this is a simple case you can just have a middleware:

class RequireRole {
     public function handle($request, Closure $next, $role) {
          abort_unless(auth()->check() && auth()->user()->type == $role, 403, "You don't have permissions to access this area");
           return $next($request);
     }
}

Then register this middleware in your Kernel.php

protected $routeMiddleware = [
        //Other middleware
        "requirerole" => RequireRole::class
];

Then you can use it in your routes e.g.

Route::get('/admin', function () { /* action */ })->middleware("requirerole:admin");

However if you find yourself in need of more complex rules then take a look at Authorization



Answered By - apokryfos
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing