Redirecting the user to the page they were on before logging in

Let's assume that you've followed the Authentication tutorial and want to display some content only to authenticated users. What happens when a user tries to access a restricted page? They will be redirected to the login form, but the login form doesn't redirect them back to the page they wanted to access before logging in. Here is how to fix that:

  1. In Login.pm, amend sub index :Path :Args(0) { ... } to read:

    # If the username and password values were found in form
    if ($username && $password) {
        # Attempt to log the user in
        if ($c->authenticate({ username => $username, 
                           password => $password} )) {
            # If successful, then let them use the application
            $c->response->redirect($c->uri_for('/places'));
            $c->response->redirect($c->flash->{redirect_after_login});  # this is new
            return;
        } else {
            # Set an error message
            $c->stash->{error_msg} = "Bad username or password.";
        }
    }
    
  2. Now we need to make sure that $c->flash->{redirect_after_log} is set. In Root.pm, change the following section of sub auto : Private { ... }:

    # If a user doesn't exist, force login
    if (!$c->user_exists) {
        # Dump a log message to the development server debug output
        $c->log->debug('***Root::auto User not found, forwarding to /login');
        # Redirect the user to the login page
        $c->response->redirect($c->uri_for('/login'));
        # Return 0 to cancel 'post-auto' processing and prevent use of application
        $c->flash->{redirect_after_login} = '' . $c->req->uri;  # this is new
        return 0;
    }
    

... And beware ...

If the user's credentials are not valid on a POST of a form (for instance, timeout of session or changed password elsewhere) the POSTed information will be lost and a simple redirect will put them back at an empty form. This can be very irritating for users, so keep it in mind when setting session timeouts.

See also

nextpageredirect

My tags:
 
Popular tags:
 
Powered by Catalyst
Powered by MojoMojo Hosted by Shadowcat - Managed by Nordaaker