File Coverage

blib/lib/CGI/Application/Plugin/Authentication.pm
Criterion Covered Total %
statement 383 415 92.2
branch 206 228 90.3
condition 82 108 75.9
subroutine 53 54 98.1
pod 26 28 92.8
total 750 833 90.0


)
line stmt bran cond sub pod time code
1             package CGI::Application::Plugin::Authentication;
2             $CGI::Application::Plugin::Authentication::VERSION = '0.21';
3 31     31   3190742 use 5.006;
  31         98  
4 31     31   148 use strict;
  31         45  
  31         1147  
5              
6             our %__CONFIG;
7              
8 31     31   512 use Class::ISA ();
  31         1715  
  31         406  
9 31     31   121 use Scalar::Util ();
  31         49  
  31         515  
10 31     31   12654 use UNIVERSAL::require;
  31         35286  
  31         277  
11 31     31   818 use Carp;
  31         48  
  31         1489  
12 31     31   13501 use CGI ();
  31         452670  
  31         812  
13 31     31   24082 use overload;
  31         22698  
  31         210  
14              
15             sub import {
16 33     33   11929 my $pkg = shift;
17 33         112 my $callpkg = caller;
18             {
19 31     31   2379 no strict qw(refs);
  31         50  
  31         3936  
  33         404  
20 33         82 *{$callpkg.'::authen'} = \&CGI::Application::Plugin::_::Authentication::authen;
  33         238  
21             }
22 33 100       232 if ( ! UNIVERSAL::isa($callpkg, 'CGI::Application') ) {
23 2         27 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";
24             } else {
25 31         266 $callpkg->add_callback( prerun => \&prerun_callback );
26             }
27             }
28              
29 31     31   17375 use Attribute::Handlers;
  31         137304  
  31         194  
30             my %RUNMODES;
31              
32             sub CGI::Application::RequireAuthentication : ATTR(CODE) {
33 1     1 0 1650 my ( $package, $symbol, $referent, $attr, $data, $phase ) = @_;
34 1   50     10 $RUNMODES{$referent} = $data || 1;
35 31     31   3030 }
  31         60  
  31         112  
36             sub CGI::Application::Authen : ATTR(CODE) {
37 1     1 0 298 my ( $package, $symbol, $referent, $attr, $data, $phase ) = @_;
38 1   50     6 $RUNMODES{$referent} = $data || 1;
39 31     31   16056 }
  31         74  
  31         164  
40              
41              
42             =head1 NAME
43              
44             CGI::Application::Plugin::Authentication - Authentication framework for CGI::Application
45              
46             =head1 SYNOPSIS
47              
48             package MyCGIApp;
49              
50             use base qw(CGI::Application); # make sure this occurs before you load the plugin
51              
52             use CGI::Application::Plugin::Authentication;
53              
54             MyCGIApp->authen->config(
55             DRIVER => [ 'Generic', { user1 => '123' } ],
56             );
57             MyCGIApp->authen->protected_runmodes('myrunmode');
58              
59             sub myrunmode {
60             my $self = shift;
61              
62             # The user should be logged in if we got here
63             my $username = $self->authen->username;
64              
65             }
66              
67             =head1 DESCRIPTION
68              
69             CGI::Application::Plugin::Authentication adds the ability to authenticate users
70             in your L modules. It imports one method called 'authen' into your
71             CGI::Application module. Through the authen method you can call all the methods of
72             the CGI::Application::Plugin::Authentication plugin.
73              
74             There are two main decisions that you need to make when using this module. How will
75             the usernames and password be verified (i.e. from a database, LDAP, etc...), and how
76             can we keep the knowledge that a user has already logged in persistent, so that they
77             will not have to enter their credentials again on the next request (i.e. how do we 'Store'
78             the authentication information across requests).
79              
80             =head2 Choosing a Driver
81              
82             There are three drivers that are included with the distribution. Also, there
83             is built in support for all of the Authen::Simple modules (search CPAN for
84             Authen::Simple for more information). This should be enough to cover
85             everyone's needs.
86              
87             If you need to authenticate against a source that is not provided, you can use
88             the Generic driver which will accept either a hash of username/password pairs,
89             or an array of arrays of credentials, or a subroutine reference that can verify
90             the credentials. So through the Generic driver you should be able to write
91             your own verification system. There is also a Dummy driver, which blindly
92             accepts any credentials (useful for testing). See the
93             L,
94             L and,
95             L docs for more
96             information on how to use these drivers. And see the L suite
97             of modules for information on those drivers.
98              
99             =head2 Choosing a Store
100              
101             The Store modules keep information about the authentication status of the user persistent
102             across multiple requests. The information that is stored in the store include the username,
103             and the expiry time of the login. There are two Store modules included with this distribution.
104             A Session based store, and a Cookie based store. If your application is already using
105             Sessions (through the L module), then I would recommend
106             that you use the Session store for authentication. If you are not using the Session
107             plugin, then you can use the Cookie store. The Cookie store keeps all the authentication
108             in a cookie, which contains a checksum to ensure that users can not change the information.
109              
110             If you do not specify which Store module you wish to use, the plugin will try to determine
111             the best one for you.
112              
113             =head2 Login page
114              
115             The Authentication plugin comes with a default login page that can be used if you do not
116             want to create a custom login page. This login form will automatically be used if you
117             do not provide either a LOGIN_URL or LOGIN_RUNMODE parameter in the configuration.
118             If you plan to create your own login page, I would recommend that you start with the HTML
119             code for the default login page, so that your login page will contain the correct form
120             fields and hidden fields.
121              
122             =head2 Ticket based authentication
123              
124             This Authentication plugin can handle ticket based authentication systems as well. All that
125             is required of you is to write a Store module that can understand the contents of the ticket.
126             The Authentication plugin will require at least the 'username' to be retrieved from the
127             ticket. A Ticket based authentication scheme will not need a Driver module at all, since the
128             actual verification of credentials is done by an external authentication system, possibly
129             even on a different host. You will need to specify the location of the login page using
130             the LOGIN_URL configuration variable, and unauthenticated users will automatically
131             be redirected to your ticket authentication login page.
132              
133              
134             =head1 EXPORTED METHODS
135              
136             =head2 authen
137              
138             This is the only method exported from this module. Everything is controlled
139             through this method call, which will return a CGI::Application::Plugin::Authentication
140             object, or just the class name if called as a class method. When using
141             the plugin, you will always first call $self->authen or __PACKAGE__->authen and
142             then the method you wish to invoke. For example:
143              
144             __PACKAGE__->authen->config(
145             LOGIN_RUNMODE => 'login',
146             );
147              
148             - or -
149              
150             $self->authen->protected_runmodes(qw(one two));
151              
152             =cut
153              
154              
155             { package # Hide from PAUSE
156             CGI::Application::Plugin::_::Authentication;
157              
158             ##############################################
159             ###
160             ### authen
161             ###
162             ##############################################
163             #
164             # Return an authen object that can be used
165             # for managing authentication.
166             #
167             # This will return a class name if called
168             # as a class name, and a singleton object
169             # if called as an object method
170             #
171             sub authen {
172 1544     1544   2714503 my $cgiapp = shift;
173              
174 1544 100       3165 if (ref($cgiapp)) {
175 1521         3290 return CGI::Application::Plugin::Authentication->instance($cgiapp);
176             } else {
177 23         314 return 'CGI::Application::Plugin::Authentication';
178             }
179             }
180              
181             }
182              
183             package CGI::Application::Plugin::Authentication;
184              
185              
186              
187             =head1 METHODS
188              
189             =head2 config
190              
191             This method is used to configure the CGI::Application::Plugin::Authentication
192             module. It can be called as an object method, or as a class method. Calling this function,
193             will not itself generate cookies or session ids.
194              
195             The following parameters are accepted:
196              
197             =over 4
198              
199             =item DRIVER
200              
201             Here you can choose which authentication module(s) you want to use to perform the authentication.
202             For simplicity, you can leave off the CGI::Application::Plugin::Authentication::Driver:: part
203             when specifying the DRIVER name If this module requires extra parameters, you
204             can pass an array reference that contains as the first parameter the name of the module,
205             and the rest of the values in the array will be considered options for the driver. You can provide
206             multiple drivers which will be used, in order, to check the credentials until
207             a valid response is received.
208              
209             DRIVER => 'Dummy' # let anyone in regardless of the password
210              
211             - or -
212              
213             DRIVER => [ 'DBI',
214             DBH => $self->dbh,
215             TABLE => 'user',
216             CONSTRAINTS => {
217             'user.name' => '__CREDENTIAL_1__',
218             'MD5:user.password' => '__CREDENTIAL_2__'
219             },
220             ],
221              
222             - or -
223              
224             DRIVER => [
225             [ 'Generic', { user1 => '123' } ],
226             [ 'Generic', sub { my ($u, $p) = @_; is_prime($p) ? 1 : 0 } ]
227             ],
228              
229             - or -
230              
231             DRIVER => [ 'Authen::Simple::LDAP',
232             host => 'ldap.company.com',
233             basedn => 'ou=People,dc=company,dc=net'
234             ],
235              
236              
237             =item STORE
238              
239             Here you can choose how we store the authenticated information after a user has successfully
240             logged in. We need to store the username so that on the next request we can tell the user
241             has already logged in, and we do not have to present them with another login form. If you
242             do not provide the STORE option, then the plugin will look to see if you are using the
243             L module and based on that info use either the Session
244             module, or fall back on the Cookie module. If the module requires extra parameters, you
245             can pass an array reference that contains as the first parameter the name of the module,
246             and the rest of the array should contain key value pairs of options for this module.
247             These storage modules generally live under the CGI::Application::Plugin::Authentication::Store::
248             name-space, and this part of the package name can be left off when specifying the STORE
249             parameter.
250              
251             STORE => 'Session'
252              
253             - or -
254              
255             STORE => ['Cookie',
256             NAME => 'MYAuthCookie',
257             SECRET => 'FortyTwo',
258             EXPIRY => '1d',
259             ]
260              
261              
262             =item POST_LOGIN_RUNMODE
263              
264             Here you can specify a runmode that the user will be redirected to if they successfully login.
265              
266             POST_LOGIN_RUNMODE => 'welcome'
267              
268             =item POST_LOGIN_URL
269              
270             Here you can specify a URL that the user will be redirected to if they successfully login.
271             If both POST_LOGIN_URL and POST_LOGIN_RUNMODE are specified, then the latter
272             will take precedence.
273              
274             POST_LOGIN_URL => 'http://example.com/start.cgi'
275              
276             =item POST_LOGIN_CALLBACK
277              
278             A code reference that is executed after login processing but before POST_LOGIN_RUNMODE or
279             redirecting to POST_LOGIN_URL. This is normally a method in your CGI::Application application
280             and as such the CGI::Application object is passed as a parameter.
281              
282             POST_LOGIN_CALLBACK => \&update_login_date
283              
284             and later in your code:
285              
286             sub update_login_date {
287             my $self = shift;
288              
289             return unless($self->authen->is_authenticated);
290              
291             ...
292             }
293              
294              
295             =item LOGIN_RUNMODE
296              
297             Here you can specify a runmode that the user will be redirected to if they need to login.
298              
299             LOGIN_RUNMODE => 'login'
300              
301             =item LOGIN_URL
302              
303             If your login page is external to this module, then you can use this option to specify a
304             URL that the user will be redirected to when they need to login. If both
305             LOGIN_URL and LOGIN_RUNMODE are specified, then the latter will take precedence.
306              
307             LOGIN_URL => 'http://example.com/login.cgi'
308              
309             =item LOGOUT_RUNMODE
310              
311             Here you can specify a runmode that the user will be redirected to if they ask to logout.
312              
313             LOGOUT_RUNMODE => 'logout'
314              
315             =item LOGOUT_URL
316              
317             If your logout page is external to this module, then you can use this option to specify a
318             URL that the user will be redirected to when they ask to logout. If both
319             LOGOUT_URL and LOGOUT_RUNMODE are specified, then the latter will take precedence.
320              
321             LOGIN_URL => 'http://example.com/logout.html'
322              
323             =item DETAINT_URL_REGEXP
324              
325             This is a regular expression used to detaint URLs used in the login form. By default it will be set to
326              
327             ^([\w\_\%\?\&\;\-\/\@\.\+\$\=\#\:\!\*\"\'\(\)\,]+)$
328              
329             This regular expression is based upon the document http://www.w3.org/Addressing/URL/url-spec.txt. You could
330             set it to a more specific regular expression to limit the domains to which users could be directed.
331              
332             =item DETAINT_USERNAME_REGEXP
333              
334             This is a regular expression used to detaint the username parameter used in the login form. By default it will be set to
335              
336             ^([\w\_]+)$
337              
338             =item CREDENTIALS
339              
340             Set this to the list of form fields where the user will type in their username and password.
341             By default this is set to ['authen_username', 'authen_password']. The form field names should
342             be set to a value that you are not likely to use in any other forms. This is important
343             because this plugin will automatically look for query parameters that match these values on
344             every request to see if a user is trying to log in. So if you use the same parameter names
345             on a user management page, you may inadvertently perform a login when that was not intended.
346             Most of the Driver modules will return the first CREDENTIAL as the username, so make sure
347             that you list the username field first. This option can be ignored if you use the built in
348             login box
349              
350             CREDENTIALS => 'authen_password'
351              
352             - or -
353              
354             CREDENTIALS => [ 'authen_username', 'authen_domain', 'authen_password' ]
355              
356              
357             =item LOGIN_SESSION_TIMEOUT
358              
359              
360             This option can be used to tell the system when to force the user to re-authenticate. There are
361             a few different possibilities that can all be used concurrently:
362              
363             =over 4
364              
365             =item IDLE_FOR
366              
367             If this value is set, a re-authentication will be forced if the user was idle for more then x amount of time.
368              
369             =item EVERY
370              
371             If this value is set, a re-authentication will be forced every x amount of time.
372              
373             =item CUSTOM
374              
375             This value can be set to a subroutine reference that returns true if the session should be timed out,
376             and false if it is still active. This can allow you to be very selective about how the timeout system
377             works. The authen object will be passed in as the only parameter.
378              
379             =back
380              
381             Time values are specified in seconds. You can also specify the time by using a number with the
382             following suffixes (m h d w), which represent minutes, hours, days and weeks. The default
383             is 0 which means the login will never timeout.
384              
385             Note that the login is also dependent on the type of STORE that is used. If the Session store is used,
386             and the session expires, then the login will also automatically expire. The same goes for the Cookie
387             store.
388              
389             For backwards compatibility, if you set LOGIN_SESSION_TIMEOUT to a time value instead of a hashref,
390             it will be treated as an IDLE_FOR time out.
391              
392             # force re-authentication if idle for more than 15 minutes
393             LOGIN_SESSION_TIMEOUT => '15m'
394              
395             # Everyone must re-authentication if idle for more than 30 minutes
396             # also, everyone must re-authentication at least once a day
397             # and root must re-authentication if idle for more than 5 minutes
398             LOGIN_SESSION_TIMEOUT => {
399             IDLE_FOR => '30m',
400             EVERY => '1d',
401             CUSTOM => sub {
402             my $authen = shift;
403             return ($authen->username eq 'root' && (time() - $authen->last_access) > 300) ? 1 : 0;
404             }
405             }
406              
407             =item RENDER_LOGIN
408              
409             This value can be set to a subroutine reference that returns the HTML of a login
410             form. The subroutine reference overrides the default call to login_box.
411             The subroutine is normally a method in your CGI::Application application and as such the
412             CGI::Application object is passed as the first parameter.
413              
414             RENDER_LOGIN => \&login_form
415              
416             and later in your code:
417              
418             sub login_form {
419             my $self = shift;
420              
421             ...
422             return $html
423             }
424              
425             =item LOGIN_FORM
426              
427             You can set this option to customize the login form that is created when a user
428             needs to be authenticated. If you wish to replace the entire login form with a
429             completely custom version, then just set LOGIN_RUNMODE to point to your custom
430             runmode.
431              
432             All of the parameters listed below are optional, and a reasonable default will
433             be used if left blank:
434              
435             =over 4
436              
437             =item DISPLAY_CLASS (default: Classic)
438              
439             the class used to display the login form. The alternative is C
440             which aims for XHTML compliance and leaving style to CSS. See
441             L for more details.
442              
443             =item TITLE (default: Sign In)
444              
445             the heading at the top of the login box
446              
447             =item USERNAME_LABEL (default: User Name)
448              
449             the label for the user name input
450              
451             =item PASSWORD_LABEL (default: Password)
452              
453             the label for the password input
454              
455             =item SUBMIT_LABEL (default: Sign In)
456              
457             the label for the submit button
458              
459             =item COMMENT (default: Please enter your username and password in the fields below.)
460              
461             a message provided on the first login attempt
462              
463             =item REMEMBERUSER_OPTION (default: 1)
464              
465             provide a checkbox to offer to remember the users name in a cookie so that
466             their user name will be pre-filled the next time they log in
467              
468             =item REMEMBERUSER_LABEL (default: Remember User Name)
469              
470             the label for the remember user name checkbox
471              
472             =item REMEMBERUSER_COOKIENAME (default: CAPAUTHTOKEN)
473              
474             the name of the cookie where the user name will be saved
475              
476             =item REGISTER_URL (default: )
477              
478             the URL for the register new account link
479              
480             =item REGISTER_LABEL (default: Register Now!)
481              
482             the label for the register new account link
483              
484             =item FORGOTPASSWORD_URL (default: )
485              
486             the URL for the forgot password link
487              
488             =item FORGOTPASSWORD_LABEL (default: Forgot Password?)
489              
490             the label for the forgot password link
491              
492             =item INVALIDPASSWORD_MESSAGE (default: Invalid username or password
(login attempt %d)
493              
494             a message given when a login failed
495              
496             =item INCLUDE_STYLESHEET (default: 1)
497              
498             use this to disable the built in style-sheet for the login box so you can provide your own custom styles
499              
500             =item FORM_SUBMIT_METHOD (default: post)
501              
502             use this to get the form to submit using 'get' instead of 'post'
503              
504             =item FOCUS_FORM_ONLOAD (default: 1)
505              
506             use this to automatically focus the login form when the page loads so a user can start typing right away.
507              
508             =item BASE_COLOUR (default: #445588)
509              
510             This is the base colour that will be used in the included login box. All other
511             colours are automatically calculated based on this colour (unless you hardcode
512             the colour values). In order to calculate other colours, you will need the
513             Color::Calc module. If you do not have the Color::Calc module, then you will
514             need to use fixed values for all of the colour options. All colour values
515             besides the BASE_COLOUR can be simple percentage values (including the % sign).
516             For example if you set the LIGHTER_COLOUR option to 80%, then the calculated
517             colour will be 80% lighter than the BASE_COLOUR.
518              
519             =item LIGHT_COLOUR (default: 50% or #a2aac4)
520              
521             A colour that is lighter than the base colour.
522              
523             =item LIGHTER_COLOUR (default: 75% or #d0d5e1)
524              
525             A colour that is another step lighter than the light colour.
526              
527             =item DARK_COLOUR (default: 30% or #303c5f)
528              
529             A colour that is darker than the base colour.
530              
531             =item DARKER_COLOUR (default: 60% or #1b2236)
532              
533             A colour that is another step darker than the dark colour.
534              
535             =item GREY_COLOUR (default: #565656)
536              
537             A grey colour that is calculated by desaturating the base colour.
538              
539             =back
540              
541             =back
542              
543             =cut
544              
545             sub config {
546 118     118 1 157 my $self = shift;
547 118 100       266 my $class = ref $self ? ref $self : $self;
548              
549             die "Calling config after the Authentication object has already been initialized"
550 118 100 100     567 if ref $self && defined $self->{initialized};
551 117         254 my $config = $self->_config;
552              
553 117 100       304 if (@_) {
554 116         128 my $props;
555 116 100       295 if ( ref( $_[0] ) eq 'HASH' ) {
556 46         51 my $rthash = %{ $_[0] };
  46         203  
557 46         222 $props = CGI::Application->_cap_hash( $_[0] );
558             } else {
559 70         369 $props = CGI::Application->_cap_hash( {@_} );
560             }
561              
562             # Check for DRIVER
563 116 100       2207 if ( defined $props->{DRIVER} ) {
564             croak "authen config error: parameter DRIVER is not a string or arrayref"
565 72 100 100     582 if ref $props->{DRIVER} && Scalar::Util::reftype( $props->{DRIVER} ) ne 'ARRAY';
566 71         166 $config->{DRIVER} = delete $props->{DRIVER};
567             # We will accept a string, or an arrayref of options, but what we really want
568             # is an array of arrayrefs of options, so that we can support multiple drivers
569             # each with their own custom options
570 31     31   22069 no warnings qw(uninitialized);
  31         42  
  31         3698  
571 71 100       300 $config->{DRIVER} = [ $config->{DRIVER} ] if Scalar::Util::reftype( $config->{DRIVER} ) ne 'ARRAY';
572 71 100       373 $config->{DRIVER} = [ $config->{DRIVER} ] if Scalar::Util::reftype( $config->{DRIVER}->[0] ) ne 'ARRAY';
573             }
574              
575             # Check for STORE
576 115 100       315 if ( defined $props->{STORE} ) {
577             croak "authen config error: parameter STORE is not a string or arrayref"
578 74 100 100     442 if ref $props->{STORE} && Scalar::Util::reftype( $props->{STORE} ) ne 'ARRAY';
579 73         128 $config->{STORE} = delete $props->{STORE};
580             # We will accept a string, but what we really want is an arrayref of the store driver,
581             # and any custom options
582 31     31   175 no warnings qw(uninitialized);
  31         49  
  31         7546  
583 73 100       314 $config->{STORE} = [ $config->{STORE} ] if Scalar::Util::reftype( $config->{STORE} ) ne 'ARRAY';
584             }
585              
586             # Check for POST_LOGIN_RUNMODE
587 114 100       257 if ( defined $props->{POST_LOGIN_RUNMODE} ) {
588             croak "authen config error: parameter POST_LOGIN_RUNMODE is not a string"
589 6 100       24 if ref $props->{POST_LOGIN_RUNMODE};
590 5         9 $config->{POST_LOGIN_RUNMODE} = delete $props->{POST_LOGIN_RUNMODE};
591             }
592              
593             # Check for POST_LOGIN_URL
594 113 100       278 if ( defined $props->{POST_LOGIN_URL} ) {
595             carp "authen config warning: parameter POST_LOGIN_URL ignored since we already have POST_LOGIN_RUNMODE"
596 9 100       47 if $config->{POST_LOGIN_RUNMODE};
597             croak "authen config error: parameter POST_LOGIN_URL is not a string"
598 9 100       902 if ref $props->{POST_LOGIN_URL};
599 8         14 $config->{POST_LOGIN_URL} = delete $props->{POST_LOGIN_URL};
600             }
601              
602             # Check for LOGIN_RUNMODE
603 112 100       247 if ( defined $props->{LOGIN_RUNMODE} ) {
604             croak "authen config error: parameter LOGIN_RUNMODE is not a string"
605 4 100       27 if ref $props->{LOGIN_RUNMODE};
606 3         7 $config->{LOGIN_RUNMODE} = delete $props->{LOGIN_RUNMODE};
607             }
608              
609             # Check for LOGIN_URL
610 111 100       245 if ( defined $props->{LOGIN_URL} ) {
611             carp "authen config warning: parameter LOGIN_URL ignored since we already have LOGIN_RUNMODE"
612 7 100       24 if $config->{LOGIN_RUNMODE};
613             croak "authen config error: parameter LOGIN_URL is not a string"
614 7 100       408 if ref $props->{LOGIN_URL};
615 6         11 $config->{LOGIN_URL} = delete $props->{LOGIN_URL};
616             }
617              
618             # Check for LOGOUT_RUNMODE
619 110 100       225 if ( defined $props->{LOGOUT_RUNMODE} ) {
620             croak "authen config error: parameter LOGOUT_RUNMODE is not a string"
621 4 100       16 if ref $props->{LOGOUT_RUNMODE};
622 3         9 $config->{LOGOUT_RUNMODE} = delete $props->{LOGOUT_RUNMODE};
623             }
624              
625             # Check for LOGOUT_URL
626 109 100       258 if ( defined $props->{LOGOUT_URL} ) {
627             carp "authen config warning: parameter LOGOUT_URL ignored since we already have LOGOUT_RUNMODE"
628 7 100       23 if $config->{LOGOUT_RUNMODE};
629             croak "authen config error: parameter LOGOUT_URL is not a string"
630 7 100       379 if ref $props->{LOGOUT_URL};
631 6         8 $config->{LOGOUT_URL} = delete $props->{LOGOUT_URL};
632             }
633              
634             # Check for CREDENTIALS
635 108 100       244 if ( defined $props->{CREDENTIALS} ) {
636             croak "authen config error: parameter CREDENTIALS is not a string or arrayref"
637 17 100 100     120 if ref $props->{CREDENTIALS} && Scalar::Util::reftype( $props->{CREDENTIALS} ) ne 'ARRAY';
638 16         29 $config->{CREDENTIALS} = delete $props->{CREDENTIALS};
639             # We will accept a string, but what we really want is an arrayref of the credentials
640 31     31   144 no warnings qw(uninitialized);
  31         43  
  31         110069  
641 16 100       104 $config->{CREDENTIALS} = [ $config->{CREDENTIALS} ] if Scalar::Util::reftype( $config->{CREDENTIALS} ) ne 'ARRAY';
642             }
643              
644             # Check for LOGIN_SESSION_TIMEOUT
645 107 100       231 if ( defined $props->{LOGIN_SESSION_TIMEOUT} ) {
646             croak "authen config error: parameter LOGIN_SESSION_TIMEOUT is not a string or a hashref"
647 20 100 100     96 if ref $props->{LOGIN_SESSION_TIMEOUT} && ref$props->{LOGIN_SESSION_TIMEOUT} ne 'HASH';
648 19         48 my $options = {};
649 19 100       44 if (! ref $props->{LOGIN_SESSION_TIMEOUT}) {
650 7         16 $options->{IDLE_FOR} = _time_to_seconds( $props->{LOGIN_SESSION_TIMEOUT} );
651 7 100       25 croak "authen config error: parameter LOGIN_SESSION_TIMEOUT is not a valid time string" unless defined $options->{IDLE_FOR};
652             } else {
653 12 100       26 if ($props->{LOGIN_SESSION_TIMEOUT}->{IDLE_FOR}) {
654 5         20 $options->{IDLE_FOR} = _time_to_seconds( delete $props->{LOGIN_SESSION_TIMEOUT}->{IDLE_FOR} );
655 5 100       22 croak "authen config error: IDLE_FOR option to LOGIN_SESSION_TIMEOUT is not a valid time string" unless defined $options->{IDLE_FOR};
656             }
657 11 100       24 if ($props->{LOGIN_SESSION_TIMEOUT}->{EVERY}) {
658 5         13 $options->{EVERY} = _time_to_seconds( delete $props->{LOGIN_SESSION_TIMEOUT}->{EVERY} );
659 5 100       22 croak "authen config error: EVERY option to LOGIN_SESSION_TIMEOUT is not a valid time string" unless defined $options->{EVERY};
660             }
661 10 100       24 if ($props->{LOGIN_SESSION_TIMEOUT}->{CUSTOM}) {
662 5         12 $options->{CUSTOM} = delete $props->{LOGIN_SESSION_TIMEOUT}->{CUSTOM};
663 5 100       26 croak "authen config error: CUSTOM option to LOGIN_SESSION_TIMEOUT must be a code reference" unless ref $options->{CUSTOM} eq 'CODE';
664             }
665 9 100       10 croak "authen config error: Invalid option(s) (" . join( ', ', keys %{$props->{LOGIN_SESSION_TIMEOUT}} ) . ") passed to LOGIN_SESSION_TIMEOUT" if %{$props->{LOGIN_SESSION_TIMEOUT}};
  1         12  
  9         25  
666             }
667              
668 14         19 $config->{LOGIN_SESSION_TIMEOUT} = $options;
669 14         26 delete $props->{LOGIN_SESSION_TIMEOUT};
670             }
671              
672             # Check for POST_LOGIN_CALLBACK
673 101 100       214 if ( defined $props->{POST_LOGIN_CALLBACK} ) {
674             croak "authen config error: parameter POST_LOGIN_CALLBACK is not a coderef"
675 33 100       126 unless( ref $props->{POST_LOGIN_CALLBACK} eq 'CODE' );
676 31         65 $config->{POST_LOGIN_CALLBACK} = delete $props->{POST_LOGIN_CALLBACK};
677             }
678              
679             # Check for RENDER_LOGIN
680 99 100       233 if ( defined $props->{RENDER_LOGIN} ) {
681             croak "authen config error: parameter RENDER_LOGIN is not a coderef"
682 3 100       39 unless( ref $props->{RENDER_LOGIN} eq 'CODE' );
683 1         4 $config->{RENDER_LOGIN} = delete $props->{RENDER_LOGIN};
684             }
685              
686             # Check for LOGIN_FORM
687 97 100       221 if ( defined $props->{LOGIN_FORM} ) {
688             croak "authen config error: parameter LOGIN_FORM is not a hashref"
689 26 100       90 unless( ref $props->{LOGIN_FORM} eq 'HASH' );
690 25         44 $config->{LOGIN_FORM} = delete $props->{LOGIN_FORM};
691             }
692              
693             # Check for DETAINT_URL_REGEXP
694 96 100       211 if ( defined $props->{DETAINT_URL_REGEXP} ) {
695 3         6 $config->{DETAINT_URL_REGEXP} = delete $props->{DETAINT_URL_REGEXP};
696             }
697             else {
698 93         169 $config->{DETAINT_URL_REGEXP} = '^([\w\_\%\?\&\;\-\/\@\.\+\$\=\#\:\!\*\"\'\(\)\,]+)$';
699             }
700              
701             # Check for DETAINT_USERNAME_REGEXP
702 96 100       192 if ( defined $props->{DETAINT_USERNAME_REGEXP} ) {
703 2         4 $config->{DETAINT_USERNAME_REGEXP} = delete $props->{DETAINT_USERNAME_REGEXP};
704             }
705             else {
706 94         152 $config->{DETAINT_USERNAME_REGEXP} = '^([\w\_]+)$';
707             }
708              
709             # If there are still entries left in $props then they are invalid
710 96 100       592 croak "Invalid option(s) (" . join( ', ', keys %$props ) . ") passed to config" if %$props;
711             }
712             }
713              
714             =head2 protected_runmodes
715              
716             This method takes a list of runmodes that are to be protected by authentication. If a user
717             tries to access one of these runmodes, then they will be redirected to a login page
718             unless they are properly logged in. The runmode names can be a list of simple strings, regular
719             expressions, or special directives that start with a colon. This method is cumulative, so
720             if it is called multiple times, the new values are added to existing entries. It returns
721             a list of all entries that have been saved so far. Calling this function,
722             will not itself generate cookies or session ids.
723              
724             =over 4
725              
726             =item :all - All runmodes in this module will require authentication
727              
728             =back
729              
730             # match all runmodes
731             __PACKAGE__->authen->protected_runmodes(':all');
732              
733             # only protect runmodes one two and three
734             __PACKAGE__->authen->protected_runmodes(qw(one two three));
735              
736             # protect only runmodes that start with auth_
737             __PACKAGE__->authen->protected_runmodes(qr/^auth_/);
738              
739             # protect all runmodes that *do not* start with public_
740             __PACKAGE__->authen->protected_runmodes(qr/^(?!public_)/);
741              
742             =cut
743              
744             sub protected_runmodes {
745 223     223 1 246 my $self = shift;
746 223         424 my $config = $self->_config;
747              
748 223   100     611 $config->{PROTECTED_RUNMODES} ||= [];
749 223 100       444 push @{$config->{PROTECTED_RUNMODES}}, @_ if @_;
  130         293  
750              
751 223         199 return @{$config->{PROTECTED_RUNMODES}};
  223         549  
752             }
753              
754             =head2 is_protected_runmode
755              
756             This method accepts the name of a runmode, and will tell you if that runmode is
757             a protected runmode (i.e. does a user need to be authenticated to access this runmode).
758             Calling this function, will not itself generate cookies or session ids.
759              
760             =cut
761              
762             sub is_protected_runmode {
763 88     88 1 136 my $self = shift;
764 88         114 my $runmode = shift;
765              
766 88         227 foreach my $runmode_test ($self->protected_runmodes) {
767 132 100 66     380 if (overload::StrVal($runmode_test) =~ /^Regexp=/) {
    100          
    100          
768             # We were passed a regular expression
769 9 100       91 return 1 if $runmode =~ $runmode_test;
770             } elsif (ref $runmode_test && ref $runmode_test eq 'CODE') {
771             # We were passed a code reference
772 8 100       56 return 1 if $runmode_test->($runmode);
773             } elsif ($runmode_test eq ':all') {
774             # all runmodes are protected
775 1         7 return 1;
776             } else {
777             # assume we were passed a string
778 114 100       1069 return 1 if $runmode eq $runmode_test;
779             }
780             }
781              
782             # See if the user is using attributes
783 19         65 my $sub = $self->_cgiapp->can($runmode);
784 19 100 66     93 return 1 if $sub && $RUNMODES{$sub};
785              
786 17         69 return;
787             }
788              
789             =head2 redirect_after_login
790              
791             This method is be called during the prerun stage to
792             redirect the user to the page that has been configured
793             as the destination after a successful login. The location is determined as follows:
794              
795             =over
796              
797             =item POST_LOGIN_RUNMODE
798              
799             If the POST_LOGIN_RUNMODE config parameter is set, that run mode will be the chosen location.
800              
801             =item POST_LOGIN_URL
802              
803             If the above fails and the POST_LOGIN_URL config parameter is set, then there will be a 302 redirection to that location.
804              
805             =item destination
806              
807             If the above fails and there is a destination query parameter, which must a taint check against the DETAINT_URL_REGEXP config parameter,
808             then there will be a 302 redirection to that location.
809              
810             =item original destination
811              
812             If all the above fail then there the originally requested page will be delivered.
813              
814             =back
815              
816             =cut
817              
818             sub redirect_after_login {
819 30     30 1 42 my $self = shift;
820 30         63 my $cgiapp = $self->_cgiapp;
821 30         122 my $config = $self->_config;
822              
823 30 100       149 if ($config->{POST_LOGIN_RUNMODE}) {
    100          
    100          
824 1         4 $cgiapp->prerun_mode($config->{POST_LOGIN_RUNMODE});
825             } elsif ($config->{POST_LOGIN_URL}) {
826 1         5 $cgiapp->header_add(-location => $config->{POST_LOGIN_URL});
827 1         33 $cgiapp->header_type('redirect');
828 1         12 $cgiapp->prerun_mode('authen_dummy_redirect');
829             } elsif (my $destination = $cgiapp->authen->_detaint_destination()) {
830 1         9 $cgiapp->header_add(-location => $destination);
831 1         55 $cgiapp->header_type('redirect');
832 1         18 $cgiapp->prerun_mode('authen_dummy_redirect');
833             }
834 30         99 return;
835             }
836              
837             =head2 redirect_to_login
838              
839             This method is be called during the prerun stage if
840             the current user is not logged in, and they are trying to
841             access a protected runmode. It will redirect to the page
842             that has been configured as the login page, based on the value
843             of LOGIN_RUNMODE or LOGIN_URL If nothing is configured
844             a simple login page will be automatically provided.
845              
846             =cut
847              
848             sub redirect_to_login {
849 63     63 1 91 my $self = shift;
850 63         121 my $cgiapp = $self->_cgiapp;
851 63         116 my $config = $self->_config;
852              
853 63 50       194 if ($config->{LOGIN_RUNMODE}) {
    50          
854 0         0 $cgiapp->prerun_mode($config->{LOGIN_RUNMODE});
855             } elsif ($config->{LOGIN_URL}) {
856 0         0 $cgiapp->header_add(-location => $config->{LOGIN_URL});
857 0         0 $cgiapp->header_type('redirect');
858 0         0 $cgiapp->prerun_mode('authen_dummy_redirect');
859             } else {
860 63         164 $cgiapp->prerun_mode('authen_login');
861             }
862             }
863              
864             =head2 redirect_to_logout
865              
866             This method is called during the prerun stage if the user
867             has requested to be logged out. It will redirect to the page
868             that has been configured as the logout page, based on the value
869             of LOGOUT_RUNMODE or LOGOUT_URL If nothing is
870             configured, the page will redirect to the website homepage.
871              
872             =cut
873              
874             sub redirect_to_logout {
875 1     1 1 2 my $self = shift;
876 1         2 my $cgiapp = $self->_cgiapp;
877 1         3 my $config = $self->_config;
878 1         5 $self->logout();
879              
880 1 50       4 if ($config->{LOGOUT_RUNMODE}) {
    50          
881 0         0 $cgiapp->prerun_mode($config->{LOGOUT_RUNMODE});
882             } elsif ($config->{LOGOUT_URL}) {
883 0         0 $cgiapp->header_add(-location => $config->{LOGOUT_URL});
884 0         0 $cgiapp->header_type('redirect');
885 0         0 $cgiapp->prerun_mode('authen_dummy_redirect');
886             } else {
887 1         5 $cgiapp->header_add(-location => '/');
888 1         35 $cgiapp->header_type('redirect');
889 1         13 $cgiapp->prerun_mode('authen_dummy_redirect');
890             }
891             }
892              
893             =head2 setup_runmodes
894              
895             This method is called during the prerun stage to register some custom
896             runmodes that the Authentication plugin requires in order to function.
897             Calling this function, will not itself generate cookies or session ids.
898              
899             =cut
900              
901             sub setup_runmodes {
902 107     107 1 123 my $self = shift;
903 107         197 my $config = $self->_config;
904              
905             $self->_cgiapp->run_modes( authen_login => \&authen_login_runmode )
906 107 50 33     578 unless $config->{LOGIN_RUNMODE} || $config->{LOGIN_URL};
907             $self->_cgiapp->run_modes( authen_logout => \&authen_logout_runmode )
908 107 50 33     2006 unless $config->{LOGOUT_RUNMODE} || $config->{LOGOUT_URL};
909 107         1215 $self->_cgiapp->run_modes( authen_dummy_redirect => \&authen_dummy_redirect );
910 107         1150 return;
911             }
912              
913             =head2 last_login
914              
915             This will return return the time of the last login for this user
916              
917             my $last_login = $self->authen->last_login;
918              
919             This function will initiate a session or cookie if one has not been created already.
920              
921             =cut
922              
923             sub last_login {
924 5     5 1 10 my $self = shift;
925 5         10 my $new = shift;
926 5         12 $self->initialize;
927              
928 5 100       11 return unless $self->username;
929 3         11 my $old = $self->store->fetch('last_login');
930 3 50       19 $self->store->save('last_login' => $new) if $new;
931 3         26 return $old;
932             }
933              
934             =head2 last_access
935              
936             This will return return the time of the last access for this user
937              
938             my $last_access = $self->authen->last_access;
939              
940             This function will initiate a session or cookie if one has not been created already.
941              
942             =cut
943              
944             sub last_access {
945 9     9 1 16 my $self = shift;
946 9         12 my $new = shift;
947 9         22 $self->initialize;
948              
949 9 100       18 return unless $self->username;
950 4         12 my $old = $self->store->fetch('last_access');
951 4 100       24 $self->store->save('last_access' => $new) if $new;
952 4         36 return $old;
953             }
954              
955             =head2 is_login_timeout
956              
957             This will return true or false depending on whether the users login status just timed out
958              
959             $self->add_message('login session timed out') if $self->authen->is_login_timeout;
960              
961             This function will initiate a session or cookie if one has not been created already.
962              
963             =cut
964              
965             sub is_login_timeout {
966 5     5 1 6 my $self = shift;
967 5         14 $self->initialize;
968              
969 5 100       29 return $self->{is_login_timeout} ? 1 : 0;
970             }
971              
972             =head2 is_authenticated
973              
974             This will return true or false depending on the login status of this user
975              
976             assert($self->authen->is_authenticated); # The user should be logged in if we got here
977              
978             This function will initiate a session or cookie if one has not been created already.
979              
980             =cut
981              
982             sub is_authenticated {
983 157     157 1 173 my $self = shift;
984 157         274 $self->initialize;
985              
986 157 100       259 return $self->username ? 1 : 0;
987             }
988              
989             =head2 login_attempts
990              
991             This method will return the number of failed login attempts have been made by this
992             user since the last successful login. This is not a number that can be trusted,
993             as it is dependent on the underlying store to be able to return the correct value for
994             this user. For example, if the store uses a cookie based session, the user trying
995             to login could delete their cookies, and hence get a new session which will not have
996             any login attempts listed. The number will be cleared upon a successful login.
997             This function will initiate a session or cookie if one has not been created already.
998              
999             =cut
1000              
1001             sub login_attempts {
1002 89     89 1 115 my $self = shift;
1003 89         187 $self->initialize;
1004              
1005 89         201 my $la = $self->store->fetch('login_attempts');
1006 89         518 return $la;
1007             }
1008              
1009             =head2 username
1010              
1011             This will return the username of the currently logged in user, or undef if
1012             no user is currently logged in.
1013              
1014             my $username = $self->authen->username;
1015              
1016             This function will initiate a session or cookie if one has not been created already.
1017              
1018             =cut
1019              
1020             sub username {
1021 322     322 1 339 my $self = shift;
1022 322         509 $self->initialize;
1023              
1024 322         492 my $u = $self->store->fetch('username');
1025 320         2200 return $u;
1026             }
1027              
1028             =head2 is_new_login
1029              
1030             This will return true or false depending on if this is a fresh login
1031              
1032             $self->log->info("New Login") if $self->authen->is_new_login;
1033              
1034             This function will initiate a session or cookie if one has not been created already.
1035              
1036             =cut
1037              
1038             sub is_new_login {
1039 106     106 1 133 my $self = shift;
1040 106         205 $self->initialize;
1041              
1042 106         1248 return $self->{is_new_login};
1043             }
1044              
1045             =head2 credentials
1046              
1047             This method will return the names of the form parameters that will be
1048             looked for during a login. By default they are authen_username and authen_password,
1049             but these values can be changed by supplying the CREDENTIALS parameters in the
1050             configuration. Calling this function, will not itself generate cookies or session ids.
1051              
1052             =cut
1053              
1054             sub credentials {
1055 141     141 1 145 my $self = shift;
1056 141         249 my $config = $self->_config;
1057 141   100     721 return $config->{CREDENTIALS} || [qw(authen_username authen_password)];
1058             }
1059              
1060             =head2 logout
1061              
1062             This will attempt to logout the user. If during a request the Authentication
1063             module sees a parameter called 'authen_logout', it will automatically call this method
1064             to log out the user.
1065              
1066             $self->authen->logout();
1067              
1068             This function will initiate a session or cookie if one has not been created already.
1069              
1070             =cut
1071              
1072             sub logout {
1073 5     5 1 8 my $self = shift;
1074 5         10 $self->initialize;
1075              
1076 5         11 $self->store->clear;
1077             }
1078              
1079             =head2 drivers
1080              
1081             This method will return a list of driver objects that are used for
1082             verifying the login credentials. Calling this function, will not itself generate cookies or session ids.
1083              
1084             =cut
1085              
1086             sub drivers {
1087 90     90 1 161 my $self = shift;
1088              
1089 90 100       306 if ( !$self->{drivers} ) {
1090 82         153 my $config = $self->_config;
1091              
1092             # Fetch the configuration parameters for the driver(s)
1093 82 100       246 my $driver_configs = defined $config->{DRIVER} ? $config->{DRIVER} : [['Dummy']];
1094              
1095 82         166 foreach my $driver_config (@$driver_configs) {
1096 106         223 my ($drivername, @params) = @$driver_config;
1097             # add support for Authen::Simple modules
1098 106 100       308 if (index($drivername, 'Authen::Simple') == 0) {
1099 2         4 unshift @params, $drivername;
1100 2         3 $drivername = 'Authen::Simple';
1101             }
1102             # Load the the class for this driver
1103 106   100     324 my $driver_class = _find_deligate_class(
1104             'CGI::Application::Plugin::Authentication::Driver::' . $drivername,
1105             $drivername
1106             ) || die "Driver ".$drivername." can not be found";
1107              
1108             # Create the driver object
1109 105   100     3233 my $driver = $driver_class->new( $self, @params )
1110             || die "Could not create new $driver_class object";
1111 104         124 push @{$self->{drivers}}, $driver;
  104         376  
1112             }
1113             }
1114              
1115 88         119 my $drivers = $self->{drivers};
1116 88         305 return @$drivers[0..$#$drivers];
1117             }
1118              
1119             =head2 store
1120              
1121             This method will return a store object that is used to store information
1122             about the status of the authentication across multiple requests.
1123             This function will initiate a session or cookie if one has not been created already.
1124              
1125             =cut
1126              
1127             sub store {
1128 534     534 1 514 my $self = shift;
1129              
1130 534 100       1036 if ( !$self->{store} ) {
1131 115         180 my $config = $self->_config;
1132              
1133             # Fetch the configuration parameters for the store
1134 115         133 my ($store_module, @store_config);
1135 115 50 33     673 ($store_module, @store_config) = @{ $config->{STORE} } if $config->{STORE} && ref $config->{STORE} eq 'ARRAY';
  115         316  
1136 115 50       267 if (!$store_module) {
1137             # No STORE configuration was provided
1138 0 0 0     0 if ($self->_cgiapp->can('session') && UNIVERSAL::isa($self->_cgiapp->session, 'CGI::Session')) {
1139             # The user is already using the Session plugin
1140 0         0 ($store_module, @store_config) = ( 'Session' );
1141             } else {
1142             # Fall back to the Cookie Store
1143 0         0 ($store_module, @store_config) = ( 'Cookie' );
1144             }
1145             }
1146              
1147             # Load the the class for this store
1148 115   50     435 my $store_class = _find_deligate_class(
1149             'CGI::Application::Plugin::Authentication::Store::' . $store_module,
1150             $store_module
1151             ) || die "Store $store_module can not be found";
1152              
1153             # Create the store object
1154 115   50     4193 $self->{store} = $store_class->new( $self, @store_config )
1155             || die "Could not create new $store_class object";
1156             }
1157              
1158 533         1317 return $self->{store};
1159             }
1160              
1161             =head2 initialize
1162              
1163             This does most of the heavy lifting for the Authentication plugin. It will
1164             check to see if the user is currently attempting to login by looking for the
1165             credential form fields in the query object. It will load the required driver
1166             objects and authenticate the user. It is OK to call this method multiple times
1167             as it checks to see if it has already been executed and will just return
1168             without doing anything if called multiple times. This allows us to call
1169             initialize as late as possible in the request so that no unnecessary work is
1170             done.
1171              
1172             The user will be logged out by calling the C method if the login
1173             session has been idle for too long, if it has been too long since the last
1174             login, or if the login has timed out. If you need to know if a user was logged
1175             out because of a time out, you can call the C method.
1176              
1177             If all goes well, a true value will be returned, although it is usually not
1178             necessary to check.
1179              
1180             This function will initiate a session or cookie if one has not been created already.
1181              
1182             =cut
1183              
1184             sub initialize {
1185 814     814 1 731 my $self = shift;
1186 814 100       1553 return 1 if $self->{initialized};
1187              
1188             # It would seem to make more sense to do this at the /end/ of the routine
1189             # but that causes an infinite loop.
1190 116         222 $self->{initialized} = 1;
1191              
1192 116 50       275 if (UNIVERSAL::can($self->_cgiapp, 'devpopup')) {
1193 0         0 $self->_cgiapp->add_callback( 'devpopup_report', \&_devpopup_report );
1194             }
1195              
1196 116         231 my $config = $self->_config;
1197              
1198             # See if the user is trying to log in
1199             # We do this before checking to see if the user is already logged in, since
1200             # a logged in user may want to log in as a different user.
1201 116   100     531 my $field_names = $config->{CREDENTIALS} || [qw(authen_username authen_password)];
1202              
1203 116         229 my $query = $self->_cgiapp->query;
1204 116         986 my @credentials = map { scalar $query->param($_) } @$field_names;
  232         1941  
1205 116 100       1687 if ($credentials[0]) {
1206             # The user is trying to login
1207             # make sure if they are already logged in, that we log them out first
1208 71         178 my $store = $self->store;
1209 71 50       194 $store->clear if $store->fetch('username');
1210 71         424 foreach my $driver ($self->drivers) {
1211 91 100       296 if (my $username = $driver->verify_credentials(@credentials)) {
1212             # This user provided the correct credentials
1213             # so save this new login in the store
1214 31         15453 my $now = time();
1215 31         129 $store->save( username => $username, login_attempts => 0, last_login => $now, last_access => $now );
1216 31         293 $self->{is_new_login} = 1;
1217             # See if we are remembering the username for this user
1218 31   100     148 my $login_config = $config->{LOGIN_FORM} || {};
1219 31 0 50     90 if ($login_config->{REMEMBERUSER_OPTION} && scalar $query->param('authen_rememberuser')) {
1220             my $cookie = $query->cookie(
1221 0   0     0 -name => $login_config->{REMEMBERUSER_COOKIENAME} || 'CAPAUTHTOKEN',
1222             -value => $username,
1223             -expiry => '10y',
1224             );
1225 0         0 $self->_cgiapp->header_add(-cookie => [$cookie]);
1226             }
1227 31         64 last;
1228             }
1229             }
1230 63 100       213 unless ($self->username) {
1231             # password mismatch - increment failed login attempts
1232 32   100     75 my $attempts = $store->fetch('login_attempts') || 0;
1233 32         208 $store->save( login_attempts => $attempts + 1 );
1234             }
1235              
1236             $config->{POST_LOGIN_CALLBACK}->($self->_cgiapp)
1237 63 100       329 if($config->{POST_LOGIN_CALLBACK});
1238             }
1239              
1240             # Check the user name last of all because only this check might create a session behind the scenes.
1241             # In other words if a website works perfectly well without authentication,
1242             # then adding a protected run mode should not add session to the unprotected modes.
1243             # See 60_parsimony.t for the test.
1244 108 100 100     988 if ($config->{LOGIN_SESSION_TIMEOUT} && !$self->{is_new_login} && $self->username) {
      100        
1245             # This is not a fresh login, and there are time out rules, so make sure the login is still valid
1246 4 100 100     29 if ($config->{LOGIN_SESSION_TIMEOUT}->{IDLE_FOR} && time() - $self->last_access >= $config->{LOGIN_SESSION_TIMEOUT}->{IDLE_FOR}) {
    100 100        
    100 66        
1247             # this login has been idle for too long
1248 1         2 $self->{is_login_timeout} = 1;
1249 1         4 $self->logout;
1250             } elsif ($config->{LOGIN_SESSION_TIMEOUT}->{EVERY} && time() - $self->last_login >= $config->{LOGIN_SESSION_TIMEOUT}->{EVERY}) {
1251             # it has been too long since the last login
1252 1         3 $self->{is_login_timeout} = 1;
1253 1         3 $self->logout;
1254             } elsif ($config->{LOGIN_SESSION_TIMEOUT}->{CUSTOM} && $config->{LOGIN_SESSION_TIMEOUT}->{CUSTOM}->($self)) {
1255             # this login has timed out
1256 1         6 $self->{is_login_timeout} = 1;
1257 1         2 $self->logout;
1258             }
1259             }
1260 108         243 return 1;
1261              
1262             }
1263              
1264             =head2 display
1265              
1266             This method will return the
1267             L object, creating
1268             and caching it if necessary.
1269              
1270             =cut
1271              
1272             sub display {
1273 142     142 1 89726 my $self = shift;
1274 142 100       567 return $self->{display} if $self->{display};
1275 66   100     117 my $config = $self->_config->{LOGIN_FORM} || {};
1276             my $class = "CGI::Application::Plugin::Authentication::Display::".
1277 66   100     294 ($config->{DISPLAY_CLASS} || 'Classic');
1278 66         458 $class->require;
1279 66         2005 $self->{display} = $class->new($self->_cgiapp);
1280 66         290 return $self->{display};
1281             }
1282              
1283             =head2 login_box
1284              
1285             This method will return the HTML for a login box that can be
1286             embedded into another page. This is the same login box that is used
1287             in the default authen_login runmode that the plugin provides.
1288              
1289             This function will initiate a session or cookie if one has not been created already.
1290              
1291             =cut
1292              
1293             sub login_box {
1294 12     12 1 16 my $self = shift;
1295 12         38 return $self->display->login_box;
1296             }
1297              
1298             =head2 new
1299              
1300             This method creates a new CGI::Application::Plugin::Authentication object. It requires
1301             as it's only parameter a CGI::Application object. This method should never be called
1302             directly, since the 'authen' method that is imported into the CGI::Application module
1303             will take care of creating the CGI::Application::Plugin::Authentication object when it
1304             is required. Calling this function, will not itself generate cookies or session ids.
1305              
1306             =cut
1307              
1308             sub new {
1309 176     176 1 223 my $class = shift;
1310 176         188 my $cgiapp = shift;
1311 176         238 my $self = {};
1312              
1313 176         274 bless $self, $class;
1314 176         1183 $self->{cgiapp} = $cgiapp;
1315 176         563 Scalar::Util::weaken($self->{cgiapp}); # weaken circular reference
1316              
1317 176         332 return $self;
1318             }
1319              
1320             =head2 instance
1321              
1322             This method works the same way as 'new', except that it returns the same Authentication
1323             object for the duration of the request. This method should never be called
1324             directly, since the 'authen' method that is imported into the CGI::Application module
1325             will take care of creating the CGI::Application::Plugin::Authentication object when it
1326             is required. Calling this function, will not itself generate cookies or session ids.
1327              
1328             =cut
1329              
1330             sub instance {
1331 1522     1522 1 2500 my $class = shift;
1332 1522         1165 my $cgiapp = shift;
1333 1522 100 100     7440 die "CGI::Application::Plugin::Authentication->instance must be called with a CGI::Application object"
1334             unless defined $cgiapp && UNIVERSAL::isa( $cgiapp, 'CGI::Application' );
1335              
1336 1520 100       3438 $cgiapp->{__CAP_AUTHENTICATION_INSTANCE} = $class->new($cgiapp) unless defined $cgiapp->{__CAP_AUTHENTICATION_INSTANCE};
1337 1520         4212 return $cgiapp->{__CAP_AUTHENTICATION_INSTANCE};
1338             }
1339              
1340              
1341             =head1 CGI::Application CALLBACKS
1342              
1343             =head2 prerun_callback
1344              
1345             This method is a CGI::Application prerun callback that will be
1346             automatically registered for you if you are using CGI::Application
1347             4.0 or greater. If you are using an older version of CGI::Application
1348             you will have to create your own cgiapp_prerun method and make sure you
1349             call this method from there.
1350              
1351             sub cgiapp_prerun {
1352             my $self = shift;
1353              
1354             $self->CGI::Application::Plugin::Authentication::prerun_callback();
1355             }
1356              
1357             =cut
1358              
1359             sub prerun_callback {
1360 115     115 1 12026 my $self = shift;
1361 115         244 my $authen = $self->authen;
1362              
1363 115         289 $authen->initialize;
1364              
1365             # setup the default login and logout runmodes
1366 107         266 $authen->setup_runmodes;
1367              
1368             # The user is asking to be logged out
1369 107 100       264 if (scalar $self->query->param('authen_logout')) {
1370             # The user wants to logout
1371 1         23 return $self->authen->redirect_to_logout;
1372             }
1373              
1374             # If the user just logged in then we may want to redirect them
1375 106 100       2073 if ($authen->is_new_login) {
1376             # User just logged in, so where to we send them?
1377 30         83 return $self->authen->redirect_after_login;
1378             }
1379              
1380             # Update any time out info
1381 76         139 my $config = $authen->_config;
1382 76 100       213 if ( $config->{LOGIN_SESSION_TIMEOUT} ) {
1383             # update the last access time
1384 4         8 my $now = time;
1385 4         8 $authen->last_access($now);
1386             }
1387              
1388             # If a perun mode is set check against that.
1389             # This allows cooperation with plugins such as CAP::ActionDispatch
1390             # that also have preun hooks.
1391             # Note the comments in the CGI::Application docs on the ordering of
1392             # callback execution.
1393 76         306 my $run_mode = $self->prerun_mode;
1394 76   33     863 $run_mode ||= $self->get_current_runmode;
1395            
1396 76 100       459 if ( $authen->is_protected_runmode( $run_mode ) ) {
1397             # This runmode requires authentication
1398 65 100       168 unless ($authen->is_authenticated) {
1399             # This user is NOT logged in
1400 63         211 return $self->authen->redirect_to_login;
1401             }
1402             }
1403             }
1404              
1405             =head1 CGI::Application RUNMODES
1406              
1407             =head2 authen_login_runmode
1408              
1409             This runmode is provided if you do not want to create your
1410             own login runmode. It will display a simple login form for the user, which
1411             can be replaced by assigning RENDER_LOGIN a coderef that returns the HTML.
1412              
1413             =cut
1414              
1415             sub authen_login_runmode {
1416 63     63 1 3463 my $self = shift;
1417 63         128 my $authen = $self->authen;
1418              
1419 63         156 my $credentials = $authen->credentials;
1420 63         107 my $username = $credentials->[0];
1421 63         90 my $password = $credentials->[1];
1422              
1423 63         61 my $html;
1424 63 50       111 if ( my $sub = $authen->_config->{RENDER_LOGIN} ) {
1425 0         0 $html = $sub->($self);
1426             }
1427             else {
1428 63         229 $html = join( "\n",
1429             CGI::start_html( -title => $authen->display->login_title ),
1430             $authen->display->login_box,
1431             CGI::end_html(),
1432             );
1433             }
1434              
1435 63         813 return $html;
1436             }
1437              
1438             =head2 authen_dummy_redirect
1439              
1440             This runmode is provided for convenience when an external redirect needs
1441             to be done. It just returns an empty string.
1442              
1443             =cut
1444              
1445             sub authen_dummy_redirect {
1446 3     3 1 164 return '';
1447             }
1448              
1449             ###
1450             ### Detainting helper methods
1451             ###
1452              
1453             sub _detaint_destination {
1454 117     117   130 my $self = shift;
1455 117         235 my $query = $self->_cgiapp->query;
1456 117         913 my $destination = scalar $query->param('destination');
1457 117         1727 my $regexp = $self->_config->{DETAINT_URL_REGEXP};
1458 117 100 100     649 if ($destination && $destination =~ /$regexp/) {
1459 4         12 $destination = $1;
1460             }
1461             else {
1462 113         130 $destination = "";
1463             }
1464 117         627 return $destination;
1465             }
1466              
1467             sub _detaint_selfurl {
1468 89     89   119 my $self = shift;
1469 89         158 my $query = $self->_cgiapp->query;
1470 89         499 my $destination = "";
1471 89         147 my $regexp = $self->_config->{DETAINT_URL_REGEXP};
1472 89 100       281 if ($query->self_url =~ /$regexp/) {
1473 87         36059 $destination = $1;
1474             }
1475 89         1247 return $destination;
1476             }
1477              
1478             sub _detaint_url {
1479 89     89   112 my $self = shift;
1480 89         174 my $query = $self->_cgiapp->query;
1481 89         580 my $regexp = $self->_config->{DETAINT_URL_REGEXP};
1482 89         111 my $url = "";
1483 89 50       370 if ($query->url( -absolute => 1, -path_info => 1 ) =~ /$regexp/) {
1484 0         0 $url = $1;
1485             }
1486 89         11621 return $url;
1487             }
1488              
1489             sub _detaint_username {
1490 74     74   93 my $self = shift;
1491 74         86 my $username = shift;
1492 74         77 my $cookiename = shift;
1493 74         124 my $query = $self->_cgiapp->query;
1494 74         455 my $regexp = $self->_config->{DETAINT_USERNAME_REGEXP};
1495 74         92 my $username_value = "";
1496 74 100 100     181 if ((scalar $query->param($username) || $query->cookie($cookiename) || '') =~ /$regexp/) {
1497 41         1184 $username_value = $1;
1498             }
1499 74         14015 return $username_value;
1500             }
1501            
1502             ###
1503             ### Helper methods
1504             ###
1505              
1506             sub _cgiapp {
1507 1191     1191   4078 return $_[0]->{cgiapp};
1508             }
1509              
1510             sub _find_deligate_class {
1511 221     221   345 foreach my $class (@_) {
1512 280 100       2149 $class->require && return $class;
1513             }
1514 1         20 return;
1515             }
1516              
1517             sub _config {
1518 1782     1782   1581 my $self = shift;
1519 1782 100       2823 my $class = ref $self ? ref $self : $self;
1520 1782         1302 my $config;
1521 1782 100       2174 if ( ref $self ) {
1522 1760   100     3952 $config = $self->{__CAP_AUTHENTICATION_CONFIG} ||= $__CONFIG{$class} || {};
      66        
1523             } else {
1524 22   100     156 $__CONFIG{$class} ||= {};
1525 22         37 $config = $__CONFIG{$class};
1526             }
1527 1782         3346 return $config;
1528             }
1529              
1530             sub _devpopup_report {
1531 0     0   0 my $cgiapp = shift;
1532 0         0 my @list;
1533 0         0 my $self=$cgiapp->authen;
1534 0 0       0 if ($self->username) {
1535 0         0 push @list,['username',$self->username];
1536             }
1537 0         0 my $config = $self->_config;
1538 0   0     0 my $field_names = $config->{CREDENTIALS} || [qw(authen_username authen_password)];
1539 0         0 my $query = $cgiapp->query;
1540 0         0 foreach my $name (@$field_names) {
1541 0   0     0 push @list, [ $name, scalar $query->param($name) || ''];
1542             }
1543 0         0 my $r=0;
1544             my $text = join $/, map {
1545 0         0 $r=1-$r;
  0         0  
1546 0 0       0 qq(
$_->[0]$_->[1]
  0         0  
1547             }
1548             @list;
1549 0         0 $cgiapp->devpopup->add_report(
1550             title => 'Authentication',
1551             summary => '',
1552             report => qq(
1553            
1556            
1557             $text
1558            
ParameterValue
1559            
1560            
1561            
1562             ),
1563             );
1564             }
1565              
1566             ###
1567             ### Helper functions
1568             ###
1569              
1570             sub _time_to_seconds {
1571 32     32   639 my $time = shift;
1572 32 50       58 return unless defined $time;
1573              
1574             # Most of this function is borrowed from CGI::Util v1.4 by Lincoln Stein
1575 32         134 my (%mult) = (
1576             's' => 1,
1577             'm' => 60,
1578             'h' => 60 * 60,
1579             'd' => 60 * 60 * 24,
1580             'w' => 60 * 60 * 24 * 7,
1581             'M' => 60 * 60 * 24 * 30,
1582             'y' => 60 * 60 * 24 * 365
1583             );
1584             # format for time can be in any of the forms...
1585             # "180" -- in 180 seconds
1586             # "180s" -- in 180 seconds
1587             # "2m" -- in 2 minutes
1588             # "12h" -- in 12 hours
1589             # "1d" -- in 1 day
1590             # "4w" -- in 4 weeks
1591             # "3M" -- in 3 months
1592             # "2y" -- in 2 years
1593 32         25 my $offset;
1594 32 100       204 if ( $time =~ /^([+-]?(?:\d+|\d*\.\d*))([smhdwMy]?)$/ ) {
1595 29 100 100     195 return if (!$2 || $2 eq 's') && $1 != int $1; #
      100        
1596 28   100     117 $offset = int ( ( $mult{$2} || 1 ) * $1 );
1597             }
1598 31         117 return $offset;
1599             }
1600              
1601              
1602             =head1 EXAMPLE
1603              
1604             In a CGI::Application module:
1605              
1606             use base qw(CGI::Application);
1607             use CGI::Application::Plugin::AutoRunmode;
1608             use CGI::Application::Plugin::Session;
1609             use CGI::Application::Plugin::Authentication;
1610              
1611             __PACKAGE__->authen->config(
1612             DRIVER => [ 'Generic', { user1 => '123' } ],
1613             STORE => 'Session',
1614             LOGOUT_RUNMODE => 'start',
1615             );
1616             __PACKAGE__->authen->protected_runmodes(qr/^auth_/, 'one');
1617              
1618             sub start : RunMode {
1619             my $self = shift;
1620              
1621             }
1622              
1623             sub one : RunMode {
1624             my $self = shift;
1625              
1626             # The user will only get here if they are logged in
1627             }
1628              
1629             sub auth_two : RunMode {
1630             my $self = shift;
1631              
1632             # This is also protected because of the
1633             # regexp call to protected_runmodes above
1634             }
1635              
1636             =head1 COMPATIBILITY WITH L
1637              
1638             The prerun callback has been modified so that it will check for the presence of a prerun mode.
1639             This is for compatibility with L. This
1640             change should be considered experimental. It is necessary to load the ActionDispatch
1641             module so that the two prerun callbacks will be called in the correct order.
1642              
1643             =head1 RECOMMENDED USAGE
1644              
1645             =over
1646              
1647             =item CSS
1648              
1649             The best practice nowadays is generally considered to be to not have CSS
1650             embedded in HTML. Thus it should be best to set LOGIN_FORM -> DISPLAY_CLASS to
1651             'Basic'.
1652              
1653             =item Post login destination
1654              
1655             Of the various means of selecting a post login destination the most secure would
1656             seem to be POST_LOGIN_URL. The C parameter could potentially be hijacked by hackers.
1657             The POST_LOGIN_RUNMODE parameter requires a hidden parameter that could potentially
1658             be hijacked.
1659              
1660             =item Taint mode
1661              
1662             Do run your code under taint mode. It should help protect your application
1663             against a number of attacks.
1664              
1665             =item URL and username checking
1666              
1667             Please set the C and C parameters
1668             as tightly as possible. In particular you should prevent the destination parameter
1669             being used to redirect authenticated users to external sites; unless of course that
1670             is what you want in which case that site should be the only possible external site.
1671              
1672             =item The login form
1673              
1674             The HTML currently generated does not seem to be standards compliant as per
1675             RT bug 58023. Also the default login form includes hidden forms which could
1676             conceivably be hijacked.
1677             Set LOGIN_FORM -> DISPLAY_CLASS to 'Basic' to fix this.
1678              
1679             =back
1680              
1681             =head1 TODO
1682              
1683             There are lots of things that can still be done to improve this plugin. If anyone else is interested
1684             in helping out feel free to dig right in. Many of these things don't need my input, but if you want
1685             to avoid duplicated efforts, send me a note, and I'll let you know of anyone else is working in the same area.
1686              
1687             =over 4
1688              
1689             =item review the code for security bugs and report
1690              
1691             =item complete the separation of presentation and logic
1692              
1693             =item write a tutorial
1694              
1695             =item build more Drivers (Class::DBI, LDAP, Radius, etc...)
1696              
1697             =item Add support for method attributes to identify runmodes that require authentication
1698              
1699             =item finish the test suite
1700              
1701             =item provide more example code
1702              
1703             =item clean up the documentation
1704              
1705             =item build a DB driver that builds it's own table structure. This can be used by people that don't have their own user database to work with, and could include a simple user management application.
1706              
1707              
1708             =back
1709              
1710             =head1 BUGS
1711              
1712             This is alpha software and as such, the features and interface
1713             are subject to change. So please check the Changes file when upgrading.
1714              
1715             Some of the test scripts appear to be incompatible with versions of
1716             L later than 0.65.
1717              
1718             =head1 SEE ALSO
1719              
1720             L, perl(1)
1721              
1722              
1723             =head1 AUTHOR
1724              
1725             Author: Cees Hek ; Co-maintainer: Nicholas Bamber .
1726              
1727             =head1 CREDITS
1728              
1729             Thanks to L for funding the
1730             development of this plugin and for releasing it to the world.
1731              
1732             Thanks to Christian Walde for suggesting changes to fix the incompatibility with
1733             L and for help with github.
1734              
1735             Thanks to Alexandr Ciornii for pointing out some typos.
1736              
1737             =head1 LICENCE AND COPYRIGHT
1738              
1739             Copyright (c) 2005, SiteSuite. All rights reserved.
1740             Copyright (c) 2010, Nicholas Bamber. (Portions of the code).
1741              
1742             This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
1743              
1744             The background images in the default login forms are used courtesy of
1745             L. Those icons
1746             are issued under the
1747             L.
1748             Those icons are copyrighted 2006 by Mark James
1749              
1750             =head1 DISCLAIMER OF WARRANTY
1751              
1752             BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION.
1753              
1754             IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
1755              
1756             =cut
1757              
1758             1;