skip to Main Content

I am studying multiple authentication.

In particular I have 3 users:

  1. a User user who must be redirected to /home when logging in
  2. an Admin user who must be redirected to /admin/home when logging in
  3. a Manager user who must be redirected to /manager/home when logging in

The problem I am having is when I log in as Admin and as Manager I am redirected to the route /home and then I get the error

["You do not have permission to access for this page."]

However, once I log in, if I manually enter the route of interest I can log in without problems.

So the problem is the route addressing once I try to log in as Admin or as Manager.
For the User user I’m not having any problems.

This is my code:

Route.php

Route::get('/', function () {
    return view('welcome');
});
  
Auth::routes();
  
/*------------------------------------------
--------------------------------------------
All Normal Users Routes List
--------------------------------------------
--------------------------------------------*/
Route::middleware(['auth', 'user-access:user'])->group(function () {
  
    Route::get('/home', [HomeController::class, 'index'])->name('home');
});
  
/*------------------------------------------
--------------------------------------------
All Admin Routes List
--------------------------------------------
--------------------------------------------*/
Route::middleware(['auth', 'user-access:admin'])->group(function () {
  
    Route::get('/admin/home', [HomeController::class, 'adminHome'])->name('admin.home');
    Route::get('/admin/link', [HomeController::class, 'adminHello'])->name('admin.hello');
    
});
  
/*------------------------------------------
--------------------------------------------
All Admin Routes List
--------------------------------------------
--------------------------------------------*/
Route::middleware(['auth', 'user-access:manager'])->group(function () {
  
    Route::get('/manager/home', [HomeController::class, 'managerHome'])->name('manager.home');
});

LoginController

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 = RouteServiceProvider::HOME;
  
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }
 
    public function login(Request $request)
    {   
        $input = $request->all();
     
        $this->validate($request, [
            'email' => 'required|email',
            'password' => 'required',
        ]);
     
        if(auth()->attempt(array('email' => $input['email'], 'password' => $input['password'])))
        {
            if (auth()->user()->type == 'admin') {
                return redirect()->route('admin.home');
            }else if (auth()->user()->type == 'manager') {
                return redirect()->route('manager.home');
            }else{
                return redirect()->route('home');
            }
        }else{
            return redirect()->route('login')
                ->with('error','Email-Address And Password Are Wrong.');
        }
          
    }
}

HomeController

<?php
  
namespace AppHttpControllers;
 
use IlluminateHttpRequest;
  
class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }
  
    /**
     * Show the application dashboard.
     *
     * @return IlluminateContractsSupportRenderable
     */
    public function index()
    {
        return view('home');
    } 
  
    /**
     * Show the application dashboard.
     *
     * @return IlluminateContractsSupportRenderable
     */
    public function adminHome()
    {
        return view('adminHome');
    }
  
    /**
     * Show the application dashboard.
     *
     * @return IlluminateContractsSupportRenderable
     */
    public function managerHome()
    {
        return view('managerHome');
    }
}

UserAccess

<?php
  
namespace AppHttpMiddleware;
  
use Closure;
use IlluminateHttpRequest;
  
class UserAccess
{
    /**
     * Handle an incoming request.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  Closure(IlluminateHttpRequest): (IlluminateHttpResponse|IlluminateHttpRedirectResponse)  $next
     * @return IlluminateHttpResponse|IlluminateHttpRedirectResponse
     */
    public function handle(Request $request, Closure $next, $userType)
    {
        if(auth()->user()->type == $userType){
            return $next($request);
        }
          
        return response()->json(['You do not have permission to access for this page.']);
        /* return response()->view('errors.check-permission'); */
    }
}

Can you kindly help me?

2

Answers


  1. In most of my applications I have an admin panel.
    Here’s how I do the redirect logic:

    I use the default Auth/AuthenticatedSessionController class from the breeze install.

    My store method looks like this:

    public function store(LoginRequest $request)
    {
        $request->authenticate();
    
        $request->session()->regenerate();
    
        if (Auth::user()->hasRole('admin')) {
            return redirect()->intended(RouteServiceProvider::ADMIN_HOME);
        }
    
        return redirect()->intended(RouteServiceProvider::HOME);
    }
    

    And of course in the RouteServiceProvider I hav my routes defined:

    public const HOME = '/myorders';
    
    public const ADMIN_HOME = '/admin/pages';
    
    Login or Signup to reply.
  2. Solution 1:

    On your AppHttpControllersAuthLoginController, just override the method:

    use IlluminateSupportFacadesAuth;
    
    public function redirectPath()
    {
        if (Auth::user()->role == 'Admin') {
            return "/admin/home";
            // or return route('admin.home');
        } 
        elseif (Auth::user()->role == 'Manager') {
            return "/manager/home";
            // or return route('manager.home');
        }
    
        return "/home";
        // or return route('home');
    }
    

    N.B: If something issue happenes with the method redirectPath, then please try with the method redirectTo. And must remove the property named redirectTo as well.

    Solution 2:

    AppHttpControllersAuthLoginController.php

    use IlluminateSupportFacadesAuth;
    
    protected function authenticated(Request $request, $user)
    {
        if (auth()->user()->hasRole(['Admin'])) {
            return redirect("/admin/home");
        } 
        elseif (auth()->user()->hasRole(['Manager'])) {
            return redirect("/manager/home");
        }
    
        return redirect("/home");
    }
    

    N.B: If you are using Laravel Spatie Permission package, then the permission checking would work in this way.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search