AppServer/Plugin/HTTPAuth.pm untested

filter: Statementstmt 0.0% 0 / 53 Branchbran 0.0% 0 / 16 Conditioncond 0.0% 0 / 12 MC/DCmcdc 0.0% 0 / 7 Subroutinesub 0.0% 0 / 8 Podpod 0.0% 0 / 2 totaltotal 0.0% 0 / 98 CC 9 SCAR 29.7
CC
9
Cov
0%
init
30.0
_auth
30.0
BEGIN
2.0
CRAP 19.5
1 package HTTP::AppServer::Plugin::HTTPAuth;
2 # Plugin for HTTP::AppServer uses HTTP authentication to
3 # authenticate a client. The authentication works based
4 # on a certain handler regex.
5 # 2010 by Tom Kirchner
6  
7 use 5.010000;
8 use strict;
9 use warnings;
10 use MIME::Base64;
11 use HTTP::AppServer::Plugin;
12 use base qw(HTTP::AppServer::Plugin);
13  
14 our $VERSION = '0.01';
15  
16 my $Logins = {};
17 my $URLs = [];
18  
19 # called by the server when the plugin is installed
20 # to determine which routes are handled by the plugin
21 sub init
22 {
23 my ($class, $server, %options) = @_;
24  
25 $Logins = $options{'Logins'} if exists $options{'Logins'};
26 $URLs = $options{'URLs'} if exists $options{'URLs'};
27
28 if (exists $options{'LoginsFile'}) {
29 my $filename = $options{'LoginsFile'};
30
31 open(FH, '<'.$filename)
32 or print STDERR "HTTPAuth: Failed to open loginsfile '$filename': $! $@\n";
33 while (my $line = <FH>) {
34 chomp $line;
35 my ($username, $password) = split /\:/, $line;
36 $Logins->{$username} = $password
37 if defined $username && length $username && defined $password;
38 }
39 close FH;
40 }
41  
42 # hash that contains all active http login accounts
43 $server->set('httpauth_logins', $Logins);
44  
45 # hash that contains all restricted area URLs
46 $server->set('httpauth_urls', $URLs);
47  
48 # the plugin installs a match-all URL handler
49 return (
50 '^(.*)$' => \&_auth,
51 );
52 }
53  
54 sub _auth
55 {
56 my ($server, $cgi, $url) = @_;
57
58 if (scalar grep { ($url =~ /$_/) == 1 } @{$server->httpauth_urls()}) {
59 my $auth = $cgi->http('Authorization');
60
61 my $authorized = 0;
62 if (defined $auth) {
63 # try to authenticate user
64 my ($prefix, $encoded) = split /\s/, $auth;
65 my ($username, $password) = split /\:/, decode_base64($encoded);
66 if (exists $server->httpauth_logins()->{$username} &&
67 $server->httpauth_logins()->{$username} eq $password) {
68
69 my $session_id = time().sprintf('%.0f', rand(100000000));
70 $authorized = 1;
71 }
72 }
73
74 unless ($authorized) {
75 # tell client to authorizate itself
76 print
77 "HTTP/1.0 401 Unauthorized\r\n".
78 $cgi->header(
79 -WWW_Authenticate => 'Basic realm="MySite"',
80 );
81 return 1;
82 }
83 }
84 return 0;
85 }
86  
87 1;
88 __END__