Remove body PSR-7 Slim3 middleware?

295 views Asked by At

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);

}
1

There are 1 answers

1
odan On

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);
}