How redirect user to previous page after login?

I use Slim Born skeleton. I have AuthMiddleware that checks if user logged in or not:

class AuthMiddleware extends Middleware {
	public function __invoke(Request $request, RequestHandler $handler): Response
	{
		// If not auth
		if(! $this->container->get('auth')->check()) {
			$this->container->get('flash')->addMessage('error', 'Необходимо войти на сайт');
			$url = $this->container->get('router')->urlFor('auth.signin');
			$response = new Response();
			return $response->withHeader('Location', $url)->withStatus(302);
		}
		$response = $handler->handle($request);
		return $response;
	}
}

If not - it redirects to auth.signin route. Here is a login form post code:

public function postSignIn( $request, $response ) {
		$data = $request->getParsedBody();
		$auth = $this->auth->attempt( $data['email'], $data['password'] );

		if ( ! $auth ) {
			$this->flash->addMessage( 'error', 'Could not sign you in with those details' );
			return $response->withHeader( 'Location', $this->router->urlFor( 'auth.signin' ) );
		}
		return $response->withHeader( 'Location', $this->router->urlFor( 'home' ) );
	}

How can I change redirect to previous page (request) instead of home page?
For example if guest ask /dashboard route it must be logged in first and then redirect back to dashboard.

The AuthMiddleware could add a ?redirect={url} query parameter to the auth.signin URL.
The postSignIn method could then read and use this redirect parameter from the request object to create a URL for the successfully redirect.

1 Like