blib/lib/CGI/Session.pm untested

filter: Statementstmt 0.0% 0 / 372 Branchbran 0.0% 0 / 200 Conditioncond 0.0% 0 / 12 MC/DCmcdc 0.0% 0 / 8 Subroutinesub 0.0% 0 / 53 Podpod 0.0% 0 / 47 totaltotal 0.0% 0 / 692 CC 101 SCAR 45.9
CC
101
Cov
0%
confirmed
380.0
set
240.0
authenticated
210.0
CRAP 98.9
1 ####################################################################
2 #
3 # CGI::Session
4 #
5 # A module which makes LDAP authentication and session state
6 # much easier to manage.
7 #
8 ####################################################################
9 #
10 # Generalized by Jeff Younker
11 # jyounker@inktomi.com (or jeff@math.uh.edu)
12 #
13 # Many thanks for the basic code and idea go to Luke
14 # Sheneman (sheneman@inktomi.com).
15 #
16 ####################################################################
17  
18 package CGI::Session;
19 use strict;
20  
21 use vars qw($VERSION);
22 $VERSION = '0.9c';
23  
24 use CGI::Carp;
25 use CGI;
26 use Date::Format;
27 use DBI;
28  
29 =head1 NAME
30  
31 CGI::Session - CGI cookie authentication against an LDAP database
32  
33 =head1 ABSTRACT
34  
35 Provides a simple API authenticate users against an LDAP server, and then
36 to cache this authentication information between invokations of CGI scripts
37 without sending passwords subsequent to login.
38  
39 The state information is maintained in a combination of a cookie, a database,
40 and a magic passkey which is sent in the contents of the web page. Acquiring
41 the login thus requires stealing both the cookie and a current copy of the
42 web page.
43  
44 CGI::Session also contains a subclass of CGI which transparently injects
45 the passkey into forms. It is strongly suggested that you use this class.
46  
47 =head1 SYNOPSIS
48  
49 =head2 Setting Things Up
50  
51 use CGI::Session;
52 use CGI;
53  
54 my $cgi = new CGI::Session::CGI;
55 my $session = new CGI::Session( $cgi );
56 $cgi->session( $session );
57  
58 my $session_store = new CGI::Session::CookieJar::DBI;
59 $session_store->set( -cookie_name=>'cookie_name',
60 -username=>'myuser',
61 -password=>'kjsdfdf',
62 -host=>'dbhost',
63 -database=>'mydb',
64 -cookie_table=>'cookiejar' );
65 $session->set( -cookie_jar => $session_store );
66  
67  
68 $session->auth_servers(
69 [ new CGI::Session::LDAPServer(
70 'ldap.server.my.domain', # host
71 389, # port
72 'ou=my,ou=domain', # root
73 'ou=people,ou=my,ou=domain' # base
74 'uid=$username,ou=people,ou=my,ou=domain' # bind
75 ) ] );
76  
77 $session->open;
78  
79 =head2 Performing the Initial Login
80  
81 my $action = $cgi->param('action');
82 my $passkey = $cgi->param('passkey');
83  
84 if ( defined $action and $action eq 'Log In' )
85 {
86 my $username = $cgi->param('username');
87 my $password = $cgi->param('password');
88 if ( $session->authenticated( $username, $password ) )
89 {
90 $session->set_passkey( $user );
91 $session->set_login_cookie( $user );
92  
93 # Notice that we use $session->header and not $cgi->header
94 #
95 print $session->header();
96 print $cgi->start_html( 'Login Succeeded' );
97 ...
98  
99 # The passkey is sent via the cgi wrapper.
100 #
101 my $passkey = $session->passkey;
102 print $cgi->start_form( -action=>'http://my.stupid/script.cgi' );
103  
104 print ...your form here...
105  
106 print $cgi->end_form;
107 ...
108 print $cgi->end_html;
109 exit 0;
110 }
111 else
112 {
113 ...
114 Login Failed
115 ...
116 $session->close;
117 exit 0;
118 }
119 }
120  
121 =head2 Confirming an Existing Session
122  
123 my $passkey = $cgi->param('passkey');
124 if ( defined $passkey and !$session->confirm_userlogin( $passkey ) )
125 {
126 print $session->header();
127 print $cgi->start_html( 'Open Session' );
128 ...
129 my $passkey = $session->passkey;
130  
131 print $cgi->start_form( -action=>'http://my.stupid/script.cgi' );
132  
133 print ...your form here...
134  
135 print $cgi->end_form;
136 ...
137 print $cgi->end_html;
138 $session->close;
139 exit 0;
140 }
141 else
142 {
143 ... Authentication Failed Page ...
144 }
145  
146 =head2 Logging out of an Existing Session
147  
148 $session->set_logout_cookie;
149 print $session->header;
150 print $cgi->start_html( 'Logout Complete' );
151 print "You have logged out.";
152 print $cgi->end_html;
153 exit 0;
154  
155 =head1 REQUIRES
156  
157 CGI.pm
158 CGI::Carp
159 DBI (and at least one DBD)
160 Mozilla::LDAP
161 Date::Format
162  
163 =head1 DESCRIPTION
164  
165 When a user first authenticates the LDAP database is consulted. If
166 the user is successfully authenticated the information is cached. For
167 subsequent login attempts. The successful login is recorded in a
168 database, and opaque references to this information are passed back to
169 the client.
170  
171 One of the opaque references is a cookie which is managed by the
172 client, and the other is a randomly chosen string which is passed
173 within the content of the web pages. The random string is referred to
174 as a passkey, and it must be resent with every page.
175  
176 On subsequent executions the cookie and the passkey are checked. If
177 either of these do not match the record in the database then the user
178 is rejected.
179  
180 When the program is complete the user is logged out by expiring the
181 cookie.
182  
183 =head1 USAGE
184  
185 There are four major operations. The first is setting up the
186 CGIviaLDAP. Gotta do this every time. The second is authenticating a
187 new user/connection. The third is authenticating an existing session.
188 The fourth is logging out an existing session. ( And somewhere in there
189 you have to send the cookie and passkey back to the client. )
190  
191 =head2 Setting up the Authentication Object
192  
193 The first step is to include the necessary libraries. These are
194 CGI::Session.pm and CGI.
195  
196 use CGI::Session::CGI;
197 use CGI::Session;
198  
199 The second step is to create the CGI::Session object which will be
200 used. It requires a CGI object when it is created. The CGI object
201 provides the machinery to manage cookies.
202  
203 my $cgi = new CGI::Session::CGI;
204 my $session = new CGI::Session( $cgi );
205 $cgi->session( $cgi );
206  
207 Now you have to tell the CGIviaLDAP several things. You have to tell it
208 which LDAP servers it should use for authentication. You need to tell it
209 how to connect to the database. You need to describe the database table
210 in which it will store its information. You need to describe the cookie
211 that it will send to the client's web browser. Finally, you need to
212 describe various aspects of the login behavior.
213  
214 =head2 Setting the Authentication Servers
215  
216 $session->auth_servers( new CGI::Session::LDAPServer( -host=>'my.host.my.domain',
217 -port=>389,
218 -bind=>'uid=$username,ou=people,dc=my,dc=domain' ) );
219  
220 The string '$username' within the -bind argument will be replaced with
221 the username when authentication occurrs.
222  
223 You can also supply more than one ldap server by passing an array of
224 servers. The servers will be checked from first to last in the array.
225  
226 my $server1 = new CGI::Session::LDAPServer( -host=>'ldap1.my.domain',
227 -port=>389,
228 -bind=>'uid=$username,ou=people,dc=my,dc=domain' );
229 my $server2 = new CGI::Session::LDAPServer( -host=>'ldap2.your.domain',
230 -port=>389,
231 -bind=>'uid=$username,ou=people,dc=your,dc=domain' );
232 $session->auth_servers( [ $server1, $server2 ] );
233  
234  
235 =head2 Describing the Database Connection
236  
237 CGIviaLDAP uses perl DBI modules to access the database. There are
238 three items of major importance. These are the connection DN, the
239 the database user, and their associated password.
240  
241 $session->dbi_dn( 'dbi:mysql:my_apps_database' );
242 $session->dbi_username( 'my_apps_user' );
243 $session->dbi_password( '!CENSORED' );
244  
245 =head2 Describing the Database Table
246  
247 You've now told the object how to connect to the database. Now you need
248 to tell it what the table it stores the information in will look like.
249 The most important is the name of the table in which the information
250 will be stored.
251  
252 $session->cookie_table( 'login_cookies' );
253  
254 There are three columns it expects. The first is the name of the
255 user; the second is the contents of the cookie; and the third is the
256 passkey. By default these are called, respectively, 'user_id',
257 'cookie', and 'cookie', and 'passkey'. You may never need to change
258 these. If you do need to change them then you would write:
259  
260 $session->user_column('username');
261 $session->cookie_column('login_cookie');
262 $session->passkey_column('login_passkey');
263  
264 =head2 Setting Cookie Parameters
265  
266 When your program sends back a cookie, the cookie needs to have several
267 parameters set. These include the name of the cookie, the path which it
268 covers, the domain for which it is good, and wether or not it should
269 be used without a secure connection.
270  
271 $session->cookie_name( 'MySessionCookie123587098' ); # The name of the cookie
272 $session->cookie_path( '/' );
273 $session->cookie_domain( '.drinktomi.com' );
274 $session->secure( 1 ); # 1=requires secure transport
275 # 0=does not require secure transport
276  
277 Most importantly you need describe how long the cookie should be valid
278 for. This is the expiration. It is given in seconds. If using the
279 refresh option (more on this later) then the expiration determines how
280 long the web browser can sit idle. If not using the refresh option
281 then it determines how long the user will remain logged in.
282  
283 $session->cookie_expiration( 60*60*2 ); # Cookies will be good for two hours.
284  
285 =head2 Setting Login Behavior
286  
287 Setting the auto refresh cookie option to 1 will the cookie's expiration
288 time to be updated every time a page is sent to the client. As long as
289 the user keeps using the application they will never be logged out.
290  
291 $session->auto_refresh_cookie(1) # 1=always refresh the session cookie
292 # 0=never automatically refresh the session cookie
293  
294 In some instances you only want people to log in when they have a
295 pre-existing database entry. In this case there are two ways of
296 managing things. The first is to create an external file containing
297 the valid user IDs. This is kind of a hack.
298  
299 $session->allowed_user_file( '/var/etc/allowed_users' );
300 $session->restricted_access( 1 ) # 1=use allowed user file
301 # 0=do not use allowed user file
302  
303 The second way of managing things is a little more to my taste. Normally
304 the auth object will register the user (create an entry for them) in the
305 cookie table. You can change this so it will not log a person in unless
306 they already have an entry in the cookie table.
307  
308 $session->register(1); # 1=automatically register users in the cookie table.
309 # 0=do not automatically register users in the cookie table.
310  
311 Some day we may support check LDAP group memberships as a third mechanism.
312  
313  
314 =head2 Sending Back a Page
315  
316 You have to do two things. The first is that you have to generate the HTTP header
317 using CGI::Session instead of CGI, and the second is that you have to make sure
318 that the passkey gets sent back with the results of the next page.
319  
320 The call CGI::Session::header is used _exactly_ like CGI::header.
321 The only difference is that it automatically injects the session
322 cookie if it needs to.
323  
324 print $session->header;
325  
326 The best way to get the passkey back to the user is by using
327 CGI::Session::CGI instead of CGI, and using the start_form
328 and end_form functions. These will automatically inject the
329 necessary html. The code looks something like this:
330  
331 print $cgi->start_form( -action=>$cgi->self_url );
332 print "YOUR FORM HERE";
333 print $cgi->end_form;
334  
335 As long as you use CGI::Session::CGI then you don't have to do
336 anything else.
337  
338 If you want to inject passkey into the document yourself then the
339 simplest way is to use a hidden text field. The current passcode is
340 contained in CGI::Session::passkey. The code to create the form
341 might look something like the next snippet.
342  
343 print "<form...>"
344 ...
345 my $key = $session->passkey;
346 print "<input type=hidden name=passkey value=$key>";
347 ...
348 print "</form>"
349  
350 If you don't send the passkey along then confirmation of the next
351 session login will fail.
352  
353 =head2 Authenticating a New Session
354  
355 Read the user name, and password from the incoming CGI form, and then
356 pass them to CGIviaLDAP::authenticated. If the user is authenticated
357 the we must generate a passkey and a session cookie.
358  
359 my $username = $cgi->param('username');
360 my $password = $cgi->param('password');
361 if ( $session->authenticated( $username, $password ) )
362 {
363 $session->set_passkey( $username );
364 $session->set_login_cookie( $username );
365 ...
366 Successfully authenticated, send response
367 ...
368 }
369 else
370 {
371 ...
372 Login Failed
373 ...
374 }
375  
376  
377 =head2 Confirming an Existing Session
378  
379 Read the passkey from the incoming CGI form, and then ask
380 CGIviaLDAP to confirm it.
381  
382 my $key = $cgi->param('passkey');
383 if ( $session->confirmed($key) )
384 {
385 ...
386 Session was confirmed and this is a valid session
387 ...
388 }
389 else
390 {
391 ...
392 Session was not confirmed, and this is not a valid session
393 ...
394 }
395  
396 Once a session has been confirmed you can do several things with it.
397 You can change the passcode; you can change the cookie identifier; or
398 you can refresh the cookie so that the expiration time will be reset.
399  
400 =head2 Changing the Passcode
401  
402 if ( $session->confirmed( $key ) )
403 {
404 $session->set_passcode;
405 ...
406 Session was confirmed and this is a valid session
407 ...
408 }
409  
410 =head2 Changing the Cookie Identifier
411  
412 if ( $session->confirmed( $key ) )
413 {
414 $session->set_login_cookie;
415 ...
416 Session was confirmed and this is a valid session
417 ...
418 }
419  
420 =head2 Refreshing the Cookie Expiration
421  
422 if ( $session->confirmed( $key ) )
423 {
424 $session->refresh_login_cookie;
425 ...
426 Session was confirmed and this is a valid session
427 ...
428 }
429  
430 =head2 Logging Out
431  
432 if ( $session->confirmed( $key ) and $logout )
433 {
434 $session->set_logout_cookie;
435 ...
436 print $session->header() # You must send back a cookie using the $session
437 print $cgi->start_html( 'Logout Page' );
438 print "You have been logged out."; # Notice that the passkey does not
439 # need to be sent back.
440 print $cgi->end_html;
441 exit 0;
442 }
443  
444  
445 =head2 Creating the Cookie Table
446  
447 Guess what? Once you have configured your CGIviaLDAP there is a function
448 which will create the table that you have described. It only works for
449 MySQL at the moment, but in the future it may work for other databases.
450  
451 $session->create_cookie_table;
452  
453  
454 =head1 TO DO
455  
456 =over 4
457  
458 =item 1. Provide function to retreive username from the database using the cookie.
459  
460 =item 2. Provide support for Net::LDAP
461  
462 =item 3. Clean up DBI code. (DBI provides the independence that the old routines did.)
463  
464 =item 4. Clean up DBI connection creation. (Makes way too many database connections.)
465  
466 =item 5. Make an 'add_cookie_table' function to alter existing tables.
467  
468 =item 6. Date tracking and garbage collection of expired cookie entries for auto-registered tables.
469  
470  
471 =back
472  
473  
474 =head1 REFERENCE
475  
476 =cut
477  
478 ############################################
479 # #
480 # Some Constants, used only within Inktomi #
481 # #
482 ############################################
483  
484 # Toggle this to limit access to the application to a specific set of
485 # people. 1 = restricted, 0 = open
486 my $RESTRICTED_ACCESS = 0;
487  
488 my $ALLOWED_USER_FILE = "/var/tmp/allowed_users";
489  
490 #
491 # Settings for the LDAP server to authenticate against
492 #
493 my $AUTH_LDAP_SERVER = "gandalf.inktomi.com";
494 my $AUTH_LDAP_PORT = 389;
495 my $AUTH_LDAP_ROOT = "o=inktomi.com";
496 my $AUTH_LDAP_BASE = $AUTH_LDAP_ROOT;
497 my $AUTH_LDAP_BIND = "uid=\$username,ou=People,$AUTH_LDAP_BASE";
498  
499 #
500 # Settings for the general-purpose LDAP server
501 #
502 my $GEN_LDAP_SERVER = "phonebook.inktomi.com";
503 my $GEN_LDAP_PORT = 389;
504 my $GEN_LDAP_ROOT = "dc=inktomi,dc=com";
505 my $GEN_LDAP_BASE = "ou=People,$GEN_LDAP_ROOT";
506 my $GEN_LDAP_BIND = "uid=\$username,$GEN_LDAP_BASE";
507  
508 my $UNIKEY = "kevinbac0n";
509  
510 my $COOKIE_LOGGED_IN = "1FA6FAACE01B7A2677";
511 my $COOKIE_LOGGED_OUT = "1FA90BCCA7510F0CC9";
512 my $COOKIE_EXPIRATION = (3600*24); # in seconds
513 my $COOKIE_PATH = "/";
514 my $COOKIE_DOMAIN = ".inktomi.com";
515 my $COOKIE_SECURE = 1;
516  
517 my $DBI_DN = 'dbi:mysql';
518 my $DBI_USERNAME = 'nobody';
519 my $DBI_PASSWORD = 'mangle';
520 my $COOKIE_TABLE = 'stock';
521  
522 my $USER_REGISTER = 1;
523 my $AUTO_REFRESH_COOKIE = 0;
524  
525 my $PASSKEY_NAME = 'passkey2134343245';
526  
527  
528 =over 4
529 =item CGI::Session::new
530  
531 Creates a new session object. Requires at least one argument. This
532 argument is a CGI object of some kind.
533  
534 my $cgi = new CGI::Session::CGI;
535 my $session = new CGI::Session( $cgi );
536  
537 You can then set values with function calls. Or, you can use the
538 handy-dandy '-PARAMETER=>VALUE' syntax just like the standard module
539 CGI.pm uses. This is in fact the prefered method, and I strongly
540 suggest that you use it.
541  
542 my $cgi = new CGI::Session::CGI;
543 my $session = new CGI::Session( $cgi,
544 -auth_servers => [ $ldap1, $ldap2 ],
545
546 -dbi_dn => 'dbi:mysql:stock',
547 -cookie_table => 'everyones_cookies',
548 -dbi_username => 'your_mythical_db_user',
549 -dbi_password => 'its_password',
550
551 -cookie_expiration => 900,
552 -cookie_name => '1FA6FAACE01B7A2677',
553 -cookie_path => '/',
554 -cookie_domain => '.inktomi.com',
555 -cookie_secure => 0,
556
557 -passkey_name => 'passkey',
558
559 -restricted_access => 0,
560 -register => 1,
561 -auto_refresh_cookie => 1 );
562  
563 =head2 Parameters for a new CGI::Session
564  
565 =over 8
566  
567 =item -cookie_name
568  
569 The name of the cookie that will be passed back to the browser.
570  
571 =item -cookie_expiration
572  
573 The lifetime of the cookie in seconds.
574  
575 =item -cookie_path
576  
577 The path of the cookie.
578  
579 =item -cookie_domain
580  
581 The domain of the cookie.
582  
583 =item -cookie_secure
584  
585 If set to 1 (-cookie_secure=>1) then SSL will be required for this
586 connection. If set to 0 or undef then then normal http can be used.
587 Defaults to 1.
588  
589 =item -auth_servers
590  
591 Points to either a single authentication server, or an anonymous
592 array of authentication servers. Currently authentication servers
593 are defined using CGI::Session::LDAPServer. Others may be added
594 in the future. (At that time this will become a very poorly named
595 module.)
596  
597 my $ldap1 = new CGI::Session::LDAPServer( -host=>'ldap.inktomi.com',
598 -port=>389,
599 -bind=>'uid=$username,ou=People,dc=inktomi,dc=com' );
600 my $ldap2 = new CGI::Session::LDAPServer( -host=>'mccoy.inktomi.com',
601 -port=>389,
602 -bind=>'uid=$username,ou=People,dc=inktomi,dc=com' );
603  
604 $session => new CGI::Session( $cgi, -auth_servers => $ldap1 );
605  
606 --or--
607  
608 $session => new CGI::Session( $cgi, -auth_servers => [ $ldap1, $ldap2 ] );
609  
610 =item -restricted_access
611  
612 This is set to either a 1 or 0 (undef is the same as 0). If set to a
613 one then access will be restricted to those users which are specfied
614 in the file corresponding to -allowed_user_file. This file contains
615 the names of the users which can be successfully authenticated. One
616 username is listed on each line of this file.
617  
618 =item -allowed_user_file
619  
620 The full path to a file containing the usernames of the users which
621 can be successfully authenticated. Each line of the file contains one
622 username. If a user is not specified in this file then authentication
623 will fail.
624  
625 This file is only consulted if -restricted_access is set to 1.
626  
627 =item -unikey
628  
629 DANGER. The password for a back door. If this value is set to 0
630 or undef then no back door exists. This is ONLY A TESTING feature.
631 DO NOT SET THIS VARIABLE IN PRODUCTION CODE.
632  
633 =item -register
634  
635 If set to 1 then an entry is automatically created in the cookie
636 table if one does not exist. If set to 0 then authentication will
637 fail if the user does not exist.
638  
639 =item -dbi_dn
640  
641 The DBI connection string which will be used to connect to the
642 database.
643  
644 =item -dbi_username
645  
646 The username which will be used to connect to the database.
647  
648 =item -dbi_password
649  
650 The password which will be used to connect to the database.
651  
652 =item -cookie_table
653  
654 The database table in which the cookie information will be stored.
655  
656 =item -user_column
657  
658 The column in the cookie_table containing the username.
659  
660 =item -passkey_column
661  
662 The column in the cookie_table containing the passkey.
663  
664 =item -cookie_column
665  
666 The column in the cookie_table containing the cookie value.
667  
668 =item -cookie_name_column
669  
670 The column in the cookie_table containing the cookie name.
671  
672  
673 =item -login_expiration_column. CURRENTLY UNUSED
674  
675 The column in the cookie_table containing the session expiration time.
676
677  
678 =item -passkey_name
679  
680 The name of the CGI parameter which contains the passkey.
681  
682 =item -debug
683  
684 Set to non-zero to generate debugging information.
685  
686 =back
687  
688 =cut
689  
690 sub new
691 {
692 my ( $type ) = shift;
693 my ( $cgi ) = shift;
694  
695 my $self = {};
696 bless $self, $type;
697  
698 # A cgi is required.
699 #
700 $self->cgi($cgi);
701  
702 # Registration behavior.
703 #
704 $self->register($USER_REGISTER);
705 $self->auto_refresh_cookie($AUTO_REFRESH_COOKIE);
706  
707 # Set cookie defaults.
708 #
709 $self->cookie_name( $COOKIE_LOGGED_IN );
710 $self->cookie_expiration( $COOKIE_EXPIRATION );
711  
712 # Default cookie parameters
713 #
714 $self->cookie_path( $COOKIE_PATH );
715 $self->cookie_domain( $COOKIE_DOMAIN );
716 $self->cookie_secure( $COOKIE_SECURE );
717  
718 # # Set default LDAP servers.
719 # #
720 # $self->auth_servers( [ new CGI::Session::LDAPServer( -host=>$AUTH_LDAP_SERVER,
721 # -port=>$AUTH_LDAP_PORT,
722 # -bind=>$AUTH_LDAP_BIND ),
723 # new CGI::Session::LDAPServer( -host=>$GEN_LDAP_SERVER,
724 # -port=>$GEN_LDAP_PORT,
725 # -bind=>$GEN_LDAP_BIND ) ] );
726  
727 $self->restricted_access( $RESTRICTED_ACCESS );
728 $self->allowed_user_file( $ALLOWED_USER_FILE );
729  
730 $self->passkey_name( $PASSKEY_NAME );
731  
732 # Set any additional arguments.
733 #
734 if ( @_ ) { $self->set( @_ ); }
735
736 return $self;
737 }
738  
739 # Open up the session if required.
740 #
741  
742 =item CGI::Session::open
743  
744 Internal function. Opens up the cookie jar. This function is called by
745 methods just before they first access a cookie jar.
746  
747 $session->open;
748  
749 =cut
750  
751 sub open
752 {
753 my ( $self ) = @_;
754 my $cookie_jar = $self->cookie_jar;
755 $cookie_jar->open();
756 if ( $cookie_jar->error )
757 {
758 croak sprintf( 'Error: Could not open the cookie jar: %s', $cookie_jar->error );
759 }
760 }
761  
762  
763 # Destroy session when needed.
764 #
765 sub DESTROY
766 {
767 my ( $self ) = shift;
768 return unless defined $self->cookie_jar;
769 $self->cookie_jar->close();
770 }
771  
772 # The cgi document which this session is connected to.
773 #
774  
775 =item CGI::Session::cgi
776  
777 Accessor method. The cgi to which the session is attached.
778  
779 =cut
780  
781 sub cgi { my $self=shift; @_ ? $self->{cgi}=shift : $self->{cgi}; }
782  
783 #################################
784 ######### Authentication results.
785  
786 =item CGI::Session::cookie
787  
788 Accessor method. The value of the current cookie.
789  
790 =cut
791  
792 #################################
793  
794 sub cookie { my $self=shift; @_ ? $self->{cookie}=shift : $self->{cookie}; }
795  
796 =item CGI::Session::passkey
797  
798 Accessor method. The value of the current passkey. Set by confirmed() and authenticated().
799  
800 =cut
801  
802 sub passkey { my $self=shift; @_ ? $self->{passkey}=shift : $self->{passkey}; }
803  
804 #################################
805  
806 =item CGI::Session::is_authenticated
807  
808 Accessor method. Authentication state. True if the session has been successfully authenticated. False if it has not.
809  
810 =cut
811  
812 sub is_authenticated { my $self=shift; @_ ? $self->{is_authenticated}=shift : $self->{is_authenticated}; }
813  
814  
815 # Fast initialization routine.
816 #
817 sub set
818 {
819 my ( $self ) = shift;
820 my %a = @_;
821  
822 $self->cookie_jar( $a{-cookie_jar} ) if defined $a{-cookie_jar};
823 $self->cookie_name( $a{-cookie_name} ) if defined $a{-cookie_name};
824 $self->cookie_expiration( $a{-cookie_expiration} ) if defined $a{-cookie_expiration};
825 $self->cookie_path( $a{-cookie_path} ) if defined $a{-cookie_path};
826 $self->cookie_domain( $a{-cookie_domain} ) if defined $a{-cookie_domain};
827 $self->cookie_secure( $a{-cookie_secure} ) if defined $a{-cookie_secure};
828 $self->auth_servers( $a{-auth_servers} ) if defined $a{-auth_servers};
829 $self->restricted_access( $a{-restricted_access} ) if defined $a{-restricted_access};
830 $self->allowed_user_file( $a{-allowed_user_file} ) if defined $a{-allowed_user_file};
831 $self->unikey( $a{-unikey} ) if defined $a{-unikey};
832 $self->register( $a{-register} ) if defined $a{-register};
833 $self->auto_refresh_cookie( $a{-auto_refresh_cookie} ) if defined $a{-auto_refresh_cookie};
834 $self->passkey_name( $a{-passkey_name} ) if defined $a{-passkey_name};
835 $self->debug( $a{-debug} ) if defined $a{-debug};
836 }
837  
838 # Cookie characteristics.
839 #
840 =item Cookie Characteristics
841  
842 These accessor methods specify the details of the cookies which are generated.
843  
844  
845 =item CGI::Session::cookie_name
846  
847 Accessor method. The name of the login cookie.
848  
849 =cut
850  
851 sub cookie_name { my $self=shift; @_ ? $self->{cookie_logged_in}=shift : $self->{cookie_logged_in}; }
852  
853 =item CGI::Session::cookie_logged_out
854  
855 Accessor method. Vestigial logout cookie. Unused. Like the wings of an
856 archeopertyx. But with no hairy feathers. Left here for strictly
857 archeological reasons.
858  
859 =cut
860  
861 sub cookie_logged_out { my $self=shift; @_ ? $self->{cookie_logged_out}=shift : $self->{cookie_logged_out}; }
862  
863  
864 =item CGI::Session::cookie_expiration
865  
866 Accessor method. The lifetime of the cookie specified in seconds.
867  
868 =cut
869  
870 sub cookie_expiration { my $self=shift; @_ ? $self->{cookie_expiration}=shift : $self->{cookie_expiration}; }
871  
872  
873 =item CGI::Session::cookie_path
874  
875 Accessor method. The path of the cookie.
876  
877 =cut
878  
879 sub cookie_path { my $self=shift; @_ ? $self->{cookie_path}=shift : $self->{cookie_path}; }
880  
881  
882 =item CGI::Session::cookie_domain
883  
884 Accessor method. The domain of the cookie.
885  
886 =cut
887  
888 sub cookie_domain { my $self=shift; @_ ? $self->{cookie_domain}=shift : $self->{cookie_domain}; }
889  
890  
891 =item CGI::Session::cookie_secure
892  
893 Accessor method. True if the cookie requires SSL. False otherwise.
894  
895 =cut
896  
897 sub cookie_secure { my $self=shift; @_ ? $self->{cookie_secure}=shift : $self->{cookie_secure}; }
898  
899  
900 # Login behavior
901 #
902  
903 =item Authentication Behavior Variables
904  
905 These are variables which affect the behavior of the authentication mechanism.
906  
907 =item CGI::Session::auth_servers
908  
909 Accessor method. The list of authentication servers which will be contacted. This value can either
910 be a single server or a reference to an array of servers.
911  
912 Currently these servers are definied by CGI::Session::LDAPServer objects.
913  
914 =cut
915  
916 sub auth_servers { my $self=shift; @_ ? $self->{authentication_servers}=shift : $self->{authentication_servers}; }
917 sub authentication_servers { my $self=shift; @_ ? $self->{authentication_servers}=shift : $self->{authentication_servers}; }
918 sub authorization_servers { my $self=shift; @_ ? $self->{authorization_servers}=shift : $self->{authorization_servers}; }
919  
920  
921 =item CGI::Session::restricted_access
922  
923 Accessor method. If set to a non-zero value then the allowed_user_file is turned on.
924  
925 =cut
926  
927 sub restricted_access { my $self=shift; @_ ? $self->{restricted_access}=shift : $self->{restricted_access}; }
928  
929  
930 =item CGI::Session::allowed_user_file
931  
932 Accessor method. The full path to the allowed_user_file.
933  
934 =cut
935  
936 sub allowed_user_file { my $self=shift; @_ ? $self->{allowed_user_file}=shift : $self->{allowed_user_file}; }
937  
938  
939 =item CGI::Session::unikey
940  
941 Accessor method. Boy this one sucks. This is a backdoor value. If this is
942 set then any user matching this ID will be successfully authenticated. Why? Strictly
943 for testing. NEVER, EVER SET THIS VALUE UNLESS YOU KNOW WHAT THE FUCK YOU ARE DOING.
944  
945 =cut
946  
947 sub unikey { my $self=shift; @_ ? $self->{unikey}=shift : $self->{unikey}; }
948  
949  
950 =item CGI::Session::register
951  
952 Accessor method. Login requires an entry to exist in the cookie table for each user.
953 If this variable is set then an entry will automatically be created for users which are
954 successfully authenticated.
955  
956 =cut
957  
958 sub register { my $self=shift; @_ ? $self->{register}=shift : $self->{register}; }
959  
960  
961 =item CGI::Session::auto_refresh_cookie
962  
963 Accessor method. Normally the cookie will expire X seconds after it is created, where X is
964 specified by CGI::Session::cookie_expiration. Whenever the cookie is refreshed this
965 timer resets. Setting this variable to a non-zero value causes the cookie to be refreshed
966 every time that it is successfully verified.
967  
968 =cut
969  
970 sub auto_refresh_cookie { my $self=shift; @_ ? $self->{auto_refresh_cookie}=shift : $self->{auto_refresh_cookie}; }
971  
972  
973 =item CGI::Session::used_with_custom_cgi
974  
975 Forget about this one. This is an internal function used by CGI::Session and CGI::Session::CGI.
976 Normally set to zero. Setting CGI::Session::CGI::session causes this value to be set.
977  
978 =cut
979  
980 sub used_with_custom_cgi { my $self=shift; @_ ? $self->{used_with_custom_cgi}=shift : $self->{used_with_custom_cgi}; }
981  
982  
983 =item CGI::Session::cookie_jar
984  
985 # Cookiejar. This handles all cookie storage.
986 #
987 Accessor method. The object encapsulating cookie storage.
988  
989 =cut
990  
991 sub cookie_jar { my $self=shift; @_ ? $self->{cookie_jar}=shift : $self->{cookie_jar}; }
992  
993  
994  
995  
996 =item CGI::Session::passkey_name
997  
998 Accessor method. The name of the passkey field in the form is stored here.
999 Not currently important, but it will be if/when the table becomes a shared
1000 resource.
1001  
1002 =cut
1003  
1004 sub passkey_name { my $self=shift; @_ ? $self->{passkey_name}=shift : $self->{passkey_name}; }
1005  
1006  
1007 =item CGI::Session::debug
1008  
1009 Accessor method. Turns on debugging. Currently this doesn't do much. I need
1010 to add more instrumentation.
1011  
1012 =cut
1013  
1014 sub debug { my $self=shift; @_ ? $self->{debug}=shift : defined $self->{debug}; }
1015  
1016  
1017 #sub %($;$) { my $self=shift; @_ ? $self->{%}=shift : $self->{%}; }
1018  
1019  
1020 =item CGI::Session::has_passkey
1021  
1022 True if the CGI session has a value for the parameter specified with
1023 -passkey_name.
1024  
1025 print "Session has passkey: ".( $session->has_passkey ? "YES" : "NO" )."\n";
1026  
1027 =cut
1028  
1029 sub has_passkey
1030 {
1031 my $self = shift;
1032 return $self->cgi->param($self->passkey_name);
1033 }
1034  
1035  
1036 =item CGI::Session::passkey_field
1037  
1038 The value of the CGI parameter specified by -passkey_name.
1039  
1040 $passkey_field = $session->passkey_field;
1041  
1042 =cut
1043  
1044 sub passkey_field
1045 {
1046 my $self = shift;
1047 my $passkey = $self->passkey;
1048 my $passkey_name = $self->passkey_name;
1049  
1050 return qq(<input type=hidden name="$passkey_name" value="$passkey">);
1051 }
1052  
1053  
1054 # Have the session activate the backend storage.
1055 #
1056  
1057  
1058  
1059 # Confirm the existance of the session
1060 #
1061 # $session->confirmed( $passkey )
1062 # -or-
1063 # $session->confirmed;
1064 #
1065 # 1 is SUCCESS
1066 # 0 is FAILURE
1067 #
1068  
1069 =item CGI::Session::confirmed
1070  
1071 Confirms that the cookie and a passkey constitute a valid login. If
1072 the session confirmation succeeds then it will return a true value.
1073 If the session confirmation fails then it will return a false value.
1074  
1075 Once this routine is called the variable of
1076 CGI::Session::is_authenticated will contain the status of the
1077 session.
1078  
1079 The function may be called in one of two ways. You can either let
1080 it extract the passkey value on its own, or you can hand it the
1081 passkey value to be checked. It is much less work to let it extract
1082 the passkey value.
1083  
1084 if ( $session->confirmed )
1085 {
1086 Session was confirmed...
1087 }
1088  
1089 If you want to handle the extraction of the passkey on your own...
1090  
1091 my $passkey = $cgi->param( 'passkey_name' );
1092 if ( $session->confirmed( $passkey ) )
1093 {
1094 Session was confirmed...
1095 }
1096  
1097 =cut
1098  
1099 sub confirmed
1100 {
1101 my ($self) = shift;
1102  
1103 $self->is_authenticated(undef);
1104 $self->open;
1105 my %args;
1106 if ( @_ ) { %args = ref @_ eq 'HASH' ? %{$_[0]} : @_ ; }
1107 my $auth_token = {};
1108 my ( $group, $groupdn, $passkey );
1109 $passkey = $args{-passkey} ? $args{-passkey} : $self->cgi->param( $self->passkey_name );
1110 if ( exists $args{-group} )
1111 {
1112 $group = ref $args{-group} eq 'ARRAY' ? $args{-group} : [$args{-group}];
1113 $auth_token->{-group} = $group;
1114 }
1115 if ( exists $args{-groupdn} )
1116 {
1117 $groupdn = ref $args{-groupdn} eq 'ARRAY' ? $args{-groupdn} : [$args{-groupdn}];
1118 $auth_token->{-groupdn} = $groupdn;
1119 }
1120  
1121 my $client_cookie;
1122 my $db_passkey;
1123
1124 $client_cookie = $self->check_cookie;
1125  
1126 if(!defined $client_cookie or !$client_cookie)
1127 {
1128 # No client Cookie!
1129 carp "No Cookie!" if $self->debug;
1130 return 0;
1131 }
1132  
1133 my $cookie_jar = $self->cookie_jar;
1134  
1135 my $session = $cookie_jar->session( -query=>{-cookie_name=>$self->cookie_name,
1136 -cookie=>$client_cookie},
1137 -omit_server_side_data=>1 );
1138 if ( defined $cookie_jar->error )
1139 {
1140 croak "Error: Encountered error while attempting to retrieve passkey: ".($cookie_jar->error);
1141 }
1142 if ( scalar @{$session} == 0 )
1143 {
1144 carp "ERROR: Passkey not found in cookie jar" if $self->debug;
1145 return 0;
1146 }
1147  
1148 $db_passkey = $session->[0]->{passkey};
1149
1150 # passkey doesn't match passkey in database
1151 if (!defined $passkey)
1152 {
1153 carp "ERROR: Passkey is not found" if $self->debug;
1154 return 0;
1155 }
1156 elsif ($passkey ne $db_passkey)
1157 {
1158 carp "ERROR: Passkeys don't match" if $self->debug;
1159 return 0;
1160 }
1161 else
1162 {
1163 $self->passkey( $passkey );
1164 $auth_token->{-username} = $self->username();
1165 }
1166  
1167 # We can only reach this point if we have been successfully authorized.
1168 # Now we check authorization.
1169 #
1170 if ( authorize( $self, $auth_token ) )
1171 {
1172 $self->is_authenticated(1);
1173 $self->refresh_login_cookie if $self->auto_refresh_cookie;
1174 return 1;
1175 }
1176 else
1177 {
1178 return 0;
1179 }
1180 }
1181  
1182 # For testing at a separate point.
1183 #
1184 # $session->confirm;
1185 # if ( $session->is_authenticated ) { ... }
1186 #
1187  
1188 =item CGI::Session::confirm
1189  
1190 The preferred way of confirming a valid login session. It extracts
1191 the cookie and session key from the CGI, checks their validity, and
1192 then sets the variable CGI::Session::is_authenticated. Used as
1193 follows:
1194  
1195 $session->confirm;
1196 if ( $session->is_authenticated )
1197 {
1198 Authentication Succeeded
1199 }
1200 else
1201 {
1202 Authentication Failed
1203 }
1204  
1205 =cut
1206  
1207 sub confirm { my $self = shift; $self->confirmed(@_); }
1208  
1209  
1210 # Authenticate User (at beginning)
1211 #
1212 # $session->authenticated( $username, $password );
1213 #
1214 # 1 = SUCCESS
1215 # 0 = FAILURE
1216 #
1217  
1218 =item CGI::Session::authenticate
1219  
1220 Call the method authenticated with the username and password that you
1221 want to check. Authenticated will check their validity. If user was
1222 successfully authenticated then it will return a true value. If the
1223 user was not successfully authenticated then it will return a false
1224 value.
1225  
1226 Once authenticated is called then is_authenticated will return the
1227 authentication status.
1228  
1229 $username = $cgi->param('your_username_field');
1230 $password = $cgi->param('your_password_field');
1231  
1232 if ( $session->authenticated( $username, $password ) )
1233 {
1234 Authentication Succeeded
1235 }
1236 else
1237 {
1238 Authentication Failed
1239 }
1240  
1241 =cut
1242  
1243 sub authenticated
1244 {
1245 my ( $self ) = shift;
1246  
1247 # Parse arguments.
1248 #
1249 my %args;
1250 if ( @_ ) { %args = ref @_ eq 'HASH' ? %{$_[0]} : @_ ; }
1251 my $auth_token = {};
1252 my ( $group, $groupdn );
1253 my $username = $args{-username};
1254 $self->user( $username );
1255 $auth_token->{-username} = $username;
1256 $auth_token->{-password} = $args{-password} if exists $args{-password};
1257 if ( exists $args{-group} )
1258 {
1259 $group = ref $args{-group} eq 'ARRAY' ? $args{-group} : [$args{-group}];
1260 $auth_token->{-group} = $group;
1261 }
1262 if ( exists $args{-groupdn} )
1263 {
1264 $groupdn = ref $args{-groupdn} eq 'ARRAY' ? $args{-groupdn} : [$args{-groupdn}];
1265 $auth_token->{-groupdn} = $groupdn;
1266 }
1267 $self->is_authenticated(undef);
1268 $self->open();
1269  
1270 return 0 unless $username;
1271  
1272 # Check each one of the auth servers in turn. If any one
1273 # of them succeeds then the user is logged in.
1274 #
1275 my $authentication_servers = $self->authentication_servers;
1276  
1277 if ( !$authentication_servers )
1278 {
1279 return 0;
1280 }
1281  
1282 # Handle a single authorization server.
1283 #
1284 my $authenticated = undef;
1285  
1286 if ( ref($authentication_servers) ne 'ARRAY' )
1287 {
1288 $authentication_servers = [ $authentication_servers ];
1289 }
1290  
1291 $self->is_authenticated(undef);
1292  
1293 foreach my $auth_server ( @{$self->authentication_servers} )
1294 {
1295 if ( $auth_server->authenticated( $auth_token ) )
1296 {
1297 $authenticated = 1;
1298 last;
1299 }
1300 }
1301  
1302 $self->is_authenticated( $authenticated );
1303 return 0 unless $authenticated;
1304  
1305 # Check each one of the authorization servers in turn. If any one
1306 # of them succeeds then the user is accepted.
1307 #
1308 # Note that we can only get to this point if the user has
1309 # been authenticated.
1310 #
1311 my $authorization_servers = $self->authorization_servers;
1312  
1313 # We succeed if there are no authorization servers.
1314 #
1315 if ( authorize( $self, $auth_token ) )
1316 {
1317 $self->register_user($username);
1318 $self->is_authenticated(1);
1319 return 1;
1320 }
1321  
1322 return 0;
1323 }
1324  
1325 # For testing at a separate point.
1326 #
1327 # $session->authenticate( $username, $password );
1328 # if ( $session->is_authenticated ) { ... }
1329 #
1330  
1331 =item CGI::Session::authenticate
1332  
1333 The preferred method of authenticating a user. Call the method
1334 authenticate with the username and password that you want to check.
1335 Authenticate will check their validity and then set the variable
1336 is_authenticated with the status. For example:
1337  
1338 $username = $cgi->param('your_username_field');
1339 $password = $cgi->param('your_password_field');
1340  
1341 $session->authenticate( $username, $password );
1342 if ( $session->is_authenticated )
1343 {
1344 Authentication Succeeded
1345 }
1346 else
1347 {
1348 Authentication Failed
1349 }
1350  
1351 =cut
1352  
1353 sub authenticate
1354 {
1355 my ( $self, $username, $password ) = @_;
1356 if ( $self->authenticated( $username, $password ) )
1357 {
1358 $self->set_passkey( $username );
1359 $self->set_login_cookie( $username );
1360 }
1361 }
1362  
1363 # Authorization happens at two points, so I've separated it out.
1364 # Returns true if the user is accepted, false if they are not.
1365 #
1366 # $is_authorized = $session->authorize( $auth_token );
1367 #
1368 =item CGI::Session::authorize
1369  
1370 An internal function which performs authorization. It must be called _after_ authentication has happened. Used as follows:
1371  
1372 my $auth_token = { -username=>$user, -group=>$group };
1373 my $authorized = $session->authorize( $auth_token );
1374  
1375 =cut
1376  
1377 sub authorize
1378 {
1379 my ( $self, $auth_token ) = @_;
1380 my $authorization_servers = $self->authorization_servers;
1381  
1382 # We succeed if there are no authorization servers.
1383 #
1384 return 1 unless $authorization_servers;
1385  
1386 # Make a single authorization server look the same as many.
1387 #
1388 if ( ref($authorization_servers) ne 'ARRAY' )
1389 {
1390 $authorization_servers = [ $authorization_servers ];
1391 }
1392  
1393 # Check each one of the authorization servers in turn. If any one
1394 # of them succeeds then the user is accepted.
1395 #
1396 foreach my $server ( @{$self->authorization_servers} )
1397 {
1398 return 1 if $server->authorized( $auth_token );
1399 }
1400 return 0;
1401 }
1402  
1403 ##############################################################
1404 #
1405 # Wrapper for CGI.pm's header function which transparently
1406 # handles creation of the cookie.
1407 #
1408  
1409 sub header_args_with_cookie
1410 {
1411 my ($self,%raw_args) = @_;
1412  
1413 # Copy the arguments. If we find a cookie argument
1414 # then we add in any cookies that we already know about.
1415 #
1416 my @processed_args ;
1417 my $cookie_is_done = 0;
1418 foreach my $arg (keys %raw_args)
1419 {
1420 push @processed_args, $arg;
1421 my $val = $raw_args{$arg};
1422 if ($arg=~/^-?cookie$/i and $self->cookie )
1423 {
1424 if ( ref($val) eq 'ARRAY' )
1425 {
1426 push @{$val}, $self->cookie;
1427 }
1428 else
1429 {
1430 $val = [ $val, $self->cookie ]
1431 }
1432 $cookie_is_done = 1;
1433 }
1434 push @processed_args, $val;
1435 }
1436  
1437 # If no cookies were found in the argument list then
1438 # we create one.
1439 #
1440 if ( $self->cookie and !$cookie_is_done )
1441 {
1442 push @processed_args, '-cookie';
1443 push @processed_args, $self->cookie;
1444 }
1445  
1446 return @processed_args;
1447 }
1448  
1449  
1450 =item CGI::Session::header
1451  
1452 Acts just like CGI.pm's header function, but it injects
1453 the authentication cookie.
1454  
1455 If you are using CGI::Session::CGI then this function will not be
1456 used. If you are using CGI.pm directly then call this function instead
1457 of CGI.pm's header method.
1458  
1459 print $session->header;
1460 print $cgi->start_html( 'my html' );
1461 ...
1462  
1463 =back
1464  
1465 =cut
1466  
1467 sub header
1468 {
1469 my ($self) = shift;
1470 my $header;
1471  
1472 # If this is being used with a custom CGI, then we just call the
1473 # custom CGI which understands how to use the header_args_with_cookie
1474 # to inject the cookie. This call shouldn't be hear, but it was
1475 # put in before I had really thought through the use of a custom
1476 # CGI.pm wrapper. (Otherwise we end up with duplicate cookies.)
1477 #
1478 if ( $self->used_with_custom_cgi )
1479 {
1480 $header = $self->cgi->header(@_);
1481 }
1482 else
1483 {
1484 $header = $self->cgi->header( $self->header_args_with_cookie(@_) );
1485 }
1486 return $header;
1487 }
1488  
1489  
1490 =item CGI::Session::user_exists
1491  
1492 Internal function. Checks the database to see if a user has an existing
1493 record within the cookie table. True if the cookie table contains
1494 an entry for the username, and false if it does not.
1495  
1496 if ( $self->user_exists( $username ) )
1497 {
1498 ... perform action for defined user ...
1499 }
1500  
1501 =cut
1502  
1503 sub user_exists
1504 {
1505 my ($self,$user) = @_;
1506 $self->open;
1507 return $self->cookie_jar->contains( -cookie_name=>$self->cookie_name, -user=>$user );
1508 }
1509  
1510  
1511 =item CGI::Session::register_user
1512  
1513 Internal function. Creates an entry for the specified user within the cookie table.
1514  
1515 if ( ! $self->user_exists( $username ) )
1516 {
1517 $self->register_user( $username );
1518 }
1519  
1520 =cut
1521  
1522 sub register_user
1523 {
1524 my( $self, $username ) = @_;
1525 $self->open;
1526 my $cookie_jar = $self->cookie_jar;
1527 if ( ! $cookie_jar->contains( -cookie_name=>$self->cookie_name, -user=>$username ) )
1528 {
1529 $cookie_jar->register_user( $self->cookie_name, $username );
1530 }
1531 }
1532  
1533  
1534 =item CGI::Session::login_cookie
1535  
1536 Internal function. Returns the cookie string for the current session. The
1537 expiration time is a unix timestamp as returned by the function time(). The
1538 expiration time is not a lifetime in seconds.
1539  
1540 my $cookie_string = $self->login_cookie( $cookie_name, $expiration_time );
1541  
1542 =cut
1543  
1544 sub login_cookie
1545 {
1546 my ($self,$cookie_value,$expiration_time) = @_;
1547 my $datetimestr = time2str("%a, %e-%b-%Y %X GMT", $expiration_time, 'GMT');
1548 my $cgi = $self->cgi;
1549 my $cookie = $cgi->cookie( -name=>$self->cookie_name,
1550 -value=>$cookie_value,
1551 -path=>$self->cookie_path,
1552 -domain=>$self->cookie_domain,
1553 -secure=>($self->cookie_secure ? 1 : 0 ),
1554 -expires=>$datetimestr );
1555 return $cookie;
1556 }
1557  
1558 #
1559 # Set the Session Cookie (login)
1560 #
1561 =item CGI::Session::set_login_cookie
1562  
1563 Sets the login cookie for an authenticated session. If a username
1564 is not specified then it pulls the username corresponding to the
1565 current cookie and passkey combination.
1566  
1567 $self->set_login_cookie( $username );
1568  
1569 ..or..
1570  
1571 $self->set_login_cookie();
1572  
1573 =cut
1574  
1575 sub set_login_cookie
1576 {
1577 my ($self) = shift;
1578 $self->open;
1579 my $cookie_jar = $self->cookie_jar;
1580  
1581 # Get user ID. Either from the argument list or from
1582 # the cookie ID.
1583 #
1584 my $user_id;
1585 if ( @_ )
1586 {
1587 $user_id = shift;
1588 $user_id = defined $user_id ? $user_id : "";
1589 }
1590 else
1591 {
1592 my $cookie_name = $self->cookie_name();
1593 my $session = $cookie_jar->session( -query => { -cookie_name=>$self->cookie_name,
1594 -cookie=>$self->cgi->cookie( $cookie_name ) },
1595 -omit_server_side_data => 1 );
1596 if ( defined $cookie_jar->error )
1597 {
1598 croak( "Error: Could not read user name fom the cookie jar: ".($cookie_jar->error) );
1599 }
1600 if ( scalar @{$session} == 0 )
1601 {
1602 croak "Error: Could not read user name from the cookie jar";
1603 }
1604 if ( scalar @{$session} > 1 )
1605 {
1606 croak "Error: Expected to retreive one username, but found several";
1607 }
1608 $user_id = $session->[0]->{user};
1609 }
1610
1611 my $r = int(rand 999999)+1;
1612 my $cookie_value = $user_id.$r;
1613 my $expiration_time = time + $self->cookie_expiration;
1614 $cookie_jar->set_session( -session=>{ user=>$user_id,
1615 cookie_name=>$self->cookie_name,
1616 cookie=>$cookie_value,
1617 expiration=>$expiration_time } );
1618 if ( defined $cookie_jar->error )
1619 {
1620 croak "Error: Could not update cookie value: ".($cookie_jar->error);
1621 }
1622
1623 # Create cookie.
1624 #
1625 my $cookie = $self->login_cookie( $cookie_value, $expiration_time );
1626 $self->cookie( $cookie );
1627  
1628 # SUCCESS
1629 #
1630 return 0;
1631 }
1632  
1633  
1634 =item CGI::Session::refresh_login_cookie
1635  
1636 Resets the expiration time for the current cookie.
1637  
1638 $self->refresh_login_cookie();
1639  
1640 =cut
1641  
1642 sub refresh_login_cookie
1643 {
1644 my ($self) = @_;
1645 $self->open;
1646 my $cookie_name = $self->cookie_name;
1647 my $cookie_value = $self->cgi->cookie( $cookie_name );
1648 my $expire = time + $self->cookie_expiration;
1649 my $cookie = $self->login_cookie( $cookie_value, $expire );
1650 my $cookie_jar = $self->cookie_jar;
1651 $cookie_jar->set_session( -session=>{ cookie_name=>$cookie_name,
1652 cookie=>$cookie_value,
1653 expiration=>$expire } );
1654 $self->cookie( $cookie );
1655 if ( $cookie_jar->error )
1656 {
1657 croak "Error: Could not set expiration for cookie: $cookie_jar->error";
1658 }
1659 }
1660  
1661  
1662  
1663 =item CGI::Session::user($)
1664  
1665 The cached name.
1666  
1667 my $username = $self->user();
1668  
1669 =cut
1670  
1671 sub user { my $self = shift; @_ ? $self->{user}=shift : $self->{user}; }
1672  
1673 =item CGI::Session::username($)
1674  
1675 Pulls the username for the current cookie/passkey pair from
1676 the database or local cache.
1677  
1678 my $username = $self->username();
1679  
1680 =cut
1681  
1682 sub username
1683 #
1684 # Gets the user ID for the current session.
1685 #
1686 # my $username = $session->username;
1687 #
1688 {
1689 my ( $self ) = @_;
1690  
1691 return $self->user if $self->user;
1692  
1693 my $cookie = $self->cgi->cookie( $self->cookie_name );
1694 my $passkey = $self->passkey;
1695  
1696 return undef unless( $cookie and $passkey );
1697  
1698 my $cookie_jar = $self->cookie_jar;
1699 my $sessions = $cookie_jar->session( -query => { -cookie_name=>$self->cookie_name,
1700 -cookie=>$cookie,
1701 -passkey=>$passkey },
1702 -omit_server_side_data => 1 );
1703 if ( defined $cookie_jar->error )
1704 {
1705 croak( "Error: Could not read user name fom the cookie jar: ".($cookie_jar->error) );
1706 }
1707 if ( scalar @{$sessions} == 0 )
1708 {
1709 croak "Error: Could not read user name from the cookie jar";
1710 }
1711 if ( scalar @{$sessions} > 1 )
1712 {
1713 croak "Error: Expected to retreive one username, but found several";
1714 }
1715  
1716 return $sessions->[0]->{user};
1717 }
1718  
1719 #
1720 # Create and assign the passkey from the database
1721 #
1722 =item CGI::Session::set_passkey
1723  
1724 Sets the passkey for the current session, and writes it into the
1725 backing store. The passkey is chosen randomly. The can either be
1726 specified within the call, or if the passkey and cookie are already set
1727 it can be extracted automatically by the session.
1728  
1729 $self->set_passkey( $username );
1730  
1731 ..or..
1732  
1733 $self->set_passkey();
1734  
1735 =cut
1736  
1737 sub set_passkey
1738 {
1739 my ($self) = shift;
1740  
1741 my $pass = int(rand 9999999)+1;
1742  
1743 $self->open;
1744 my $cookie_jar = $self->cookie_jar;
1745  
1746 # Set passkey based either on the specified username, or
1747 # upon the current login cookie.
1748 #
1749 if ( @_ )
1750 {
1751 my $user_id = shift;
1752 $user_id = defined $user_id ? $user_id : "";
1753 $cookie_jar->set_session( -session=>{ cookie_name=>$self->cookie_name,
1754 user=>$user_id,
1755 passkey=>$pass } );
1756 }
1757 else
1758 {
1759 my $cookie = $self->cgi->cookie( $self->cookie_name );
1760 $cookie_jar->set_session( -session=>{ cookie_name=>$self->cookie_name,
1761 cookie=>$cookie,
1762 passkey=>$pass } );
1763 }
1764 if ( $cookie_jar->error )
1765 {
1766 croak "Error: Problem encountered when attempting to store the passkey in the cookie jar: ".($cookie_jar->error);
1767 }
1768  
1769 $self->passkey( $pass );
1770  
1771 # SUCCESS
1772 #
1773 return 0;
1774 }
1775  
1776 sub server_side_data
1777 {
1778 my $self = shift;
1779  
1780 $self->open;
1781 my $username = $self->username;
1782 my $cookie_jar = $self->cookie_jar;
1783  
1784 # Set or retreive the server side data depending upon
1785 # whether or not another argument was specified.
1786 #
1787 if ( @_ )
1788 {
1789 my $server_side_data = shift;
1790 $cookie_jar->set_session( -session=>{ cookie_name=>$self->cookie_name,
1791 user=>$username,
1792 server_side_data=>$server_side_data } );
1793 if ( $cookie_jar->error )
1794 {
1795 croak "Error: Problem encountered when attempting to store the passkey in the cookie jar: ".($cookie_jar->error);
1796 }
1797 }
1798 else
1799 {
1800 my $session = $cookie_jar->session( -query=>{ -cookie_name=>$self->cookie_name,
1801 -user=>$username } );
1802 if ( $cookie_jar->error )
1803 {
1804 croak "Error: Problem encountered when attempting to store the passkey in the cookie jar: ".($cookie_jar->error);
1805 }
1806 return $session->[0]->{server_side_data};
1807 }
1808 }
1809  
1810  
1811 =item CGI::Session::logout_cookie
1812  
1813 Returns a login_cookie which has expired. (Expiration date
1814 is set to epoch.)
1815  
1816 my $cookie = $self->logout_cookie();
1817  
1818 =cut
1819  
1820 sub logout_cookie
1821 {
1822 my ($self) = @_;
1823 my $datetimestr = "Thu, 01-Jan-2000 00:00:01 GMT";
1824 my $cgi = $self->cgi;
1825 my $cookie = $cgi->cookie( -name=>$self->cookie_name,
1826 -value=>{},
1827 -path=>$self->cookie_path,
1828 -domain=>$self->cookie_domain,
1829 -secure=>($self->cookie_secure ? 1 : 0 ),
1830 -expires=>$datetimestr );
1831 return $cookie;
1832 }
1833  
1834 #
1835 # logout here (as far as cookies are concerned)
1836 #
1837 =item CGI::Session::set_logout_cookie
1838  
1839 Expires the cookie in the backing store.
1840  
1841 my $cookie = $self->set_logout_cookie();
1842  
1843 =cut
1844  
1845 sub set_logout_cookie
1846 {
1847 my ($self) = @_;
1848  
1849 my $logout_cookie = $self->logout_cookie;
1850 $self->cookie( $logout_cookie );
1851
1852 # SUCCESS
1853 return 0;
1854 }
1855  
1856 #
1857 # Check Cookie
1858 #
1859 =item CGI::Session::check_cookie
1860  
1861 Returns the cookie for this session if it exists. If a
1862 cookie does not exist then it returns nothing.
1863  
1864 my $login_cookie = $self->check_cookie();
1865  
1866 =cut
1867  
1868 sub check_cookie
1869 {
1870 my ($self) = @_;
1871 return $self->cgi->cookie($self->cookie_name);
1872 }
1873  
1874 1;