Slim 3 Middleware Redirect

I want to check if the user is registered. So I have a class that returns true or false. Now I want middleware that checks if the user is logged in.

$app->get('/login', '\Controller\AccountController:loginGet')->add(Auth::class)->setName('login'); $app->post('/login', '\Controller\AccountController:loginPost')->add(Auth::class); 

Auth class

 class Auth { protected $ci; private $account; //Constructor public function __construct(ContainerInterface $ci) { $this->ci = $ci; $this->account = new \Account($this->ci); } public function __invoke($request, \Slim\Http\Response $response, $next) { if($this->account->login_check()) { $response = $next($request, $response); return $response; } else { //Redirect to Homepage } } } 

Thus, when the user is registered on the page, it will be displayed correctly. But when the user is not authorized, I want to redirect to the home page. But how?!

 $response->withRedirect($router->pathFor('home'); 

This does not work!

+6
source share
3 answers

You need to answer return . Remember that request and response objects are immutable.

 return $response = $response->withRedirect(...); 

I have a similar middleware, and I do so that it also adds a 403 (unauthorized) header.

 $uri = $request->getUri()->withPath($this->router->pathFor('home')); return $response = $response->withRedirect($uri, 403); 
+9
source

After completing the tflight answer, you will need to do the following so that everything works as intended. I tried to present this as a revision, given that the code provided in tflight's answer will not work with the framework out of the box, but it was rejected, therefore, providing it in a separate answer:

You will need the following addition to your middleware:

 protected $router; public function __construct($router) { $this->router = $router; } 

In addition, when declaring middleware, you need to add the following constructor:

 $app->getContainer()->get('router') 

Something like:

 $app->add(new YourMiddleware($app->getContainer()->get('router'))); 

Without these changes, the solution will not work, and you will receive an error message that $ this-> router does not exist.

With these changes, you can use the code provided by tflight

 $uri = $request->getUri()->withPath($this->router->pathFor('home')); return $response = $response->withRedirect($uri, 403); 
+1
source

Using:

 http_response_code(303); header('Location: ' . $url); exit; 
-3
source

All Articles