0

I'm trying to redirect user to a login page when is not authenticated. I'm using a middleware in Slim3 to check using Sentinel. Works but I need to override the body to not show the content. For example, I could use CURL to access to a route like /users and I can get all the page. Because of that I need to remove/override the body if the user is not authenticated.

public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next)
{

    $route = parse_url($request->getUri(), PHP_URL_PATH);

    if ($route !== '/login' && ! $user = Sentinel::check() )
    {
        $response = $response
            ->withStatus(301)
            ->withHeader("location", '/login')
        ;
    }
    return $next($request, $response);

}
fpilee
  • 1,918
  • 2
  • 22
  • 38
  • 1
    When not authenticated, I wouldn't think that the middleware stack would even let the request proceed to any content generation. I think you could do that here by simply returning `$response->with...` instead of letting it proceed to the `$next` call. – Greg Schmidt Nov 17 '18 at 01:21
  • You are right. Also, the body will be restored if I call next. So I cannot change it and call $next. – fpilee Nov 17 '18 at 01:29
  • 1
    Well, you could capture the return value from `$next`, then override the body, then return as required. That's the expected way of modifying something "on the way out", for example recognizing URLs in the body and replacing them with links. Returning early seems by far the better approach for your need, for a number of reasons; just wanted to be clear that it is absolutely possible to modify the response that the next thing in the middleware queue passes back to you. – Greg Schmidt Nov 17 '18 at 01:33
  • 1
    Is `! $user = Sentinel::check()` correct? – Script47 Nov 17 '18 at 01:37
  • yes that works fine, the library(sentinel) returns false if the user is not authenticated – fpilee Nov 17 '18 at 01:50
  • replace `$response = $response->...` with `return $response->...` as suggested by odan answer. – Zamrony P. Juhara Nov 18 '18 at 22:30
  • I fixed with Greg comment 2 days ago. – fpilee Nov 19 '18 at 17:06

1 Answers1

1

You should not call the $next callback if you only want to redirect the user:

public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next)
{
    $route = parse_url($request->getUri(), PHP_URL_PATH);

    if ($route !== '/login' && ! $user = Sentinel::check() )
    {
        return $response
            ->withHeader('Location', '/login')
            ->withStatus(302);
    }

    return $next($request, $response);
}
odan
  • 4,757
  • 5
  • 20
  • 49