I have the following middleware that I'll attach to my route:
class RequireAuth extends Base
{
public function __invoke(Request $request, RequestHandler $handler): Response
{
// On my way in, get authenticated user...
// I want to decide whether to redirect the response now, but i don't have
// the response object yet like I did in Slim 3.
// So, get the response instance from handler
$response = $handler->handle($request);
// Now on my way out... and too late to decide whether to redirect to /login
if ($user) {
return $response;
} else {
return $response
->withHeader('Location', '/login')
->withStatus(302);
}
}
}
Now this redirect works. However, it would appear it's redirecting after hitting the app and on the way out. I can confirm this by putting a die('hello');
within my controller. If the user is not authenticated then it shouldn't get that far, as the redirect should be attached on the way in. But, the controller is being envoked even though I'm not authenticated. This is bad. In Slim 3 I had access to the $response object, and would pass it in through a $next handler. But it seems in Slim 4 I only have request $handler which is going to hit the app before I have my hands on the $response to decide whether I want to redirect to /login for example.
How can I return a redirecting $response on the way in, rather than on the way out?