Search code examples
phpauthenticationslimslim-3

Slim 3 Middleware Redirect


I want to check if a user is logged in. Therefor I have an Class witch returns true or false. Now I want a middleware which 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
        }

    }
}

So when the user is logged in the page will render correctly. But when the user is not autoriesed I want to redirect to the homepage. But how?!

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

This doesn't work!


Solution

  • You need to return the response. Don't forget that the request and response objects are immutable.

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

    I have a similar auth middleware and this is how I do it which also adds a 403 (unauthorized) header.

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