CGI-Application-Plugin-Authentication

 view release on metacpan or  search on metacpan

lib/CGI/Application/Plugin/Authentication.pm  view on Meta::CPAN

    my $callpkg = caller;
    {
        no strict qw(refs);
        *{$callpkg.'::authen'} = \&CGI::Application::Plugin::_::Authentication::authen;
    }
    if ( ! UNIVERSAL::isa($callpkg, 'CGI::Application') ) {
        warn "Calling package is not a CGI::Application module so not setting up the prerun hook.  If you are using \@ISA instead of 'use base', make sure it is in a BEGIN { } block, and make sure these statements appear before the plugin is loaded";
    } else {
        $callpkg->add_callback( prerun => \&prerun_callback );
    }
}

use Attribute::Handlers;
my %RUNMODES;

sub CGI::Application::RequireAuthentication : ATTR(CODE) {
    my ( $package, $symbol, $referent, $attr, $data, $phase ) = @_;
    $RUNMODES{$referent} = $data || 1;
}
sub CGI::Application::Authen : ATTR(CODE) {
    my ( $package, $symbol, $referent, $attr, $data, $phase ) = @_;
    $RUNMODES{$referent} = $data || 1;
}


=head1 NAME

CGI::Application::Plugin::Authentication - Authentication framework for CGI::Application

=head1 SYNOPSIS

 package MyCGIApp;

 use base qw(CGI::Application); # make sure this occurs before you load the plugin

 use CGI::Application::Plugin::Authentication;

 MyCGIApp->authen->config(
       DRIVER => [ 'Generic', { user1 => '123' } ],
 );
 MyCGIApp->authen->protected_runmodes('myrunmode');

 sub myrunmode {
    my $self = shift;

    # The user should be logged in if we got here
    my $username = $self->authen->username;

 }

=head1 DESCRIPTION

CGI::Application::Plugin::Authentication adds the ability to authenticate users
in your L<CGI::Application> modules.  It imports one method called 'authen' into your
CGI::Application module.  Through the authen method you can call all the methods of
the CGI::Application::Plugin::Authentication plugin.

There are two main decisions that you need to make when using this module.  How will
the usernames and password be verified (i.e. from a database, LDAP, etc...), and how
can we keep the knowledge that a user has already logged in persistent, so that they
will not have to enter their credentials again on the next request (i.e. how do we 'Store'
the authentication information across requests).

=head2 Choosing a Driver

There are three drivers that are included with the distribution.  Also, there
is built in support for all of the Authen::Simple modules (search CPAN for
Authen::Simple for more information).  This should be enough to cover
everyone's needs.  

If you need to authenticate against a source that is not provided, you can use
the Generic driver which will accept either a hash of username/password pairs,
or an array of arrays of credentials, or a subroutine reference that can verify
the credentials.  So through the Generic driver you should be able to write
your own verification system.  There is also a Dummy driver, which blindly
accepts any credentials (useful for testing).  See the
L<CGI::Application::Plugin::Authentication::Driver::Generic>,
L<CGI::Application::Plugin::Authentication::Driver::DBI> and,
L<CGI::Application::Plugin::Authentication::Driver::Dummy> docs for more
information on how to use these drivers.  And see the L<Authen::Simple> suite
of modules for information on those drivers.

=head2 Choosing a Store

The Store modules keep information about the authentication status of the user persistent
across multiple requests.  The information that is stored in the store include the username,
and the expiry time of the login.  There are two Store modules included with this distribution.
A Session based store, and a Cookie based store.  If your application is already using
Sessions (through the L<CGI::Application::Plugin::Session> module), then I would recommend
that you use the Session store for authentication.  If you are not using the Session
plugin, then you can use the Cookie store.  The Cookie store keeps all the authentication
in a cookie, which contains a checksum to ensure that users can not change the information.

If you do not specify which Store module you wish to use, the plugin will try to determine
the best one for you.

=head2 Login page

The Authentication plugin comes with a default login page that can be used if you do not
want to create a custom login page.  This login form will automatically be used if you
do not provide either a LOGIN_URL or LOGIN_RUNMODE parameter in the configuration.
If you plan to create your own login page, I would recommend that you start with the HTML
code for the default login page, so that your login page will contain the correct form
fields and hidden fields.

=head2 Ticket based authentication

This Authentication plugin can handle ticket based authentication systems as well.  All that
is required of you is to write a Store module that can understand the contents of the ticket.
The Authentication plugin will require at least the 'username' to be retrieved from the
ticket.  A Ticket based authentication scheme will not need a Driver module at all, since the
actual verification of credentials is done by an external authentication system, possibly
even on a different host.  You will need to specify the location of the login page using
the LOGIN_URL configuration variable, and unauthenticated users will automatically
be redirected to your ticket authentication login page.


=head1 EXPORTED METHODS

=head2 authen

This is the only method exported from this module.  Everything is controlled
through this method call, which will return a CGI::Application::Plugin::Authentication
object, or just the class name if called as a class method.  When using
the plugin, you will always first call $self->authen or __PACKAGE__->authen and
then the method you wish to invoke.  For example:

  __PACKAGE__->authen->config(
        LOGIN_RUNMODE => 'login',
  );

- or -

  $self->authen->protected_runmodes(qw(one two));

=cut


{   package # Hide from PAUSE
        CGI::Application::Plugin::_::Authentication;

    ##############################################
    ###
    ###   authen
    ###
    ##############################################
    #
    # Return an authen object that can be used
    # for managing authentication.
    #
    # This will return a class name if called
    # as a class name, and a singleton object
    # if called as an object method
    #
    sub authen {
        my $cgiapp = shift;

        if (ref($cgiapp)) {
            return CGI::Application::Plugin::Authentication->instance($cgiapp);
        } else {
            return 'CGI::Application::Plugin::Authentication';
        }
    }

}

package CGI::Application::Plugin::Authentication;



=head1 METHODS

=head2 config

This method is used to configure the CGI::Application::Plugin::Authentication
module.  It can be called as an object method, or as a class method. Calling this function,
will not itself generate cookies or session ids.

The following parameters are accepted:

=over 4

=item DRIVER

Here you can choose which authentication module(s) you want to use to perform the authentication.
For simplicity, you can leave off the CGI::Application::Plugin::Authentication::Driver:: part
when specifying the DRIVER name  If this module requires extra parameters, you
can pass an array reference that contains as the first parameter the name of the module,
and the rest of the values in the array will be considered options for the driver.  You can provide
multiple drivers which will be used, in order, to check the credentials until
a valid response is received.

     DRIVER => 'Dummy' # let anyone in regardless of the password

  - or -

     DRIVER => [ 'DBI',
         DBH         => $self->dbh,
         TABLE       => 'user',
         CONSTRAINTS => {
             'user.name'         => '__CREDENTIAL_1__',
             'MD5:user.password' => '__CREDENTIAL_2__'
         },
     ],

  - or -

     DRIVER => [
         [ 'Generic', { user1 => '123' } ],
         [ 'Generic', sub { my ($u, $p) = @_; is_prime($p) ? 1 : 0 } ]
     ],

  - or -

     DRIVER => [ 'Authen::Simple::LDAP',
         host   => 'ldap.company.com',
         basedn => 'ou=People,dc=company,dc=net'
     ],


=item STORE

Here you can choose how we store the authenticated information after a user has successfully 
logged in.  We need to store the username so that on the next request we can tell the user
has already logged in, and we do not have to present them with another login form.  If you
do not provide the STORE option, then the plugin will look to see if you are using the
L<CGI::Application::Plugin::Session> module and based on that info use either the Session
module, or fall back on the Cookie module.  If the module requires extra parameters, you
can pass an array reference that contains as the first parameter the name of the module,
and the rest of the array should contain key value pairs of options for this module.
These storage modules generally live under the CGI::Application::Plugin::Authentication::Store::
name-space, and this part of the package name can be left off when specifying the STORE
parameter.

    STORE => 'Session'

  - or -

    STORE => ['Cookie',
        NAME   => 'MYAuthCookie',
        SECRET => 'FortyTwo',
        EXPIRY => '1d',
    ]


=item POST_LOGIN_RUNMODE

Here you can specify a runmode that the user will be redirected to if they successfully login.

  POST_LOGIN_RUNMODE => 'welcome'

lib/CGI/Application/Plugin/Authentication.pm  view on Meta::CPAN

            $config->{STORE} = delete $props->{STORE};
            # We will accept a string, but what we really want is an arrayref of the store driver,
            # and any custom options
            no warnings qw(uninitialized);
            $config->{STORE} = [ $config->{STORE} ] if Scalar::Util::reftype( $config->{STORE} ) ne 'ARRAY';
        }

        # Check for POST_LOGIN_RUNMODE
        if ( defined $props->{POST_LOGIN_RUNMODE} ) {
            croak "authen config error:  parameter POST_LOGIN_RUNMODE is not a string"
              if ref $props->{POST_LOGIN_RUNMODE};
            $config->{POST_LOGIN_RUNMODE} = delete $props->{POST_LOGIN_RUNMODE};
        }

        # Check for POST_LOGIN_URL
        if ( defined $props->{POST_LOGIN_URL} ) {
            carp "authen config warning:  parameter POST_LOGIN_URL ignored since we already have POST_LOGIN_RUNMODE"
              if $config->{POST_LOGIN_RUNMODE};
            croak "authen config error:  parameter POST_LOGIN_URL is not a string"
              if ref $props->{POST_LOGIN_URL};
            $config->{POST_LOGIN_URL} = delete $props->{POST_LOGIN_URL};
        }

        # Check for LOGIN_RUNMODE
        if ( defined $props->{LOGIN_RUNMODE} ) {
            croak "authen config error:  parameter LOGIN_RUNMODE is not a string"
              if ref $props->{LOGIN_RUNMODE};
            $config->{LOGIN_RUNMODE} = delete $props->{LOGIN_RUNMODE};
        }

        # Check for LOGIN_URL
        if ( defined $props->{LOGIN_URL} ) {
            carp "authen config warning:  parameter LOGIN_URL ignored since we already have LOGIN_RUNMODE"
              if $config->{LOGIN_RUNMODE};
            croak "authen config error:  parameter LOGIN_URL is not a string"
              if ref $props->{LOGIN_URL};
            $config->{LOGIN_URL} = delete $props->{LOGIN_URL};
        }

        # Check for LOGOUT_RUNMODE
        if ( defined $props->{LOGOUT_RUNMODE} ) {
            croak "authen config error:  parameter LOGOUT_RUNMODE is not a string"
              if ref $props->{LOGOUT_RUNMODE};
            $config->{LOGOUT_RUNMODE} = delete $props->{LOGOUT_RUNMODE};
        }

        # Check for LOGOUT_URL
        if ( defined $props->{LOGOUT_URL} ) {
            carp "authen config warning:  parameter LOGOUT_URL ignored since we already have LOGOUT_RUNMODE"
              if $config->{LOGOUT_RUNMODE};
            croak "authen config error:  parameter LOGOUT_URL is not a string"
              if ref $props->{LOGOUT_URL};
            $config->{LOGOUT_URL} = delete $props->{LOGOUT_URL};
        }

        # Check for CREDENTIALS
        if ( defined $props->{CREDENTIALS} ) {
            croak "authen config error:  parameter CREDENTIALS is not a string or arrayref"
              if ref $props->{CREDENTIALS} && Scalar::Util::reftype( $props->{CREDENTIALS} ) ne 'ARRAY';
            $config->{CREDENTIALS} = delete $props->{CREDENTIALS};
            # We will accept a string, but what we really want is an arrayref of the credentials
            no warnings qw(uninitialized);
            $config->{CREDENTIALS} = [ $config->{CREDENTIALS} ] if Scalar::Util::reftype( $config->{CREDENTIALS} ) ne 'ARRAY';
        }

        # Check for LOGIN_SESSION_TIMEOUT
        if ( defined $props->{LOGIN_SESSION_TIMEOUT} ) {
            croak "authen config error:  parameter LOGIN_SESSION_TIMEOUT is not a string or a hashref"
              if ref $props->{LOGIN_SESSION_TIMEOUT} && ref$props->{LOGIN_SESSION_TIMEOUT} ne 'HASH';
            my $options = {};
            if (! ref $props->{LOGIN_SESSION_TIMEOUT}) {
                $options->{IDLE_FOR} = _time_to_seconds( $props->{LOGIN_SESSION_TIMEOUT} );
                croak "authen config error: parameter LOGIN_SESSION_TIMEOUT is not a valid time string" unless defined $options->{IDLE_FOR};
            } else {
                if ($props->{LOGIN_SESSION_TIMEOUT}->{IDLE_FOR}) {
                    $options->{IDLE_FOR} = _time_to_seconds( delete $props->{LOGIN_SESSION_TIMEOUT}->{IDLE_FOR} );
                    croak "authen config error: IDLE_FOR option to LOGIN_SESSION_TIMEOUT is not a valid time string" unless defined $options->{IDLE_FOR};
                }
                if ($props->{LOGIN_SESSION_TIMEOUT}->{EVERY}) {
                    $options->{EVERY} = _time_to_seconds( delete $props->{LOGIN_SESSION_TIMEOUT}->{EVERY} );
                    croak "authen config error: EVERY option to LOGIN_SESSION_TIMEOUT is not a valid time string" unless defined $options->{EVERY};
                }
                if ($props->{LOGIN_SESSION_TIMEOUT}->{CUSTOM}) {
                    $options->{CUSTOM} = delete $props->{LOGIN_SESSION_TIMEOUT}->{CUSTOM};
                    croak "authen config error: CUSTOM option to LOGIN_SESSION_TIMEOUT must be a code reference" unless ref $options->{CUSTOM} eq 'CODE';
                }
                croak "authen config error: Invalid option(s) (" . join( ', ', keys %{$props->{LOGIN_SESSION_TIMEOUT}} ) . ") passed to LOGIN_SESSION_TIMEOUT" if %{$props->{LOGIN_SESSION_TIMEOUT}};
            }

            $config->{LOGIN_SESSION_TIMEOUT} = $options;
            delete $props->{LOGIN_SESSION_TIMEOUT};
        }

        # Check for POST_LOGIN_CALLBACK
        if ( defined $props->{POST_LOGIN_CALLBACK} ) {
            croak "authen config error:  parameter POST_LOGIN_CALLBACK is not a coderef"
              unless( ref $props->{POST_LOGIN_CALLBACK} eq 'CODE' );
            $config->{POST_LOGIN_CALLBACK} = delete $props->{POST_LOGIN_CALLBACK};
        }

        # Check for RENDER_LOGIN
        if ( defined $props->{RENDER_LOGIN} ) {
            croak "authen config error:  parameter RENDER_LOGIN is not a coderef"
              unless( ref $props->{RENDER_LOGIN} eq 'CODE' );
            $config->{RENDER_LOGIN} = delete $props->{RENDER_LOGIN};
        }

        # Check for LOGIN_FORM
        if ( defined $props->{LOGIN_FORM} ) {
            croak "authen config error:  parameter LOGIN_FORM is not a hashref"
              unless( ref $props->{LOGIN_FORM} eq 'HASH' );
            $config->{LOGIN_FORM} = delete $props->{LOGIN_FORM};
        }

	# Check for DETAINT_URL_REGEXP
        if ( defined $props->{DETAINT_URL_REGEXP} ) {
            $config->{DETAINT_URL_REGEXP} = delete $props->{DETAINT_URL_REGEXP};
        }
	else {
	    $config->{DETAINT_URL_REGEXP} =  '^([\w\_\%\?\&\;\-\/\@\.\+\$\=\#\:\!\*\"\'\(\)\,]+)$';
	}

lib/CGI/Application/Plugin/Authentication.pm  view on Meta::CPAN


    return $self->username ? 1 : 0;
}

=head2 login_attempts

This method will return the number of failed login attempts have been made by this
user since the last successful login.  This is not a number that can be trusted,
as it is dependent on the underlying store to be able to return the correct value for
this user.  For example, if the store uses a cookie based session, the user trying
to login could delete their cookies, and hence get a new session which will not have
any login attempts listed.  The number will be cleared upon a successful login.
This function will initiate a session or cookie if one has not been created already.

=cut

sub login_attempts {
    my $self = shift;
    $self->initialize;

    my $la = $self->store->fetch('login_attempts');
    return $la;
}

=head2 username

This will return the username of the currently logged in user, or undef if
no user is currently logged in.

  my $username = $self->authen->username;

This function will initiate a session or cookie if one has not been created already.

=cut

sub username {
    my $self = shift;
    $self->initialize;

    my $u = $self->store->fetch('username');
    return $u;
}

=head2 is_new_login

This will return true or false depending on if this is a fresh login

  $self->log->info("New Login") if $self->authen->is_new_login;

This function will initiate a session or cookie if one has not been created already.

=cut

sub is_new_login {
    my $self = shift;
    $self->initialize;

    return $self->{is_new_login};
}

=head2 credentials

This method will return the names of the form parameters that will be
looked for during a login.  By default they are authen_username and authen_password,
but these values can be changed by supplying the CREDENTIALS parameters in the
configuration. Calling this function, will not itself generate cookies or session ids.

=cut

sub credentials {
    my $self = shift;
    my $config = $self->_config;
    return $config->{CREDENTIALS} || [qw(authen_username authen_password)];
}

=head2 logout

This will attempt to logout the user.  If during a request the Authentication
module sees a parameter called 'authen_logout', it will automatically call this method
to log out the user.

  $self->authen->logout();

This function will initiate a session or cookie if one has not been created already.

=cut

sub logout {
    my $self = shift;
    $self->initialize;

    $self->store->clear;
}

=head2 drivers

This method will return a list of driver objects that are used for
verifying the login credentials. Calling this function, will not itself generate cookies or session ids.

=cut

sub drivers {
    my $self = shift;

    if ( !$self->{drivers} ) {
        my $config = $self->_config;

        # Fetch the configuration parameters for the driver(s)
        my $driver_configs = defined $config->{DRIVER} ? $config->{DRIVER} : [['Dummy']];

        foreach my $driver_config (@$driver_configs) {
            my ($drivername, @params) = @$driver_config;
            # add support for Authen::Simple modules
            if (index($drivername, 'Authen::Simple') == 0) {
                unshift @params, $drivername;
                $drivername = 'Authen::Simple';
            }
            # Load the the class for this driver
            my $driver_class = _find_deligate_class(
                'CGI::Application::Plugin::Authentication::Driver::' . $drivername,
                $drivername
            ) || die "Driver ".$drivername." can not be found";

            # Create the driver object
            my $driver = $driver_class->new( $self, @params )
              || die "Could not create new $driver_class object";
            push @{$self->{drivers}}, $driver;
        }
    }

    my $drivers = $self->{drivers};
    return @$drivers[0..$#$drivers];
}

=head2 store

This method will return a store object that is used to store information
about the status of the authentication across multiple requests.
This function will initiate a session or cookie if one has not been created already.

=cut

sub store {
    my $self = shift;

    if ( !$self->{store} ) {
        my $config = $self->_config;

        # Fetch the configuration parameters for the store
        my ($store_module, @store_config);
        ($store_module, @store_config) = @{ $config->{STORE} } if $config->{STORE} && ref $config->{STORE} eq 'ARRAY';
        if (!$store_module) {
            # No STORE configuration was provided
            if ($self->_cgiapp->can('session') && UNIVERSAL::isa($self->_cgiapp->session, 'CGI::Session')) {
                # The user is already using the Session plugin
                ($store_module, @store_config) = ( 'Session' );
            } else {
                # Fall back to the Cookie Store

lib/CGI/Application/Plugin/Authentication.pm  view on Meta::CPAN

            }
        }

        # Load the the class for this store
        my $store_class = _find_deligate_class(
            'CGI::Application::Plugin::Authentication::Store::' . $store_module,
            $store_module
        ) || die "Store $store_module can not be found";

        # Create the store object
        $self->{store} = $store_class->new( $self, @store_config )
          || die "Could not create new $store_class object";
    }

    return $self->{store};
}

=head2 initialize

This does most of the heavy lifting for the Authentication plugin.  It will
check to see if the user is currently attempting to login by looking for the
credential form fields in the query object.  It will load the required driver
objects and authenticate the user.  It is OK to call this method multiple times
as it checks to see if it has already been executed and will just return
without doing anything if called multiple times.  This allows us to call
initialize as late as possible in the request so that no unnecessary work is
done.

The user will be logged out by calling the C<logout()> method if the login
session has been idle for too long, if it has been too long since the last
login, or if the login has timed out.  If you need to know if a user was logged
out because of a time out, you can call the C<is_login_timeout> method.

If all goes well, a true value will be returned, although it is usually not
necessary to check.

This function will initiate a session or cookie if one has not been created already.

=cut

sub initialize {
    my $self = shift;
    return 1 if $self->{initialized};

    # It would seem to make more sense to do this at the /end/ of the routine
    # but that causes an infinite loop. 
    $self->{initialized} = 1;

    if (UNIVERSAL::can($self->_cgiapp, 'devpopup')) {
        $self->_cgiapp->add_callback( 'devpopup_report', \&_devpopup_report );
    }

    my $config = $self->_config;

    # See if the user is trying to log in
    #  We do this before checking to see if the user is already logged in, since
    #  a logged in user may want to log in as a different user.
    my $field_names = $config->{CREDENTIALS} || [qw(authen_username authen_password)];

    my $query = $self->_cgiapp->query;
    my @credentials = map { scalar $query->param($_) } @$field_names;
    if ($credentials[0]) {
        # The user is trying to login
        # make sure if they are already logged in, that we log them out first
        my $store = $self->store;
        $store->clear if $store->fetch('username');
        foreach my $driver ($self->drivers) {
            if (my $username = $driver->verify_credentials(@credentials)) {
                # This user provided the correct credentials
                # so save this new login in the store
                my $now = time();
                $store->save( username => $username,  login_attempts => 0, last_login => $now, last_access => $now );
                $self->{is_new_login} = 1;
                # See if we are remembering the username for this user
                my $login_config = $config->{LOGIN_FORM} || {};
                if ($login_config->{REMEMBERUSER_OPTION} && scalar $query->param('authen_rememberuser')) {
                    my $cookie = $query->cookie(
                        -name   => $login_config->{REMEMBERUSER_COOKIENAME} || 'CAPAUTHTOKEN',
                        -value  => $username,
                        -expiry => '10y',
                    );
                    $self->_cgiapp->header_add(-cookie => [$cookie]);
                }
                last;
            }
        }
        unless ($self->username) {
            # password mismatch - increment failed login attempts
            my $attempts = $store->fetch('login_attempts') || 0; 
            $store->save( login_attempts => $attempts + 1 );
        }

        $config->{POST_LOGIN_CALLBACK}->($self->_cgiapp) 
          if($config->{POST_LOGIN_CALLBACK});
    }

    # Check the user name last of all because only this check might create a session behind the scenes.
    # In other words if a website works perfectly well without authentication,
    # then adding a protected run mode should not add session to the unprotected modes.
    # See 60_parsimony.t for the test.
    if ($config->{LOGIN_SESSION_TIMEOUT} && !$self->{is_new_login} && $self->username) {
        # This is not a fresh login, and there are time out rules, so make sure the login is still valid
        if ($config->{LOGIN_SESSION_TIMEOUT}->{IDLE_FOR} && time() - $self->last_access >= $config->{LOGIN_SESSION_TIMEOUT}->{IDLE_FOR}) {
            # this login has been idle for too long
            $self->{is_login_timeout} = 1;
            $self->logout;
        } elsif ($config->{LOGIN_SESSION_TIMEOUT}->{EVERY} && time() - $self->last_login >=  $config->{LOGIN_SESSION_TIMEOUT}->{EVERY}) {
            # it has been too long since the last login
            $self->{is_login_timeout} = 1;
            $self->logout;
        } elsif ($config->{LOGIN_SESSION_TIMEOUT}->{CUSTOM} && $config->{LOGIN_SESSION_TIMEOUT}->{CUSTOM}->($self)) {
            # this login has timed out
            $self->{is_login_timeout} = 1;
            $self->logout;
        }
    }
    return 1;

}

=head2 display 

This method will return the
L<CGI::Application::Plugin::Authentication::Display> object, creating
and caching it if necessary.

=cut

sub display {

lib/CGI/Application/Plugin/Authentication.pm  view on Meta::CPAN

sub prerun_callback {
    my $self = shift;
    my $authen = $self->authen;

    $authen->initialize;

    # setup the default login and logout runmodes
    $authen->setup_runmodes;

    # The user is asking to be logged out
    if (scalar $self->query->param('authen_logout')) {
        # The user wants to logout
        return $self->authen->redirect_to_logout;
    }

    # If the user just logged in then we may want to redirect them
    if ($authen->is_new_login) {
        # User just logged in, so where to we send them?
        return $self->authen->redirect_after_login;
    }

    # Update any time out info
    my $config = $authen->_config;
    if ( $config->{LOGIN_SESSION_TIMEOUT} ) {
        # update the last access time
        my $now = time;
        $authen->last_access($now);
    }

    # If a perun mode is set check against that. 
    # This allows cooperation with plugins such as CAP::ActionDispatch
    # that also have preun hooks.
    # Note the comments in the CGI::Application docs on the ordering of
    # callback execution.
    my $run_mode = $self->prerun_mode;
    $run_mode ||= $self->get_current_runmode;
    
    if ( $authen->is_protected_runmode( $run_mode ) ) {
        # This runmode requires authentication
        unless ($authen->is_authenticated) {
            # This user is NOT logged in
            return $self->authen->redirect_to_login;
        }
    }
}

=head1 CGI::Application RUNMODES

=head2 authen_login_runmode

This runmode is provided if you do not want to create your
own login runmode.  It will display a simple login form for the user, which
can be replaced by assigning RENDER_LOGIN a coderef that returns the HTML.

=cut

sub authen_login_runmode {
    my $self   = shift;
    my $authen = $self->authen;

    my $credentials = $authen->credentials;
    my $username    = $credentials->[0];
    my $password    = $credentials->[1];

    my $html;
    if ( my $sub = $authen->_config->{RENDER_LOGIN} ) {
        $html = $sub->($self);
    }
    else {
        $html = join( "\n",
            CGI::start_html( -title => $authen->display->login_title ),
            $authen->display->login_box,
            CGI::end_html(),
        );
    }

    return $html;
}

=head2 authen_dummy_redirect

This runmode is provided for convenience when an external redirect needs
to be done.  It just returns an empty string.

=cut

sub authen_dummy_redirect {
    return '';
}

###
### Detainting helper methods
###

sub _detaint_destination {
    my $self = shift;
    my $query       = $self->_cgiapp->query;
    my $destination = scalar $query->param('destination');
    my $regexp = $self->_config->{DETAINT_URL_REGEXP};
    if ($destination && $destination =~ /$regexp/) {
	$destination = $1;
    }
    else {
	$destination = "";
    }
    return $destination;
}

sub _detaint_selfurl {
    my $self = shift;
    my $query       = $self->_cgiapp->query;
    my $destination = "";
    my $regexp = $self->_config->{DETAINT_URL_REGEXP};
    if ($query->self_url =~ /$regexp/) {
        $destination = $1;
    }
    return $destination;
}

sub _detaint_url {
    my $self = shift;
    my $query       = $self->_cgiapp->query;
    my $regexp = $self->_config->{DETAINT_URL_REGEXP};



( run in 2.010 seconds using v1.01-cache-2.11-cpan-140bd7fdf52 )