Authentication, private pages direct urls

Yeah, originally I had just replaced my controller with what you posted. I ended up combining the two to get something that works, so, I’m not sure how elegant it is. I’ll post it all together since it does seem to be working

Login Controller

<?php 

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

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

    // go to this url if login was successful
   if($_POST['location'] != '') {
    $redirect = $_POST['location']; 
   } else {
      //go to the client page if login was successful but no location is found
      $redirect = $site->page('client'); 
   }

   // redirect immediately if user is already logged in
   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);

};

Login Template

<?php snippet('header') ?>

<h1><?php echo $page->title()->html() ?></h1>

<?php if($error): ?>
<div class="alert"><?php echo $page->alert()->html() ?></div>
<?php endif ?>

<form method="post">

  <input type="hidden" name="location" value="<?php if(isset($_GET['location'])) {
    echo htmlspecialchars($_GET['location']);} ?>" />

  <div>
    <label for="username"><?php echo $page->username()->html() ?></label>
    <input type="text" id="username" name="username">
  </div>
  <div>
    <label for="password"><?php echo $page->password()->html() ?></label>
    <input type="password" id="password" name="password">
  </div>
  <div>      
    <input type="submit" name="login" value="<?php echo $page->button()->html() ?>">
  </div>
</form>

<?php snippet('footer') ?>

Project Template

<?php if(!$site->user() && $page->privacy()->isTrue()) go('login?location=' . urlencode(kirby()->request()->path())); ?>

Thanks so much for you help @texnixe. I’m pretty new to php, so its hard for me to say if this is a hacky solution or not.

1 Like