Yancy/Plugin/Auth/Password.pm

filter: Statementstmt 13.4% 27 / 201 Branchbran 0.0% 0 / 60 Conditioncond 0.0% 0 / 53 MC/DCmcdc 0.0% 0 / 25 Subroutinesub 17.3% 4 / 23 Podpod 0.0% 0 / 4 totaltotal 8.4% 31 / 366 CC 53 SCAR 41.2
CC
53
Cov
9%
init
182.0
login_form
72.0
_post_register
72.0
CRAP 61.3
« Yancy/Controller/Yancy/MultiTenant.pm ↑ Summary Yancy/Plugin/Editor.pm »
1 package Yancy::Plugin::Auth::Password;
2 1 our $VERSION = '1.078';
3 # ABSTRACT: A simple password-based auth
4  
5 #pod =encoding utf8
6 #pod
7 #pod =head1 SYNOPSIS
8 #pod
9 #pod use Mojolicious::Lite;
10 #pod plugin Yancy => {
11 #pod backend => 'sqlite://myapp.db',
12 #pod schema => {
13 #pod users => {
14 #pod 'x-id-field' => 'username',
15 #pod properties => {
16 #pod username => { type => 'string' },
17 #pod password => { type => 'string', format => 'password' },
18 #pod },
19 #pod },
20 #pod },
21 #pod };
22 #pod app->yancy->plugin( 'Auth::Password' => {
23 #pod schema => 'users',
24 #pod username_field => 'username',
25 #pod password_field => 'password',
26 #pod password_digest => {
27 #pod type => 'SHA-1',
28 #pod },
29 #pod } );
30 #pod
31 #pod =head1 DESCRIPTION
32 #pod
33 #pod B<Note:> This module is C<EXPERIMENTAL> and its API may change before
34 #pod Yancy v2.000 is released.
35 #pod
36 #pod This plugin provides a basic password-based authentication scheme for
37 #pod a site.
38 #pod
39 #pod This module composes the L<Yancy::Auth::Plugin::Role::RequireUser> role
40 #pod to provide the
41 #pod L<require_user|Yancy::Auth::Plugin::Role::RequireUser/require_user>
42 #pod authorization method.
43 #pod
44 #pod =head2 Adding Users
45 #pod
46 #pod To add the initial user (or any user), use the L<C<mojo eval>
47 #pod command|Mojolicious::Command::eval>:
48 #pod
49 #pod ./myapp.pl eval 'yancy->create( users => { username => "dbell", password => "123qwe" } )'
50 #pod
51 #pod This plugin adds the L</auth.digest> filter to the C<password> field, so
52 #pod the password passed to C<< yancy->create >> will be properly hashed in
53 #pod the database.
54 #pod
55 #pod You can use this same technique to edit users from the command-line if
56 #pod someone gets locked out:
57 #pod
58 #pod ./myapp.pl eval 'yancy->update( users => "dbell", { password => "123qwe" } )'
59 #pod
60 #pod =head2 Migrate from Auth::Basic
61 #pod
62 #pod To migrate from the deprecated L<Yancy::Plugin::Auth::Basic> module, you
63 #pod should set the C<migrate_digest> config setting to the C<password_digest>
64 #pod settings from your Auth::Basic configuration. If they are the same as your
65 #pod current password digest settings, you don't need to do anything at all.
66 #pod
67 #pod # Migrate from Auth::Basic, which had SHA-1 passwords, to
68 #pod # Auth::Password using SHA-256 passwords
69 #pod app->yancy->plugin( 'Auth::Password' => {
70 #pod schema => 'users',
71 #pod username_field => 'username',
72 #pod password_field => 'password',
73 #pod migrate_digest => {
74 #pod type => 'SHA-1',
75 #pod },
76 #pod password_digest => {
77 #pod type => 'SHA-256',
78 #pod },
79 #pod } );
80 #pod
81 #pod # Migrate from Auth::Basic, which had SHA-1 passwords, to
82 #pod # Auth::Password using SHA-1 passwords
83 #pod app->yancy->plugin( 'Auth::Password' => {
84 #pod schema => 'users',
85 #pod username_field => 'username',
86 #pod password_field => 'password',
87 #pod password_digest => {
88 #pod type => 'SHA-1',
89 #pod },
90 #pod } );
91 #pod
92 #pod =head2 Verifying Yancy Passwords in SQL (or other languages)
93 #pod
94 #pod Passwords are stored as base64. The Perl L<Digest> module's removes the
95 #pod trailing padding from a base64 string. This means that if you try to use
96 #pod another method to verify passwords, you must also remove any trailing
97 #pod C<=> from the base64 hash you generate.
98 #pod
99 #pod Here are some examples for how to generate the same password hash in
100 #pod different databases/languages:
101 #pod
102 #pod * Perl:
103 #pod
104 #pod $ perl -MDigest -E'say Digest->new( "SHA-1" )->add( "password" )->b64digest'
105 #pod W6ph5Mm5Pz8GgiULbPgzG37mj9g
106 #pod
107 #pod * MySQL:
108 #pod
109 #pod mysql> SELECT TRIM( TRAILING "=" FROM TO_BASE64( UNHEX( SHA1( "password" ) ) ) );
110 #pod +--------------------------------------------------------------------+
111 #pod | TRIM( TRAILING "=" FROM TO_BASE64( UNHEX( SHA1( "password" ) ) ) ) |
112 #pod +--------------------------------------------------------------------+
113 #pod | W6ph5Mm5Pz8GgiULbPgzG37mj9g |
114 #pod +--------------------------------------------------------------------+
115 #pod
116 #pod * Postgres:
117 #pod
118 #pod yancy=# CREATE EXTENSION pgcrypto;
119 #pod CREATE EXTENSION
120 #pod yancy=# SELECT TRIM( TRAILING '=' FROM encode( digest( 'password', 'sha1' ), 'base64' ) );
121 #pod rtrim
122 #pod -----------------------------
123 #pod W6ph5Mm5Pz8GgiULbPgzG37mj9g
124 #pod (1 row)
125 #pod
126 #pod =head1 CONFIGURATION
127 #pod
128 #pod This plugin has the following configuration options.
129 #pod
130 #pod =head2 schema
131 #pod
132 #pod The name of the Yancy schema that holds users. Required.
133 #pod
134 #pod =head2 username_field
135 #pod
136 #pod The name of the field in the schema which is the user's identifier.
137 #pod This can be a user name, ID, or e-mail address, and is provided by the
138 #pod user during login.
139 #pod
140 #pod This field is optional. If not specified, the schema's ID field will
141 #pod be used. For example, if the schema uses the C<username> field as
142 #pod a unique identifier, we don't need to provide a C<username_field>.
143 #pod
144 #pod plugin Yancy => {
145 #pod schema => {
146 #pod users => {
147 #pod 'x-id-field' => 'username',
148 #pod properties => {
149 #pod username => { type => 'string' },
150 #pod password => { type => 'string' },
151 #pod },
152 #pod },
153 #pod },
154 #pod };
155 #pod app->yancy->plugin( 'Auth::Password' => {
156 #pod schema => 'users',
157 #pod password_digest => { type => 'SHA-1' },
158 #pod } );
159 #pod
160 #pod =head2 password_field
161 #pod
162 #pod The name of the field to use for the password. Defaults to C<password>.
163 #pod
164 #pod This field will automatically be set up to use the L</auth.digest> filter to
165 #pod properly hash the password when updating it.
166 #pod
167 #pod =head2 password_digest
168 #pod
169 #pod This is the hashing mechanism that should be used for hashing passwords.
170 #pod This value should be a hash of digest configuration. The one required
171 #pod field is C<type>, and should be a type supported by the L<Digest> module:
172 #pod
173 #pod =over
174 #pod
175 #pod =item * MD5 (part of core Perl)
176 #pod
177 #pod =item * SHA-1 (part of core Perl)
178 #pod
179 #pod =item * SHA-256 (part of core Perl)
180 #pod
181 #pod =item * SHA-512 (part of core Perl)
182 #pod
183 #pod =item * Bcrypt (recommended)
184 #pod
185 #pod =back
186 #pod
187 #pod Additional fields are given as configuration to the L<Digest> module.
188 #pod Not all Digest types require additional configuration.
189 #pod
190 #pod There is no default: Perl core provides SHA-1 hashes, but those aren't good
191 #pod enough. We recommend installing L<Digest::Bcrypt> for password hashing.
192 #pod
193 #pod # Use Bcrypt for passwords
194 #pod # Install the Digest::Bcrypt module first!
195 #pod app->yancy->plugin( 'Auth::Basic' => {
196 #pod password_digest => {
197 #pod type => 'Bcrypt',
198 #pod cost => 12,
199 #pod salt => 'abcdefgh♥stuff',
200 #pod },
201 #pod } );
202 #pod
203 #pod Digest information is stored with the password so that password digests
204 #pod can be updated transparently when necessary. Changing the digest
205 #pod configuration will result in a user's password being upgraded the next
206 #pod time they log in.
207 #pod
208 #pod =head2 allow_register
209 #pod
210 #pod If true, allow the visitor to register their own user account.
211 #pod
212 #pod =head2 register_fields
213 #pod
214 #pod An array of fields to show to the user when registering an account. By
215 #pod default, all required fields from the schema will be presented in the
216 #pod form to register.
217 #pod
218 #pod =head2 Sessions
219 #pod
220 #pod This module uses L<Mojolicious
221 #pod sessions|https://mojolicious.org/perldoc/Mojolicious/Controller#session>
222 #pod to store the login information in a secure, signed cookie.
223 #pod
224 #pod To configure the default expiration of a session, use
225 #pod L<Mojolicious::Sessions
226 #pod default_expiration|https://mojolicious.org/perldoc/Mojolicious/Sessions#default_expiration>.
227 #pod
228 #pod use Mojolicious::Lite;
229 #pod # Expire a session after 1 day of inactivity
230 #pod app->sessions->default_expiration( 24 * 60 * 60 );
231 #pod
232 #pod =head1 FILTERS
233 #pod
234 #pod This module provides the following filters. See L<Yancy/Extended Field
235 #pod Configuration> for how to use filters.
236 #pod
237 #pod =head2 auth.digest
238 #pod
239 #pod Run the field value through the configured password L<Digest> object and
240 #pod store the Base64-encoded result instead.
241 #pod
242 #pod =head1 HELPERS
243 #pod
244 #pod This plugin has the following helpers.
245 #pod
246 #pod =head2 yancy.auth.current_user
247 #pod
248 #pod Get the current user from the session, if any. Returns C<undef> if no
249 #pod user was found in the session.
250 #pod
251 #pod my $user = $c->yancy->auth->current_user
252 #pod || return $c->render( status => 401, text => 'Unauthorized' );
253 #pod
254 #pod =head2 yancy.auth.require_user
255 #pod
256 #pod Validate there is a logged-in user and optionally that the user data has
257 #pod certain values. See L<Yancy::Plugin::Auth::Role::RequireUser/require_user>.
258 #pod
259 #pod # Display the user dashboard, but only to logged-in users
260 #pod my $auth_route = $app->routes->under( '/user', $app->yancy->auth->require_user );
261 #pod $auth_route->get( '' )->to( 'user#dashboard' );
262 #pod
263 #pod =head2 yancy.auth.login_form
264 #pod
265 #pod Return an HTML string containing the rendered login form.
266 #pod
267 #pod %# Display a login form to an unauthenticated visitor
268 #pod % if ( !$c->yancy->auth->current_user ) {
269 #pod %= $c->yancy->auth->login_form
270 #pod % }
271 #pod
272 #pod The login form will create a C<return_to> hidden field to try to bring
273 #pod the user back to what they were doing when they were asked to log in.
274 #pod This field defaults to the value of the C<return_to> parameter or the
275 #pod value of the C<return_to> flash value. If neither is set, it defaults to
276 #pod the HTTP referrer if the form is displayed on the login page (under the
277 #pod URL C</yancy/auth/password>) or the current page.
278 #pod
279 #pod # Redirect user to login page, and return them here
280 #pod under sub( $c ) {
281 #pod return 1 if $c->yancy->auth->current_user;
282 #pod $c->flash({ return_to => $c->req->url });
283 #pod $c->redirect_to('yancy.auth.password.login');
284 #pod return undef;
285 #pod }
286 #pod
287 #pod # Build a link to log in and then redirect to the dashboard
288 #pod $c->url_for( 'yancy.auth.password.login' )
289 #pod ->query({ return_to => $c->url_for( 'dashboard' ) });
290 #pod
291 #pod =head2 yancy.auth.logout
292 #pod
293 #pod Log out any current account. Use this in your own controller actions to
294 #pod perform a logout.
295 #pod
296 #pod =head1 ROUTES
297 #pod
298 #pod This plugin creates the following L<named
299 #pod routes|https://mojolicious.org/perldoc/Mojolicious/Guides/Routing#Named-routes>.
300 #pod Use named routes with helpers like
301 #pod L<url_for|Mojolicious::Plugin::DefaultHelpers/url_for>,
302 #pod L<link_to|Mojolicious::Plugin::TagHelpers/link_to>, and
303 #pod L<form_for|Mojolicious::Plugin::TagHelpers/form_for>.
304 #pod
305 #pod =head2 yancy.auth.password.login_form
306 #pod
307 #pod Display the login form using the L</yancy/auth/password/login_form.html.ep> template. This route handles C<GET>
308 #pod requests and can be used with the L<redirect_to|https://mojolicious.org/perldoc/Mojolicious/Plugin/DefaultHelpers#redirect_to>,
309 #pod L<url_for|https://mojolicious.org/perldoc/Mojolicious/Plugin/DefaultHelpers#url_for>,
310 #pod and L<link_to|https://mojolicious.org/perldoc/Mojolicious/Plugin/TagHelpers#link_to> helpers.
311 #pod
312 #pod %= link_to Login => 'yancy.auth.password.login_form'
313 #pod <%= link_to 'yancy.auth.password.login_form', begin %>Login<% end %>
314 #pod <p>Login here: <%= url_for 'yancy.auth.password.login_form' %></p>
315 #pod
316 #pod =head2 yancy.auth.password.login
317 #pod
318 #pod Handle login by checking the user's username and password. This route
319 #pod handles C<POST> requests and can be used with the
320 #pod L<url_for|https://mojolicious.org/perldoc/Mojolicious/Plugin/DefaultHelpers#url_for>
321 #pod and L<form_for|https://mojolicious.org/perldoc/Mojolicious/Plugin/TagHelpers#form_for>
322 #pod helpers.
323 #pod
324 #pod %= form_for 'yancy.auth.password.login' => begin
325 #pod %= text_field 'username', placeholder => 'Username'
326 #pod %= text_field 'password', placeholder => 'Password'
327 #pod %= submit_button
328 #pod % end
329 #pod
330 #pod =head2 yancy.auth.password.logout
331 #pod
332 #pod Clear the current login and allow the user to log in again. This route handles C<GET>
333 #pod requests and can be used with the L<redirect_to|https://mojolicious.org/perldoc/Mojolicious/Plugin/DefaultHelpers#redirect_to>,
334 #pod L<url_for|https://mojolicious.org/perldoc/Mojolicious/Plugin/DefaultHelpers#url_for>,
335 #pod and L<link_to|https://mojolicious.org/perldoc/Mojolicious/Plugin/TagHelpers#link_to> helpers.
336 #pod
337 #pod %= link_to Logout => 'yancy.auth.password.logout'
338 #pod <%= link_to 'yancy.auth.password.logout', begin %>Logout<% end %>
339 #pod <p>Logout here: <%= url_for 'yancy.auth.password.logout' %></p>
340 #pod
341 #pod =head2 yancy.auth.password.register_form
342 #pod
343 #pod Display the form to register a new user, if registration is enabled. This route handles C<GET>
344 #pod requests and can be used with the L<redirect_to|https://mojolicious.org/perldoc/Mojolicious/Plugin/DefaultHelpers#redirect_to>,
345 #pod L<url_for|https://mojolicious.org/perldoc/Mojolicious/Plugin/DefaultHelpers#url_for>,
346 #pod and L<link_to|https://mojolicious.org/perldoc/Mojolicious/Plugin/TagHelpers#link_to> helpers.
347 #pod
348 #pod %= link_to Register => 'yancy.auth.password.register_form'
349 #pod <%= link_to 'yancy.auth.password.register_form', begin %>Register<% end %>
350 #pod <p>Register here: <%= url_for 'yancy.auth.password.register_form' %></p>
351 #pod
352 #pod =head2 yancy.auth.password.register
353 #pod
354 #pod Register a new user, if registration is enabled. This route
355 #pod handles C<POST> requests and can be used with the
356 #pod L<url_for|https://mojolicious.org/perldoc/Mojolicious/Plugin/DefaultHelpers#url_for>
357 #pod and L<form_for|https://mojolicious.org/perldoc/Mojolicious/Plugin/TagHelpers#form_for>
358 #pod helpers.
359 #pod
360 #pod %= form_for 'yancy.auth.password.register' => begin
361 #pod %= text_field 'username', placeholder => 'Username'
362 #pod %= text_field 'password', placeholder => 'Password'
363 #pod %= text_field 'password-verify', placeholder => 'Password (again)'
364 #pod %# ... Display other fields required for registration
365 #pod %= submit_button
366 #pod % end
367 #pod
368 #pod =head1 TEMPLATES
369 #pod
370 #pod To override these templates, add your own at the designated path inside
371 #pod your app's C<templates/> directory.
372 #pod
373 #pod =head2 yancy/auth/password/login_form.html.ep
374 #pod
375 #pod The form to log in.
376 #pod
377 #pod =head2 yancy/auth/password/login_page.html.ep
378 #pod
379 #pod The page containing the form to log in. Uses the C<login_form.html.ep>
380 #pod template for the form itself.
381 #pod
382 #pod =head2 yancy/auth/unauthorized.html.ep
383 #pod
384 #pod This template displays an error message that the user is not authorized
385 #pod to view this page. This most-often appears when the user is not logged
386 #pod in.
387 #pod
388 #pod =head2 yancy/auth/unauthorized.json.ep
389 #pod
390 #pod This template renders a JSON object with an "errors" array explaining
391 #pod the error.
392 #pod
393 #pod =head2 layouts/yancy/auth.html.ep
394 #pod
395 #pod The layout that Yancy uses when displaying the login form, the
396 #pod unauthorized error message, and other auth-related pages.
397 #pod
398 #pod =head2 yancy/auth/password/register.html.ep
399 #pod
400 #pod The page containing the form to register a new user. Will display all of the
401 #pod L</register_fields>.
402 #pod
403 #pod =head1 SEE ALSO
404 #pod
405 #pod L<Yancy::Plugin::Auth>
406 #pod
407 #pod =cut
408  
409 1 ▶use Mojo::Base 'Mojolicious::Plugin';
Subroutine BEGIN: called CC=1 SCAR=0.0
410 1 ▶use Role::Tiny::With;
Subroutine BEGIN: called CC=1 SCAR=0.0
411 1 with 'Yancy::Plugin::Auth::Role::RequireUser';
412 1 ▶use Yancy::Util qw( currym derp );
Subroutine BEGIN: called CC=1 SCAR=0.0
413 1 ▶use Digest;
Subroutine BEGIN: called CC=1 SCAR=0.0
414  
415 1 has log =>;
416 1 has schema =>;
417 1 has username_field =>;
418 1 has password_field => 'password';
419 1 has allow_register => 0;
420 1 has plugin_field => undef;
421 0 ▶has register_fields => sub { [] };
Subroutine __ANON__: not called CC=1 SCAR=1.2
422 1 has moniker => 'password';
423 1 has default_digest =>;
424 1 has route =>;
425 1 has logout_route =>;
426  
427 # The Auth::Basic digest configuration to migrate from. Auth::Basic did
428 # not store the digest information in the password, so we need to fix
429 # it.
430 1 has migrate_digest =>;
431  
432 sub register {
433 my ( $self, $app, $config ) = @_;
434 $self->init( $app, $config );
435 $app->helper(
436 'yancy.auth.current_user' => currym( $self, 'current_user' ),
437 );
438 $app->helper(
439 'yancy.auth.logout' => currym( $self, 'logout' ),
440 );
441 $app->helper(
442 'yancy.auth.login_form' => currym( $self, 'login_form' ),
443 );
444 }
445  
446 sub init {
447 0 ▶ my ( $self, $app, $config ) = @_;
Subroutine init: not called CC=13 SCAR=52.0
Pod undocumented
448 my $schema_name = $config->{schema} || $config->{collection}
449 0 ▶ || die "Error configuring Auth::Password plugin: No schema defined\n";
Condition0%0/5
$config->{'schema'} || $config->{'collection'} || die("Error configuring Auth::Password plugin: No schema defined\n")
l!l
00
$config->{"schema"} or $config->{"collection"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$config->{'schema'} || $config->{'collection'} || die("Error configuring Auth::Password plugin: No schema defined\n")
$config->{"schema"} $config->{"collection"}
Truth table0%0/3
A or B
A= $config->{"schema"}B= $config->{"collection"}
ABresult
1X1
011
000
450 derp "'collection' configuration in Auth::Token is now 'schema'. Please fix your configuration.\n"
451 0 ▶ if $config->{collection};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"collection"} 0 0 0
452 0 my $schema = $app->yancy->schema( $schema_name );
453 0 ▶ die sprintf(
Branch: 1 branch
BranchTrueFalseTotal
unless $schema 0 0 0
454 q{Error configuring Auth::Password plugin: Collection "%s" not found}."\n",
455 $schema_name,
456 ) unless $schema;
457  
458 0 $self->log( $app->log );
459 0 $self->schema( $schema_name );
460 0 $self->username_field( $config->{username_field} );
461 0 ▶ $self->password_field( $config->{password_field} || 'password' );
Condition0%0/2
$config->{'password_field'} || 'password'
l!l
00
MC/DC0%0/1
$config->{'password_field'} || 'password'
$config->{'password_field'}
Truth table0%0/2
A
A= $config->{'password_field'}
Aresult
11
00
462 0 $self->default_digest( $config->{password_digest} );
463 0 $self->migrate_digest( $config->{migrate_digest} );
464 0 $self->allow_register( $config->{allow_register} );
465 $self->register_fields(
466 0 ▶ $config->{register_fields} || $app->yancy->schema( $schema_name )->{required} || []
Condition0%0/5
$config->{'register_fields'} || $app->yancy->schema($schema_name)->{'required'} || []
l!l
00
$config->{"register_fields"} or $app->yancy->schema($schema_name)->{"required"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$config->{'register_fields'} || $app->yancy->schema($schema_name)->{'required'} || []
$config->{"register_fields"} $app->yancy->schema($schema_name)->{"required"}
Truth table0%0/3
A or B
A= $config->{"register_fields"}B= $app->yancy->schema($schema_name)->{"required"}
ABresult
1X1
011
000
467 );
468 $app->yancy->filter->add( 'yancy.plugin.auth.password' => sub {
469 0 ▶ my ( $key, $value, $schema, @params ) = @_;
Subroutine __ANON__: not called CC=1 SCAR=6.9
470 0 return $self->_digest_password( $value );
471 0 } );
472  
473 # Update the schema to digest the password correctly
474 0 my $field = $schema->{properties}{ $self->password_field };
475 0 ▶ push @{ $field->{ 'x-filter' } ||= [] },
Condition0%0/2
$field->{"x-filter"} ||= []
l!l
00
MC/DC0%0/1
$field->{"x-filter"} ||= []
$field->{"x-filter"}
Truth table0%0/2
A
A= $field->{"x-filter"}
Aresult
11
00
476 'yancy.plugin.auth.password';
477 0 $field->{ format } = 'password';
478 0 $app->yancy->schema( $schema_name, $schema );
479  
480 # Add fields that may not technically be required by the schema, but
481 # are required for registration
482 my @user_fields = (
483 0 ▶ $self->username_field || $schema->{'x-id-field'} || 'id',
Condition0%0/5
$self->username_field || $schema->{'x-id-field'} || 'id'
l!l
00
$self->username_field or $schema->{"x-id-field"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->username_field || $schema->{'x-id-field'} || 'id'
$self->username_field $schema->{"x-id-field"}
Truth table0%0/3
A or B
A= $self->username_fieldB= $schema->{"x-id-field"}
ABresult
1X1
011
000
484 $self->password_field,
485 );
486 0 for my $field ( @user_fields ) {
487 0 ▶ if ( !grep { $_ eq $field } @{ $self->register_fields } ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {$_ eq $field;} @{$self->register_fields;}) 0 0 0
488 0 unshift @{ $self->register_fields }, $field;
489 }
490 }
491  
492 0 my $route = $app->yancy->routify( $config->{route}, '/yancy/auth/' . $self->moniker );
493 0 $self->route( $route );
494 0 $route->get( 'register' )->to( cb => currym( $self, '_get_register' ) )->name( 'yancy.auth.password.register_form' );
495 0 $route->post( 'register' )->to( cb => currym( $self, '_post_register' ) )->name( 'yancy.auth.password.register' );
496 0 $self->logout_route(
497 $route->get( 'logout' )->to( cb => currym( $self, '_get_logout' ) )->name( 'yancy.auth.password.logout' )
498 );
499 0 $route->get( '' )->to( cb => currym( $self, '_get_login' ) )->name( 'yancy.auth.password.login_form' );
500 0 $route->post( '' )->to( cb => currym( $self, '_post_login' ) )->name( 'yancy.auth.password.login' );
501 }
502  
503 sub _get_user {
504 0 ▶ my ( $self, $c, $username ) = @_;
Subroutine _get_user: not called CC=3 SCAR=24.8
505 0 my $schema_name = $self->schema;
506 0 my $username_field = $self->username_field;
507 0 my %search;
508 0 ▶ if ( my $field = $self->plugin_field ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $field = $self->plugin_field) 0 0 0
509 0 $search{ $field } = $self->moniker;
510 }
511 0 ▶ if ( $username_field ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($username_field) 0 0 0
512 0 $search{ $username_field } = $username;
513 0 my ( $user ) = @{ $c->yancy->backend->list( $schema_name, \%search, { limit => 1 } )->{items} };
514 0 return $user;
515 }
516 0 return $c->yancy->backend->get( $schema_name, $username );
517 }
518  
519 sub _digest_password {
520 0 ▶ my ( $self, $password ) = @_;
Subroutine _digest_password: not called CC=1 SCAR=6.9
521 0 my $config = $self->default_digest;
522 0 my $digest_config_string = _build_digest_config_string( $config );
523 0 my $digest = _get_digest_by_config_string( $digest_config_string );
524 0 my $password_string = join '$', $digest->add( $password )->b64digest, $digest_config_string;
525 0 return $password_string;
526 }
527  
528 sub _set_password {
529 0 ▶ my ( $self, $c, $username, $password ) = @_;
Subroutine _set_password: not called CC=2 SCAR=17.9
530 0 my $password_string = eval { $self->_digest_password( $password ) };
531 0 ▶ if ( $@ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
532 0 $self->log->error(
533 sprintf 'Error setting password for user "%s": %s', $username, $@,
534 );
535 }
536  
537 0 my $id = $self->_get_id_for_username( $c, $username );
538 0 $c->yancy->backend->set( $self->schema, $id, { $self->password_field => $password_string } );
539 }
540  
541 sub _get_id_for_username {
542 0 ▶ my ( $self, $c, $username ) = @_;
Subroutine _get_id_for_username: not called CC=4 SCAR=30.0
543 0 my $schema_name = $self->schema;
544 0 my $schema = $c->yancy->schema( $schema_name );
545 0 my $id = $username;
546 0 ▶ my $id_field = $schema->{'x-id-field'} || 'id';
Condition0%0/2
$schema->{'x-id-field'} || 'id'
l!l
00
MC/DC0%0/1
$schema->{'x-id-field'} || 'id'
$schema->{'x-id-field'}
Truth table0%0/2
A
A= $schema->{'x-id-field'}
Aresult
11
00
547 0 my $username_field = $self->username_field;
548 0 ▶ if ( $username_field && $username_field ne $id_field ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($username_field and $username_field ne $id_field) 0 0 0
Condition0%0/3
$username_field and $username_field ne $id_field
!ll&&!rl&&r
000
MC/DC0%0/2
$username_field and $username_field ne $id_field
$username_field $username_field ne $id_field
Truth table0%0/3
A and B
A= $username_fieldB= $username_field ne $id_field
ABresult
0X0
100
111
549 0 $id = $self->_get_user( $c, $username )->{ $id_field };
550 }
551 0 return $id;
552 }
553  
554 sub current_user {
555 0 ▶ my ( $self, $c ) = @_;
Subroutine current_user: not called CC=5 SCAR=34.0
Pod undocumented
556 0 ▶ return undef unless my $session = $c->session;
Branch: 1 branch
BranchTrueFalseTotal
unless my $session = $c->session 0 0 0
557 0 ▶ my $yancy = $session->{yancy} or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $yancy = $session->{"yancy"} or return undef 0 0 0
558 0 ▶ my $auth = $yancy->{auth} or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $auth = $yancy->{"auth"} or return undef 0 0 0
559 0 ▶ my $username = $auth->{password} or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $username = $auth->{"password"} or return undef 0 0 0
560 0 my $user = $self->_get_user( $c, $username );
561 0 delete $user->{ $self->password_field };
562 0 return $user;
563 }
564  
565 sub login_form {
566 0 ▶ my ( $self, $c ) = @_;
Subroutine login_form: not called CC=8 SCAR=42.8
Pod undocumented
567 0 ▶ my $return_to
Branch: 3 branches
BranchTrueFalseTotal
$c->req->param('return_to') ? : 0 0 0
$c->flash('return_to') ? : 0 0 0
$c->current_route =~ /^yancy\.auth/u && $c->req->headers->referrer && !($c->req->headers->referrer =~ m[^(?:\w+:|//)]u) ? : 0 0 0
Condition0%0/8
$c->current_route =~ /^yancy\.auth/u and $c->req->headers->referrer and not $c->req->headers->referrer =~ m[^(?:\w+:|//)]u
!ll&&!rl&&r
000
$c->current_route =~ /^yancy\.auth/u and $c->req->headers->referrer
!ll&&!rl&&r
000
$c->req->url->path or "/"
l!l
00
MC/DC0%0/3
$c->current_route =~ /^yancy\.auth/u and $c->req->headers->referrer and not $c->req->headers->referrer =~ m[^(?:\w+:|//)]u
$c->current_route =~ /^yancy\.auth/u $c->req->headers->referrer not $c->req->headers->referrer =~ m[^(?:\w+:|//)]u
MC/DC0%0/1
$c->req->url->path or "/"
$c->req->url->path
Truth table0%0/4
A and B and not(C)
A= $c->current_route =~ /^yancy\.auth/uB= $c->req->headers->referrerC= not $c->req->headers->referrer =~ m[^(?:\w+:|//)]u
ABCresult
0XX0
10X0
1100
1111
Truth table0%0/2
A
A= $c->req->url->path
Aresult
11
00
568 # If we've specified one, go there directly
569 = $c->req->param( 'return_to' )
570 ? $c->req->param( 'return_to' )
571 # Check flash storage, perhaps from a redirect to the login form
572 : $c->flash('return_to') ? $c->flash('return_to')
573 # If this is the login page, go back to referer
574 : $c->current_route =~ /^yancy\.auth/
575 && $c->req->headers->referrer
576 && $c->req->headers->referrer !~ m{^(?:\w+:|//)}
577 ? $c->req->headers->referrer
578 # Otherwise, return the user here
579 : ( $c->req->url->path || '/' )
580 ;
581 0 ▶ if ( $return_to =~ m{^(?:\w+:|//)} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($return_to =~ m[^(?:\w+:|//)]u) 0 0 0
582 0 return $c->reply->exception(
583 q{`return_to` can not contain URL scheme or host},
584 );
585 }
586 0 return $c->render_to_string(
587 'yancy/auth/password/login_form',
588 plugin => $self,
589 return_to => $return_to,
590 );
591 }
592  
593 sub _get_login {
594 0 ▶ my ( $self, $c ) = @_;
Subroutine _get_login: not called CC=1 SCAR=6.9
595 0 return $c->render( 'yancy/auth/password/login_page',
596 plugin => $self,
597 );
598 }
599  
600 sub _post_login {
601 0 ▶ my ( $self, $c ) = @_;
Subroutine _post_login: not called CC=4 SCAR=30.0
602 0 my $user = $c->param( 'username' );
603 0 my $pass = $c->param( 'password' );
604 0 ▶ if ( $self->_check_pass( $c, $user, $pass ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_check_pass($c, $user, $pass)) 0 0 0
605 0 $c->session->{yancy}{auth}{password} = $user;
606 0 ▶ my $to = $c->req->param( 'return_to' ) || '/';
Condition0%0/2
$c->req->param('return_to') || '/'
l!l
00
MC/DC0%0/1
$c->req->param('return_to') || '/'
$c->req->param('return_to')
Truth table0%0/2
A
A= $c->req->param('return_to')
Aresult
11
00
607  
608 # Do not allow return_to to redirect the user to another site.
609 # http://cwe.mitre.org/data/definitions/601.html
610 0 ▶ if ( $to =~ m{^(?:\w+:|//)} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($to =~ m[^(?:\w+:|//)]u) 0 0 0
611 0 return $c->reply->exception(
612 q{`return_to` can not contain URL scheme or host},
613 );
614 }
615  
616 0 $c->res->headers->location( $to );
617 0 return $c->rendered( 303 );
618 }
619 0 $c->flash( error => 'Username or password incorrect' );
620 0 return $c->render( 'yancy/auth/password/login_page',
621 status => 400,
622 plugin => $self,
623 user => $user,
624 login_failed => 1,
625 );
626 }
627  
628 sub _get_register {
629 0 ▶ my ( $self, $c ) = @_;
Subroutine _get_register: not called CC=2 SCAR=17.9
630 0 ▶ if ( !$self->allow_register ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->allow_register) 0 0 0
631 0 $c->app->log->error( 'Registration not allowed (set allow_register)' );
632 0 $c->reply->not_found;
633 0 return;
634 }
635 0 return $c->render( 'yancy/auth/password/register',
636 plugin => $self,
637 );
638 }
639  
640 sub _post_register {
641 0 ▶ my ( $self, $c ) = @_;
Subroutine _post_register: not called CC=8 SCAR=42.8
642 0 ▶ if ( !$self->allow_register ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->allow_register) 0 0 0
643 0 $c->app->log->error( 'Registration not allowed (set allow_register)' );
644 0 $c->reply->not_found;
645 0 return;
646 }
647  
648 0 my $schema_name = $self->schema;
649 0 my $schema = $c->yancy->schema( $schema_name );
650 0 ▶ my $username_field = $self->username_field || $schema->{'x-id-field'} || 'id';
Condition0%0/5
$self->username_field || $schema->{'x-id-field'} || 'id'
l!l
00
$self->username_field or $schema->{"x-id-field"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->username_field || $schema->{'x-id-field'} || 'id'
$self->username_field $schema->{"x-id-field"}
Truth table0%0/3
A or B
A= $self->username_fieldB= $schema->{"x-id-field"}
ABresult
1X1
011
000
651 0 my $password_field = $self->password_field;
652  
653 0 my $username = $c->param( $username_field );
654 0 my $pass = $c->param( $self->password_field );
655 0 ▶ if ( $pass ne $c->param( $self->password_field . '-verify' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pass ne $c->param($self->password_field . '-verify')) 0 0 0
656 0 return $c->render( 'yancy/auth/password/register',
657 status => 400,
658 plugin => $self,
659 user => $username,
660 error => 'password_verify',
661 );
662 }
663 0 ▶ if ( $self->_get_user( $c, $username ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_get_user($c, $username)) 0 0 0
664 0 return $c->render( 'yancy/auth/password/register',
665 status => 400,
666 plugin => $self,
667 user => $username,
668 error => 'user_exists',
669 );
670 }
671  
672 # Create new user
673 my $item = {
674 $username_field => $username,
675 $password_field => $pass,
676 (
677 0 map { $_ => $c->param( $_ ) }
678 0 grep { !/^(?:$username_field|$password_field)$/ }
679 0 @{ $self->register_fields }
680 ),
681 };
682 0 my $id = eval { $c->yancy->create( $schema_name, $item ) };
683 0 ▶ if ( my $exception = $@ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $exception = $@) 0 0 0
684 0 ▶ my $error = ref $exception eq 'ARRAY' ? 'validation' : 'create';
Branch: 1 branch
BranchTrueFalseTotal
ref $exception eq 'ARRAY' ? : 0 0 0
685 0 $c->app->log->error( 'Error creating user: ' . $exception );
686 0 return $c->render( 'yancy/auth/password/register',
687 status => 400,
688 plugin => $self,
689 user => $username,
690 error => $error,
691 exception => $exception,
692 );
693 }
694  
695 # Get them to log in
696 0 $c->flash( info => 'user_created' );
697 0 return $c->redirect_to( 'yancy.auth.password.login' );
698 }
699  
700 sub _get_digest {
701 0 ▶ my ( $type, @config ) = @_;
Subroutine _get_digest: not called CC=3 SCAR=24.8
702 0 my $digest = eval {
703 0 Digest->new( $type, @config )
704 };
705 0 ▶ if ( my $error = $@ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $error = $@) 0 0 0
706 0 ▶ if ( $error =~ m{Can't locate Digest/${type}\.pm in \@INC} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($error =~ m[Can't locate Digest/$type\.pm in \@INC]u) 0 0 0
707 0 die sprintf q{Password digest type "%s" not found}."\n", $type;
708 }
709 0 die sprintf "Error loading Digest module: %s\n", $@;
710 }
711 0 return $digest;
712 }
713  
714 sub _get_digest_by_config_string {
715 0 ▶ my ( $config_string ) = @_;
Subroutine _get_digest_by_config_string: not called CC=1 SCAR=6.9
716 0 my @digest_parts = split /\$/, $config_string;
717 0 return _get_digest( @digest_parts );
718 }
719  
720 sub _build_digest_config_string {
721 0 ▶ my ( $config ) = @_;
Subroutine _build_digest_config_string: not called CC=1 SCAR=6.9
722 my @config_parts = (
723 0 map { $_, $config->{$_} } grep !/^type$/, keys %$config
724 );
725 0 return join '$', $config->{type}, @config_parts;
726 }
727  
728 sub _check_pass {
729 0 ▶ my ( $self, $c, $username, $input_password ) = @_;
Subroutine _check_pass: not called CC=8 SCAR=42.8
730 0 my $user = $self->_get_user( $c, $username );
731  
732 0 ▶ if ( !$user ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($user) 0 0 0
733 0 $self->log->error(
734 sprintf 'Error checking password for user "%s": User does not exist',
735 $username
736 );
737 0 return undef;
738 }
739  
740 my ( $user_password, $user_digest_config_string )
741 0 = split /\$/, $user->{ $self->password_field }, 2;
742  
743 0 my $force_upgrade = 0;
744 0 ▶ if ( !$user_digest_config_string ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($user_digest_config_string) 0 0 0
745 # This password must have come from the Auth::Basic module,
746 # which did not have digest configuration stored with the
747 # password. So, we need to know what kind of digest to use, and
748 # we need to fix the password.
749 0 ▶ $user_digest_config_string = _build_digest_config_string(
Condition0%0/3
$self->migrate_digest || $self->default_digest
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->migrate_digest || $self->default_digest
$self->migrate_digest $self->default_digest
Truth table0%0/3
A || B
A= $self->migrate_digestB= $self->default_digest
ABresult
1X1
011
000
750 $self->migrate_digest || $self->default_digest
751 );
752 0 $force_upgrade = 1;
753 }
754  
755 0 my $digest = eval { _get_digest_by_config_string( $user_digest_config_string ) };
756 0 ▶ if ( $@ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
757 0 die sprintf 'Error checking password for user "%s": %s', $username, $@;
758 }
759 0 my $check_password = $digest->add( $input_password )->b64digest;
760  
761 0 my $success = $check_password eq $user_password;
762  
763 0 my $default_config_string = _build_digest_config_string( $self->default_digest );
764 0 ▶ if ( $success && ( $force_upgrade || $user_digest_config_string ne $default_config_string ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($success and $force_upgrade || $user_digest_config_string ne $default_config_string) 0 0 0
Condition0%0/6
$success and $force_upgrade || $user_digest_config_string ne $default_config_string
!ll&&!rl&&r
000
$force_upgrade or $user_digest_config_string ne $default_config_string
l!l&&r!l&&!r
000
MC/DC0%0/3
$success and $force_upgrade || $user_digest_config_string ne $default_config_string
$success $force_upgrade $user_digest_config_string ne $default_config_string
Truth table0%0/4
A and B or C
A= $successB= $force_upgradeC= $user_digest_config_string ne $default_config_string
ABCresult
0XX0
1000
11X1
1011
765 # We need to re-create the user's password field using the new
766 # settings
767 0 $self->_set_password( $c, $username, $input_password );
768 }
769  
770 0 return $success;
771 }
772  
773 sub logout {
774 0 ▶ my ( $self, $c ) = @_;
Subroutine logout: not called CC=1 SCAR=6.9
Pod undocumented
775 0 delete $c->session->{yancy}{auth}{password};
776 }
777  
778 sub _get_logout {
779 0 ▶ my ( $self, $c ) = @_;
Subroutine _get_logout: not called CC=4 SCAR=30.0
780 0 $self->logout( $c );
781 0 $c->res->code( 303 );
782 0 ▶ my $redirect_to = $c->param( 'redirect_to' ) // $c->req->headers->referrer // '/';
Condition0%0/5
($c->param("redirect_to") // $c->req->headers->referrer) // "/"
l!l
00
$c->param("redirect_to") // $c->req->headers->referrer
l!l&&r!l&&!r
000
MC/DC0%0/2
($c->param("redirect_to") // $c->req->headers->referrer) // "/"
$c->param("redirect_to") $c->req->headers->referrer
Truth table0%0/3
A // B
A= $c->param("redirect_to")B= $c->req->headers->referrer
ABresult
1X1
011
000
783 0 ▶ if ( $redirect_to eq $c->req->url->path ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($redirect_to eq $c->req->url->path) 0 0 0
784 0 $redirect_to = '/';
785 }
786 0 return $c->redirect_to( $redirect_to );
787 }
788  
789 1 1;
790  
791 __END__
« Yancy/Controller/Yancy/MultiTenant.pm ↑ Summary Yancy/Plugin/Editor.pm »