Extensible.pm

filter: Statementstmt 97.6% 572 / 586 Branchbran 88.2% 203 / 230 (2 uncoverable) Conditioncond 85.7% 86 / 112 (10 uncoverable) MC/DCmcdc 74.1% 31 / 62 (15 uncoverable) Subroutinesub 95.8% 93 / 97 Podpod 85.0% 17 / 20 totaltotal 92.7% 1002 / 1107 (27 uncoverable) CC 169 SCAR 20.0
CC
169
Cov
94%
_post_login_route
20.5
user_password
17.1
__ANON__
15.2
CRAP 7.4
« Extensible/Test.pm ↑ Summary Extensible/Provider/Config.pm »
1 package Dancer2::Plugin::Auth::Extensible;
2  
3 16 our $VERSION = '0.714';
4  
5 16 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 16 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 16 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 16 ▶use Dancer2::Core::Types qw(ArrayRef Bool HashRef Maybe Int Str);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 16 ▶use Dancer2::FileUtils qw(path);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 16 ▶use Dancer2::Template::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 16 ▶use File::Share qw(dist_dir);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 16 ▶use HTTP::BrowserDetect;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 16 ▶use List::Util qw(first);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 16 ▶use Module::Runtime qw(use_module);
Subroutine BEGIN: called CC=1 SCAR=0.0
15 16 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
16 16 ▶use Session::Token;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 16 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 16 ▶use URI::Escape;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 16 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 16 ▶use URI::QueryParam; # Needed to access query_form_hash(), although may be loaded anyway
Subroutine BEGIN: called CC=1 SCAR=0.0
21 16 ▶use Dancer2::Plugin;
Subroutine BEGIN: called CC=1 SCAR=0.0
22  
23 #
24 # config attributes
25 #
26  
27 has denied_page => (
28 is => 'ro',
29 isa => Str,
30 16 ▶ from_config => sub { '/login/denied' },
Subroutine __ANON__: called CC=1 SCAR=0.0
31 16 );
32  
33 has disable_roles => (
34 is => 'ro',
35 isa => Bool,
36 3 ▶ from_config => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=0.0
37 16 );
38  
39 has exit_page => (
40 is => 'ro',
41 isa => Str,
42 3 ▶ from_config => sub { '/' },
Subroutine __ANON__: called CC=1 SCAR=0.0
43 16 );
44  
45 has login_page => (
46 is => 'ro',
47 isa => Str,
48 17 ▶ from_config => sub { '/login' },
Subroutine __ANON__: called CC=1 SCAR=0.0
49 16 );
50  
51 has login_template => (
52 is => 'ro',
53 isa => Str,
54 4 ▶ from_config => sub { 'login' },
Subroutine __ANON__: called CC=1 SCAR=0.0
55 16 );
56  
57 has login_page_handler => (
58 is => 'ro',
59 isa => Str,
60 3 ▶ from_config => sub { '_default_login_page' },
Subroutine __ANON__: called CC=1 SCAR=0.0
61 16 );
62  
63 has login_without_redirect => (
64 is => 'ro',
65 isa => Bool,
66 16 ▶ from_config => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=0.0
67 16 );
68  
69 has logout_page => (
70 is => 'ro',
71 isa => Str,
72 16 ▶ from_config => sub { '/logout' },
Subroutine __ANON__: called CC=1 SCAR=0.0
73 16 );
74  
75 has no_login_handler => (
76 is => 'ro',
77 isa => Bool,
78 from_config => 1,
79 16 ▶ default => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=0.0
80 16 );
81  
82 has mailer => (
83 is => 'ro',
84 isa => HashRef,
85 0 ▶ from_config => sub { '' },
Subroutine __ANON__: not called CC=1 SCAR=6.9
86 16 );
87  
88 has mail_from => (
89 is => 'ro',
90 isa => Str,
91 2 ▶ from_config => sub { '' },
Subroutine __ANON__: called CC=1 SCAR=0.0
92 16 );
93  
94 has no_default_pages => (
95 is => 'ro',
96 isa => Bool,
97 16 ▶ from_config => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=0.0
98 16 );
99  
100 has password_generator => (
101 is => 'ro',
102 isa => Str,
103 1 ▶ from_config => sub { '_default_password_generator' },
Subroutine __ANON__: called CC=1 SCAR=0.0
104 16 );
105  
106 has password_reset_send_email => (
107 is => 'ro',
108 isa => Str,
109 2 ▶ from_config => sub { '_default_email_password_reset' },
Subroutine __ANON__: called CC=1 SCAR=0.0
110 16 );
111  
112 has password_reset_text => (
113 is => 'ro',
114 isa => Str,
115 2 ▶ from_config => sub { '' },
Subroutine __ANON__: called CC=1 SCAR=0.0
116 16 );
117  
118 has permission_denied_handler => (
119 is => 'ro',
120 isa => Str,
121 0 ▶ from_config => sub { '_default_permission_denied_handler' },
Subroutine __ANON__: not called CC=1 SCAR=6.9
122 16 );
123  
124 has permission_denied_page_handler => (
125 is => 'ro',
126 isa => Str,
127 2 ▶ from_config => sub { '_default_permission_denied_page' },
Subroutine __ANON__: called CC=1 SCAR=0.0
128 16 );
129  
130 has realms => (
131 is => 'ro',
132 isa => ArrayRef,
133 18 ▶ default => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
134 18 my @realms;
135 18 ▶ while ( my ( $name, $realm ) = each %{ $_[0]->config->{realms} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %{$_[0]->config->{"realms"};}) 39 18 57
136 39 ▶ $realm->{priority} ||= 0;
Condition100%2/2
$realm->{"priority"} ||= 0
l!l
2316
MC/DC100%1/1
$realm->{"priority"} ||= 0
$realm->{"priority"}
Truth table100%2/2
A
A= $realm->{"priority"}
Aresult
11
00
137 39 push @realms, { name => $name, %$realm };
138 };
139 18 return [ sort { $b->{priority} <=> $a->{priority} } @realms ];
140 },
141 16 );
142  
143 has realm_names => (
144 is => 'lazy',
145 isa => ArrayRef,
146 18 ▶ default => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
147 18 return [ map { $_->{name} } @{ $_[0]->realms } ];
148 },
149 16 );
150  
151 has realm_count => (
152 is => 'lazy',
153 isa => Int,
154 18 ▶ default => sub { return scalar @{ $_[0]->realms } },
Subroutine __ANON__: called CC=1 SCAR=0.0
155 16 );
156  
157 # return realm config hash reference by name
158 45 ▶sub realm {
Subroutine realm: called CC=2 SCAR=6.9
Pod undocumented
159 45 my ( $self, $name ) = @_;
160 45 ▶ croak "realm name not provided" unless $name;
Branch: 1 branch
BranchTrueFalseTotal
unless $name 4 41 45
161 41 ▶ my $realm = first { $_->{name} eq $name } @{ $self->realms };
Subroutine __ANON__: called CC=1 SCAR=0.0
162 41 return $realm;
163 }
164  
165 has record_lastlogin => (
166 is => 'ro',
167 isa => Bool,
168 5 ▶ from_config => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=0.0
169 16 );
170  
171 has reset_password_handler => (
172 is => 'ro',
173 isa => Bool,
174 4 ▶ from_config => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=0.0
175 16 plugin_keyword => 1,
176 );
177  
178 16 has uri_base => (
179 is => 'ro',
180 isa => Maybe[Str],
181 from_config => 1,
182 );
183  
184 # Use the uri_base from the configuration if set, otherwise the one from this
185 # particular request. This can potentially generate security vulnerabilities if
186 # the calling application allows unsanitised host headers (see pod for
187 # uri_base).
188 sub uri_base_request
189 6 ▶{ my $plugin = shift;
Subroutine uri_base_request: called CC=2 SCAR=7.0
Pod undocumented
190 6 ▶ my $base = $plugin->uri_base || $plugin->app->request->uri_base;
Condition66%2/3
$plugin->uri_base || $plugin->app->request->uri_base
l!l&&r!l&&!r
240
MC/DC0%0/2
$plugin->uri_base || $plugin->app->request->uri_base
$plugin->uri_base $plugin->app->request->uri_base
Truth table66%2/3
A || B
A= $plugin->uri_baseB= $plugin->app->request->uri_base
ABresult
1X1
011
000
191 6 my $uri = URI->new($base);
192 # Make sure that URI always ends in separator, so that the path can be
193 # appended
194 6 $uri->path($uri->path =~ s!/*$!/!r);
195 6 $uri;
196 }
197  
198 has user_home_page => (
199 is => 'ro',
200 isa => Str,
201 3 ▶ from_config => sub { '/' },
Subroutine __ANON__: called CC=1 SCAR=0.0
202 16 );
203  
204 has welcome_send => (
205 is => 'ro',
206 isa => Str,
207 2 ▶ from_config => sub { '_default_welcome_send' },
Subroutine __ANON__: called CC=1 SCAR=0.0
208 16 );
209  
210 has welcome_text => (
211 is => 'ro',
212 isa => Str,
213 2 ▶ from_config => sub { '' },
Subroutine __ANON__: called CC=1 SCAR=0.0
214 16 );
215  
216 #
217 # other attributes
218 #
219  
220 has realm_providers => (
221 is => 'ro',
222 isa => HashRef,
223 18 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
224 16 init_arg => undef,
225 );
226  
227 has _template_tiny => (
228 is => 'ro',
229 18 ▶ default => sub { Dancer2::Template::Tiny->new },
Subroutine __ANON__: called CC=1 SCAR=0.0
230 16 );
231  
232 #
233 # hooks
234 #
235  
236 16 plugin_hooks 'before_authenticate_user', 'after_authenticate_user',
237 'before_create_user', 'after_create_user', 'after_reset_code_success',
238 'login_required', 'permission_denied', 'after_login_success',
239 'before_logout';
240  
241 #
242 # keywords
243 #
244  
245 16 plugin_keywords 'authenticate_user', 'create_user', 'get_user_details',
246 'logged_in_user', 'logged_in_user_lastlogin',
247 'logged_in_user_password_expired', 'password_reset_send',
248 [ 'require_all_roles', 'requires_all_roles' ],
249 [ 'require_any_role', 'requires_any_role' ],
250 [ 'require_login', 'requires_login' ],
251 [ 'require_role', 'requires_role' ],
252 'update_current_user', 'update_user', 'user_has_role', 'user_password',
253 'user_roles';
254  
255 #
256 # public methods
257 #
258  
259 18 ▶sub BUILD {
Subroutine BUILD: called CC=7 SCAR=19.5
Pod undocumented
260 18 my $plugin = shift;
261 18 my $app = $plugin->app;
262  
263 18 Scalar::Util::weaken( my $weak_plugin = $plugin );
264  
265 18 ▶ warn "No Auth::Extensible realms configured with which to authenticate user"
Branch: 1 branch
BranchTrueFalseTotal
unless $plugin->realm_count 1 17 18
266 unless $plugin->realm_count;
267  
268 # Force all providers to load whilst we have access to the full dsl.
269 # If we try and load later, then if the provider is using other
270 # keywords (such as schema) they will not be available from the dsl.
271 18 for my $realm ( @{ $plugin->realm_names } ) {
272 39 $plugin->auth_provider( $realm );
273 }
274  
275 17 ▶ if ( !$plugin->no_default_pages ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($plugin->no_default_pages) 16 1 17
276  
277 16 my $login_page = $plugin->login_page;
278 16 my $denied_page = $plugin->denied_page;
279  
280 # Match optional reset code, but not "denied"
281 $app->add_route(
282 method => 'get',
283 regexp => qr!^$login_page/?([\w]{32})?$!,
284 21 ▶ code => sub {
Subroutine __ANON__: called CC=6 SCAR=17.9
285 21 my $app = shift;
286  
287 21 ▶ if ( $weak_plugin->logged_in_user ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_plugin->logged_in_user) 5 16 21
288 # User is already logged in so redirect elsewhere
289 # uncoverable condition false
290 5 ▶ $app->redirect(
Condition100%2/3
_return_url($app) || $weak_plugin->user_home_page
l!l&&r!l&&!r
320
MC/DC100%0/2
_return_url($app) || $weak_plugin->user_home_page
_return_url($app) $weak_plugin->user_home_page
Truth table100%2/3
A || B
A= _return_url($app)B= $weak_plugin->user_home_page
ABresult
1X1
011
000
291 _return_url($app) || $weak_plugin->user_home_page );
292 }
293  
294 # Reset password code submitted?
295 16 my ($code) = $app->request->splat;
296  
297 16 ▶ if ( $code
Branch: 1 branch
BranchTrueFalseTotal
if ($code and $weak_plugin->reset_password_handler and $weak_plugin->user_password("code", $code)) 1 15 16
Condition100%6/6
$code and $weak_plugin->reset_password_handler and $weak_plugin->user_password("code", $code)
!ll&&!rl&&r
1411
$code and $weak_plugin->reset_password_handler
!ll&&!rl&&r
1312
MC/DC100%3/3
$code and $weak_plugin->reset_password_handler and $weak_plugin->user_password("code", $code)
$code $weak_plugin->reset_password_handler $weak_plugin->user_password("code", $code)
Truth table100%4/4
A and B and C
A= $codeB= $weak_plugin->reset_password_handlerC= $weak_plugin->user_password("code", $code)
ABCresult
0XX0
10X0
1100
1111
298 && $weak_plugin->reset_password_handler
299 && $weak_plugin->user_password( code => $code ) )
300 {
301 1 $app->request->parameters->set('password_code_valid' => 1),
302 }
303  
304 16 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
305 16 return &{ $weak_plugin->login_page_handler }($weak_plugin);
306 },
307 16 );
308  
309 $app->add_route(
310 method => 'get',
311 regexp => qr!^$denied_page$!,
312 2 ▶ code => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
313 2 my $app = shift;
314 2 $app->response->status(403);
315 16 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
316 2 return &{ $weak_plugin->permission_denied_page_handler }($weak_plugin);
317 },
318 16 );
319 }
320  
321 17 ▶ if ( !$plugin->no_login_handler ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($plugin->no_login_handler) 16 1 17
322  
323 16 my $login_page = $plugin->login_page;
324 16 my $logout_page = $plugin->logout_page;
325  
326 # Match optional reset code, but not "denied"
327 16 $app->add_route(
328 method => 'post',
329 regexp => qr!^$login_page/?([\w]{32})?$!,
330 code => \&_post_login_route,
331 );
332  
333 16 for my $method (qw/get post/) {
334 32 $app->add_route(
335 method => $method,
336 regexp => qr!^$logout_page$!,
337 code => \&_logout_route,
338 );
339 }
340 }
341  
342 17 ▶ if ( $plugin->login_without_redirect ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plugin->login_without_redirect) 1 16 17
343  
344 # Add a post route so we can catch transparent login.
345 # This is a little sucky but since no hooks are called before
346 # route dispatch then adding this wildcard route now does at
347 # least make sure it gets added before any routes that use this
348 # plugin's route decorators are added.
349  
350 $plugin->app->add_route(
351 method => 'post',
352 regexp => qr/.*/,
353 9 ▶ code => sub {
Subroutine __ANON__: called CC=6 SCAR=17.9
354 9 my $app = shift;
355 9 my $request = $app->request;
356  
357 # See if this is actually a POST login.
358 9 my $username = $request->body_parameters->get(
359 '__auth_extensible_username');
360  
361 9 my $password = $request->body_parameters->get(
362 '__auth_extensible_password');
363  
364 9 ▶ if ( defined $username && defined $password ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $username and defined $password) 6 3 9
Condition66%2/3
defined $username and defined $password
!ll&&!rl&&r
306
MC/DC50%1/2
defined $username and defined $password
defined $username defined $password
Truth table66%2/3
A and B
A= defined $usernameB= defined $password
ABresult
0X0
100
111
365  
366 6 my $auth_realm = $request->body_parameters->get(
367 '__auth_extensible_realm');
368  
369 # Remove the auth params since the forward we call later
370 # will cause dispatch to retry this route again if
371 # the original route was a post since dispatch starts
372 # again from the start of the route list and this
373 # wildcard route will get hit again causing a loop.
374 6 foreach (qw/username password realm/) {
375 18 $request->body_parameters->remove(
376 "__auth_extensible_$_");
377 }
378  
379 # Stash method and params since we delete these from
380 # the session if login is successful but we still need
381 # them for the forward to the original route after
382 # success.
383 6 my $method =
384 $app->session->read('__auth_extensible_method');
385 6 my $params =
386 $app->session->read('__auth_extensible_params');
387  
388 # Attempt authentication.
389 6 my ( $success, $realm ) =
390 $weak_plugin->authenticate_user( $username,
391 $password, $auth_realm );
392  
393 6 ▶ if ($success) {
Branch: 1 branch
BranchTrueFalseTotal
if ($success) { } 3 3 6
394 3 $app->session->delete('__auth_extensible_params');
395 3 $app->session->delete('__auth_extensible_method');
396  
397 # Change session ID if we have a new enough D2
398 # version with support.
399 3 ▶ $app->change_session_id
Branch: 1 branch
BranchTrueFalseTotal
if $app->can("change_session_id") 3 0 3
400 if $app->can('change_session_id');
401  
402 3 $app->session->write( logged_in_user => $username );
403 3 $app->session->write( logged_in_user_realm => $realm );
404 3 $app->log( core => "Realm is $realm" );
405 3 $weak_plugin->execute_plugin_hook(
406 'after_login_success');
407  
408 }
409 else {
410 3 $app->request->var( login_failed => 1 );
411 }
412 # Now forward to the original route using method and
413 # params stashed in the session.
414 6 $app->forward(
415 $request->path,
416 $params,
417 { method => $method }
418 );
419 }
420 3 $app->pass;
421 },
422 1 );
423 }
424 }
425  
426 479 ▶sub auth_provider {
Subroutine auth_provider: called CC=7 SCAR=19.5
Pod documented
427 479 my ( $plugin, $realm ) = @_;
428  
429 # If no realm was provided, but we have a logged in user, use their realm.
430 # Don't try and read the session any earlier though, as it won't be
431 # available on plugin load
432 479 ▶ if ( !defined $realm ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $realm) 33 446 479
433 33 ▶ if ( $plugin->app->session->read('logged_in_user') ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plugin->app->session->read('logged_in_user')) { } 31 2 33
434 31 $realm = $plugin->app->session->read('logged_in_user_realm');
435 }
436 else {
437 2 croak "auth_provider needs realm or there must be a logged in user";
438 }
439 }
440  
441 # First, if we already have a provider for this realm, go ahead and use it:
442 return $plugin->realm_providers->{$realm}
443 477 ▶ if exists $plugin->realm_providers->{$realm};
Branch: 1 branch
BranchTrueFalseTotal
if exists $plugin->realm_providers->{$realm} 436 41 477
444  
445 # OK, we need to find out what provider this realm uses, and get an instance
446 # of that provider, configured with the settings from the realm.
447 41 ▶ my $realm_settings = $plugin->realm($realm)
Branch: 1 branch
BranchTrueFalseTotal
my $realm_settings = $plugin->realm($realm) or croak("Invalid realm $realm") 39 2 41
448 or croak "Invalid realm $realm";
449  
450 my $provider_class = $realm_settings->{provider}
451 39 ▶ or croak "No provider configured - consult documentation for "
Branch: 1 branch
BranchTrueFalseTotal
my $provider_class = $realm_settings->{"provider"} or croak("No provider configured - consult documentation for Dancer2::Plugin::Auth::Extensible") 38 1 39
452 . __PACKAGE__;
453  
454 38 ▶ if ( $provider_class !~ /::/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($provider_class =~ /::/) 27 11 38
455 27 $provider_class = __PACKAGE__ . "::Provider::$provider_class";
456 }
457  
458 38 return $plugin->realm_providers->{$realm} =
459 use_module($provider_class)->new(
460 plugin => $plugin,
461 %$realm_settings,
462 );
463 }
464  
465 134 ▶sub authenticate_user {
Subroutine authenticate_user: called CC=14 SCAR=26.4
Pod documented
466 134 my ( $plugin, $username, $password, $realm ) = @_;
467 134 my ( @errors, $success, $auth_realm );
468  
469 134 $plugin->execute_plugin_hook( 'before_authenticate_user',
470 { username => $username, password => $password, realm => $realm } );
471  
472 # username and password must be simple non-empty scalars
473 134 ▶ if ( defined $username
Branch: 1 branch
BranchTrueFalseTotal
if (defined $username and ref $username eq "" and $username ne "" and defined $password and ref $password eq "" and $password ne "") 71 63 134
Condition100%15/15
defined $username and ref $username eq "" and $username ne "" and defined $password and ref $password eq "" and $password ne ""
!ll&&!rl&&r
531071
defined $username and ref $username eq "" and $username ne "" and defined $password and ref $password eq ""
!ll&&!rl&&r
51281
defined $username and ref $username eq "" and $username ne "" and defined $password
!ll&&!rl&&r
49283
defined $username and ref $username eq "" and $username ne ""
!ll&&!rl&&r
232685
defined $username and ref $username eq ""
!ll&&!rl&&r
158111
MC/DC100%6/6
defined $username and ref $username eq "" and $username ne "" and defined $password and ref $password eq "" and $password ne ""
defined $username ref $username eq "" $username ne "" defined $password ref $password eq "" $password ne ""
Truth table100%7/7
A and B and C and D and E and F
A= defined $usernameB= ref $username eq ""C= $username ne ""D= defined $passwordE= ref $password eq ""F= $password ne ""
ABCDEFresult
0XXXXX0
10XXXX0
110XXX0
1110XX0
11110X0
1111100
1111111
474 && ref($username) eq ''
475 && $username ne ''
476 && defined $password
477 && ref($password) eq ''
478 && $password ne '' )
479 {
480 71 ▶ my @realms_to_check = $realm ? ($realm) : @{ $plugin->realm_names };
Branch: 1 branch
BranchTrueFalseTotal
$realm ? : 14 57 71
481  
482 71 for my $realm (@realms_to_check) {
483 173 $plugin->app->log( debug =>
484 "Attempting to authenticate $username against realm $realm" );
485 173 my $provider = $plugin->auth_provider($realm);
486  
487 173 ▶ my %lastlogin =
Branch: 1 branch
BranchTrueFalseTotal
$plugin->record_lastlogin ? : 108 65 173
488 $plugin->record_lastlogin
489 ? ( lastlogin => 'logged_in_user_lastlogin' )
490 : ();
491  
492 eval {
493 173 $success =
494 $provider->authenticate_user( $username, $password,
495 %lastlogin );
496 172 1;
497 173 ▶ } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $success = $provider->authenticate_user($username, $password, %lastlogin); 1 } } or do { my $err = $@ || "Unknown error"; $plugin->app->log("error", "$realm provider threw error: $err"); push @errors, $err } 172 1 173
498 # uncoverable condition right
499 1 ▶ my $err = $@ || "Unknown error";
Condition100%1/2
$@ || 'Unknown error'
l!l
10
MC/DC100%0/1
$@ || 'Unknown error'
$@
Truth table100%1/2
A
A= $@
Aresult
11
00
500 1 $plugin->app->log(
501 error => "$realm provider threw error: $err" );
502 1 push @errors, $err;
503 };
504 173 ▶ if ($success) {
Branch: 1 branch
BranchTrueFalseTotal
if ($success) 46 127 173
505 46 $plugin->app->log( debug => "$realm accepted user $username" );
506 46 $auth_realm = $realm;
507 46 last;
508 }
509 }
510 }
511  
512 # force 0 or 1 for success
513 134 $success = 0+!!$success;
514  
515 134 $plugin->execute_plugin_hook(
516 'after_authenticate_user',
517 {
518 username => $username,
519 password => $password,
520 realm => $auth_realm,
521 errors => \@errors,
522 success => $success,
523 }
524 );
525  
526 134 ▶ return wantarray ? ( $success, $auth_realm ) : $success;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 101 33 134
527 }
528  
529 15 ▶sub create_user {
Subroutine create_user: called CC=11 SCAR=24.0
Pod documented
530 15 my $plugin = shift;
531 15 my %options = @_;
532 15 my ( $user, @errors );
533  
534 croak "Realm must be specified when more than one realm configured"
535 15 ▶ if !$options{realm} && $plugin->realm_count > 1;
Branch: 1 branch
BranchTrueFalseTotal
if not $options{"realm"} and $plugin->realm_count > 1 1 14 15
Condition100%3/3
not $options{"realm"} and $plugin->realm_count > 1
!ll&&!rl&&r
861
MC/DC100%2/2
not $options{"realm"} and $plugin->realm_count > 1
not $options{"realm"} $plugin->realm_count > 1
Truth table100%3/3
not(A) and B
A= not $options{"realm"}B= $plugin->realm_count > 1
ABresult
0X0
100
111
536  
537 14 $plugin->execute_plugin_hook( 'before_create_user', \%options );
538  
539 # uncoverable condition false
540 14 ▶ my $realm = delete $options{realm} || $plugin->realm_names->[0];
Condition100%2/3
delete $options{'realm'} || $plugin->realm_names->[0]
l!l&&r!l&&!r
860
MC/DC100%0/2
delete $options{'realm'} || $plugin->realm_names->[0]
delete $options{'realm'} $plugin->realm_names->[0]
Truth table100%2/3
A || B
A= delete $options{'realm'}B= $plugin->realm_names->[0]
ABresult
1X1
011
000
541 14 my $email_welcome = delete $options{email_welcome};
542 14 my $password = delete $options{password};
543 14 my $provider = $plugin->auth_provider($realm);
544  
545 14 ▶ eval { $user = $provider->create_user(%options); 1; } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $user = $provider->create_user(%options); 1 } } or do { my $err = $@ || "Unknown error"; $plugin->app->log("error", "$realm provider threw error: $err"); push @errors, $err } 12 2 14
546 # uncoverable condition right
547 2 ▶ my $err = $@ || "Unknown error";
Condition100%1/2
$@ || 'Unknown error'
l!l
20
MC/DC100%0/1
$@ || 'Unknown error'
$@
Truth table100%1/2
A
A= $@
Aresult
11
00
548 2 $plugin->app->log( error => "$realm provider threw error: $err" );
549 2 push @errors, $err;
550 };
551  
552 14 ▶ if ($user) {
Branch: 1 branch
BranchTrueFalseTotal
if ($user) 12 2 14
553 # user creation successful
554 12 ▶ if ($email_welcome) {
Branch: 2 branches
BranchTrueFalseTotal
if ($email_welcome) { } 4 8 12
elsif ($password) { } 6 2 8
555 4 my $code = _reset_code();
556  
557 # Would be slightly more efficient to do this at time of creation,
558 # but this keeps the code simpler for the provider
559 $provider->set_user_details( $options{username},
560 4 pw_reset_code => $code );
561  
562 # email hard-coded as per password_reset_send()
563 my %params =
564 4 ( code => $code, email => $options{email}, user => $user );
565  
566 16 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
567 4 &{ $plugin->welcome_send }( $plugin, %params );
568 }
569 elsif ($password) {
570 eval {
571 6 $provider->set_user_password( $options{username}, $password );
572 5 1;
573 6 ▶ } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $provider->set_user_password($options{"username"}, $password); 1 } } or do { my $err = $@ || "Unknown error"; $plugin->app->log("error", "$realm provider threw error: $err"); push @errors, $err } 5 1 6
574 # uncoverable condition right
575 1 ▶ my $err = $@ || "Unknown error";
Condition100%1/2
$@ || 'Unknown error'
l!l
10
MC/DC100%0/1
$@ || 'Unknown error'
$@
Truth table100%1/2
A
A= $@
Aresult
11
00
576 1 $plugin->app->log(
577 error => "$realm provider threw error: $err" );
578 1 push @errors, $err;
579 };
580 }
581 }
582  
583 $plugin->execute_plugin_hook( 'after_create_user', $options{username},
584 14 $user, \@errors );
585  
586 14 return $user;
587 }
588  
589 88 ▶sub get_user_details {
Subroutine get_user_details: called CC=7 SCAR=19.5
Pod documented
590 88 my ( $plugin, $username, $realm ) = @_;
591 88 my $user;
592 88 ▶ return unless defined $username;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $username 2 86 88
593  
594 86 ▶ my @realms_to_check = $realm ? ($realm) : @{ $plugin->realm_names };
Branch: 1 branch
BranchTrueFalseTotal
$realm ? : 81 5 86
595  
596 86 for my $realm (@realms_to_check) {
597 94 $plugin->app->log(
598 debug => "Attempting to find user $username in realm $realm" );
599 94 my $provider = $plugin->auth_provider($realm);
600 94 ▶ eval { $user = $provider->get_user_details($username); 1; } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $user = $provider->get_user_details($username); 1 } } or do { my $err = $@ || "Unknown error"; $plugin->app->log("error", "$realm provider threw error: $err") } 93 1 94
601 # uncoverable condition right
602 1 ▶ my $err = $@ || "Unknown error";
Condition100%1/2
$@ || 'Unknown error'
l!l
10
MC/DC100%0/1
$@ || 'Unknown error'
$@
Truth table100%1/2
A
A= $@
Aresult
11
00
603 1 $plugin->app->log( error => "$realm provider threw error: $err" );
604 };
605 94 ▶ last if $user;
Branch: 1 branch
BranchTrueFalseTotal
if $user 81 13 94
606 }
607 86 return $user;
608 }
609  
610 173 ▶sub logged_in_user {
Subroutine logged_in_user: called CC=4 SCAR=13.9
Pod documented
611 173 my $plugin = shift;
612 173 my $app = $plugin->app;
613 173 my $session = $app->session;
614 173 my $request = $app->request;
615  
616 173 ▶ if ( my $username = $session->read('logged_in_user') ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $username = $session->read('logged_in_user')) { } 74 99 173
617 74 my $existing = $request->vars->{logged_in_user_hash};
618 74 ▶ return $existing if $existing;
Branch: 1 branch
BranchTrueFalseTotal
if $existing 4 70 74
619 70 my $realm = $session->read('logged_in_user_realm');
620 70 my $provider = $plugin->auth_provider($realm);
621 70 ▶ my $user =
Branch: 1 branch
BranchTrueFalseTotal
$provider->can('get_user_details') ? : 69 1 70
622 $provider->can('get_user_details')
623 ? $plugin->get_user_details( $username, $realm )
624 : +{ username => $username };
625 70 $request->vars->{logged_in_user_hash} = $user;
626 70 return $user;
627 }
628 else {
629 99 return undef; # Ensure function doesn't cause problems in list context (GH92)
630 }
631 }
632  
633 2 ▶sub logged_in_user_lastlogin {
Subroutine logged_in_user_lastlogin: called CC=4 SCAR=14.0
Pod documented
634 2 my $lastlogin = shift->app->session->read('logged_in_user_lastlogin');
635 # We don't expect any bad $lastlogin values during testing so mark as many
636 # as possible as uncoverable.
637 # uncoverable branch false
638 # uncoverable condition right
639 2 ▶ if ( defined $lastlogin && ref($lastlogin) eq '' && $lastlogin =~ /^\d+$/ )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $lastlogin and ref $lastlogin eq "" and $lastlogin =~ /^\d+$/) 1 1 2
Condition83%4/6
defined $lastlogin and ref $lastlogin eq "" and $lastlogin =~ /^\d+$/
!ll&&!rl&&r
101
defined $lastlogin and ref $lastlogin eq ""
!ll&&!rl&&r
101
MC/DC66%1/3
defined $lastlogin and ref $lastlogin eq "" and $lastlogin =~ /^\d+$/
defined $lastlogin ref $lastlogin eq "" $lastlogin =~ /^\d+$/
Truth table75%2/4
A and B and C
A= defined $lastloginB= ref $lastlogin eq ""C= $lastlogin =~ /^\d+$/
ABCresult
0XX0
10X0
1100
1111
640 {
641 # A sane epoch time. Old Provider::DBIC stores DateTime in the session
642 # which might get stringified or perhaps not and some session engines
643 # might fail to serialize/deserialize so we now store epoch and
644 # convert back to DateTime.
645 1 $lastlogin = DateTime->from_epoch( epoch => $lastlogin );
646 }
647 2 return $lastlogin;
648 }
649  
650 3 ▶sub logged_in_user_password_expired {
Subroutine logged_in_user_password_expired: called CC=2 SCAR=6.9
Pod documented
651 3 my $plugin = shift;
652 3 ▶ return unless $plugin->logged_in_user;
Branch: 1 branch
BranchTrueFalseTotal
unless $plugin->logged_in_user 1 2 3
653 2 my $provider = $plugin->auth_provider;
654 2 $provider->password_expired( $plugin->logged_in_user );
655 }
656  
657 5 ▶sub password_reset_send {
Subroutine password_reset_send: called CC=8 SCAR=21.0
Pod documented
658 5 my ( $plugin, %options ) = @_;
659  
660 5 my $result = 0;
661  
662 my @realms_to_check =
663 $options{realm}
664 ? ( $options{realm} )
665 5 ▶ : @{ $plugin->realm_names };
Branch: 1 branch
BranchTrueFalseTotal
$options{'realm'} ? : 0 5 5
666  
667 my $username = $options{username}
668 5 ▶ or croak "username must be passed to password_reset_send";
Branch: 1 branch
BranchTrueFalseTotal
my $username = $options{"username"} or croak("username must be passed to password_reset_send") 5 0 5
669  
670 5 foreach my $realm (@realms_to_check) {
671 9 my $this_result;
672 9 $plugin->app->log( debug =>
673 "Attempting to find $username in realm $realm for password reset"
674 );
675 9 my $provider = $plugin->auth_provider($realm);
676  
677 # Generate random string for the password reset URL
678 9 my $code = _reset_code();
679 9 ▶ my $user = try {
Subroutine __ANON__: called CC=1 SCAR=0.0
680 9 $provider->set_user_details( $username, pw_reset_code => $code );
681 }
682 0 ▶ catch {
Subroutine __ANON__: not called CC=1 SCAR=6.9
683 0 $plugin->app->log(
684 debug => "Failed to set_user_details with $realm: $_" );
685 9 };
686 9 ▶ if ($user) {
Branch: 1 branch
BranchTrueFalseTotal
if ($user) 4 5 9
687 4 $plugin->app->log(
688 debug => "got one");
689  
690 # Okay, so email key is hard-coded, and therefore relies on the
691 # provider returning that key. The alternative is to have a
692 # separate provider function to get an email address, which seems
693 # an overkill. Providers can make the email key configurable if
694 # need be
695 4 ▶ my $email = blessed $user ? $user->email : $user->{email};
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($user) ? : 0 4 4
696 4 my %options = ( code => $code, email => $email );
697  
698 16 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
699 $result++
700 4 ▶ if &{ $plugin->password_reset_send_email }( $plugin, %options );
Branch: 1 branch
BranchTrueFalseTotal
if &{$plugin->password_reset_send_email;}($plugin, %options) 4 0 4
701 }
702 }
703 5 ▶ $result ? 1 : 0; # 1 if at least one send was successful
Branch: 1 branch
BranchTrueFalseTotal
$result ? : 4 1 5
704 }
705  
706 5 ▶sub require_all_roles {
Subroutine require_all_roles: called CC=2 SCAR=6.9
Pod documented
707 5 my $plugin = shift;
708 5 ▶ croak "Cannot use require_all_roles since roles are disabled by disable_roles setting"
Branch: 1 branch
BranchTrueFalseTotal
if $plugin->disable_roles 1 4 5
709 if $plugin->disable_roles;
710 4 return $plugin->_build_wrapper( @_, 'all' );
711 }
712  
713 3 ▶sub require_any_role {
Subroutine require_any_role: called CC=2 SCAR=6.9
Pod documented
714 3 my $plugin = shift;
715 3 ▶ croak "Cannot use require_any_role since roles are disabled by disable_roles setting"
Branch: 1 branch
BranchTrueFalseTotal
if $plugin->disable_roles 1 2 3
716 if $plugin->disable_roles;
717 2 return $plugin->_build_wrapper( @_, 'any' );
718 }
719  
720  
721 18 ▶sub require_login {
Subroutine require_login: called CC=1 SCAR=0.0
Pod documented
722 18 my $plugin = shift;
723 18 my $coderef = shift;
724  
725 69 ▶ return sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
726 69 ▶ if ( !$coderef || ref $coderef ne 'CODE' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $coderef or ref $coderef ne "CODE") 4 65 69
Condition100%3/3
not $coderef or ref $coderef ne "CODE"
l!l&&r!l&&!r
2265
MC/DC100%2/2
not $coderef or ref $coderef ne "CODE"
not $coderef ref $coderef ne "CODE"
Truth table100%3/3
not(A) or B
A= not $coderefB= ref $coderef ne "CODE"
ABresult
1X1
011
000
727 4 $plugin->app->log(
728 warning => "Invalid require_login usage, please see docs" );
729 }
730  
731 # User already logged in so give them the page.
732 69 ▶ return $coderef->($plugin)
Branch: 1 branch
BranchTrueFalseTotal
if $plugin->logged_in_user 38 31 69
733 if $plugin->logged_in_user;
734  
735 31 return $plugin->_check_for_login( $coderef );
736 18 };
737 }
738  
739 9 ▶sub require_role {
Subroutine require_role: called CC=2 SCAR=6.9
Pod documented
740 9 my $plugin = shift;
741 9 ▶ croak "Cannot use require_role since roles are disabled by disable_roles setting"
Branch: 1 branch
BranchTrueFalseTotal
if $plugin->disable_roles 1 8 9
742 if $plugin->disable_roles;
743 8 return $plugin->_build_wrapper( @_, 'single' );
744 }
745  
746 3 ▶sub update_current_user {
Subroutine update_current_user: called CC=2 SCAR=6.9
Pod documented
747 3 my ( $plugin, %update ) = @_;
748  
749 3 my $session = $plugin->app->session;
750 3 ▶ if ( my $username = $session->read('logged_in_user') ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $username = $session->read('logged_in_user')) { } 2 1 3
751 2 my $realm = $session->read('logged_in_user_realm');
752 2 $plugin->update_user( $username, realm => $realm, %update );
753 }
754 else {
755 1 $plugin->app->log( debug =>
756 "Could not update current user as no user currently logged in" );
757 }
758 }
759  
760 9 ▶sub update_user {
Subroutine update_user: called CC=6 SCAR=17.9
Pod documented
761 9 my ( $plugin, $username, %update ) = @_;
762  
763 croak "Realm must be specified when more than one realm configured"
764 9 ▶ if !$update{realm} && $plugin->realm_count > 1;
Branch: 1 branch
BranchTrueFalseTotal
if not $update{"realm"} and $plugin->realm_count > 1 1 8 9
Condition100%3/3
not $update{"realm"} and $plugin->realm_count > 1
!ll&&!rl&&r
711
MC/DC100%2/2
not $update{"realm"} and $plugin->realm_count > 1
not $update{"realm"} $plugin->realm_count > 1
Truth table100%3/3
not(A) and B
A= not $update{"realm"}B= $plugin->realm_count > 1
ABresult
0X0
100
111
765  
766 # uncoverable condition false
767 8 ▶ my $realm = delete $update{realm} || $plugin->realm_names->[0];
Condition100%2/3
delete $update{'realm'} || $plugin->realm_names->[0]
l!l&&r!l&&!r
710
MC/DC100%0/2
delete $update{'realm'} || $plugin->realm_names->[0]
delete $update{'realm'} $plugin->realm_names->[0]
Truth table100%2/3
A || B
A= delete $update{'realm'}B= $plugin->realm_names->[0]
ABresult
1X1
011
000
768 8 my $provider = $plugin->auth_provider($realm);
769 8 my $updated = $provider->set_user_details( $username, %update );
770 8 my $cur_user = $plugin->app->session->read('logged_in_user');
771 8 ▶ $plugin->app->request->vars->{logged_in_user_hash} = $updated
Branch: 1 branch
BranchTrueFalseTotal
if $cur_user and $cur_user eq $username 2 6 8
Condition100%3/3
$cur_user and $cur_user eq $username
!ll&&!rl&&r
332
MC/DC100%2/2
$cur_user and $cur_user eq $username
$cur_user $cur_user eq $username
Truth table100%3/3
A and B
A= $cur_userB= $cur_user eq $username
ABresult
0X0
100
111
772 if $cur_user && $cur_user eq $username;
773 8 $updated;
774 }
775  
776 15 ▶sub user_has_role {
Subroutine user_has_role: called CC=6 SCAR=17.9
Pod documented
777 15 my $plugin = shift;
778 15 ▶ croak "Cannot call user_has_role since roles are disabled by disable_roles setting"
Branch: 1 branch
BranchTrueFalseTotal
if $plugin->disable_roles 1 14 15
779 if $plugin->disable_roles;
780  
781 14 my ( $username, $want_role );
782 14 ▶ if ( @_ == 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 2) { } 6 8 14
783 6 ( $username, $want_role ) = @_;
784 }
785 else {
786 8 $username = $plugin->app->session->read('logged_in_user');
787 8 $want_role = shift;
788 }
789  
790 14 ▶ return unless defined $username;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $username 2 12 14
791  
792 12 my $roles = $plugin->user_roles($username);
793  
794 12 for my $has_role (@$roles) {
795 18 ▶ return 1 if $has_role eq $want_role;
Branch: 1 branch
BranchTrueFalseTotal
if $has_role eq $want_role 8 10 18
796 }
797  
798 4 return 0;
799 }
800  
801 16 ▶sub user_password {
Subroutine user_password: called CC=17 SCAR=28.4
Pod documented
802 16 my ( $plugin, %params ) = @_;
803  
804 16 my ( $username, $realm );
805  
806 my @realms_to_check =
807 $params{realm}
808 ? ( $params{realm} )
809 16 ▶ : @{ $plugin->realm_names };
Branch: 1 branch
BranchTrueFalseTotal
$params{'realm'} ? : 2 14 16
810  
811 # Expect either a code, username or nothing (for logged-in user)
812 16 ▶ if ( exists $params{code} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{'code'}) { } 6 10 16
813 6 ▶ my $code = $params{code} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $code = $params{"code"} or return 6 0 6
814 6 foreach my $realm_check (@realms_to_check) {
815 18 my $provider = $plugin->auth_provider($realm_check);
816  
817 # Realm may not support get_user_by_code
818 18 ▶ $username = try {
Subroutine __ANON__: called CC=1 SCAR=0.0
819 18 $provider->get_user_by_code($code);
820 }
821 0 ▶ catch {
Subroutine __ANON__: not called CC=1 SCAR=6.9
822 0 $plugin->app->log( 'debug',
823 "Failed to check for code with $realm_check: $_" );
824 18 };
825 18 ▶ if ($username) {
Branch: 1 branch
BranchTrueFalseTotal
if ($username) { } 3 15 18
826 3 $plugin->app->log( 'debug',
827 "Found $username for code with $realm_check" );
828 3 $realm = $realm_check;
829 3 last;
830 }
831 else {
832 15 $plugin->app->log( 'debug',
833 "No user found in realm $realm_check with code $code" );
834 }
835 }
836 6 ▶ return unless $username;
Branch: 1 branch
BranchTrueFalseTotal
unless $username 3 3 6
837 }
838 else {
839 10 ▶ if ( !$params{username} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $params{'username'}) { } 2 8 10
840 2 ▶ $username = $plugin->app->session->read('logged_in_user')
Branch: 1 branch
BranchTrueFalseTotal
$username = $plugin->app->session->read("logged_in_user") or croak("No username specified and no logged-in user") 2 0 2
841 or croak "No username specified and no logged-in user";
842 2 $realm = $plugin->app->session->read('logged_in_user_realm');
843 }
844 else {
845 8 $username = $params{username};
846 8 $realm = $params{realm};
847 }
848 10 ▶ if ( exists $params{password} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"password"}) 8 2 10
849 8 my $success;
850  
851 # Possible that realm will not be set before this statement
852 ( $success, $realm ) =
853 $plugin->authenticate_user( $username, $params{password},
854 8 $realm );
855 8 ▶ $success or return;
Branch: 1 branch
BranchTrueFalseTotal
$success or return 4 4 8
856 }
857 }
858  
859 # We now have a valid user. Reset the password?
860 9 ▶ if ( my $new_password = $params{new_password} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $new_password = $params{"new_password"}) 4 5 9
861 4 ▶ if ( !$realm ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($realm) 2 2 4
862  
863 # It's possible that the realm is unknown at this stage
864 2 foreach my $realm_check (@realms_to_check) {
865 6 my $provider = $plugin->auth_provider($realm_check);
866 6 ▶ $realm = $realm_check if $provider->get_user_details($username);
Branch: 1 branch
BranchTrueFalseTotal
if $provider->get_user_details($username) 2 4 6
867 }
868 2 ▶ return unless $realm; # Invalid user
Branch: 1 branch
BranchTrueFalseTotal
unless $realm 0 2 2
869 }
870 4 my $provider = $plugin->auth_provider($realm);
871 4 $provider->set_user_password( $username, $new_password );
872 4 ▶ if ( $params{code} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params{"code"}) 1 3 4
873  
874 # Stop reset code being reused
875 1 $provider->set_user_details( $username, pw_reset_code => undef );
876  
877 # Force them to login if this was a reset with a code. This forces
878 # a check that they have the new password correct, and there is a
879 # chance they could have been logged-in as another user
880 1 $plugin->app->destroy_session;
881 }
882 }
883 9 $username;
884 }
885  
886 32 ▶sub user_roles {
Subroutine user_roles: called CC=6 SCAR=17.9
Pod documented
887 32 my ( $plugin, $username, $realm ) = @_;
888 32 ▶ croak
Branch: 1 branch
BranchTrueFalseTotal
if $plugin->disable_roles 1 31 32
889 "Cannot call user_roles since roles are disabled by disable_roles setting"
890 if $plugin->disable_roles;
891  
892 31 ▶ if ( !defined $username ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $username) 15 16 31
893 # assume logged_in_user so clear realm and look for user
894 15 $realm = undef;
895 15 $username = $plugin->app->session->read('logged_in_user');
896 15 ▶ croak "user_roles needs a username or a logged in user"
Branch: 1 branch
BranchTrueFalseTotal
unless $username 2 13 15
897 unless $username;
898 }
899  
900 29 my $roles = $plugin->auth_provider($realm)->get_user_roles($username);
901 29 ▶ return unless defined $roles;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $roles 0 29 29
902 29 ▶ return wantarray ? @$roles : $roles;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 11 18 29
903 }
904  
905 #
906 # private methods
907 #
908  
909 14 ▶sub _build_wrapper {
Subroutine _build_wrapper: called CC=2 SCAR=6.9
910 14 my $plugin = shift;
911 14 my $require_role = shift;
912 14 my $coderef = shift;
913 14 my $mode = shift;
914  
915 14 ▶ my @role_list =
Branch: 1 branch
BranchTrueFalseTotal
ref $require_role eq 'ARRAY' ? : 6 8 14
916 ref $require_role eq 'ARRAY'
917 ? @$require_role
918 : $require_role;
919  
920 21 ▶ return sub {
Subroutine __ANON__: called CC=15 SCAR=27.2
921 21 ▶ return $plugin->_check_for_login( $coderef )
Branch: 1 branch
BranchTrueFalseTotal
unless $plugin->logged_in_user 6 15 21
922 unless $plugin->logged_in_user;
923  
924 15 my $role_match;
925  
926 # this is a private method and we should never need 'else'
927 # uncoverable branch false count:3
928 15 ▶ if ( $mode eq 'single' ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($mode eq 'single') { } 9 6 15
elsif ($mode eq 'any') { } 2 4 6
elsif ($mode eq 'all') { } 4 0 4
929 9 for ( $plugin->user_roles ) {
930 18 ▶ $role_match++ and last if _smart_match( $_, $require_role );
Branch: 1 branch
BranchTrueFalseTotal
if _smart_match($_, $require_role) 6 12 18
Condition60%3/5
_smart_match($_, $require_role) && ($role_match++ && (last))
!ll&&!rl&&r
1260
$role_match++ and last
!ll
60
MC/DC0%0/2
_smart_match($_, $require_role) && ($role_match++ && (last))
_smart_match($_, $require_role) $role_match++
Truth table66%2/3
A && B
A= _smart_match($_, $require_role)B= $role_match++
ABresult
0X0
100
111
931 }
932 }
933 elsif ( $mode eq 'any' ) {
934 2 my %role_ok = map { $_ => 1 } @role_list;
935 2 for ( $plugin->user_roles ) {
936 4 ▶ $role_match++ and last if $role_ok{$_};
Branch: 1 branch
BranchTrueFalseTotal
if $role_ok{$_} 2 2 4
Condition60%3/5
$role_ok{$_} && ($role_match++ && (last))
!ll&&!rl&&r
220
$role_match++ and last
!ll
20
MC/DC0%0/2
$role_ok{$_} && ($role_match++ && (last))
$role_ok{$_} $role_match++
Truth table66%2/3
A && B
A= $role_ok{$_}B= $role_match++
ABresult
0X0
100
111
937 }
938 }
939 elsif ( $mode eq 'all' ) {
940 4 $role_match++;
941 4 for my $role (@role_list) {
942 8 ▶ if ( !$plugin->user_has_role($role) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($plugin->user_has_role($role)) 2 6 8
943 2 $role_match = 0;
944 2 last;
945 }
946 }
947 }
948  
949 15 ▶ if ($role_match) {
Branch: 1 branch
BranchTrueFalseTotal
if ($role_match) 10 5 15
950  
951 # We're happy with their roles, so go head and execute the route
952 # handler coderef.
953 10 return $coderef->($plugin);
954 }
955  
956 5 $plugin->execute_plugin_hook( 'permission_denied', $coderef );
957  
958 # TODO: see if any code executed by that hook set up a response
959  
960 5 $plugin->app->response->status(403);
961 5 my $options;
962 5 my $view = $plugin->denied_page;
963 5 my $template_engine = $plugin->app->template_engine;
964 5 my $path = $template_engine->view_pathname($view);
965 5 ▶ if ( !$template_engine->pathname_exists($path) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($template_engine->pathname_exists($path)) 5 0 5
966 5 $plugin->app->log(
967 debug => "app has no denied_page template defined" );
968 5 $options->{content} = $plugin->_render_template('login_denied.tt');
969 5 undef $view;
970 }
971 5 return $plugin->app->template( $view, undef, $options );
972 14 };
973 }
974  
975 37 ▶sub _check_for_login {
Subroutine _check_for_login: called CC=6 SCAR=17.9
976 37 my ( $plugin, $coderef ) = @_;
977 37 $plugin->execute_plugin_hook( 'login_required', $coderef );
978  
979 # TODO: see if any code executed by that hook set up a response
980  
981 37 my $request = $plugin->app->request;
982  
983 37 ▶ if ( $plugin->login_without_redirect ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plugin->login_without_redirect) 8 29 37
984 8 my $tokens = {
985 login_failed => $request->var('login_failed'),
986 reset_password_handler => $plugin->reset_password_handler
987 };
988  
989 # The WWW-Authenticate header added varies depending on whether
990 # the client is a robot or not.
991 8 my $ua = HTTP::BrowserDetect->new( $request->env->{HTTP_USER_AGENT} );
992 8 my $base = $request->base;
993 8 my $auth_method;
994  
995 8 ▶ if ( !$ua->browser_string || $ua->robot ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $ua->browser_string or $ua->robot) { } 7 1 8
Condition66%2/3
not $ua->browser_string or $ua->robot
l!l&&r!l&&!r
701
MC/DC50%1/2
not $ua->browser_string or $ua->robot
not $ua->browser_string $ua->robot
Truth table66%2/3
not(A) or B
A= not $ua->browser_stringB= $ua->robot
ABresult
1X1
011
000
996 7 $auth_method = $auth_method = qq{Basic realm="$base"};
997 }
998 else {
999 1 $auth_method = qq{FormBasedLogin realm="$base", }
1000 . q{comment="use form to log in"};
1001 }
1002  
1003 8 $plugin->app->response->status(401);
1004 8 $plugin->app->response->push_header(
1005 'WWW-Authenticate' => $auth_method );
1006  
1007 # If this is the first attempt to reach a protected page and *not*
1008 # a failed passthrough login then we need to stash method and params.
1009 8 ▶ if ( !$request->var('login_failed') ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($request->var("login_failed")) 5 3 8
1010 5 $plugin->app->session->write(
1011 '__auth_extensible_method' => lc($request->method) );
1012 $plugin->app->session->write(
1013 5 '__auth_extensible_params' => \%{ $request->params } );
1014 }
1015  
1016 8 return $plugin->_render_login_page( 'transparent_login.tt', $tokens );
1017 }
1018  
1019 # old-fashioned redirect to login page with return_url set
1020 29 my $forward = $request->path;
1021 29 ▶ $forward .= "?".$request->query_string
Branch: 1 branch
BranchTrueFalseTotal
if $request->query_string 1 28 29
1022 if $request->query_string;
1023 29 return $plugin->app->redirect(
1024 $request->uri_for(
1025 # Do not use request_uri, as it is the raw string sent by the
1026 # browser, not taking into account the application mount point.
1027 # This means that when it is then concatenated with the base URL,
1028 # the application mount point is specified twice. See GH PR #81
1029 $plugin->login_page, { return_url => $forward }
1030 )
1031 );
1032 }
1033  
1034 24 ▶sub _render_login_page {
Subroutine _render_login_page: called CC=2 SCAR=6.9
1035 24 my ( $plugin, $default_template, $tokens ) = @_;
1036  
1037 # If app has its own login page view then use it
1038 # otherwise render our internal one and pass that to 'template'.
1039 24 my ( $view, $options ) = ( $plugin->login_template, {} );
1040 24 my $template_engine = $plugin->app->template_engine;
1041 24 my $path = $template_engine->view_pathname($view);
1042 24 ▶ if ( !$template_engine->pathname_exists($path) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($template_engine->pathname_exists($path)) 23 1 24
1043 23 $plugin->app->log( debug => "app has no login template defined" );
1044 $options->{content} =
1045 23 $plugin->_render_template( $default_template, $tokens );
1046 23 undef $view;
1047 }
1048 24 return $plugin->app->template( $view, $tokens, $options );
1049 }
1050  
1051 3 ▶sub _default_email_password_reset {
Subroutine _default_email_password_reset: called CC=3 SCAR=11.3
1052 3 my ( $plugin, %options ) = @_;
1053  
1054 3 my %message;
1055 3 ▶ if ( my $password_reset_text = $plugin->password_reset_text ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $password_reset_text = $plugin->password_reset_text) { } 0 3 3
1056 16 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
1057 0 %message = &{$password_reset_text}( $plugin, %options );
1058 }
1059 else {
1060 3 my $link = URI->new_abs("login/$options{code}", $plugin->uri_base_request);
1061 3 ▶ my $appname = $plugin->app->config->{appname} || '[unknown]';
Condition50%1/2
$plugin->app->config->{'appname'} || '[unknown]'
l!l
03
MC/DC0%0/1
$plugin->app->config->{'appname'} || '[unknown]'
$plugin->app->config->{'appname'}
Truth table50%1/2
A
A= $plugin->app->config->{'appname'}
Aresult
11
00
1062 3 $message{subject} = "Password reset request";
1063 3 $message{from} = $plugin->mail_from;
1064 3 $message{plain} = <<__EMAIL;
1065 A request has been received to reset your password for $appname. If
1066 you would like to do so, please follow the link below:
1067  
1068 $link
1069 __EMAIL
1070 }
1071  
1072 3 $plugin->_send_email( to => $options{email}, %message );
1073 }
1074  
1075 30 ▶sub _render_template {
Subroutine _render_template: called CC=2 SCAR=6.9
1076 30 my ( $plugin, $view, $tokens ) = @_;
1077 30 ▶ $tokens ||= +{};
Condition100%2/2
$tokens ||= {}
l!l
237
MC/DC100%1/1
$tokens ||= {}
$tokens
Truth table100%2/2
A
A= $tokens
Aresult
11
00
1078  
1079 30 my $template =
1080 path( dist_dir('Dancer2-Plugin-Auth-Extensible'), 'views', $view );
1081  
1082 30 $plugin->_template_tiny->render( $template, $tokens );
1083 }
1084  
1085 16 ▶sub _default_login_page {
Subroutine _default_login_page: called CC=2 SCAR=6.9
1086 16 my $plugin = shift;
1087 16 my $request = $plugin->app->request;
1088  
1089 # Simple escape of new_password param.
1090 # This only works with the default password generator but since we
1091 # are planning to remove password generation in favour of user-specified
1092 # password on reset then this will do for now.
1093 16 my $new_password = $request->parameters->get('new_password');
1094 16 ▶ if ( defined $new_password ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $new_password) 1 15 16
1095 1 $new_password =~ s/[^a-zA-Z0-9]//g;
1096 }
1097  
1098 # Make sure all tokens are escaped in some way.
1099 16 my $tokens = {
1100 loginpage => uri_escape( $plugin->login_page ),
1101 login_failed => !!$request->var('login_failed'),
1102 new_password => $new_password,
1103 password_code_valid =>
1104 !!$request->parameters->get('password_code_valid'),
1105 reset_sent => !!$request->parameters->get('reset_sent'),
1106 reset_password_handler => !!$plugin->reset_password_handler,
1107 return_url => uri_escape( $request->parameters->get('return_url') ),
1108 };
1109  
1110 16 return $plugin->_render_login_page( 'login.tt', $tokens );
1111 }
1112  
1113 2 ▶sub _default_permission_denied_page {
Subroutine _default_permission_denied_page: called CC=1 SCAR=0.0
1114 2 shift->_render_template( 'login_denied.tt' );
1115 }
1116  
1117 3 ▶sub _default_welcome_send {
Subroutine _default_welcome_send: called CC=3 SCAR=11.3
1118 3 my ( $plugin, %options ) = @_;
1119  
1120 3 my %message;
1121 3 ▶ if ( my $welcome_text = $plugin->welcome_text ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $welcome_text = $plugin->welcome_text) { } 0 3 3
1122 16 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
1123 0 %message = &{$welcome_text}( $plugin, %options );
1124 }
1125 else {
1126 3 ▶ my $appname = $plugin->app->config->{appname} || '[unknown]';
Condition50%1/2
$plugin->app->config->{'appname'} || '[unknown]'
l!l
03
MC/DC0%0/1
$plugin->app->config->{'appname'} || '[unknown]'
$plugin->app->config->{'appname'}
Truth table50%1/2
A
A= $plugin->app->config->{'appname'}
Aresult
11
00
1127 3 my $reset_link = URI->new_abs("login/$options{code}", $plugin->uri_base_request);
1128 3 $message{subject} = "Welcome to $appname";
1129 3 $message{from} = $plugin->mail_from;
1130 3 $message{plain} = <<__EMAIL;
1131 An account has been created for you at $appname. If you would like
1132 to accept this, please follow the link below to set a password:
1133  
1134 $reset_link
1135 __EMAIL
1136 }
1137  
1138 3 $plugin->_send_email( to => $options{email}, %message );
1139 }
1140  
1141 6 ▶sub _email_mail_message {
Subroutine _email_mail_message: called CC=6 SCAR=19.1
1142 6 my ( $plugin, %params ) = @_;
1143  
1144 6 ▶ my $mailer_options = $plugin->mailer->{options} || {};
Condition50%1/2
$plugin->mailer->{'options'} || {}
l!l
60
MC/DC0%0/1
$plugin->mailer->{'options'} || {}
$plugin->mailer->{'options'}
Truth table50%1/2
A
A= $plugin->mailer->{'options'}
Aresult
11
00
1145  
1146 6 my @parts;
1147  
1148 push @parts,
1149 Mail::Message::Body::String->new(
1150 mime_type => 'text/plain',
1151 disposition => 'inline',
1152 data => $params{plain},
1153 6 ▶ ) if ( $params{plain} );
Branch: 1 branch
BranchTrueFalseTotal
if $params{"plain"} 6 0 6
1154  
1155 push @parts,
1156 Mail::Message::Body::String->new(
1157 mime_type => 'text/html',
1158 disposition => 'inline',
1159 data => $params{html},
1160 6 ▶ ) if ( $params{html} );
Branch: 1 branch
BranchTrueFalseTotal
if $params{"html"} 0 6 6
1161  
1162 6 ▶ @parts or croak "No plain or HTML email text supplied";
Branch: 1 branch
BranchTrueFalseTotal
@parts or croak("No plain or HTML email text supplied") 6 0 6
1163  
1164 6 ▶ my $content_type = @parts > 1 ? 'multipart/alternative' : $parts[0]->type;
Branch: 1 branch
BranchTrueFalseTotal
@parts > 1 ? : 0 6 6
1165  
1166 Mail::Message->build(
1167 To => $params{to},
1168 Subject => $params{subject},
1169 From => $params{from},
1170 6 'Content-Type' => $content_type,
1171 attach => \@parts,
1172 )->send(%$mailer_options);
1173 }
1174  
1175 6 ▶sub _send_email {
Subroutine _send_email: called CC=4 SCAR=15.0
1176 6 my $plugin = shift;
1177  
1178 6 ▶ my $mailer = $plugin->mailer or croak "No mailer configured";
Branch: 1 branch
BranchTrueFalseTotal
my $mailer = $plugin->mailer or croak("No mailer configured") 6 0 6
1179  
1180 my $module = $mailer->{module}
1181 6 ▶ or croak "No email module specified for mailer";
Branch: 1 branch
BranchTrueFalseTotal
my $module = $mailer->{"module"} or croak("No email module specified for mailer") 6 0 6
1182  
1183 6 ▶ if ( $module eq 'Mail::Message' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($module eq 'Mail::Message') { } 6 0 6
1184  
1185 # require Mail::Message;
1186 6 require Mail::Message::Body::String;
1187 6 return $plugin->_email_mail_message(@_);
1188 }
1189 else {
1190 0 croak "No support for $module. Please submit a PR!";
1191 }
1192 }
1193  
1194 66 ▶sub _return_url {
Subroutine _return_url: called CC=3 SCAR=11.0
1195 66 my $app = shift;
1196 66 ▶ my $return_url = $app->request->query_parameters->get('return_url')
Branch: 1 branch
BranchTrueFalseTotal
my $return_url = $app->request->query_parameters->get("return_url") || $app->request->body_parameters->get("return_url") or return undef 11 55 66
Condition100%3/3
$app->request->query_parameters->get('return_url') || $app->request->body_parameters->get('return_url')
l!l&&r!l&&!r
7455
MC/DC100%2/2
$app->request->query_parameters->get('return_url') || $app->request->body_parameters->get('return_url')
$app->request->query_parameters->get('return_url') $app->request->body_parameters->get('return_url')
Truth table100%3/3
A || B
A= $app->request->query_parameters->get('return_url')B= $app->request->body_parameters->get('return_url')
ABresult
1X1
011
000
1197 || $app->request->body_parameters->get('return_url')
1198 or return undef;
1199 11 $return_url = uri_unescape($return_url);
1200 11 my $uri = URI->new($return_url);
1201 # Construct a URL using uri_for, which ensures that the correct base domain
1202 # is used (preventing open URL redirection attacks). The query needs to be
1203 # parsed and passed as an option, otherwise it is not encoded properly
1204 11 return $app->request->uri_for($uri->path, $uri->query_form_hash);
1205 }
1206  
1207 #
1208 # routes
1209 #
1210  
1211 # implementation of logout route
1212 28 ▶sub _logout_route {
Subroutine _logout_route: called CC=3 SCAR=11.1
1213 28 my $app = shift;
1214 28 my $req = $app->request;
1215 28 my $plugin = $app->with_plugin('Auth::Extensible');
1216  
1217 28 $plugin->execute_plugin_hook( 'before_logout' );
1218  
1219 28 $app->destroy_session;
1220  
1221 28 ▶ if ( my $url = _return_url($app) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (my $url = _return_url($app)) { } 2 26 28
elsif ($plugin->exit_page) { } 26 0 26
1222 2 $app->redirect( $url );
1223 }
1224 elsif ($plugin->exit_page) {
1225 26 $app->redirect($plugin->exit_page);
1226 }
1227 else {
1228 # TODO: perhaps make this more configurable, perhaps by attempting to
1229 # render a template first.
1230 0 return "OK, logged out successfully.";
1231 }
1232 }
1233  
1234 # implementation of post login route
1235 43 ▶sub _post_login_route {
Subroutine _post_login_route: called CC=20 SCAR=30.2
1236 43 my $app = shift;
1237 43 my $plugin = $app->with_plugin('Auth::Extensible');
1238 43 my $params = $app->request->body_parameters->as_hashref;
1239  
1240 # First check for password reset request, if applicable
1241 43 ▶ if ( $plugin->reset_password_handler && $params->{submit_reset} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plugin->reset_password_handler and $params->{"submit_reset"}) 2 41 43
Condition100%3/3
$plugin->reset_password_handler and $params->{"submit_reset"}
!ll&&!rl&&r
15262
MC/DC100%2/2
$plugin->reset_password_handler and $params->{"submit_reset"}
$plugin->reset_password_handler $params->{"submit_reset"}
Truth table100%3/3
A and B
A= $plugin->reset_password_handlerB= $params->{"submit_reset"}
ABresult
0X0
100
111
1242 2 my $username = $params->{username_reset};
1243 2 ▶ croak "Attempt to pass reference to reset blocked" if ref $username;
Branch: 1 branch
BranchTrueFalseTotal
if ref $username 0 2 2
1244 2 $plugin->password_reset_send( username => $username );
1245 2 return $app->forward(
1246 $plugin->login_page,
1247 { reset_sent => 1 },
1248 { method => 'GET' }
1249 );
1250 }
1251  
1252 # Then for a password reset itself (confirmed by POST request)
1253 my ($code) =
1254 $plugin->reset_password_handler
1255 && $params->{confirm_reset}
1256 41 ▶ && $app->request->splat;
Condition83%5/6
$plugin->reset_password_handler && $params->{'confirm_reset'} && $app->request->splat
!ll&&!rl&&r
3902
$plugin->reset_password_handler and $params->{"confirm_reset"}
!ll&&!rl&&r
15242
MC/DC66%2/3
$plugin->reset_password_handler && $params->{'confirm_reset'} && $app->request->splat
$plugin->reset_password_handler $params->{"confirm_reset"} $app->request->splat
Truth table75%3/4
A and B && C
A= $plugin->reset_password_handlerB= $params->{"confirm_reset"}C= $app->request->splat
ABCresult
0XX0
10X0
1100
1111
1257  
1258 41 ▶ if ($code) {
Branch: 1 branch
BranchTrueFalseTotal
if ($code) 2 39 41
1259 16 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
1260 2 my $randompw = &{ $plugin->password_generator };
1261 2 ▶ if (my $username = $plugin->user_password( code => $code, new_password => $randompw ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $username = $plugin->user_password("code", $code, "new_password", $randompw)) 1 1 2
1262 # Support a custom 'Change password' page or other app-based
1263 # intervention after a successful reset code has been applied
1264 1 foreach my $realm_check (@{ $plugin->realm_names }) { # $params->{realm} isn't defined at this point...
1265 3 my $provider = $plugin->auth_provider($realm_check);
1266 3 ▶ $params->{realm} = $realm_check if $provider->get_user_details($username);
Branch: 1 branch
BranchTrueFalseTotal
if $provider->get_user_details($username) 1 2 3
1267 }
1268  
1269 $plugin->execute_plugin_hook( 'after_reset_code_success',
1270 1 { username => $username, password => $randompw, realm => $params->{realm} } );
1271  
1272 1 return $app->forward(
1273 $plugin->login_page,
1274 { new_password => $randompw },
1275 { method => 'GET' }
1276 );
1277 }
1278 }
1279  
1280 # For security, ensure the username and password are straight scalars; if
1281 # the app is using a serializer and we were sent a blob of JSON, they could
1282 # have come from that JSON, and thus could be hashrefs (JSON SQL injection)
1283 # - for database providers, feeding a carefully crafted hashref to the SQL
1284 # builder could result in different SQL to what we'd expect.
1285 # For instance, if we pass password => params->{password} to an SQL builder,
1286 # we'd expect the query to include e.g. "WHERE password = '...'" (likely
1287 # with paremeterisation) - but if params->{password} was something
1288 # different, e.g. { 'like' => '%' }, we might end up with some SQL like
1289 # WHERE password LIKE '%' instead - which would not be a Good Thing.
1290 40 ▶ my $username = $params->{username} || $params->{__auth_extensible_username};
Condition66%2/3
$params->{'username'} || $params->{'__auth_extensible_username'}
l!l&&r!l&&!r
3505
MC/DC50%1/2
$params->{'username'} || $params->{'__auth_extensible_username'}
$params->{'username'} $params->{'__auth_extensible_username'}
Truth table66%2/3
A || B
A= $params->{'username'}B= $params->{'__auth_extensible_username'}
ABresult
1X1
011
000
1291 40 ▶ my $password = $params->{password} || $params->{__auth_extensible_password};
Condition66%2/3
$params->{'password'} || $params->{'__auth_extensible_password'}
l!l&&r!l&&!r
3505
MC/DC50%1/2
$params->{'password'} || $params->{'__auth_extensible_password'}
$params->{'password'} $params->{'__auth_extensible_password'}
Truth table66%2/3
A || B
A= $params->{'password'}B= $params->{'__auth_extensible_password'}
ABresult
1X1
011
000
1292  
1293 40 for ( $username, $password ) {
1294 80 ▶ if ( ref $_ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $_) 0 80 80
1295  
1296 # TODO: handle more cleanly
1297 0 croak "Attempt to pass a reference as username/password blocked";
1298 }
1299 }
1300  
1301 40 ▶ if ( $plugin->logged_in_user ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plugin->logged_in_user) 1 39 40
1302 # uncoverable condition false
1303 1 ▶ $app->redirect( _return_url($app) || $plugin->user_home_page );
Condition66%1/3
_return_url($app) || $plugin->user_home_page
l!l&&r!l&&!r
010
MC/DC100%0/2
_return_url($app) || $plugin->user_home_page
_return_url($app) $plugin->user_home_page
Truth table66%1/3
A || B
A= _return_url($app)B= $plugin->user_home_page
ABresult
1X1
011
000
1304 }
1305  
1306 39 ▶ my $auth_realm = $params->{realm} || $params->{__auth_extensible_realm};
Condition66%2/3
$params->{'realm'} || $params->{'__auth_extensible_realm'}
l!l&&r!l&&!r
5034
MC/DC50%1/2
$params->{'realm'} || $params->{'__auth_extensible_realm'}
$params->{'realm'} $params->{'__auth_extensible_realm'}
Truth table66%2/3
A || B
A= $params->{'realm'}B= $params->{'__auth_extensible_realm'}
ABresult
1X1
011
000
1307 39 my ( $success, $realm ) =
1308 $plugin->authenticate_user( $username, $password, $auth_realm );
1309  
1310 39 ▶ if ($success) {
Branch: 1 branch
BranchTrueFalseTotal
if ($success) { } 32 7 39
1311  
1312 # change session ID if we have a new enough D2 version with support
1313 32 ▶ $plugin->app->change_session_id
Branch: 1 branch
BranchTrueFalseTotal
if $plugin->app->can("change_session_id") 32 0 32
1314 if $plugin->app->can('change_session_id');
1315  
1316 32 $app->session->write( logged_in_user => $username );
1317 32 $app->session->write( logged_in_user_realm => $realm );
1318 32 $app->log( core => "Realm is $realm" );
1319 32 $plugin->execute_plugin_hook( 'after_login_success' );
1320 # uncoverable condition false
1321 32 ▶ $app->redirect( _return_url($app) || $plugin->user_home_page );
Condition100%2/3
_return_url($app) || $plugin->user_home_page
l!l&&r!l&&!r
6260
MC/DC100%0/2
_return_url($app) || $plugin->user_home_page
_return_url($app) $plugin->user_home_page
Truth table100%2/3
A || B
A= _return_url($app)B= $plugin->user_home_page
ABresult
1X1
011
000
1322 }
1323 else {
1324 7 $app->request->vars->{login_failed}++;
1325 7 $app->forward(
1326 $plugin->login_page,
1327 { login_failed => 1 },
1328 { method => 'GET' }
1329 );
1330 }
1331 }
1332  
1333 #
1334 # private functions
1335 #
1336  
1337 2 ▶sub _default_password_generator {
Subroutine _default_password_generator: called CC=1 SCAR=0.0
1338 2 Session::Token->new( length => 8 )->get;
1339 }
1340  
1341 13 ▶sub _reset_code {
Subroutine _reset_code: called CC=1 SCAR=0.0
1342 13 Session::Token->new( length => 32 )->get;
1343 }
1344  
1345 # Replacement for much maligned and misunderstood smartmatch operator
1346 18 ▶sub _smart_match {
Subroutine _smart_match: called CC=4 SCAR=17.2
1347 18 my ( $got, $want ) = @_;
1348 18 ▶ if ( !ref $want ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not ref $want) { } 14 4 18
elsif (ref $want eq 'Regexp') { } 4 0 4
elsif (ref $want eq 'ARRAY') { } 0 0 0
1349 14 return $got eq $want;
1350 }
1351 elsif ( ref $want eq 'Regexp' ) {
1352 4 return $got =~ $want;
1353 }
1354 elsif ( ref $want eq 'ARRAY' ) {
1355 0 return grep { $_ eq $got } @$want;
1356 }
1357 else {
1358 0 carp "Don't know how to match against a " . ref $want;
1359 }
1360 }
1361  
1362 =head1 NAME
1363  
1364 Dancer2::Plugin::Auth::Extensible - extensible authentication framework for Dancer2 apps
1365  
1366 =head1 DESCRIPTION
1367  
1368 A user authentication and authorisation framework plugin for Dancer2 apps.
1369  
1370 Makes it easy to require a user to be logged in to access certain routes,
1371 provides role-based access control, and supports various authentication
1372 methods/sources (config file, database, Unix system users, etc).
1373  
1374 Designed to support multiple authentication realms and to be as extensible as
1375 possible, and to make secure password handling easy. The base class for auth
1376 providers makes handling C<RFC2307>-style hashed passwords really simple, so you
1377 have no excuse for storing plain-text passwords. A simple script called
1378 B<dancer2-generate-crypted-password> to generate
1379 RFC2307-style hashed passwords is included, or you can use L<Crypt::SaltedHash>
1380 yourself to do so, or use the C<slappasswd> utility if you have it installed.
1381  
1382 =head1 SYNOPSIS
1383  
1384 Configure the plugin to use the authentication provider class you wish to use:
1385  
1386 plugins:
1387 Auth::Extensible:
1388 realms:
1389 users:
1390 provider: Config
1391 ....
1392  
1393 The configuration you provide will depend on the authentication provider module
1394 in use. For a simple example, see
1395 L<Dancer2::Plugin::Auth::Extensible::Provider::Config>.
1396  
1397 Define that a user must be logged in and have the proper permissions to
1398 access a route:
1399  
1400 get '/secret' => require_role Confidant => sub { tell_secrets(); };
1401  
1402 Define that a user must be logged in to access a route - and find out who is
1403 logged in with the C<logged_in_user> keyword:
1404  
1405 get '/users' => require_login sub {
1406 my $user = logged_in_user;
1407 return "Hi there, $user->{username}";
1408 };
1409  
1410 =head1 AUTHENTICATION PROVIDERS
1411  
1412 For flexibility, this authentication framework uses simple authentication
1413 provider classes, which implement a simple interface and do whatever is required
1414 to authenticate a user against the chosen source of authentication.
1415  
1416 For an example of how simple provider classes are, so you can build your own if
1417 required or just try out this authentication framework plugin easily,
1418 see L<Dancer2::Plugin::Auth::Extensible::Provider::Config>.
1419  
1420 This framework supplies the following providers out-of-the-box:
1421  
1422 =over 4
1423  
1424 =item L<Dancer2::Plugin::Auth::Extensible::Provider::Unix>
1425  
1426 Authenticates users using system accounts on Linux/Unix type boxes
1427  
1428 =item L<Dancer2::Plugin::Auth::Extensible::Provider::Config>
1429  
1430 Authenticates users stored in the app's config
1431  
1432 =back
1433  
1434 The following external providers are also available on the CPAN:
1435  
1436 =over 4
1437  
1438 =item L<Dancer2::Plugin::Auth::Extensible::Provider::DBIC>
1439  
1440 Authenticates users stored in a database table using L<Dancer2::Plugin::DBIC>
1441  
1442 =item L<Dancer2::Plugin::Auth::Extensible::Provider::Database>
1443  
1444 Authenticates users stored in a database table
1445  
1446 =item L<Dancer2::Plugin::Auth::Extensible::Provider::IMAP>
1447  
1448 Authenticates users via in an IMAP server.
1449  
1450 =item L<Dancer2::Plugin::Auth::Extensible::Provider::LDAP>
1451  
1452 Authenticates users stored in an LDAP directory.
1453  
1454 =item L<Dancer2::Plugin::Auth::Extensible::Provider::Usergroup>
1455  
1456 An alternative L<Dancer2::Plugin::DBIC>-based provider.
1457  
1458 =back
1459  
1460 Need to write your own? Just create a new provider class which consumes
1461 L<Dancer2::Plugin::Auth::Extensible::Role::Provider> and implements the
1462 required methods, and you're good to go!
1463  
1464 =head1 CONTROLLING ACCESS TO ROUTES
1465  
1466 Keywords are provided to check if a user is logged in / has appropriate roles.
1467  
1468 =head2 require_login - require the user to be logged in
1469  
1470 get '/dashboard' => require_login sub { .... };
1471  
1472 If the user is not logged in, they will be redirected to the login page URL to
1473 log in. The default URL is C</login> - this may be changed with the
1474 C<login_page> option.
1475  
1476 =head2 require_role - require the user to have a specified role
1477  
1478 get '/beer' => require_role BeerDrinker => sub { ... };
1479  
1480 Requires that the user be logged in as a user who has the specified role. If
1481 the user is not logged in, they will be redirected to the login page URL. If
1482 they are logged in, but do not have the required role, they will be redirected
1483 to the access denied URL.
1484  
1485 If C<disable_roles> configuration option is set to a true value then using
1486 L</require_role> will cause the application to croak on load.
1487  
1488 =head2 require_any_role - require the user to have one of a list of roles
1489  
1490 get '/drink' => require_any_role [qw(BeerDrinker VodaDrinker)] => sub {
1491 ...
1492 };
1493  
1494 Requires that the user be logged in as a user who has any one (or more) of the
1495 roles listed. If the user is not logged in, they will be redirected to the
1496 login page URL. If they are logged in, but do not have any of the specified
1497 roles, they will be redirected to the access denied URL.
1498  
1499 If C<disable_roles> configuration option is set to a true value then using
1500 L</require_any_role> will cause the application to croak on load.
1501  
1502 =head2 require_all_roles - require the user to have all roles listed
1503  
1504 get '/foo' => require_all_roles [qw(Foo Bar)] => sub { ... };
1505  
1506 Requires that the user be logged in as a user who has all of the roles listed.
1507 If the user is not logged in, they will be redirected to the login page URL. If
1508 they are logged in but do not have all of the specified roles, they will be
1509 redirected to the access denied URL.
1510  
1511 If C<disable_roles> configuration option is set to a true value then using
1512 L</require_all_roles> will cause the application to croak on load.
1513  
1514 =head1 NO-REDIRECT LOGIN
1515  
1516 By default when a page is requested that requires login and the user is not
1517 logged in then the plugin redirects the user to the L</login_page> and sets
1518 C<return_url> to the page originally requested. After successful login the
1519 user is redirected to the originally-requested page.
1520  
1521 As an alternative if L</login_without_redirect> is true then the login
1522 process happens with no redirects. Instead a C<401> C<Unauthorized> code
1523 is returned and a login page is displayed. This login page is posted to the
1524 original URI and on successful login an internal L<Dancer2::Manual/forward>
1525 is performed so that the originally requested page is displayed. Any
1526 L<Dancer2::Manual/params> from the original request are added to the
1527 forward so that they are available to the page's route handler either using
1528 L<Dancer2::Manual/params> or L<Dancer2::Manual/query_parameters>.
1529  
1530 This relies on the login form having no C<action> set and also it must use
1531 C<__auth_extensible_username> and C<__auth_extensible_password> input names.
1532 Optionally C<__auth_extensible_realm> can also be used in a custom login
1533 page.
1534  
1535 See L<http://shadow.cat/blog/matt-s-trout/humane-login-screens/> for the
1536 original idea for this functionality.
1537  
1538 =head1 CUSTOMISING C</login> AND C</login/denied>
1539  
1540 =head2 login_template
1541  
1542 The L</login_template> setting determines the name of the view you use
1543 for your custom login page. If this view exists in your application then it
1544 will be used instead of the default login template.
1545  
1546 If you are using L</login_without_redirect> and assuming you are using
1547 L<Template::Toolkit> then your custom login page should be something like this:
1548  
1549 <h1>Login Required</h1>
1550  
1551 <p>You need to log in to continue.</p>
1552  
1553 [%- IF login_failed -%]
1554 <p>LOGIN FAILED</p>
1555 [%- END -%]
1556  
1557 <form method="post">
1558 <label for="username">Username:</label>
1559 <input type="text" name="__auth_extensible_username" id="username">
1560 <br />
1561 <label for="password">Password:</label>
1562 <input type="password" name="__auth_extensible_password" id="password">
1563 <br />
1564 <input type="submit" value="Login">
1565 </form>
1566  
1567 [%- IF reset_password_handler -%]
1568 <form method="post" action="[% login_page %]">
1569 <h2>Password reset</h2>
1570 <p>Enter your username to obtain an email to reset your password</p>
1571 <label for="username_reset">Username:</label>
1572 <input type="text" name="username_reset" id="username_reset">
1573 <input type="submit" name="submit_reset" value="Submit">
1574 </form>
1575 [%- END -%]
1576  
1577 If you are B<not> using L</login_without_redirect> and assuming you are using
1578 L<Template::Toolkit> then your custom login page should be something like this:
1579  
1580 <h1>Login Required</h1>
1581  
1582 <p>You need to log in to continue.</p>
1583  
1584 [%- IF login_failed -%]
1585 <p>LOGIN FAILED</p>
1586 [%- END -%]
1587  
1588 <form method="post">
1589 <label for="username">Username:</label>
1590 <input type="text" name="username" id="username">
1591 <br />
1592 <label for="password">Password:</label>
1593 <input type="password" name="password" id="password">
1594 <br />
1595 <input type="submit" value="Login">
1596  
1597 [%- IF return_url -%]
1598 <input type="hidden" name="return_url" value="[% return_url %]">
1599 [%- END -%]
1600  
1601 [%- IF reset_password_handler -%]
1602 <h2>Password reset</h2>
1603 <p>Enter your username to obtain an email to reset your password</p>
1604 <label for="username_reset">Username:</label>
1605 <input type="text" name="username_reset" id="username_reset">
1606 <input type="submit" name="submit_reset" value="Submit">
1607 [%- END -%]
1608  
1609 </form>
1610  
1611 =head2 Replacing the default C< /login > and C< /login/denied > routes
1612  
1613 By default, the plugin adds a route to present a simple login form at that URL.
1614 If you would rather add your own, set the C<no_default_pages> setting to a true
1615 value, and define your own route which responds to C</login> with a login page.
1616 Alternatively you can let DPAE add the routes and handle the status codes, etc.
1617 and simply define the setting C<login_page_handler> and/or
1618 C<permission_denied_page_handler> with the name of a subroutine to be called to
1619 handle the route. Note that it must be a fully qualified sub. E.g.
1620  
1621 plugins:
1622 Auth::Extensible:
1623 login_page_handler: 'My::App::login_page_handler'
1624 permission_denied_page_handler: 'My::App::permission_denied_page_handler'
1625  
1626 Then in your code you might simply use a template:
1627  
1628 sub login_page_handler {
1629 my $return_url = query_parameters->get('return_url');
1630 template
1631 'account/login',
1632 { title => 'Sign in',
1633 return_url => $return_url,
1634 },
1635 { layout => 'login.tt',
1636 };
1637 }
1638  
1639 sub permission_denied_page_handler {
1640 template 'account/login';
1641 }
1642  
1643 and your account/login.tt template might look like:
1644  
1645 [% IF vars.login_failed %]
1646 <div class="alert alert-danger">
1647 <strong>Login Failed</strong> Try again
1648 <button type="button" class="close" data-dismiss="alert" aria-label="Close">
1649 <span aria-hidden="true">&times;</span>
1650 </button>
1651 </div>
1652 [% END %]
1653  
1654 <form method = "post" lpformnum="1" class="form-signin">
1655 <h2 class="form-signin-heading">Please sign in</h2>
1656 <label for="username" class="sr-only">Username</label>
1657 <input type="text" name="username" id="username" class="form-control" placeholder="User name" required autofocus>
1658 <label for="password" class="sr-only">Password</label>
1659 <input type="password" name="password" id="password" class="form-control" placeholder="Password" required>
1660 <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
1661 <br>
1662 <input type="hidden" name="return_url" value="[% return_url %]">
1663 </form>
1664  
1665  
1666 If the user is logged in, but tries to access a route which requires a specific
1667 role they don't have, they will be redirected to the "permission denied" page
1668 URL, which defaults to C</login/denied> but may be changed using the
1669 C<denied_page> option.
1670  
1671 Again, by default a route is added to respond to that URL with a default page;
1672 again, you can disable this by setting C<no_default_pages> and creating your
1673 own.
1674  
1675 This would still leave the routes C<post '/login'> and C<any '/logout'>
1676 routes in place. To disable them too, set the option C<no_login_handler>
1677 to a true value. In this case, these routes should be defined by the user,
1678 and should do at least the following:
1679  
1680 post '/login' => sub {
1681 my ($success, $realm) = authenticate_user(
1682 params->{username}, params->{password}
1683 );
1684 if ($success) {
1685 # change session ID if we have a new enough D2 version with support
1686 # (security best practice on privilege level change)
1687 app->change_session_id
1688 if app->can('change_session_id');
1689 session logged_in_user => params->{username};
1690 session logged_in_user_realm => $realm;
1691 # other code here
1692 } else {
1693 # authentication failed
1694 }
1695 };
1696
1697 any '/logout' => sub {
1698 app->destroy_session;
1699 };
1700  
1701 If you want to use the default C<post '/login'> and C<any '/logout'> routes
1702 you can configure them. See below.
1703  
1704 The default routes also contain functionality for a user to perform password
1705 resets. See the L<PASSWORD RESETS> documentation for more details.
1706  
1707 =head1 KEYWORDS
1708  
1709 The following keywords are provided in additional to the route decorators
1710 specified in L</CONTROLLING ACCESS TO ROUTES>:
1711  
1712 =head2 logged_in_user
1713  
1714 Returns a hashref of details of the currently logged-in user or some kind of
1715 user object, if there is one.
1716  
1717 The details you get back will depend upon the authentication provider in use.
1718  
1719 =head2 get_user_details
1720  
1721 Returns a hashref of details of the specified user. The realm can optionally
1722 be specified as the second parameter. If the realm is not specified, each
1723 realm will be checked, and the first matching user will be returned.
1724  
1725 The details you get back will depend upon the authentication provider in use.
1726  
1727 =head2 user_has_role
1728  
1729 Check if a user has the role named.
1730  
1731 By default, the currently-logged-in user will be checked, so you need only name
1732 the role you're looking for:
1733  
1734 if (user_has_role('BeerDrinker')) { pour_beer(); }
1735  
1736 You can also provide the username to check;
1737  
1738 if (user_has_role($user, $role)) { .... }
1739  
1740 If C<disable_roles> configuration option is set to a true value then using
1741 L</user_has_role> will cause the application to croak at runtime.
1742  
1743 =head2 user_roles
1744  
1745 Returns a list of the roles of a user.
1746  
1747 By default, roles for the currently-logged-in user will be checked;
1748 alternatively, you may supply a username to check.
1749  
1750 Returns a list or arrayref depending on context.
1751  
1752 If C<disable_roles> configuration option is set to a true value then using
1753 L</user_roles> will cause the application to croak at runtime.
1754  
1755 =head2 authenticate_user
1756  
1757 Usually you'll want to let the built-in login handling code deal with
1758 authenticating users, but in case you need to do it yourself, this keyword
1759 accepts a username and password, and optionally a specific realm, and checks
1760 whether the username and password are valid.
1761  
1762 For example:
1763  
1764 if (authenticate_user($username, $password)) {
1765 ...
1766 }
1767  
1768 If you are using multiple authentication realms, by default each realm will be
1769 consulted in turn. If you only wish to check one of them (for instance, you're
1770 authenticating an admin user, and there's only one realm which applies to them),
1771 you can supply the realm as an optional third parameter.
1772  
1773 In boolean context, returns simply true or false; in list context, returns
1774 C<($success, $realm)>.
1775  
1776 =head2 logged_in_user_lastlogin
1777  
1778 Returns (as a DateTime object) the time of the last successful login of the
1779 current logged in user.
1780  
1781 To enable this functionality, set the configuration key C<record_lastlogin> to
1782 a true value. The backend provider must support write access for a user and
1783 have lastlogin functionality implemented.
1784  
1785 =head2 update_user
1786  
1787 Updates a user's details. If the authentication provider supports it, this
1788 keyword allows a user's details to be updated within the backend data store.
1789  
1790 In order to update the user's details, the keyword should be called with the
1791 username to be updated, followed by a hash of the values to be updated. Note
1792 that whilst the password can be updated using this method, any new value will
1793 be stored directly into the provider as-is, not encrypted. It is recommended to
1794 use L</user_password> instead.
1795  
1796 If only one realm is configured then this will be used to search for the user.
1797 Otherwise, the realm must be specified with the realm key.
1798  
1799 # Update user, only one realm configured
1800 update_user "jsmith", surname => "Smith"
1801  
1802 # Update a user's username, more than one realm
1803 update_user "jsmith", realm => "dbic", username => "jjones"
1804  
1805 The updated user's details are returned, as per L<logged_in_user>.
1806  
1807 =head2 update_current_user
1808  
1809 The same as L<update_user>, but does not take a username as the first parameter,
1810 instead updating the currently logged-in user.
1811  
1812 # Update user, only one realm configured
1813 update_current_user surname => "Smith"
1814  
1815 The updated user's details are returned, as per L<logged_in_user>.
1816  
1817 =head2 create_user
1818  
1819 Creates a new user, if the authentication provider supports it. Optionally
1820 sends a welcome message with a password reset request, in which case an
1821 email key must be provided. If sending welcome emails, see the C<uri_base>
1822 configuration parameter: to prevent an attacker creating malicious links,
1823 either this must be set or the application must enforce a valid hostname.
1824  
1825 This function works in the same manner as L<update_user>, except that
1826 the username key is mandatory. As with L<update_user>, it is recommended
1827 not to set a password directly using this method, otherwise it will be
1828 stored in plain text.
1829  
1830 The realm to use must be specified with the key C<realm> if there is more
1831 than one realm configured.
1832  
1833 # Create new user
1834 create_user username => "jsmith", realm => "dbic", surname => "Smith"
1835  
1836 # Create new user and send welcome email
1837 create_user username => "jsmith", email => "john@you.com", email_welcome => 1
1838  
1839 On success, the created user's details are returned, as per L<logged_in_user>.
1840  
1841 The text sent in the welcome email can be customised in 2 ways, in the same way
1842 as L<password_reset_send>:
1843  
1844 =over
1845  
1846 =item welcome_send
1847  
1848 This can be used to specify a subroutine that will be called to perform the
1849 entire message construction and email sending. Note that it must be a
1850 fully-qualified sub such as C<My::App:email_welcome_send>. The subroutine will
1851 be passed the dsl as the first parameter, followed by a hash with the keys
1852 C<code>, C<email> and C<user>, which contain the generated reset code, user
1853 email address, and user hashref respectively. For example:
1854  
1855 sub reset_send_handler {
1856 my ($dsl, %params) = @_;
1857 my $user_email = $params{email};
1858 my $reset_code = $params{code};
1859 # Send email
1860 return $result;
1861 }
1862  
1863 =item welcome_text
1864  
1865 This can be used to generate the text for the welcome email, with this module
1866 sending the actual email itself. It must be a fully-qualified sub, as per the
1867 previous option. It will be passed the same parameters as
1868 L<welcome_send>, and should return a hash with the same keys as
1869 L<password_reset_send_email>.
1870  
1871 =back
1872  
1873 =head2 password_reset_send
1874  
1875 L</password_reset_send> sends a user an email with a password reset link. Along
1876 with L</user_password>, it allows a user to reset their password. See the
1877 C<uri_base> configuration parameter: to prevent an attacker creating malicious
1878 links, either this must be set or the application must enforce a valid
1879 hostname.
1880  
1881 The function must be called with the key C<username> and a value that is the
1882 username. The username specified will be sent an email with a link to reset
1883 their password. Note that the provider being used must return the email address
1884 in the key C<email>, which in the case of a database will normally require that
1885 column to exist in the user's table. The provider must be able to write values
1886 to the user in order for this function to store the generated code.
1887  
1888 If the username is not found, a value of 0 is returned. If the username is
1889 found and the email is sent successfully, 1 is returned. Otherwise undef is
1890 returned. Note: if you are displaying a success message, and you do not want
1891 people to be able to check the existance of a user on your system, then you
1892 should check for the return value being defined, not true. For example:
1893  
1894 say "Success" if defined password_reset_send username => username;
1895  
1896 Note that this still leaves the possibility of checking the existance of a user
1897 if the email send mechanism is failing.
1898  
1899 The realm can also be specified using the key realm:
1900  
1901 password_reset_send username => 'jsmith', realm => 'dbic'
1902  
1903 Default text for the email is automatically produced and emailed. This can be
1904 customized with one of 2 config parameters:
1905  
1906 =over
1907  
1908 =item password_reset_send_email
1909  
1910 This can be used to specify a subroutine that will be called to perform the
1911 entire message construction and email sending. Note that it must be a
1912 fully-qualified sub such as C<My::App:reset_send_handler>. The subroutine will
1913 be passed the dsl as the first parameter, followed by a hash with the keys
1914 C<code> and C<email>, which contain the generated reset code and user email
1915 address respectively. For example:
1916  
1917 sub reset_send_handler {
1918 my ($dsl, %params) = @_;
1919 my $user_email = $params{email};
1920 my $reset_code = $params{code};
1921 # Send email
1922 return $result;
1923 }
1924  
1925 =item password_reset_text
1926  
1927 This can be used to generate the text for the email, with this module sending
1928 the actual email itself. It must be a fully-qualified sub, as per the previous
1929 option. It will be passed the same parameters as L<password_reset_send_email>,
1930 and should return a hash with the following keys:
1931  
1932 =over
1933  
1934 =item subject
1935  
1936 The subject of the email message.
1937  
1938 =item from
1939  
1940 The sender of the email message (optional, can also be specified using
1941 C<mail_from>.
1942  
1943 =item plain
1944  
1945 Plain text for the email. Either this, or html, or both should be returned.
1946  
1947 =item html
1948  
1949 HTML text for the email (optional, as per plain).
1950  
1951 =back
1952  
1953 Here is an example subroutine:
1954  
1955 sub reset_text_handler {
1956 my ($dsl, %params) = @_;
1957 return (
1958 from => '"My name" <myapp@example.com',
1959 subject => 'the subject',
1960 plain => "reset here: $params{code}",
1961 );
1962 }
1963  
1964 # Example configuration
1965  
1966 Auth::Extensible:
1967 mailer:
1968 module: Mail::Message # Module to send email with
1969 options: # Module options
1970 via: sendmail
1971 mail_from: '"My app" <myapp@example.com>'
1972 password_reset_text: MyApp::reset_send
1973  
1974 =back
1975  
1976 =head2 user_password
1977  
1978 This provides various functions to check or reset a user's password, either
1979 from a reset code that was previously send by L<password_reset_send> or
1980 directly by specifying a username and password. Functions that update a
1981 password rely on a provider that has write access to a user's details.
1982  
1983 By default, the user to update is the currently logged-in user. A specific user
1984 can be specified with the key C<username> for a certain username, or C<code>
1985 for a previously sent reset code. Using these parameters on their own will
1986 return the username if it is a valid request.
1987  
1988 If the above parameters are specified with the additional parameter
1989 C<new_password>, then the password will be set to that value, assuming that it
1990 is a valid request.
1991  
1992 The realm can be optionally specified with the keyword C<realm>.
1993  
1994 Examples:
1995  
1996 Check the logged-in user's password:
1997  
1998 user_password password => 'mysecret'
1999  
2000 Check a specific user's password:
2001  
2002 user_password username => 'jsmith', password => 'bigsecret'
2003  
2004 Check a previously sent reset code:
2005  
2006 user_password code => 'XXXX'
2007  
2008 Reset a password with a previously sent code:
2009  
2010 user_password code => 'XXXX', new_password => 'newsecret'
2011  
2012 Change a user's password (username optional)
2013  
2014 user_password username => 'jbloggs', password => 'old', new_password => 'secret'
2015  
2016 Force set a specific user's password, without checking existing password:
2017  
2018 user_password username => 'jbloggs', new_password => 'secret'
2019  
2020 =head2 logged_in_user_password_expired
2021  
2022 Returns true if the password of the currently logged in user has expired. To
2023 use this functionality, the provider must support the C<password_expired>
2024 function, and must be configured accordingly. See the relevant provider for
2025 full configuration details.
2026  
2027 Note that this functionality does B<not> prevent the user accessing any
2028 protected pages, even if the password has expired. This is so that the
2029 developer can still leave some protected routes available, such as a page to
2030 change the password. Therefore, if using this functionality, it is suggested
2031 that a check is done in the C<before> hook:
2032  
2033 hook before => sub {
2034 if (logged_in_user_password_expired)
2035 {
2036 # Redirect to user details page if password expired, but only if that
2037 # is not the currently request page to prevent redirect loops
2038 redirect '/password_update' unless request->uri eq '/password_update';
2039 }
2040 }
2041  
2042 =head2 PASSWORD RESETS
2043  
2044 A variety of functionality is provided to make it easier to manage requests
2045 from users to reset their passwords. The keywords L<password_reset_send> and
2046 L<user_password> form the core of this functionality - see the documentation of
2047 these keywords for full details. This functionality can only be used with a
2048 provider that supports write access.
2049  
2050 When utilising this functionality, it is wise to only allow passwords to be
2051 reset with a POST request. This is because some email scanners "open" links
2052 before delivering the email to the end user. With only a single-use GET
2053 request, this will result in the link being "used" by the time it reaches the
2054 end user, thus rendering it invalid.
2055  
2056 Password reset functionality is also built-in to the default route handlers.
2057 To enable this, set the configuration value C<reset_password_handler> to a true
2058 value (having already configured the mail handler, as per the keyword
2059 documentation above). Once this is done, the default login page will contain
2060 additional form controls to allow the user to enter their username and request
2061 a reset password link.
2062  
2063 By default, the default handlers will generate a random 8 character password using
2064 L<Session::Token>. To use your own function, set C<password_generator> in your
2065 configuration. See the L<SAMPLE CONFIGURATION> for an example.
2066  
2067 If using C<login_page_handler> to replace the default login page, you can still
2068 use the default password reset handlers. Add 2 controls to your form for
2069 submitting a password reset request: a text input called username_reset for the
2070 username, and submit_reset to submit the request. Your login_page_handler is
2071 then passed the following additional params:
2072  
2073 =over
2074  
2075 =item new_password
2076  
2077 Contains the new automatically-generated password, once the password reset has
2078 been performed successfully.
2079  
2080 =item reset_sent
2081  
2082 Is true when a password reset has been emailed to the user.
2083  
2084 =item password_code_valid
2085  
2086 Is true when a valid password reset code has been submitted with a GET request.
2087 In this case, the user should be given the chance to confirm with a POST
2088 request, with a form control called C<confirm_reset>.
2089  
2090 For a full example, see the default handler in this module's code.
2091  
2092 =back
2093  
2094 =head2 SAMPLE CONFIGURATION
2095  
2096 In your application's configuation file:
2097  
2098 session: simple
2099 plugins:
2100 Auth::Extensible:
2101 # Set to 1 if you want to disable the use of roles (0 is default)
2102 # If roles are disabled then any use of role-based route decorators
2103 # will cause app to croak on load. Use of 'user_roles' and
2104 # 'user_has_role' will croak at runtime.
2105 disable_roles: 0
2106 # Set to 1 to use the no-redirect login functionality
2107 login_without_redirect: 0
2108 # Set the view name for a custom login page, defaults to 'login'
2109 login_template: login
2110 # After /login: If no return_url is given: land here ('/' is default)
2111 user_home_page: '/user'
2112 # After /logout: If no return_url is given: land here (no default)
2113 exit_page: '/'
2114  
2115 # Mailer options for reset password and welcome emails
2116 mailer:
2117 module: Mail::Message # Email module to use
2118 options: # Options for module
2119 via: sendmail # Options passed to $msg->send
2120 mail_from: '"App name" <myapp@example.com>' # From email address
2121  
2122 # Set to true to enable password reset code in the default handlers
2123 reset_password_handler: 1
2124 password_generator: My::App::random_pw # Optional random password generator
2125  
2126 # Set to a true value to enable recording of successful last login times
2127 record_lastlogin: 1
2128  
2129 # Password reset functionality
2130 password_reset_send_email: My::App::reset_send # Customise sending sub
2131 password_reset_text: My::App::reset_text # Customise reset text
2132  
2133 # Specify the base hostname for URIs generated by the plugin. By
2134 # default this will be lazily-built from a value obtained from
2135 # Dancer (which uses the request header supplied by the client).
2136 # Because this can be controlled by an attacker, it is recommended
2137 # to force the value here, unless your application enforces this
2138 # value in other ways (e.g. redirecting within the application in
2139 # the event that the specified hostname is unknown). The value
2140 # specified here will be coerced into a URI object.
2141 uri_base: https://myserver.example.com
2142  
2143 # create_user options
2144 welcome_send: My::App::welcome_send # Customise welcome email sub
2145 welcome_text: My::App::welcome_text # Customise welcome email text
2146  
2147 # List each authentication realm, with the provider to use and the
2148 # provider-specific settings (see the documentation for the provider
2149 # you wish to use)
2150 realms:
2151 realm_one:
2152 priority: 3 # Defaults to 0. Realms are checked in descending order
2153 provider: Database
2154 db_connection_name: 'foo'
2155 realm_two:
2156 priority: 0 # Will be checked after realm_one
2157 provider: Config
2158  
2159 B<Please note> that you B<must> have a session provider configured. The
2160 authentication framework requires sessions in order to track information about
2161 the currently logged in user.
2162 Please see L<Dancer2::Core::Session> for information on how to configure session
2163 management within your application.
2164  
2165 =head1 METHODS
2166  
2167 =head2 auth_provider($dsl, $realm)
2168  
2169 Given a realm, returns a configured and ready to use instance of the provider
2170 specified by that realm's config.
2171  
2172 =head1 HOOKS
2173  
2174 This plugin provides the following hooks:
2175  
2176 =head2 before_authenticate_user
2177  
2178 Called at the start of L</authenticate_user>.
2179  
2180 Receives a hash reference of C<username>, C<password> and C<realm>.
2181  
2182 =head2 after_authenticate_user
2183  
2184 Called at the end of L</authenticate_user>.
2185  
2186 Receives a hash reference of C<username>, C<password>, C<realm>, C<errors>
2187 and C<success>.
2188  
2189 C<realm> is the realm that the user authenticated against of undef if auth
2190 failed.
2191  
2192 The value of C<errors> is an array reference of any errors thrown by
2193 authentication providers (if any).
2194  
2195 The value of C<success> is either C<1> or C<0> to show whether or not
2196 authentication was successful.
2197  
2198 =head2 before_create_user
2199  
2200 Called at the start of L</create_user>.
2201  
2202 Receives a hash reference of the arguments passed to L</create_user>.
2203  
2204 =head2 after_create_user
2205  
2206 Called at the end of L</create_user>.
2207  
2208 Receives the requested username, the created user (or undef) and an array
2209 reference of any errors from the main method or from the provider.
2210  
2211 =head2 login_required
2212  
2213 =head2 permission_denied
2214  
2215 =head2 after_reset_code_success
2216  
2217 Called after successful reset code has been provided. Supports a custom 'Change
2218 password' page or other app-based intervention after a successful reset code
2219 has been applied.
2220  
2221 =head2 after_login_success
2222  
2223 Called after successful login just before redirect is called.
2224  
2225 =head2 before_logout
2226  
2227 Called just before the session gets destroyed on logout.
2228  
2229 =head1 SECURITY CONSIDERATIONS
2230  
2231 If not used correctly, this module can potentially be abused to insert
2232 malicious URIs in the emails that it generates. See the documentation for
2233 uri_base, create_user and password_reset_send.
2234  
2235 =head1 AUTHOR
2236  
2237 David Precious, C<< <davidp at preshweb.co.uk> >>
2238  
2239 Dancer2 port of Dancer::Plugin::Auth::Extensible by:
2240  
2241 Stefan Hornburg (Racke), C<< <racke at linuxia.de> >>
2242  
2243 Conversion to Dancer2's new plugin system plus much cleanup & reorg:
2244  
2245 Peter Mottram (SysPete), C<< <peter at sysnix.com> >>
2246  
2247 =head1 BUGS / FEATURE REQUESTS
2248  
2249 This is an early version; there may still be bugs present or features missing.
2250  
2251 This is developed on GitHub - please feel free to raise issues or pull requests
2252 against the repo at:
2253 L<https://github.com/PerlDancer/Dancer2-Plugin-Auth-Extensible>
2254  
2255 =head1 ACKNOWLEDGEMENTS
2256  
2257 Valuable feedback on the early design of this module came from many people,
2258 including Matt S Trout (mst), David Golden (xdg), Damien Krotkine (dams),
2259 Daniel Perrett, and others.
2260  
2261 Configurable login/logout URLs added by Rene (hertell)
2262  
2263 Regex support for require_role by chenryn
2264  
2265 Support for user_roles looking in other realms by Colin Ewen (casao)
2266  
2267 LDAP provider added by Mark Meyer (ofosos)
2268  
2269 Documentation fix by Vince Willems.
2270  
2271 Henk van Oers (GH #8, #13, #55).
2272  
2273 Andrew Beverly (GH #6, #7, #10, #17, #22, #24, #25, #26, #54).
2274 This includes support for creating and editing users and manage user passwords.
2275  
2276 Gabor Szabo (GH #11, #16, #18).
2277  
2278 Evan Brown (GH #20, #32).
2279  
2280 Jason Lewis (Unix provider problem, GH#62).
2281  
2282 Matt S. Trout (mst) for L<Zero redirect login the easy and friendly way|http://shadow.cat/blog/matt-s-trout/humane-login-screens/>.
2283  
2284 Ben Kaufman "whosgonna" (GH#79)
2285  
2286 Dominic Sonntag (GH#70)
2287  
2288 =head1 LICENSE AND COPYRIGHT
2289  
2290 Copyright 2012-16 David Precious.
2291  
2292 This program is free software; you can redistribute it and/or modify it
2293 under the terms of either: the GNU General Public License as published
2294 by the Free Software Foundation; or the Artistic License.
2295  
2296 See http://dev.perl.org/licenses/ for more information.
2297  
2298 =cut
2299  
2300 16 1; # End of Dancer2::Plugin::Auth::Extensible
« Extensible/Test.pm ↑ Summary Extensible/Provider/Config.pm »