File Coverage

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


)
line stmt bran cond sub pod time code
1             package CGI::Application::Plugin::Authentication;
2             $CGI::Application::Plugin::Authentication::VERSION = '0.23';
3 31     31   2564023 use 5.006;
  31         356  
4 31     31   150 use strict;
  31         64  
  31         925  
5              
6             our %__CONFIG;
7              
8 31     31   517 use Class::ISA ();
  31         1851  
  31         454  
9 31     31   149 use Scalar::Util ();
  31         51  
  31         525  
10 31     31   10686 use UNIVERSAL::require;
  31         29248  
  31         243  
11 31     31   704 use Carp;
  31         53  
  31         1270  
12 31     31   11491 use CGI ();
  31         390681  
  31         629  
13 31     31   20089 use overload;
  31         17634  
  31         191  
14              
15             sub import {
16 33     33   8945 my $pkg = shift;
17 33         100 my $callpkg = caller;
18             {
19 31     31   2172 no strict qw(refs);
  31         64  
  31         3082  
  33         362  
20 33         83 *{$callpkg.'::authen'} = \&CGI::Application::Plugin::_::Authentication::authen;
  33         228  
21             }
22 33 100       203 if ( ! UNIVERSAL::isa($callpkg, 'CGI::Application') ) {
23 2         34 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         199 $callpkg->add_callback( prerun => \&prerun_callback );
26             }
27             }
28              
29 31     31   12918 use Attribute::Handlers;
  31         119651  
  31         141  
30             my %RUNMODES;
31              
32             sub CGI::Application::RequireAuthentication : ATTR(CODE) {
33 1     1 0 1494 my ( $package, $symbol, $referent, $attr, $data, $phase ) = @_;
34 1   50     8 $RUNMODES{$referent} = $data || 1;
35 31     31   2170 }
  31         58  
  31         114  
36             sub CGI::Application::Authen : ATTR(CODE) {
37 1     1 0 255 my ( $package, $symbol, $referent, $attr, $data, $phase ) = @_;
38 1   50     7 $RUNMODES{$referent} = $data || 1;
39 31     31   15766 }
  31         77  
  31         128  
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 1589     1589   2755083 my $cgiapp = shift;
173              
174 1589 100       3481 if (ref($cgiapp)) {
175 1566         3605 return CGI::Application::Plugin::Authentication->instance($cgiapp);
176             } else {
177 23         261 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 213 my $self = shift;
547 118 100       312 my $class = ref $self ? ref $self : $self;
548              
549             die "Calling config after the Authentication object has already been initialized"
550 118 100 100     448 if ref $self && defined $self->{initialized};
551 117         259 my $config = $self->_config;
552              
553 117 100       310 if (@_) {
554 116         187 my $props;
555 116 100       279 if ( ref( $_[0] ) eq 'HASH' ) {
556 46         65 my $rthash = %{ $_[0] };
  46         107  
557 46         196 $props = CGI::Application->_cap_hash( $_[0] );
558             } else {
559 70         300 $props = CGI::Application->_cap_hash( {@_} );
560             }
561              
562             # Check for DRIVER
563 116 100       2661 if ( defined $props->{DRIVER} ) {
564             croak "authen config error: parameter DRIVER is not a string or arrayref"
565 72 100 100     494 if ref $props->{DRIVER} && Scalar::Util::reftype( $props->{DRIVER} ) ne 'ARRAY';
566 71         208 $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   20932 no warnings qw(uninitialized);
  31         68  
  31         3417  
571 71 100       285 $config->{DRIVER} = [ $config->{DRIVER} ] if Scalar::Util::reftype( $config->{DRIVER} ) ne 'ARRAY';
572 71 100       331 $config->{DRIVER} = [ $config->{DRIVER} ] if Scalar::Util::reftype( $config->{DRIVER}->[0] ) ne 'ARRAY';
573             }
574              
575             # Check for STORE
576 115 100       305 if ( defined $props->{STORE} ) {
577             croak "authen config error: parameter STORE is not a string or arrayref"
578 74 100 100     410 if ref $props->{STORE} && Scalar::Util::reftype( $props->{STORE} ) ne 'ARRAY';
579 73         151 $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   195 no warnings qw(uninitialized);
  31         71  
  31         6582  
583 73 100       274 $config->{STORE} = [ $config->{STORE} ] if Scalar::Util::reftype( $config->{STORE} ) ne 'ARRAY';
584             }
585              
586             # Check for POST_LOGIN_RUNMODE
587 114 100       275 if ( defined $props->{POST_LOGIN_RUNMODE} ) {
588             croak "authen config error: parameter POST_LOGIN_RUNMODE is not a string"
589 6 100       51 if ref $props->{POST_LOGIN_RUNMODE};
590 5         14 $config->{POST_LOGIN_RUNMODE} = delete $props->{POST_LOGIN_RUNMODE};
591             }
592              
593             # Check for POST_LOGIN_URL
594 113 100       247 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       54 if $config->{POST_LOGIN_RUNMODE};
597             croak "authen config error: parameter POST_LOGIN_URL is not a string"
598 9 100       966 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       262 if ( defined $props->{LOGIN_RUNMODE} ) {
604             croak "authen config error: parameter LOGIN_RUNMODE is not a string"
605 4 100       16 if ref $props->{LOGIN_RUNMODE};
606 3         6 $config->{LOGIN_RUNMODE} = delete $props->{LOGIN_RUNMODE};
607             }
608              
609             # Check for LOGIN_URL
610 111 100       257 if ( defined $props->{LOGIN_URL} ) {
611             carp "authen config warning: parameter LOGIN_URL ignored since we already have LOGIN_RUNMODE"
612 7 100       26 if $config->{LOGIN_RUNMODE};
613             croak "authen config error: parameter LOGIN_URL is not a string"
614 7 100       466 if ref $props->{LOGIN_URL};
615 6         13 $config->{LOGIN_URL} = delete $props->{LOGIN_URL};
616             }
617              
618             # Check for LOGOUT_RUNMODE
619 110 100       284 if ( defined $props->{LOGOUT_RUNMODE} ) {
620             croak "authen config error: parameter LOGOUT_RUNMODE is not a string"
621 4 100       15 if ref $props->{LOGOUT_RUNMODE};
622 3         7 $config->{LOGOUT_RUNMODE} = delete $props->{LOGOUT_RUNMODE};
623             }
624              
625             # Check for LOGOUT_URL
626 109 100       271 if ( defined $props->{LOGOUT_URL} ) {
627             carp "authen config warning: parameter LOGOUT_URL ignored since we already have LOGOUT_RUNMODE"
628 7 100       25 if $config->{LOGOUT_RUNMODE};
629             croak "authen config error: parameter LOGOUT_URL is not a string"
630 7 100       461 if ref $props->{LOGOUT_URL};
631 6         9 $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     100 if ref $props->{CREDENTIALS} && Scalar::Util::reftype( $props->{CREDENTIALS} ) ne 'ARRAY';
638 16         43 $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   194 no warnings qw(uninitialized);
  31         63  
  31         99561  
641 16 100       93 $config->{CREDENTIALS} = [ $config->{CREDENTIALS} ] if Scalar::Util::reftype( $config->{CREDENTIALS} ) ne 'ARRAY';
642             }
643              
644             # Check for LOGIN_SESSION_TIMEOUT
645 107 100       250 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     110 if ref $props->{LOGIN_SESSION_TIMEOUT} && ref$props->{LOGIN_SESSION_TIMEOUT} ne 'HASH';
648 19         30 my $options = {};
649 19 100       46 if (! ref $props->{LOGIN_SESSION_TIMEOUT}) {
650 7         17 $options->{IDLE_FOR} = _time_to_seconds( $props->{LOGIN_SESSION_TIMEOUT} );
651 7 100       26 croak "authen config error: parameter LOGIN_SESSION_TIMEOUT is not a valid time string" unless defined $options->{IDLE_FOR};
652             } else {
653 12 100       30 if ($props->{LOGIN_SESSION_TIMEOUT}->{IDLE_FOR}) {
654 5         17 $options->{IDLE_FOR} = _time_to_seconds( delete $props->{LOGIN_SESSION_TIMEOUT}->{IDLE_FOR} );
655 5 100       21 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       28 if ($props->{LOGIN_SESSION_TIMEOUT}->{EVERY}) {
658 5         17 $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       23 if ($props->{LOGIN_SESSION_TIMEOUT}->{CUSTOM}) {
662 5         12 $options->{CUSTOM} = delete $props->{LOGIN_SESSION_TIMEOUT}->{CUSTOM};
663 5 100       30 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       14 croak "authen config error: Invalid option(s) (" . join( ', ', keys %{$props->{LOGIN_SESSION_TIMEOUT}} ) . ") passed to LOGIN_SESSION_TIMEOUT" if %{$props->{LOGIN_SESSION_TIMEOUT}};
  1         16  
  9         24  
666             }
667              
668 14         40 $config->{LOGIN_SESSION_TIMEOUT} = $options;
669 14         29 delete $props->{LOGIN_SESSION_TIMEOUT};
670             }
671              
672             # Check for POST_LOGIN_CALLBACK
673 101 100       239 if ( defined $props->{POST_LOGIN_CALLBACK} ) {
674             croak "authen config error: parameter POST_LOGIN_CALLBACK is not a coderef"
675 33 100       128 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       249 if ( defined $props->{RENDER_LOGIN} ) {
681             croak "authen config error: parameter RENDER_LOGIN is not a coderef"
682 3 100       23 unless( ref $props->{RENDER_LOGIN} eq 'CODE' );
683 1         2 $config->{RENDER_LOGIN} = delete $props->{RENDER_LOGIN};
684             }
685              
686             # Check for LOGIN_FORM
687 97 100       226 if ( defined $props->{LOGIN_FORM} ) {
688             croak "authen config error: parameter LOGIN_FORM is not a hashref"
689 26 100       112 unless( ref $props->{LOGIN_FORM} eq 'HASH' );
690 25         56 $config->{LOGIN_FORM} = delete $props->{LOGIN_FORM};
691             }
692              
693             # Check for DETAINT_URL_REGEXP
694 96 100       222 if ( defined $props->{DETAINT_URL_REGEXP} ) {
695 3         7 $config->{DETAINT_URL_REGEXP} = delete $props->{DETAINT_URL_REGEXP};
696             }
697             else {
698 93         198 $config->{DETAINT_URL_REGEXP} = '^([\w\_\%\?\&\;\-\/\@\.\+\$\=\#\:\!\*\"\'\(\)\,]+)$';
699             }
700              
701             # Check for DETAINT_USERNAME_REGEXP
702 96 100       246 if ( defined $props->{DETAINT_USERNAME_REGEXP} ) {
703 2         6 $config->{DETAINT_USERNAME_REGEXP} = delete $props->{DETAINT_USERNAME_REGEXP};
704             }
705             else {
706 94         203 $config->{DETAINT_USERNAME_REGEXP} = '^([\w\_]+)$';
707             }
708              
709             # If there are still entries left in $props then they are invalid
710 96 100       507 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 228     228 1 352 my $self = shift;
746 228         474 my $config = $self->_config;
747              
748 228   100     709 $config->{PROTECTED_RUNMODES} ||= [];
749 228 100       578 push @{$config->{PROTECTED_RUNMODES}}, @_ if @_;
  133         342  
750              
751 228         316 return @{$config->{PROTECTED_RUNMODES}};
  228         628  
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 90     90 1 161 my $self = shift;
764 90         142 my $runmode = shift;
765              
766 90         207 foreach my $runmode_test ($self->protected_runmodes) {
767 134 100 66     425 if (overload::StrVal($runmode_test) =~ /^Regexp=/) {
    100          
    100          
768             # We were passed a regular expression
769 9 100       85 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       52 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 116 100       1050 return 1 if $runmode eq $runmode_test;
779             }
780             }
781              
782             # See if the user is using attributes
783 19         102 my $sub = $self->_cgiapp->can($runmode);
784 19 100 100     163 return 1 if $sub && $RUNMODES{$sub};
785              
786 17         87 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 31     31 1 56 my $self = shift;
820 31         72 my $cgiapp = $self->_cgiapp;
821 31         79 my $config = $self->_config;
822              
823 31 100       150 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         6 $cgiapp->header_add(-location => $config->{POST_LOGIN_URL});
827 1         41 $cgiapp->header_type('redirect');
828 1         18 $cgiapp->prerun_mode('authen_dummy_redirect');
829             } elsif (my $destination = $cgiapp->authen->_detaint_destination()) {
830 1         11 $cgiapp->header_add(-location => $destination);
831 1         59 $cgiapp->header_type('redirect');
832 1         22 $cgiapp->prerun_mode('authen_dummy_redirect');
833             }
834 31         119 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 66     66 1 123 my $self = shift;
850 66         203 my $cgiapp = $self->_cgiapp;
851 66         181 my $config = $self->_config;
852              
853 66 50       223 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 66         190 $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 3 my $self = shift;
876 1         3 my $cgiapp = $self->_cgiapp;
877 1         2 my $config = $self->_config;
878 1         4 $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         41 $cgiapp->header_type('redirect');
889 1         18 $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 110     110 1 178 my $self = shift;
903 110         279 my $config = $self->_config;
904              
905             $self->_cgiapp->run_modes( authen_login => \&authen_login_runmode )
906 110 50 33     574 unless $config->{LOGIN_RUNMODE} || $config->{LOGIN_URL};
907             $self->_cgiapp->run_modes( authen_logout => \&authen_logout_runmode )
908 110 50 33     2281 unless $config->{LOGOUT_RUNMODE} || $config->{LOGOUT_URL};
909 110         1515 $self->_cgiapp->run_modes( authen_dummy_redirect => \&authen_dummy_redirect );
910 110         1431 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 11 my $self = shift;
925 5         11 my $new = shift;
926 5         14 $self->initialize;
927              
928 5 100       14 return unless $self->username;
929 3         9 my $old = $self->store->fetch('last_login');
930 3 50       19 $self->store->save('last_login' => $new) if $new;
931 3         20 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 31 my $self = shift;
946 9         16 my $new = shift;
947 9         27 $self->initialize;
948              
949 9 100       21 return unless $self->username;
950 4         10 my $old = $self->store->fetch('last_access');
951 4 100       24 $self->store->save('last_access' => $new) if $new;
952 4         29 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 11 my $self = shift;
967 5         15 $self->initialize;
968              
969 5 100       25 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 162     162 1 272 my $self = shift;
984 162         415 $self->initialize;
985              
986 162 100       338 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 92     92 1 166 my $self = shift;
1003 92         255 $self->initialize;
1004              
1005 92         236 my $la = $self->store->fetch('login_attempts');
1006 92         1830 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 331     331 1 595 my $self = shift;
1022 331         802 $self->initialize;
1023              
1024 331         682 my $u = $self->store->fetch('username');
1025 330         2267 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 109     109 1 233 my $self = shift;
1040 109         254 $self->initialize;
1041              
1042 109         276 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 147     147 1 244 my $self = shift;
1056 147         342 my $config = $self->_config;
1057 147   100     675 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 11 my $self = shift;
1074 5         15 $self->initialize;
1075              
1076 5         14 $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 93     93 1 154 my $self = shift;
1088              
1089 93 100       233 if ( !$self->{drivers} ) {
1090 85         203 my $config = $self->_config;
1091              
1092             # Fetch the configuration parameters for the driver(s)
1093 85 100       259 my $driver_configs = defined $config->{DRIVER} ? $config->{DRIVER} : [['Dummy']];
1094              
1095 85         188 foreach my $driver_config (@$driver_configs) {
1096 109         274 my ($drivername, @params) = @$driver_config;
1097             # add support for Authen::Simple modules
1098 109 100       322 if (index($drivername, 'Authen::Simple') == 0) {
1099 2         5 unshift @params, $drivername;
1100 2         4 $drivername = 'Authen::Simple';
1101             }
1102             # Load the the class for this driver
1103 109   100     351 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 108   100     3320 my $driver = $driver_class->new( $self, @params )
1110             || die "Could not create new $driver_class object";
1111 107         231 push @{$self->{drivers}}, $driver;
  107         372  
1112             }
1113             }
1114              
1115 91         175 my $drivers = $self->{drivers};
1116 91         297 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 549     549 1 817 my $self = shift;
1129              
1130 549 100       1221 if ( !$self->{store} ) {
1131 118         243 my $config = $self->_config;
1132              
1133             # Fetch the configuration parameters for the store
1134 118         229 my ($store_module, @store_config);
1135 118 50 33     654 ($store_module, @store_config) = @{ $config->{STORE} } if $config->{STORE} && ref $config->{STORE} eq 'ARRAY';
  118         372  
1136 118 50       312 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 118   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 118   50     4594 $self->{store} = $store_class->new( $self, @store_config )
1155             || die "Could not create new $store_class object";
1156             }
1157              
1158 548         1551 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 837     837 1 1179 my $self = shift;
1186 837 100       1837 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 119         238 $self->{initialized} = 1;
1191              
1192 119 50       316 if (UNIVERSAL::can($self->_cgiapp, 'devpopup')) {
1193 0         0 $self->_cgiapp->add_callback( 'devpopup_report', \&_devpopup_report );
1194             }
1195              
1196 119         313 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 119   100     496 my $field_names = $config->{CREDENTIALS} || [qw(authen_username authen_password)];
1202              
1203 119         300 my $query = $self->_cgiapp->query;
1204 119         1321 my @credentials = map { scalar $query->param($_) } @$field_names;
  238         2430  
1205 119 100       2014 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 74         187 my $store = $self->store;
1209 74 50       254 $store->clear if $store->fetch('username');
1210 74         461 foreach my $driver ($self->drivers) {
1211 94 100       291 if (my $username = $driver->verify_credentials(@credentials)) {
1212             # This user provided the correct credentials
1213             # so save this new login in the store
1214 32         18240 my $now = time();
1215 32         140 $store->save( username => $username, login_attempts => 0, last_login => $now, last_access => $now );
1216 32         312 $self->{is_new_login} = 1;
1217             # See if we are remembering the username for this user
1218 32   100     256 my $login_config = $config->{LOGIN_FORM} || {};
1219 32 0 50     93 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 32         79 last;
1228             }
1229             }
1230 66 100       2132 unless ($self->username) {
1231             # password mismatch - increment failed login attempts
1232 34   100     87 my $attempts = $store->fetch('login_attempts') || 0;
1233 34         195 $store->save( login_attempts => $attempts + 1 );
1234             }
1235              
1236             $config->{POST_LOGIN_CALLBACK}->($self->_cgiapp)
1237 66 100       342 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 111 100 100     1087 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     36 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         3 $self->{is_login_timeout} = 1;
1249 1         5 $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         5 $self->{is_login_timeout} = 1;
1253 1         4 $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         4 $self->logout;
1258             }
1259             }
1260 111         334 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 148     148 1 101344 my $self = shift;
1274 148 100       558 return $self->{display} if $self->{display};
1275 69   100     137 my $config = $self->_config->{LOGIN_FORM} || {};
1276             my $class = "CGI::Application::Plugin::Authentication::Display::".
1277 69   100     353 ($config->{DISPLAY_CLASS} || 'Classic');
1278 69         485 $class->require;
1279 69         2102 $self->{display} = $class->new($self->_cgiapp);
1280 69         274 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 28 my $self = shift;
1295 12         36 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 179     179 1 307 my $class = shift;
1310 179         272 my $cgiapp = shift;
1311 179         290 my $self = {};
1312              
1313 179         342 bless $self, $class;
1314 179         1126 $self->{cgiapp} = $cgiapp;
1315 179         652 Scalar::Util::weaken($self->{cgiapp}); # weaken circular reference
1316              
1317 179         372 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 1567     1567 1 3192 my $class = shift;
1332 1567         2085 my $cgiapp = shift;
1333 1567 100 100     6608 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 1565 100       3430 $cgiapp->{__CAP_AUTHENTICATION_INSTANCE} = $class->new($cgiapp) unless defined $cgiapp->{__CAP_AUTHENTICATION_INSTANCE};
1337 1565         4716 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 118     118 1 15227 my $self = shift;
1361 118         316 my $authen = $self->authen;
1362              
1363 118         361 $authen->initialize;
1364              
1365             # setup the default login and logout runmodes
1366 110         358 $authen->setup_runmodes;
1367              
1368             # The user is asking to be logged out
1369 110 100       267 if (scalar $self->query->param('authen_logout')) {
1370             # The user wants to logout
1371 1         29 return $self->authen->redirect_to_logout;
1372             }
1373              
1374             # If the user just logged in then we may want to redirect them
1375 109 100       2805 if ($authen->is_new_login) {
1376             # User just logged in, so where to we send them?
1377 31         99 return $self->authen->redirect_after_login;
1378             }
1379              
1380             # Update any time out info
1381 78         182 my $config = $authen->_config;
1382 78 100       198 if ( $config->{LOGIN_SESSION_TIMEOUT} ) {
1383             # update the last access time
1384 4         10 my $now = time;
1385 4         22 $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 78         303 my $run_mode = $self->prerun_mode;
1394 78   33     1040 $run_mode ||= $self->get_current_runmode;
1395            
1396 78 100       548 if ( $authen->is_protected_runmode( $run_mode ) ) {
1397             # This runmode requires authentication
1398 67 100       210 unless ($authen->is_authenticated) {
1399             # This user is NOT logged in
1400 66         177 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 66     66 1 4744 my $self = shift;
1417 66         153 my $authen = $self->authen;
1418              
1419 66         176 my $credentials = $authen->credentials;
1420 66         133 my $username = $credentials->[0];
1421 66         115 my $password = $credentials->[1];
1422              
1423 66         95 my $html;
1424 66 50       126 if ( my $sub = $authen->_config->{RENDER_LOGIN} ) {
1425 0         0 $html = $sub->($self);
1426             }
1427             else {
1428 66         233 $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 66         1189 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 219 return '';
1447             }
1448              
1449             ###
1450             ### Detainting helper methods
1451             ###
1452              
1453             sub _detaint_destination {
1454 121     121   218 my $self = shift;
1455 121         293 my $query = $self->_cgiapp->query;
1456 121         1192 my $destination = scalar $query->param('destination');
1457 121         2122 my $regexp = $self->_config->{DETAINT_URL_REGEXP};
1458 121 100 100     703 if ($destination && $destination =~ /$regexp/) {
1459 4         15 $destination = $1;
1460             }
1461             else {
1462 117         191 $destination = "";
1463             }
1464 121         510 return $destination;
1465             }
1466              
1467             sub _detaint_selfurl {
1468 92     92   159 my $self = shift;
1469 92         182 my $query = $self->_cgiapp->query;
1470 92         697 my $destination = "";
1471 92         194 my $regexp = $self->_config->{DETAINT_URL_REGEXP};
1472 92 100       342 if ($query->self_url =~ /$regexp/) {
1473 90         45381 $destination = $1;
1474             }
1475 92         1521 return $destination;
1476             }
1477              
1478             sub _detaint_url {
1479 92     92   178 my $self = shift;
1480 92         216 my $query = $self->_cgiapp->query;
1481 92         829 my $regexp = $self->_config->{DETAINT_URL_REGEXP};
1482 92         173 my $url = "";
1483 92 50       319 if ($query->url( -absolute => 1, -path_info => 1 ) =~ /$regexp/) {
1484 0         0 $url = $1;
1485             }
1486 92         14979 return $url;
1487             }
1488              
1489             sub _detaint_username {
1490 77     77   135 my $self = shift;
1491 77         129 my $username = shift;
1492 77         133 my $cookiename = shift;
1493 77         193 my $query = $self->_cgiapp->query;
1494 77         688 my $regexp = $self->_config->{DETAINT_USERNAME_REGEXP};
1495 77         145 my $username_value = "";
1496 77 100 100     215 if ((scalar $query->param($username) || $query->cookie($cookiename) || '') =~ /$regexp/) {
1497 43         1416 $username_value = $1;
1498             }
1499 77         14885 return $username_value;
1500             }
1501            
1502             ###
1503             ### Helper methods
1504             ###
1505              
1506             sub _cgiapp {
1507 1246     1246   4549 return $_[0]->{cgiapp};
1508             }
1509              
1510             sub _find_deligate_class {
1511 227     227   437 foreach my $class (@_) {
1512 286 100       2964 $class->require && return $class;
1513             }
1514 1         18 return;
1515             }
1516              
1517             sub _config {
1518 1839     1839   2668 my $self = shift;
1519 1839 100       3541 my $class = ref $self ? ref $self : $self;
1520 1839         2412 my $config;
1521 1839 100       3794 if ( ref $self ) {
1522 1817   100     4205 $config = $self->{__CAP_AUTHENTICATION_CONFIG} ||= $__CONFIG{$class} || {};
      66        
1523             } else {
1524 22   100     133 $__CONFIG{$class} ||= {};
1525 22         44 $config = $__CONFIG{$class};
1526             }
1527 1839         4170 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   645 my $time = shift;
1572 32 50       67 return unless defined $time;
1573              
1574             # Most of this function is borrowed from CGI::Util v1.4 by Lincoln Stein
1575 32         140 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         50 my $offset;
1594 32 100       159 if ( $time =~ /^([+-]?(?:\d+|\d*\.\d*))([smhdwMy]?)$/ ) {
1595 29 100 100     173 return if (!$2 || $2 eq 's') && $1 != int $1; #
      100        
1596 28   100     113 $offset = int ( ( $mult{$2} || 1 ) * $1 );
1597             }
1598 31         118 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;