blib/lib/Web/Authenticate.pm untested

filter: Statementstmt 0.0% 0 / 152 Branchbran 0.0% 0 / 50 Conditioncond 0.0% 0 / 21 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 17 Podpod 0.0% 0 / 6 totaltotal 0.0% 0 / 246 CC 26 SCAR 36.8
CC
26
Cov
0%
is_authenticated
90.0
login
56.0
create_user
42.0
CRAP 39.6
1 use strict;
2 package Web::Authenticate;
3 $Web::Authenticate::VERSION = '0.003';
4 use Mouse;
5 use Carp;
6 use Web::Authenticate::Cookie::Handler;
7 use Web::Authenticate::RedirectHandler;
8 use Web::Authenticate::Result::CreateUser;
9 use Web::Authenticate::Result::Login;
10 use Web::Authenticate::Result::Authenticate;
11 use Web::Authenticate::Result::IsAuthenticated;
12 use Web::Authenticate::RequestUrlProvider::CgiRequestUrlProvider;
13 use Ref::Util qw/is_arrayref/;
14 #ABSTRACT: Allows web authentication using cookies and a storage engine.
15  
16  
17  
18  
19 has user_storage_handler => (
20 does => 'Web::Authenticate::User::Storage::Handler::Role',
21 is => 'ro',
22 required => 1,
23 );
24  
25  
26 has session_handler => (
27 does => 'Web::Authenticate::Session::Handler::Role',
28 is => 'ro',
29 required => 1,
30 );
31  
32  
33 has cookie_handler => (
34 does => 'Web::Authenticate::Cookie::Handler::Role',
35 is => 'ro',
36 required => 1,
37 default => sub { Web::Authenticate::Cookie::Handler->new },
38 );
39  
40  
41 has redirect_handler => (
42 does => 'Web::Authenticate::RedirectHandler::Role',
43 is => 'ro',
44 required => 1,
45 default => sub { Web::Authenticate::RedirectHandler->new },
46 );
47  
48  
49  
50  
51 has request_url_provider => (
52 does => 'Web::Authenticate::RequestUrlProvider::Role',
53 is => 'ro',
54 required => 1,
55 default => sub { Web::Authenticate::RequestUrlProvider::CgiRequestUrlProvider->new },
56 );
57  
58  
59 has login_url => (
60 isa => 'Str',
61 is => 'ro',
62 required => 1,
63 );
64  
65  
66 has after_login_url => (
67 isa => 'Str',
68 is => 'ro',
69 required => 1,
70 );
71  
72  
73 has after_logout_url => (
74 isa => 'Str',
75 is => 'ro',
76 required => 1,
77 );
78  
79  
80 has authenticate_fail_url => (
81 isa => 'Str|Undef',
82 is => 'rw',
83 );
84  
85  
86 has update_expires_on_authenticate => (
87 isa => 'Bool',
88 is => 'ro',
89 required => 1,
90 default => 1,
91 );
92  
93  
94 has allow_after_login_redirect_override => (
95 isa => 'Bool',
96 is => 'ro',
97 required => 1,
98 default => 1,
99 );
100  
101  
102 has allow_after_login_redirect_time_seconds => (
103 isa => 'Int',
104 is => 'ro',
105 required => 1,
106 default => 300,
107 );
108  
109 has _after_login_redirect_override_cookie_name => (
110 isa => 'Str',
111 is => 'ro',
112 required => '1',
113 default => 'after_login_redirect',
114 );
115  
116  
117 sub login {
118 my $self = shift;
119 my %params = @_;
120  
121 croak "must provide login_args and login_args must be arrayref" unless $params{login_args} and is_arrayref($params{login_args});
122 _validate_role_arrayref('authenticators', $params{authenticators}, 'Web::Authenticate::Authenticator::Role');
123 _validate_role_arrayref('auth_redirects', $params{auth_redirects}, 'Web::Authenticate::Authenticator::Redirect::Role');
124  
125 $params{authenticators} //= [];
126 $params{auth_redirects} //= [];
127  
128 my $user = $self->user_storage_handler->load_user(@{$params{login_args}});
129  
130 return Web::Authenticate::Result::Login->new(success => undef) unless $user;
131  
132 for my $authenticator (@{$params{authenticators}}) {
133 return Web::Authenticate::Result::Login->new(success => undef, user => $user, failed_authenticator => $authenticator)
134 unless $authenticator->authenticate($user);
135 }
136
137 $self->session_handler->invalidate_user_sessions($user);
138 $self->session_handler->create_session($user);
139  
140 my $redirect_url = $self->after_login_url;
141 my $allow_after_login_redirect_override_url;
142 my $result_auth_redirect;
143 if ($self->allow_after_login_redirect_override) {
144 my $override_cookie_name = $self->_after_login_redirect_override_cookie_name;
145 $allow_after_login_redirect_override_url = $self->cookie_handler->get_cookie($override_cookie_name);
146 $self->cookie_handler->delete_cookie($override_cookie_name);
147 }
148
149 if ($allow_after_login_redirect_override_url) {
150 $redirect_url = $allow_after_login_redirect_override_url;
151 } else {
152 for my $auth_redirect (@{$params{auth_redirects}}) {
153 if ($auth_redirect->authenticator->authenticate($user)) {
154 $redirect_url = $auth_redirect->url;
155 $result_auth_redirect = $auth_redirect;
156 last;
157 }
158 }
159 }
160  
161 $self->redirect_handler->redirect($redirect_url);
162  
163 return Web::Authenticate::Result::Login->new(success => 1, user => $user, auth_redirect => $result_auth_redirect);
164 }
165  
166  
167 sub logout {
168 my ($self) = @_;
169  
170 $self->session_handler->delete_session;
171 $self->redirect_handler->redirect($self->after_logout_url);
172 }
173  
174  
175 sub authenticate {
176 my ($self) = shift;
177 my %params = @_;
178  
179 _validate_role_arrayref('auth_redirects', $params{auth_redirects}, 'Web::Authenticate::Authenticator::Redirect::Role');
180  
181 $params{auth_redirects} //= [];
182  
183 my $is_authenticated = $self->is_authenticated(@_, redirect => 1);
184  
185 unless ($is_authenticated->success) {
186 if ($is_authenticated->user) {
187 return Web::Authenticate::Result::Authenticate->new(success => undef, user => $is_authenticated->user, failed_authenticator => $is_authenticated->failed_authenticator);
188 } else {
189 return Web::Authenticate::Result::Authenticate->new(success => undef);
190 }
191 }
192  
193 # in this function, unlike in login, if redirect role fails then they're directed there.
194 my $user = $is_authenticated->user;
195 for my $auth_redirect (@{$params{auth_redirects}}) {
196 unless ($auth_redirect->authenticator->authenticate($user)) {
197 $self->redirect_handler->redirect($auth_redirect->url);
198 return Web::Authenticate::Result::Authenticate->new(success => undef, user => $user, auth_redirect => $auth_redirect);
199 }
200 }
201  
202 $self->session_handler->update_expires if $self->update_expires_on_authenticate;
203  
204 return Web::Authenticate::Result::Authenticate->new(success => 1, user => $user);
205 }
206  
207  
208 sub is_authenticated {
209 my ($self) = shift;
210 my %params = @_;
211  
212 _validate_role_arrayref('authenticators', $params{authenticators}, 'Web::Authenticate::Authenticator::Role');
213  
214 $params{authenticators} //= [];
215  
216 my $session = $self->session_handler->get_session;
217  
218 unless ($session) {
219 if ($self->allow_after_login_redirect_override) {
220 my $url = $self->request_url_provider->url;
221 $self->cookie_handler->set_cookie($self->_after_login_redirect_override_cookie_name, $url, $self->allow_after_login_redirect_time_seconds);
222 }
223 $self->redirect_handler->redirect($self->login_url) if $params{redirect};
224 return Web::Authenticate::Result::IsAuthenticated->new(success => undef) unless $session;
225 }
226  
227 my $user = $session->user;
228 unless ($user) {
229 $self->redirect_handler->redirect($self->login_url) if $params{redirect};
230 return Web::Authenticate::Result::IsAuthenticated->new(success => undef);
231 }
232
233 for my $authenticator (@{$params{authenticators}}) {
234 unless ($authenticator->authenticate($user)) {
235 $self->redirect_handler->redirect($self->authenticate_fail_url) if $params{redirect};
236 return Web::Authenticate::Result::IsAuthenticated->new(success => undef, user => $user, failed_authenticator => $authenticator);
237 }
238 }
239  
240 return Web::Authenticate::Result::IsAuthenticated->new(success => 1, user => $user);
241 }
242  
243  
244 sub create_user {
245 my ($self) = shift;
246 my %params = @_;
247  
248 my $username = delete $params{username};
249 my $password = delete $params{password};
250 croak "must provide username" unless $username;
251 croak "must provide password" unless $password;
252  
253 my $username_verifiers = delete $params{username_verifiers};
254 my $password_verifiers = delete $params{password_verifiers};
255  
256 _validate_role_arrayref('username_verifiers', $username_verifiers, 'Web::Authenticate::User::CredentialVerifier::Role');
257 _validate_role_arrayref('password_verifiers', $password_verifiers, 'Web::Authenticate::User::CredentialVerifier::Role');
258  
259 $username_verifiers //= [];
260 $password_verifiers //= [];
261  
262 my @failed_username_verifiers;
263 for my $verifier (@$username_verifiers) {
264 unless ($verifier->verify($username)) {
265 push @failed_username_verifiers, $verifier;
266 }
267 }
268  
269 my @failed_password_verifiers;
270 for my $verifier (@$password_verifiers) {
271 unless ($verifier->verify($password)) {
272 push @failed_password_verifiers, $verifier;
273 }
274 }
275  
276 if (@failed_username_verifiers or @failed_password_verifiers) {
277 return Web::Authenticate::Result::CreateUser->new(success => undef, failed_username_verifiers => \@failed_username_verifiers, failed_password_verifiers => \@failed_password_verifiers);
278 }
279  
280 my $user = $self->user_storage_handler->store_user($username, $password, $params{user_values});
281 return Web::Authenticate::Result::CreateUser->new(success => 1, user => $user);
282 }
283  
284 sub _validate_role_arrayref {
285 my ($param_name, $arrayref, $role) = @_;
286 croak "$param_name must be an arrayref" if $arrayref and not is_arrayref($arrayref);
287  
288 for my $item (@$arrayref) {
289 croak "all items in $param_name must do $role" unless $item->does($role);
290 }
291 }
292  
293 1;
294  
295 __END__
296  
297 =pod
298  
299 =encoding UTF-8
300  
301 =head1 NAME
302  
303 Web::Authenticate - Allows web authentication using cookies and a storage engine.
304  
305 =head1 VERSION
306  
307 version 0.003
308  
309 =head1 SYNOPSIS
310  
311 my $dbix_raw = DBIx::Raw->new(dsn => 'dbi:mysql:test:127.0.0.1:3306', user => 'user', password => 'password');
312 my $user_storage_handler = Web::Authenticate::User::Storage::Handler::SQL->new(dbix_raw => $dbix_raw);
313 my $storage_handler = Web::Authenticate::Session::Storage::Handler::SQL->new(dbix_raw => $dbix_raw, user_storage_handler => $user_storage_handler);
314 my $session_handler = Web::Authenticate::Session::Handler->new(session_storage_handler => $storage_handler);
315 my $web_authenticate = Web::Authenticate->new(
316 user_storage_handler => $user_storage_handler,
317 session_handler => $session_handler,
318 after_login_url => 'http://www.google.com/account.cgi',
319 after_logout_url => 'http://www.google.com/',
320 login_url => 'http://www.google.com/login.cgi',
321 );
322  
323 # login user
324 my $login_result = $web_authenticate->login(login_args => [$username, $password]);
325  
326 if ($login_result->success) {
327 # success!
328 }
329  
330 # authenticate a user to be on a page just with their session
331 my $authenticate_result = $web_authenticate->authenticate;
332  
333 if ($authenticate_result->succes) {
334 # success! allowed to access page
335 }
336  
337 # authenticate user with authenticators
338 my $authenticate_result = $web_authenticate->authenticate(authenticators => $authenticators);
339  
340 if ($authenticate_result->succes) {
341 # success! allowed to access page
342 }
343  
344
345 # create a user
346 my $create_user_result = $web_authenticate->create_user(username => $username, password => $password);
347  
348 if ($create_user_result->success) {
349 print "Created user " . $create_user_result->user->id . "\n";
350 }
351  
352 # create a user and verify username and password meet requirements
353 my $create_user_result = $web_authenticate->create_user(username => $username, password => $password, username_verifiers => $username_verifiers, password_verifiers => $password_verifiers);
354  
355 if ($create_user_result->success) {
356 print "Created user " . $create_user_result->user->id . "\n";
357 } else {
358 print "username errors: \n";
359 for my $verifier (@{$create_user_result->failed_username_verifiers}) {
360 print "\t" . $verifier->error_msg . "\n";
361 }
362  
363 print "password errors: \n";
364 for my $verifier (@{$create_user_result->failed_password_verifiers}) {
365 print "\t" . $verifier->error_msg . "\n";
366 }
367 }
368  
369 # create a user with additional values
370 my $user_values => {
371 age => 22,
372 address => '123 Hopper Ln, Austin TX 78705',
373 };
374 my $create_user_result = $web_authenticate->create_user(username => $username, password => $password, user_values => $user_values);
375  
376 if ($create_user_result->success) {
377 print "Created user " . $create_user_result->user->id . "\n";
378 print "user age " . $create_user_result->user->row->{age} . "\n";
379 print "user address " . $create_user_result->user->row->{address} . "\n";
380 }
381  
382 =head1 DESCRIPTION
383  
384 This modules allows easy management of user authentication via cookies, redirects, a storage engine, a session handler, and cookie handler.
385 It is flexible so you can rewrite any of those pieces for your applications' needs.
386  
387 =head1 METHODS
388  
389 =head2 user_storage_handler
390  
391 Sets the L<Web::Authenticate::User::Storage::Handler::Role> to be used. This is required with no default.
392  
393 =head2 session_handler
394  
395 Sets the L<Web::Authenticate::Session::Handler::Role> to be used. This is required with no default.
396  
397 =head2 cookie_handler
398  
399 Sets the object that does L<Web::Authenticate::Cookie::Handler::Role> to be used. The default is the default L<Web::Authenticate::Cookie::Handler>.
400  
401 =head2 redirect_handler
402  
403 Sets the object that does L<Web::Authenticate::RedirectHandler::Role> to be used. The default is the default L<Web::Authenticate::RedirectHandler>.
404  
405 =head2 request_url_provider
406  
407 Sets the object that does L<Web::Authenticate::RequestUrlProvider::Role> to get the url for the current request
408 (used to store the current url if L</allow_after_login_redirect_override> is set to true and L</authenticate> fails).
409 Default is L<Web::Authenticate::RequestUrlProvider::CgiRequestUrlProvider>.
410  
411 =head2 login_url
412  
413 Sets the login url that a user will be redirected to if they need to login. This is required with no default.
414  
415 my $web_auth = Web::Authenticate->new(login_url => "http://www.google.com/login");
416  
417 OR
418  
419 $web_auth->login_url("http://www.google.com/login");
420  
421 =head2 after_login_url
422  
423 The url the user will be redirected to after a successful login.
424  
425 =head2 after_logout_url
426  
427 The url the user will be redirected to after a successful logout. This is required with no default.
428  
429 =head2 authenticate_fail_url
430  
431 The url the user will be redirected to if they are logged in, but fail to pass all authenticators in the
432 authenticators arrayref for L</authenticate>.
433  
434 =head2 update_expires_on_authenticate
435  
436 If set to true (1), updates the expires time for the session upon successful authentication. Default is true.
437  
438 =head2 allow_after_login_redirect_override
439  
440 If a user requests a page that requires authentication and is redirected to login, if allow_after_login_redirect_override is set to true (1), then
441 the user will be redirected to that url after a successful login. If set to false, then the user will be redirected to L</after_login_url>.
442  
443 =head2 allow_after_login_redirect_time_seconds
444  
445 The url of the page the user tried to load is set to a cookie if they are redirected to login from L</authenticate>. This sets the amount of time (in seconds)
446 for the cookie to be valid. Default is 5 minutes.
447  
448 =head2 login
449  
450 =over
451  
452 =item
453  
454 B<login_args (required)> - the arguments that the L<Web::Authenticate::User::Storage::Handler::Role> requires for
455 L<Web::Authenticate::User::Storage::Handler::Role/load_user>.
456  
457 =item
458  
459 B<authenticators (optional)> - An arrayref of L<Web::Authenticate::Authenticator::Role>. If any of the authenticators does not
460 authenticate, then login will fail.
461  
462 =item
463  
464 B<auth_redirects (optional)> - An arrayref of L<Web::Authenticate::Authenticator::Redirect::Role>. If the user logins successfully, the user will
465 be redirected to the L<Web::Authenticate::Authenticator::Redirect::Role/url> of the first L<Web::Authenticate::Authenticator::Redirect::Role/authenticator>
466 that authenticates. If none of the auth_redirects authenticate, then the user will be redirected to L</after_login_url>.
467  
468 =back
469  
470 Verifies the arguments required by L<Web::Authenticate::User::Storage::Handler::Role> in L</user_storage_handler>. If they are correct, if L</allow_after_login_redirect_override>
471 is set to 1 and the user has a cookie set for this, the user will be redirected to that url. If not, the user is redirected to the
472 first the L<Web::Authenticate::Authenticator::Redirect::Role/url> of the first succesful L<Web::Authenticate::Authenticator::Redirect::Role> in auth_redirects.
473 If auth_redirects is empty or none authenticate, then the user is redirected to L</after_login_url>
474 Returns a L<Web::Authenticate::Result::Login> object.
475  
476 my $login_result = $web_auth->login(login_args => [$username, $password]);
477  
478 if ($login_result->success) {
479 log("user id is " . $login_result->user->id);
480 exit; # already set to redirect to appropriate page
481 } else {
482 # handle login failure
483 if ($login_result->authenticator) {
484 # this authenticator caused the failure
485 }
486 }
487  
488 =head2 logout
489  
490 Logs a user out of their current session by deleting their session cookie and their storage-backed session.
491  
492 $web_authenticate->logout;
493  
494 =head2 authenticate
495  
496 =over
497  
498 =item
499  
500 B<authenticators (optional)> - An arrayref of L<Web::Authenticate::Authenticator::Role>. If any of the authenticators does not
501 authenticate, then the user will be redirected to L</authenticate_fail_url>.
502  
503 =item
504  
505 B<auth_redirects (optional)> - An arrayref of L<Web::Authenticate::Authenticator::Redirect::Role>. The user will
506 be redirected to the L<Web::Authenticate::Authenticator::Redirect::Role/url> of the first L<Web::Authenticate::Authenticator::Redirect::Role/authenticator>
507 that fails to authenticates. If none of the auth_redirects fail to authenticate, then the user will not be redirected.
508  
509 =back
510  
511 First makes sure that the user authenticates as being logged in with a session. If the user is not, the user is redirected to L</login_url>.
512 Then, the method tries to authenticate all authenticators. If any authenticator fails, the user is redirected to L</authenticate_fail_url>.
513 Then, all auth_redirects are checked. If any auth_redirect fails to authenticate, the user will be redirected to the L<Web::Authenticate::Authenticator::Redirect::Role/url>
514 for that auth_redirect. auth_redirects are processed in order. This method returns a L<Web::Authenticate::Result::Authenticate> object.
515  
516 my $authenticate_result = $web_auth->authenticate;
517  
518 # OR
519 my $authenticate_result = $web_auth->authenticate(authenticators => $authenticators, auth_redirects => $auth_redirects);
520  
521 if ($authenticate_result->success) {
522 print "User " . $authenticate_result->user->id . " successfully authenticated\n";
523 } else {
524 # failed to authenticate user.
525 if ($authenticate_result->failed_authenticator) {
526 # this authenticator caused the failure
527 }
528 }
529  
530 =head2 is_authenticated
531  
532 =over
533  
534 =item
535  
536 B<authenticators (optional)> - An arrayref of L<Web::Authenticate::Authenticator::Role>. If any of the authenticators does not
537 authenticate, then the user will be redirected to L</authenticate_fail_url>.
538  
539 =item
540  
541 B<redirect (optional)> - If set to true, this method will redirect appropriately if the user does not authenticate.
542  
543 =back
544  
545 First makes sure that the user authenticates as being logged in with a session. If the user is not, the user is redirected to L</login_url> if redirect is set to 1.
546 Then, the method tries to authenticate all authenticators. If any authenticator fails, the user is redirected to L</authenticate_fail_url> if redirect is set to 1.
547 This method returns a L<Web::Authenticate::Result::IsAuthenticated> object.
548  
549 my $is_authenticated_result = $web_auth->is_authenticated;
550  
551 # OR
552 my $is_authenticated_result = $web_auth->is_authenticated(authenticators => $authenticators);
553  
554 if ($is_authenticated_result->success) {
555 print "User " . $is_authenticated_result->user->id . " successfully authenticated\n";
556 } else {
557 # failed to authenticate user.
558 if ($is_authenticated_result->failed_authenticator) {
559 # this authenticator caused the failure
560 }
561 }
562  
563 This method does not update the expires time for the session. It does however respect L</allow_after_login_redirect_override>.
564  
565 =head2 create_user
566  
567 =over
568  
569 =item
570  
571 B<username (required)> - The username for the user to create.
572  
573 =item
574  
575 B<password (required)> - The password for the user to create.
576  
577 =item
578  
579 B<username_verifiers (optional)> - optional arrayref of L<Web::Authenticate::User::CredentialVerifier> to verify if an entered username is correct.
580  
581 =item
582  
583 B<password_verifiers (optional)> - optional arrayref of L<Web::Authenticate::User::CredentialVerifier> to verify if an entered password is correct.
584  
585 =item
586  
587 B<user_values (optional)> - optional hashref where column names are the keys and the values for those columns are the values. These values will be
588 passed on to L<Web::Authenticate::User::Storage::Handler::Role> when creating the user.
589  
590 =back
591  
592 This is a convenience method that can be used if the L<Web::Authenticate::User::Storage::Handler::Role> you are using accepts its
593 L<Web::Authenticate::User::Storage::Handler::Role/store_user> arguments as:
594  
595 store_user($username, $password, $user_values)
596  
597 Such as L<Web::Authenticate::User::Storage::Handler::SQL>.
598  
599 my $create_user_result = $web_authenticate->create_user(
600 username => $username,
601 password => $password,
602 username_verifiers => $username_verifiers,
603 password_verifiers => $password_verifiers,
604 user_values => {
605 age => $age,
606 insert_time => \'NOW()',
607 },
608 );
609  
610 if ($create_user_result->success) {
611 print "User " . $create_user_result->user->id . " created\n";
612 } else {
613 print "username errors: \n";
614 for my $verifier (@{$create_user_result->failed_username_verifiers}) {
615 print "\t" . $verifier->error_msg . "\n";
616 }
617  
618 print "password errors: \n";
619 for my $verifier (@{$create_user_result->failed_password_verifiers}) {
620 print "\t" . $verifier->error_msg . "\n";
621 }
622 }
623  
624 =head1 AUTHOR
625  
626 Adam Hopkins <srchulo@cpan.org>
627  
628 =head1 COPYRIGHT AND LICENSE
629  
630 This software is copyright (c) 2017 by Adam Hopkins.
631  
632 This is free software; you can redistribute it and/or modify it under
633 the same terms as the Perl 5 programming language system itself.
634  
635 =cut