blib/lib/CGI/Application/Plugin/Authentication/Driver/DBI.pm

filter: Statementstmt 69.4% 50 / 72 Branchbran 40.4% 17 / 42 Conditioncond 40.0% 2 / 5 MC/DCmcdc 0.0% 0 / 3 Subroutinesub 100% 4 / 4 Podpod 100% 1 / 1 totaltotal 58.2% 74 / 127 CC 25 SCAR 43.3
CC
25
Cov
58%
verify_credentials
85.3
BEGIN
1.0
BEGIN
1.0
CRAP 76.3
↑ Summary blib/lib/CGI/Application/Plugin/Authentication.pm »
1 package CGI::Application::Plugin::Authentication::Driver::DBI;
2  
3 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 3 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 3 ▶use base qw(CGI::Application::Plugin::Authentication::Driver);
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 =head1 NAME
9  
10 CGI::Application::Plugin::Authentication::Driver::DBI - DBI Authentication driver
11  
12  
13 =head1 SYNOPSIS
14  
15 use base qw(CGI::Application);
16 use CGI::Application::Plugin::Authentication;
17  
18 __PACKAGE__->authen->config(
19 DRIVER => [ 'DBI',
20 DBH => $self->dbh,
21 TABLE => 'user',
22 CONSTRAINTS => {
23 'user.name' => '__CREDENTIAL_1__',
24 'MD5:user.password' => '__CREDENTIAL_2__'
25 },
26 ],
27 );
28  
29  
30 =head1 DESCRIPTION
31  
32 This Authentication driver uses the DBI module to allow you to authenticate against
33 any database for which there is a DBD module. You can either provide an active
34 database handle, or provide the parameters necessary to connect to the database.
35  
36 When describing the database structure, you need to specify some or all of the
37 following parameters: TABLE(S), JOIN_ON, COLUMNS, CONSTRAINTS, ORDER_BY and
38 LIMIT.
39  
40 =head2 DBH
41  
42 The DBI database handle to use. Defaults to C<$self->dbh()>, which is provided and configured
43 through L<CGI::Application::Plugin::DBH|CGI::Application::Plugin::DBH>
44  
45 =head2 TABLE(S) (required)
46  
47 Provide either a single table name, or an array of table names. You can give the
48 table names aliases which can be referenced in later columns.
49  
50 TABLE => 'users',
51  
52 - or -
53  
54 TABLES => ['users U', 'domains D'],
55  
56  
57 =head2 JOIN_ON (conditionally required)
58  
59 If you have specified multiple tables, then you need to provide an SQL expression that
60 can be used to join those tables.
61  
62 JOIN_ON => 'user.domainid = domain.id',
63  
64 - or -
65  
66 JOIN_ON => 'U.domainid = D.id',
67  
68  
69 =head2 COLUMNS (optional)
70  
71 This is a hash of columns/values that should be pulled out of the database and validated
72 locally in perl. Most credentials can be checked right in the database (example
73 username = ?), but some parameters may need to be tested locally in perl, so they
74 must be listed in the COLUMNS option. One example of a value that needs to be tested
75 in perl is a crypted password. In order to test a crypted password, you need to
76 take the entered password, and crypt it with the salt of the already crypted password.
77 But until we actually see the password that is in the database, we will not know the
78 value of the salt that was used to encrypt the password. So we pull the value out
79 using COLUMNS, and the test will be performed automatically in perl.
80  
81 Any value that matches __CREDENTIAL_n__ (where n is a number) will be replaced with
82 the corresponding credential that was entered by the user. For an explanation of
83 what the credentials are and where they come from, see the section headed with
84 CREDENTIALS in L<CGI::Application::Plugin::Authentication>.
85  
86 COLUMNS => { 'crypt:password' => '__CREDENTIAL_2__' },
87  
88  
89 =head2 CONSTRAINTS (optional)
90  
91 You will most likely always have some constraints to use. These constraints
92 will be added to the WHERE clause of the SQL query, and will ideally reduce
93 the number of returned rows to one.
94  
95 Any value that matches __CREDENTIAL_n__ (where n is a number) will be replaced with
96 the corresponding credential that was entered by the user. For an explanation of
97 what the credentials are and where they come from, see the section headed with
98 CREDENTIALS in L<CGI::Application::Plugin::Authentication>.
99  
100 CONSTRAINTS => {
101 'users.email' => '__CREDENTIAL_1__',
102 'MD5:users.passphrase' => '__CREDENTIAL_2__',
103 'users.active' => 1,
104 }
105  
106  
107 =head2 ORDER_BY (optional)
108  
109 This option allows you to order the result set, in case the query returns
110 multiple rows.
111  
112 ORDER_BY => 'created DESC'
113  
114 Note: This option is only useful if you also specify the COLUMNS option.
115  
116 =head2 LIMIT (optional)
117  
118 In some situations your query may return multiple rows when you only want it to
119 return one. For example if you insert and date a new row instead of updating
120 the existing row when the details for an account change. In this case you want
121 the newest record from the result set, so it will be important to order the
122 result set and limit it to return only one row.
123  
124 LIMIT => 1
125  
126 Note: This option is only useful if you also specify the COLUMNS option.
127  
128 =head1 ENCODED PASSWORDS
129  
130 It is quite common to store passwords in a database in some form that makes them hard
131 (or virtually impossible) to guess. Most of the time one way encryption techniques
132 like Unix crypt or MD5 hashes are used to store the password securely (I would recommend
133 using MD5 or SHA1 over Unix crypt). If you look at the examples listed above, you can
134 see that you can mark your columns with an encoding type. Here is another example:
135  
136 CONSTRAINTS => {
137 username => '__CREDENTIAL_1__',
138 'MD5:password' => '__CREDENTIAL_2__',
139 }
140  
141 Here the password field is expected to be stored in the database in MD5 format. In order for the
142 MD5 check to work for all databases, the password will be encoded using perl, and then checked
143 against the value in the database. So in effect, the following will be done:
144  
145 $username = 'test';
146 $password = '123';
147 $encoded_password = 'ICy5YqxZB1uWSwcVLSNLcA';
148 $sth = $dbh->prepare('SELECT count(*) FROM users WHERE username = ? AND password = ?';
149 $sth->execute($username, $encoded_password);
150 # I we found a row, then the user credentials are valid and the user is logged in
151  
152 This is all automatically performed behind the scenes when you specify that a certain field
153 in the database is encoded.
154  
155 We have to handle this slightly different when working with Unix crypt. In order to crypt
156 a password, you need to provide the crypt function with a 2 character salt value. These are
157 usually just generated randomly, and when the value is crypted, the first two characters of
158 the resulting string will be the 2 salt characters. The problem comes into play when you want
159 to check a password against a crypted password. You need to know the salt in order to
160 properly test the password. But in our case, the crypted password is in the DB. This means we
161 can not generate the crypted test password before we run the query against the database.
162  
163 So instead we pull the value of the crypted password out of the database, and then perform the
164 tests after the query, instead of before. Here is an example:
165  
166 CONSTRAINTS => { 'username' => '__CREDENTIAL_1__' },
167 COLUMNS => { 'crypt:password' => '__CREDENTIAL_2__' },
168  
169 And here is what will happen behind the scenes:
170  
171 $username = 'test';
172 $password = '123';
173 $sth = $dbh->prepare('SELECT password FROM users WHERE username = ?';
174 $sth->execute($username);
175 ($encoded_password) = $sth->fetchrow_array;
176 if ($encoded_password eq crypt($password, $encoded_password)) {
177 # The credentials are valid and the user is logged in
178 }
179  
180 Again, this is all done automatically behind the scenes, but I've included it here to illustrate how
181 the queries are performed, and how the comparisons are handled. For more information
182 see the section labelled ENCODED PASSWORDS in the L<CGI::Application::Plugin::Authentication::Driver>
183 docs.
184  
185  
186  
187 =head1 EXAMPLE
188  
189 # using multiple tables
190 # Here we check three credentials (user, password and domain) across
191 # two separate tables.
192 __PACKAGE__->authen->config(
193 DRIVER => [ 'DBI',
194 # the handle comes from $self->dbh, via the "DBH" plugin.
195 TABLES => ['user', 'domain'],
196 JOIN_ON => 'user.domainid = domain.id',
197 CONSTRAINTS => {
198 'user.name' => '__CREDENTIAL_1__',
199 'user.password' => '__CREDENTIAL_2__',
200 'domain.name' => '__CREDENTIAL_3__'
201 }
202 ],
203 );
204  
205 - or -
206  
207 # using filtered fields
208 # Here the password column contains values that are encoded using unix crypt
209 # and since we need to know the salt in order to encrypt the password
210 # properly, we need to pull out the password, and check it locally
211 __PACKAGE__->authen->config(
212 DRIVER => [ 'DBI',
213 DBH => $dbh, # provide your own DBI handle
214 TABLE => 'user',
215 CONSTRAINTS => { 'user.name' => '__CREDENTIAL_1__' }
216 COLUMNS => { 'crypt:password' => '__CREDENTIAL_2__' },
217 ],
218 );
219  
220 - or -
221  
222 # extra constraints
223 # Here we only check users where the 'active' column is true
224 __PACKAGE__->authen->config(
225 DRIVER => [ 'DBI',
226 TABLE => 'user',
227 CONSTRAINTS => {
228 'user.name' => '__CREDENTIAL_1__',
229 'user.password' => '__CREDENTIAL_2__',
230 'user.active' => 't'
231 },
232 ],
233 );
234  
235 - or -
236  
237 # all of them combined
238 # Here the user is required to enter a username and password (which is
239 # crypted), and a daily code that changes every day (which is encoded using
240 # an MD5 hash hex format and stored in upper case).
241 __PACKAGE__->authen->config(
242 DRIVER => [ 'DBI',
243 TABLES => ['user U', 'dailycode D'],
244 JOIN_ON => 'U.userid = D.userid',
245 CONSTRAINTS => {
246 'U.name' => '__CREDENTIAL_1__',
247 'uc:md5_hex:D.code' => '__CREDENTIAL_3__',
248 'D.date' => 'now'
249 },
250 COLUMNS => {
251 'crypt:U.password' => '__CREDENTIAL_2__'
252 },
253 ],
254 );
255  
256  
257  
258 =head1 METHODS
259  
260 =head2 verify_credentials
261  
262 This method will test the provided credentials against the values found in the database,
263 according to the Driver configuration.
264  
265 =cut
266  
267 sub verify_credentials {
268 3 ▶ my $self = shift;
Subroutine verify_credentials: called CC=25 SCAR=44.5
Pod documented
269 3 my @creds = @_;
270  
271 # verify that all the options are OK
272 3 my @_options = $self->options;
273 3 ▶ die "The DBI driver requires a hash of options" if @_options % 2;
Branch: 1 branch
BranchTrueFalseTotal
if @_options % 2 1 2 3
274 2 my %options = @_options;
275  
276 # Get a database handle - either one that is given to us, or see if there
277 # is a ->dbh method in the CGIApp module (This is provided by the
278 # CGI::Application::Plugin::DBH module, so use it if it is there).
279 2 my $dbh;
280 2 ▶ if ( $options{DBH} ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($options{'DBH'}) { } 1 1 2
elsif ($self->authen->_cgiapp->can('dbh')) { } 0 1 1
281 1 $dbh = $options{DBH};
282 } elsif ( $self->authen->_cgiapp->can('dbh') ) {
283 0 $dbh = $self->authen->_cgiapp->dbh;
284 } else {
285 1 die "No DBH handle passed to the DBI Driver, and no dbh() method detected";
286 }
287  
288 # Grab the database table names (TABLE and TABLES are synonymous)
289 1 ▶ my $tables = $options{TABLES} || $options{TABLE};
Condition33%1/3
$options{'TABLES'} || $options{'TABLE'}
l!l&&r!l&&!r
010
MC/DC0%0/2
$options{'TABLES'} || $options{'TABLE'}
$options{'TABLES'} $options{'TABLE'}
Truth table33%1/3
A || B
A= $options{'TABLES'}B= $options{'TABLE'}
ABresult
1X1
011
000
290 1 ▶ die "No TABLE parameter defined" unless defined($tables);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $tables 0 1 1
291 1 ▶ $tables = [$tables] unless ref $tables eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $tables eq "ARRAY" 1 0 1
292  
293 # See if we need to order the result set
294 1 ▶ my $order_by = $options{ORDER_BY} ? ' ORDER BY '.$options{ORDER_BY} : '';
Branch: 1 branch
BranchTrueFalseTotal
$options{'ORDER_BY'} ? : 0 1 1
295  
296 # See if we need to limit the result set
297 1 ▶ my $limit = $options{LIMIT} ? ' LIMIT '.$options{LIMIT} : '';
Branch: 1 branch
BranchTrueFalseTotal
$options{'LIMIT'} ? : 0 1 1
298  
299 # Grab all the columns that we need to pull out. We also grab a list of
300 # columns that are stripped of any encoding information.
301 # If no columns are provided we just select count(*) for efficiency.
302 1 my @columns;
303 my @stripped_columns;
304 1 ▶ if ( $options{COLUMNS} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options{'COLUMNS'}) { } 0 1 1
305 0 ▶ die "COLUMNS must be a hashref" unless ref $options{COLUMNS} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $options{"COLUMNS"} eq "HASH" 0 0 0
306 0 @columns = keys %{ $options{COLUMNS} };
307 0 @stripped_columns = $self->strip_field_names(@columns);
308 } else {
309 1 @columns = ('count(*)');
310 1 @stripped_columns = @columns;
311 }
312  
313 # Process the constraints.
314 # We need to check for values indicate they should be replaced by
315 # a credential (__CREDENTIAL_\d+__), and we need to filter any values
316 # that are configured to be filtered
317 1 my %constraints;
318 1 ▶ if ( $options{CONSTRAINTS} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options{"CONSTRAINTS"}) 1 0 1
319 1 ▶ die "CONSTRAINTS must be a hashref" unless ref $options{CONSTRAINTS} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $options{"CONSTRAINTS"} eq "HASH" 0 1 1
320 1 ▶ while ( my ( $column, $value ) = each %{ $options{CONSTRAINTS} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %{$options{"CONSTRAINTS"};}) 2 1 3
321 2 ▶ if ( $value =~ /^__CREDENTIAL_(\d+)__$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($value =~ /^__CREDENTIAL_(\d+)__$/) 2 0 2
322 2 $value = $creds[ $1 - 1 ];
323 }
324 2 $value = $self->filter( $column, $value );
325 2 $column = $self->strip_field_names($column);
326 2 $constraints{$column} = $value;
327 }
328 }
329  
330 # If we have multiple tables, then we need a join constraint
331 1 my $join_on = $options{JOIN_ON};
332  
333 # Build the SQL statement
334 1 my $sql = 'SELECT ' . join( ', ', @stripped_columns ) . ' FROM ' . join( ', ', @$tables ) . ' WHERE ';
335 1 my @where;
336 1 ▶ push @where, $join_on if $join_on;
Branch: 1 branch
BranchTrueFalseTotal
if $join_on 0 1 1
337 1 push @where, map { $_ . ' = ?' } keys %constraints;
338 1 $sql .= join( ' AND ', @where );
339 1 my @params = values %constraints;
340 1 $sql .= $order_by;
341 1 $sql .= $limit;
342  
343 # prepare and execute the SQL
344 1 ▶ my $sth = $dbh->prepare_cached($sql) || die "Failed to prepare SQL statement: " . $dbh->errstr;
Condition50%1/2
$dbh->prepare_cached($sql) || die('Failed to prepare SQL statement: ' . $dbh->errstr)
l!l
10
MC/DC0%0/1
$dbh->prepare_cached($sql) || die('Failed to prepare SQL statement: ' . $dbh->errstr)
$dbh->prepare_cached($sql)
Truth table50%1/2
A
A= $dbh->prepare_cached($sql)
Aresult
11
00
345 1 ▶ $sth->execute(@params) or die $dbh->errstr;
Branch: 1 branch
BranchTrueFalseTotal
$sth->execute(@params) or die $dbh->errstr 1 0 1
346  
347 # Figure out what to do with the results
348 0 ▶ if ( $options{COLUMNS} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options{'COLUMNS'}) { } 0 0 0
349 # Since we pulled out some columns, we assume that these columns were not checked
350 # in the constraints section, and we test them here.
351 # It is possible that we could have multiple rows, so keep checking until we
352 # find a row where all comparisons are successful.
353 0 ▶ while ( my @array = $sth->fetchrow_array ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@array) = $sth->fetchrow_array) 0 0 0
354 0 my $match = 1;
355 0 foreach my $index ( 0 .. $#columns ) {
356 0 my $value = $options{COLUMNS}->{ $columns[$index] };
357 0 ▶ if ( $value =~ /^__CREDENTIAL_(\d+)__$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($value =~ /^__CREDENTIAL_(\d+)__$/) 0 0 0
358 0 $value = $creds[ $1 - 1 ];
359 }
360 0 ▶ if ( !$self->check_filtered( $columns[$index], $value, $array[$index] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->check_filtered($columns[$index], $value, $array[$index])) 0 0 0
361 # This test failed, so there is no sense checking the rest of the values
362 # in this row so we bail out early
363 0 $match = 0;
364 0 last;
365 }
366 }
367 0 ▶ if ($match) {
Branch: 1 branch
BranchTrueFalseTotal
if ($match) 0 0 0
368 # we found a match so clean up and return the first credential
369 0 $sth->finish;
370 0 return $creds[0];
371 }
372 }
373 } else {
374 # Since we are not pulling specific columns we just check
375 # to see if we matched at least one row
376 0 my ($count) = $sth->fetchrow_array;
377 0 $sth->finish;
378 0 ▶ return $creds[0] if $count;
Branch: 1 branch
BranchTrueFalseTotal
if $count 0 0 0
379 }
380 0 return;
381 }
382  
383 =head1 SEE ALSO
384  
385 L<CGI::Application::Plugin::Authentication::Driver>, L<CGI::Application::Plugin::Authentication>, perl(1)
386  
387  
388 =head1 LICENCE AND COPYRIGHT
389  
390 Copyright (c) 2005, SiteSuite. All rights reserved.
391  
392 This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
393  
394  
395 =head1 DISCLAIMER OF WARRANTY
396  
397 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.
398  
399 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.
400  
401 =cut
402  
403 3 1;
↑ Summary blib/lib/CGI/Application/Plugin/Authentication.pm »