Slim Framework PHP - block routes access to users in some conditions

php slim

416 просмотра

1 ответ

I'm using Slim Framework v3 for PHP and here is the code I use in a class to create my API:

public function __construct( ) {
    $this->slim = new \Slim\App;
    $this->init();
    $this->slim->run();
}

private function init () {
    $this->slim->add(function ($request, $response, $next) {
        // my code ...
        return $response;
    });
    $this->slim->get('/getElements', array($this, 'getElements'));
    $this->slim->get('/getElements2', array($this, 'getElements2'));
    // and more...
}

public function getElements ( $request, $response, $args ) {
    // my code ...
}

public function getElements2 ( $request, $response, $args ) {
    // my code ...
}

In some conditions I need to restrict APIs access to users, so in the case above I need to return a response with error when they try to access the application routes. So, users will receive an error when trying to access getElements, getElements2 and all other routes.

I have been thinking to put some code in init() function and block user there, but what code can I use to do that?

Also, another way to do that would be by putting some code for each route callback and doing something like this:

public function getElements ( $request, $response, $args ) {
   echo json_encode(array(
      'error' => array(
         'msg' => "MESSAGE...",
      ),
   ));
   return $response;

   // my code ...
}

but I have many routes and prefer avoiding that.

Any idea?

Edit: I forgot to mention that I need to access the $request object before deciding whether a user should be blocked or not.

Thanks

Автор: Frank Источник Размещён: 08.11.2019 11:24

Ответы (1)


0 плюса

Решение

I just solved by doing this:

if ( !$check ) {
  return $response->withStatus(403);
}

in my $this->slim->add() function.

Автор: Frank Размещён: 20.08.2016 02:55
Вопросы из категории :
32x32