Home > Enterprise >  Admin and Manager user is redirected to route /home when logging in but must be redirected to route
Admin and Manager user is redirected to route /home when logging in but must be redirected to route

Time:10-08

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 App\Http\Controllers;
 
use Illuminate\Http\Request;
  
class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }
  
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        return view('home');
    } 
  
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function adminHome()
    {
        return view('adminHome');
    }
  
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function managerHome()
    {
        return view('managerHome');
    }
}

UserAccess

<?php
  
namespace App\Http\Middleware;
  
use Closure;
use Illuminate\Http\Request;
  
class UserAccess
{
    /**
     * 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, $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?

CodePudding user response:

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';

CodePudding user response:

On your App\Http\Controllers\Auth\LoginController, just override the method:

use Illuminate\Support\Facades\Auth;

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.

  • Related