If login is successful, redirect to previous page

This is my simple controller for the login page.
Is it possible, when the login is successful, to redirect to previous page and not to homepage?

return function ($kirby) {

  // don't show the login screen to already logged in users
  if ($kirby->user()) {
    go('/');
  }

  $error = false;

  // handle the form submission
  if ($kirby->request()->is('POST') && get('login')) {

    // try to log the user in with the provided credentials
    try {
      $kirby->auth()->login(get('email'), get('password'), $long = true);

      // redirect to the homepage if the login was successful
      go('/');
    } catch (Exception $e) {
      $error = true;
    }

  }

  return [
    'error' => $error
  ];

};

the only idea that comes to mind is to store the previous url in the kirby session and recall it, but I don’t know how to do it.

Can you help me? Thanks!

Hi,

If I am understanding what you are trying to do, you can add the $page object as an argument to the function:

return function ($kirby, $page) {

and then use that in the controller:

go($page->url())

You need to pass the previous page to the controller somehow, for example via a hidden input field that contains this information or via session data.

I guess the login form is not on every page, but when user tries to access a protected page, they are redirected to the login page?

This refers to the current page, in the case of a form that goes to the login page, this would then redirect to login page again, which is not wanted.

Ah yep I had misunderstood - ignore me!

I can add an input field like this one:

<input type="hidden" id="previousPage" name="previousPage" value="">

But I have no idea how to store previous page url inside the value.

The login form is not present in all pages, but there is a button that takes you to the login page.
Could my alternative be to place the direct login on every page, so that I just stay on that page after login?

There are several options. For example, you could store the url of a protected page that a user wants to visit in the session if the user is not logged in. Then after the user is logged in, fetch the value from the session, redirect and delete the value from the session.

If you have a login form on every protected page, you can add this hidden field with a value of $page->url() (or uuid) that is then sent to the login controller with all the other form data. In that case you can use this field value for the redirect after successful login.