authentication - redirect a whole group on condition with slim -


i'm working slim , created groups simplify routes file. since group should unauthorized non admin users, redirect routes in group instead of redirect routes 1 one this:

index.php

$app->group('/admin', function () use ($app) { // crée un "groupe d'url"      $app->get('/users', function () use ($app){         if(isset($_session["type"]) && $_session["type"] == "admin") {             $ctrl = new usercontroller();             $ctrl->listing($app);         }else{             $app->redirect($app->urlfor('indexadmin'));         }     })       $app->get('/users', function () use ($app){         if(isset($_session["type"]) && $_session["type"] == "admin") {             $ctrl = new usercontroller();             $ctrl->listing($app);         }else{             $app->redirect($app->urlfor('indexadmin'));         }     }) 

as see same code appears several times, possible factorise ?

you can use route middleware.

create route middleware , add variable:

$handleauthorization = function () {     if(!(isset($_session["type"]) && $_session["type"] == "admin")) {         $app = \slim\slim::getinstance();         $app->redirect($app->urlfor('indexadmin'));     } }; 

create routes using route middleware variable:

$app->get('/', function (){     echo "home!!"; })->name('indexadmin');  $app->group('/admin', $handleauthorization, function () use ($app) { // crée un "groupe d'url"      $app->get('/users', function () use ($app){         $ctrl = new usercontroller();         $ctrl->listing($app);     });       $app->get('/users2', function () use ($app){         $ctrl = new usercontroller();         $ctrl->listing($app);     }); }); 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -