0

According to the docs I can't set a name for group of routes in Slim 3.
In auth middleware I want to split routes for needed authentication and not. Like:

# These routes will return 302 redirect on auth false
$app->group('', function () use ($app) {
    $app->get('/first', 'HomeCtrl:first')->setName('first');
    $app->get('/second', 'HomeCtrl:second')->setName('second');
})->add(new \Lib\Middlewares\CheckSession());

# These routes will return 403 on auth false
$app->group('api/', function () use ($app) {
    $app->get('users', 'UsersCtrl:getUsers')->setName('users');
    $app->get('pages', 'PagesCtrl:getPages')->setName('pages');
})->add(new \Lib\Middlewares\CheckSession());

In the second group I want the auth middleware to return 403 for ajax calls instead of redirecting in the first.

I don't want to manage an array with names of all routes like suggested in this great answer. It should be a name of the group and based on it to decide what kind of response code to return.

I don't want to manage two middlewares either. I'm looking for an elegant solution for managing current routes group.

Community
  • 1
  • 1
Doc999tor
  • 170
  • 1
  • 13

1 Answers1

1

Slim 3 groups do not have names - they are essentially syntactic sugar that does two things:

  1. Prepend an optional URL segment to a set of route definitions.
  2. Apply middleware to a set of route definitions.

To do what you want to do, your CheckSession middleware needs to check the request's path to work out if it starts with api/ and do send a 403 in that case. Alternatively, CheckSession could look for the X-Requested-With header which is usually sent with ajax requests.

Rob Allen
  • 12,444
  • 1
  • 35
  • 46
  • Thanks. I can accept it, but it doesn't seem to me like an elegant solution. I don't really need a name of the routes group but kind of indication what group I use now. Even if it impossible at all, don't you think it can be a needed feature? I haven't check the issues in Slim bugtracker, I think it can be a nice candidate. – Doc999tor May 05 '17 at 11:17
  • It would be a major piece of surgery to the code, as there's no concept of "group" when `$app->run()` is executing. – Rob Allen May 05 '17 at 11:29