Middleware Group Authentication Laravel

0

save folks, I want to know how to design my admin route so that the user does not have access to this route but they both have to be authenticated.

My routes

Route::group(['middleware' => ['auth']], function () {

    Route::get('/Admin', function () { //ADM ADM

        return "Seu ID: " . Auth::user()->id . " Você é ADM";

    })->name('admin');

    Route::get('/Usuario', function () { //USER USER

        return "Seu ID: " . Auth::user()->id . " Você é Usuario";

    })->name('usuario');

    Route::get('/semLogar', function () { // SEM LOGAR

        return "Você não está autenticado";

        })->name('semLogar');

    Route::get('/login/admin',['middleware' => 'Check:admin','uses' => 'AdminController@index', 'as' => 'indexAdm']);
});

My controler

public function index (){

    return "Opa controller adm";
}

Middleware

public function handle ($ request, Closure $ next, $ role) {     if (! Auth :: check ()) {

    return redirect()->route('semLogar');

}
if(Auth::user()->role == $role){

    return redirect()->route('admin');

} else if (Auth::user()->role !== $role){

    return redirect()->route('usuario');
}

return $next($request);

}

middlewareGroups

'CheckGrupo' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'Check' => \App\Http\Middleware\CheckAdmin::class,
    ], 

routeMiddleware

    'Check' => \App\Http\Middleware\CheckAdmin::class,  

What I want is that when the user is logged in he could not put in the URL / admin and enter the route / admin that he can only enter if it is adm.

NOTE: I am registering an ENUM ('user', 'admin') in the database.

    
asked by anonymous 29.01.2018 / 17:48

1 answer

2

You can define a group of routes and add middleware like this:

Route::middleware('auth')->group(function () {

   Route::middleware('Check')->group(function () {

     // Rotas que só o admin pode acessar
   });

   // Demais rotas
});

For the middleware of Check I would recommend the following code:

public function handle($request, Closure $next, $role)
{
    if (Auth::user()->role == $role) {

         return $next($request);
    } 

    return redirect()->route('usuario');   
}  

Since the auth middleware runs before this middleware, it is not necessary to check if the user is logged in, and if you have more than one page for the admin you will not want to redirect it to admin p>

Documentation link:

link

    
30.01.2018 / 03:21