Retain url parameter with routes - Kirby v2

I think I somehow didn’t really understand your code, trying to get it right now.

  1. On the protected page, you send the user to the login page, attaching the original URL as a query parameter ( = GET request).

  2. Ok, now I understand why you use $_GET in the hidden form element. That get’s the location from the URL, so that should actually be OK then.

  3. But in your controller, the first thing you do it to check for the $_POST variable, even if you don’t even have a post request.

That somehow doesn’t all really make sense.


Come to think of it, it can all be much easier, no hidden field, just the location parameter

In redirect template:

<? if (!$site->user() && $page->protectedtoggle()->bool()) : ?>

    <?php go('login?location=' . urlencode(kirby()->request()->path())); ?>

<? endif // Ending the if user is logged in ?>

In your controller:

<?php

return function($site, $pages, $page) {

  // don't show the login screen to already logged in users
  $redirect = get('location') ?? $site->url();
  if($site->user()) go($redirect);

  // handle the form submission
  if(r::is('post') and get('login')) {

    // fetch the user by username and run the
    // login method with the password
    if($user = $site->user(get('username')) and $user->login(get('password'))) {
      // redirect to the homepage
      // if the login was successful
      go($redirect);
    } else {
      // make sure the alert is being
      // displayed in the template
      $error = true;
    }

  } else {
    // nothing has been submitted
    // nothing has gone wrong
    $error = false;
  }

  return array('error' => $error);

};

That’s it.