Laravel 7 : Redirect to different logins on different guards

Viewed 3468

i'm using the auth middleware and creating and admin guard for controlling the admin access. Im having some problems when im trying to access to the admin routes, i would like to redirect the unathenticated trafict associated to the admins routes to an /admin/login page, but instead of that, it redirect me to the /login page. I don't know how to get the guards associated to a route in the class Authenticate.

 protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            return route('login');
        }
    }
}

that's the code, i would like to be something like :

 protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            if(Auth::guard('admin'))
               return route('admin.login);
            else
               return route(login);
        }
    }
}

but it doesn't work, 'cos the only parameter that i have is the $request.

Those are my routes...


//Admin Routes
Route::middleware(['auth:admin'])->group(function () {
Route::get('/admin', 'AdminController@index')->name('admin');
Route::get('/newDoncente', 'AdminController@addDocenteView')->name('newDocente');

//Docentes Routes
Route::get('/docentes', 'Docente\DocenteController@getDocentesView')->name('getDocentesView');
Route::get('/editDocente/{id}', 'Docente\DocenteController@editDocenteView')->name('editDocentesView');
Route::get('/docentesTables', 'Docente\DocenteController@getDocentesDatatables')->name('getDocentesTables');
Route::get('/docente/{id}', 'Docente\DocenteController@getDocenteView')->name('getDocenteView');

Thanks.

4 Answers

I've been looking for a guard based answer, where I was looking to check the guard than redirects based on the guard type. However I couldn't find a solution.

However, I found another solution that gets the job done but it isn't as dynamic as the answer I'm looking for. However, it's working fine for me

in

App\Http\Middleware\Authinticate.php

class, add the following code:

protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            if($request->is('admin') || $request->is('admin/*'))
            return route('admin.login');
            
            return route('login');
        }
    }

Also, don't forget to prefix all admin routes with admin/ . Hope this answer helps you.

go to the app/Exception/Handler.php

use this class

use Illuminate\Auth\AuthenticationException;

and add this function in the class


    protected function unauthenticated($request, AuthenticationException $exception)
    {
        if (request()->expectsJson()) {
            return Response()->json(['error' => 'UnAuthorized'], 401); //exeption for api
        }

        $guard = data_get($exception->guards(), 0);
        switch ($guard) {
            case 'admin':
                $login = 'admin.login';
                break;
            default:
                $login = 'login';
                break;
        }
        return redirect()->guest(route($login));
    }

I'm not sure if this is the right way , I overrode the handle method so I can get the guards from it as follows:

protected $guards = [];

public function handle($request, Closure $next, ...$guards)
{
    $this->guards = $guards;

    return parent::handle($request, $next, ...$guards);
}
protected function redirectTo($request)
{
    if (in_array("admin", $this->guards)) {
        return "admin/login";
    }

}

Ok, i've resolve it, i guess that's quite a good approach. I create a middleware and i asked for the auth guard on the middleware.

First I create the middleware


class IsAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
    
        if (Auth::guard('admin')->check()) 
        return $next($request);
        else 
        return redirect('/admin/login');

    }
}

Then I put the middleware in the Kernel file

 protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'isAdmin' => \App\Http\Middleware\IsAdmin::class,

Last, i change the middleware for the routes

Route::get('/admin', 'AdminController@index')->name('admin');

Now it's working fine, but if you have a better solution, i really wanted to know it.

Related