blib/lib/WWW/AuthTicket.pm untested

filter: Statementstmt 0.0% 0 / 113 Branchbran 0.0% 0 / 26 Conditioncond 0.0% 0 / 24 MC/DCmcdc 0.0% 0 / 14 Subroutinesub 0.0% 0 / 23 Podpod 0.0% 0 / 12 totaltotal 0.0% 0 / 212 CC 14 SCAR 24.2
CC
14
Cov
0%
verify_auth_cookie
42.0
new
12.0
_auth_expired
12.0
CRAP 11.2
1 package WWW::AuthTicket;
2  
3 =pod
4  
5 =head1 NAME
6  
7 AuthTicket.pm
8  
9 =head1 SYNOPSIS
10  
11 Handle authorization for web services or restricted areas of a website.
12  
13 This object oriented module is meant to be sub-classed.
14  
15 =head1 USAGE
16  
17 Keep in mind that you'll want to create your own class that inherits this one.
18 See the SUB-CLASSING EXAMPLE section below.
19  
20 use WWW::AuthTicket;
21  
22 my $auth = WWW::AuthTicket->new(-env => \%ENV, -secret_key => '[ABC123]');
23  
24 my ($auth_ok, $msg) = $auth->verify_auth_cookie();
25  
26 unless ($auth_ok) {
27  
28 ## send to log in screen (problem described in $msg)
29  
30 }
31  
32 my ($successful, $msg) = $auth->authenticate_user($username, $password);
33  
34 if ($successful) {
35  
36 print "Set-Cookie: " . $auth->issue_auth_cookie() . "\n";
37  
38 }
39 else {
40  
41 ## failure reason in $msg
42  
43 }
44  
45 ## log out
46  
47 print "Set-Cookie: " . $auth->void_auth_cookie() . "\n";
48  
49 =head1 METHODS
50  
51 =over
52  
53 =cut
54  
55 use strict;
56 use CGI::Cookie;
57 use Digest::SHA1 qw(sha1_hex);
58 use vars qw($VERSION);
59  
60 $VERSION = 0.01;
61  
62 use constant TRUE => 1;
63 use constant FALSE => !TRUE;
64  
65 use constant DEFAULT_SECRET_KEY => '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
66 use constant DEFAULT_COOKIE_NAME => 'auth';
67 use constant RET_ADDR_COOKIE_NAME => 'requesturi';
68 use constant NEVER_EXPIRES => '0E0';
69 use constant HTTP_DEFAULT_PORT => '80';
70  
71 =pod
72  
73 =item new()
74  
75 Object constructor. Specify parameters as key/value pairs. Possible keys are:
76  
77 =over
78  
79 =item -env (required)
80  
81 A reference to the %ENV hash
82  
83 =item -secret_key (optional, but recommended)
84  
85 A string of any length for the hashing algorithm
86  
87 =item -auth_expires (optional)
88  
89 Length of time in minutes before the authorization should expire
90 (default is no expiration, just the end of the browser's session).
91 You would only need to specify this parameter when you are going to
92 call C<issue_auth_cookie()> because this value gets embedded in the
93 cookie itself with C<issue_auth_cookie()>.
94  
95 =item -cookie_name (optional)
96  
97 If you want to call the cookie something other than the default name, "auth"
98  
99 =item -cookie_domain (optional)
100  
101 Use this to specify a domain for use in the cookie.
102 Default is to use the "SERVER_NAME" environment variable which makes the cookie
103 valid only for that particular host. You would specify a value here if you want
104 the cookie to be good for other hosts under your domain.
105  
106 =back
107  
108 my $auth = WWW::AuthTicket->new(-env => \%ENV, -secret_key => '*foobarbaz*');
109  
110 =cut
111  
112 sub new
113 {
114 my $class = shift;
115 my %args = @_;
116  
117 my $env_href = $args{'-env'};
118  
119 die "Environment variable hash reference is missing" unless ref($env_href) eq 'HASH';
120 die "Can't find client's IP address - \$ENV{REMOTE_ADDR} empty" unless $env_href->{REMOTE_ADDR};
121  
122 my $secret_key = $args{'-secret_key'} || DEFAULT_SECRET_KEY;
123 my $auth_expires = $args{'-auth_expires'} || NEVER_EXPIRES;
124 my $cookie_name = $args{'-cookie_name'} || DEFAULT_COOKIE_NAME;
125 my $cookie_domain = $args{'-cookie_domain'} || $env_href->{SERVER_NAME};
126  
127 ## truncated version of ip address to account for proxy servers
128 (my $ip_trunc = $env_href->{REMOTE_ADDR}) =~ s/\d{1,3}$//;
129  
130 my %cookies = CGI::Cookie->parse($env_href->{'HTTP_COOKIE'});
131  
132 my $self = {
133 'env' => $env_href,
134 'ip_truncated' => $ip_trunc,
135 'secret_key' => $secret_key,
136 'auth_expires' => $auth_expires,
137 'cookie_name' => $cookie_name,
138 'cookie_domain' => $cookie_domain,
139 'cookies' => \%cookies,
140 'cookie_values' => {}, ## to be determined by authenticate_user()
141 };
142  
143 return bless $self, $class;
144 }
145  
146 =pod
147  
148 =item authenticate_user()
149  
150 Given a username/user ID and password, verifies the credentials and returns
151 a boolean for whether or not the verification was successful and a message
152 explaining any failure that might have occurred.
153  
154 my ($successful, $msg) = $auth->authenticate_user($username, $password);
155  
156 B<NOTE:> This module can (and should) be sub-classed in order to provide your own
157 customized authentication handling - like with a database. Values pulled from your
158 user database can be added to the authorization cookie and also extracted from it
159 after the cookie has been verified. See the C<get_cookie_value()> method.
160  
161 =cut
162  
163 sub authenticate_user
164 {
165 warn "Using AuthTicket::authenticate_user() - this should not be used.",
166 "AuthTicket should be sub-classed and authenticate_user() should be overridden by a customized method.";
167  
168 my ($self, $user, $pass) = @_;
169  
170 my ($success, $msg);
171  
172 if ($user eq 'test' && $pass eq 'test')
173 {
174 $success = TRUE;
175 $self->add_cookie_value('userid' => 1);
176 }
177 else
178 {
179 $success = FALSE;
180 $msg = "Invalid username or password";
181 }
182  
183 return($success, $msg);
184 }
185  
186 =pod
187  
188 =item add_cookie_value()
189  
190 Use this method to add name/value pairs you want included in the authorization cookie.
191 This method is useful for inclusion in your own C<authenticate_user()> method that you
192 create when you sub-class the AuthTicket class. Use it to save user-specific info that you
193 pull back from your user database so that you don't have to look it up in the database
194 for every request the user sends.
195  
196 my $num_added = $self->add_cookie_value('userid' => $uid, 'authlevel' => $authlevel, ...);
197  
198 It can return the number of values added for checking, but that is optional.
199 You could just call it in a void context.
200  
201 These values can then be retreived from the cookie using the C<get_cookie_value()> method.
202  
203 =cut
204  
205 sub add_cookie_value
206 {
207 my $self = shift;
208 my %cookies = @_;
209  
210 my $count = 0;
211  
212 foreach my $key (keys %cookies)
213 {
214 $self->{'cookie_values'}->{$key} = $cookies{$key};
215 $count++;
216 }
217  
218 return $count if defined wantarray;
219 }
220  
221 =pod
222  
223 =item get_cookie_value()
224  
225 Returns the value from the specified part of the authorization cookie -
226 C<verify_auth_cookie()> method must be called first.
227  
228 my $userid = $auth->get_cookie_value('userid'); # example
229  
230 =cut
231  
232 sub get_cookie_value
233 {
234 my ($self, $value_name) = @_;
235 warn "AuthTicket::get_cookie_value() - '$value_name' does not exist" unless exists $self->{'cookie_values'}->{$value_name};
236 return $self->{'cookie_values'}->{$value_name};
237 }
238  
239 =pod
240  
241 =item issue_auth_cookie()
242  
243 Returns a C<CGI::Cookie>-formatted cookie. Use after C<authenticate_user()> returns successful.
244  
245 print "Set-Cookie: " . $auth->issue_auth_cookie() . "\n";
246  
247 =cut
248  
249 sub issue_auth_cookie
250 {
251 my $self = shift;
252  
253 my %cookie_values = %{$self->{'cookie_values'}};
254  
255 $cookie_values{'ip'} = $self->{'ip_truncated'};
256 $cookie_values{'time'} = time();
257 $cookie_values{'expires'} = $self->{'auth_expires'};
258  
259 my @hash_these;
260 push @hash_these, $cookie_values{$_} for (sort keys %cookie_values);
261  
262 my $hash = sha1_hex($self->{'secret_key'} . sha1_hex(join(':', $self->{'secret_key'}, @hash_these)));
263 $cookie_values{'hash'} = $hash;
264  
265 return CGI::Cookie->new(
266 -name => $self->{'cookie_name'},
267 -path => '/',
268 -domain => $self->{'cookie_domain'},
269 -value => \%cookie_values,
270 );
271 }
272  
273 =pod
274  
275 =item void_auth_cookie()
276  
277 Returns a C<CGI::Cookie>-formatted cookie that deletes the auth cookie. Use for logging a user out.
278  
279 print "Set-Cookie: " . $auth->void_auth_cookie() . "\n";
280  
281 =cut
282  
283 sub void_auth_cookie
284 {
285 my $self = shift;
286 return CGI::Cookie->new(
287 -name => $self->{'cookie_name'},
288 -path => '/',
289 -domain => $self->{'cookie_domain'},
290 -value => '',
291 -expires => '-1M',
292 );
293 }
294  
295 =pod
296  
297 =item verify_auth_cookie()
298  
299 Parses and verifies the authorization cookie. Returns a boolean for whether or not the
300 verification was successful and a message explaining any failure that might have occurred.
301  
302 my ($auth_ok, $msg) = $auth->verify_auth_cookie();
303  
304 =cut
305  
306 sub verify_auth_cookie
307 {
308 my $self = shift;
309  
310 return(FALSE, 'no cookie') unless exists $self->{'cookies'}->{$self->{'cookie_name'}};
311  
312 my %auth_cookie = $self->{'cookies'}->{$self->{'cookie_name'}}->value;
313  
314 return(FALSE, 'malformed cookie')
315 unless $auth_cookie{'hash'} && $auth_cookie{'ip'}
316 && $auth_cookie{'time'} && length($auth_cookie{'expires'});
317  
318 return(FALSE, 'IP address mismatch') if $auth_cookie{'ip'} ne $self->{'ip_truncated'};
319  
320 return(FALSE, 'authorization has expired') if _auth_expired(\%auth_cookie);
321  
322 my $hash = delete $auth_cookie{'hash'};
323  
324 my @hash_these;
325 push @hash_these, $auth_cookie{$_} for (sort keys %auth_cookie);
326  
327 my $new_hash = sha1_hex($self->{'secret_key'} . sha1_hex(join(':', $self->{'secret_key'}, @hash_these)));
328  
329 return(FALSE, 'hash mismatch - cookie value possibly tampered with') if $new_hash ne $hash;
330  
331 $self->{'auth_expires'} = $auth_cookie{'expires'};
332  
333 while (my ($k, $v) = each %auth_cookie)
334 {
335 $self->{'cookie_values'}->{$k} = $v;
336 }
337  
338 return(TRUE, '');
339 }
340  
341 =pod
342  
343 =item make_return_address()
344  
345 Returns a C<CGI::Cookie>-formatted cookie that contains the URI the user is trying to access.
346 Here's how to use this: say a user is trying to access a URI that requires them to be logged
347 in, but they are either not logged in or their login has expired. Use this to save the URI for
348 the page they were trying to access so that after they log in you can send them where they
349 were trying to go before they were interrupted with the log-in process.
350  
351 print "Set-Cookie: " . $auth->make_return_address() . "\n";
352  
353 =cut
354  
355 sub make_return_address
356 {
357 my $self = shift;
358  
359 my $uri = 'http://' . $self->{'env'}->{'SERVER_NAME'}
360 . ($self->{'env'}->{'SERVER_PORT'} ne HTTP_DEFAULT_PORT ? ':'.$self->{'env'}->{'SERVER_PORT'} : "")
361 . $self->{'env'}->{'REQUEST_URI'};
362  
363 return CGI::Cookie->new(
364 -name => RET_ADDR_COOKIE_NAME,
365 -value => $uri,
366 -domain => $self->{'cookie_domain'},
367 -path => '/'
368 );
369 }
370  
371 =pod
372  
373 =item get_return_address()
374  
375 Returns the URI from the cookie set with C<make_return_address()>.
376  
377 my $requested_uri = $auth->get_return_address();
378  
379 =cut
380  
381 sub get_return_address
382 {
383 my $self = shift;
384 return $self->{'cookies'}->{RET_ADDR_COOKIE_NAME()};
385 }
386  
387 =pod
388  
389 =item clear_return_address()
390  
391 Returns a C<CGI::Cookie>-formatted cookie that deletes the return address
392 cookie that was set with C<make_return_address()>. Use after a successful log
393 in so that the user doesn't get redirected to the saved URI over and over again.
394  
395 print "Set-Cookie: " . $auth->clear_return_address() . "\n";
396  
397 =cut
398  
399 sub clear_return_address
400 {
401 my $self = shift;
402 return CGI::Cookie->new(
403 -name => RET_ADDR_COOKIE_NAME,
404 -value => '',
405 -domain => $self->{'cookie_domain'},
406 -path => '/',
407 -expires => '-1M',
408 );
409 }
410  
411 sub _auth_expired
412 {
413 my $auth_cookie_href = shift;
414 return FALSE if $auth_cookie_href->{'expires'} eq NEVER_EXPIRES;
415 return FALSE if _to_minutes(time - $auth_cookie_href->{'time'}) < $auth_cookie_href->{'expires'};
416 return TRUE;
417 }
418  
419 sub _to_minutes
420 {
421 my $seconds = shift;
422 return $seconds / 60;
423 }
424  
425 1;
426  
427 __END__