blib/lib/Lemonldap/NG/Portal/Plugins/MailPasswordReset.pm untested

filter: Statementstmt 0.0% 0 / 250 Branchbran 0.0% 0 / 112 Conditioncond 0.0% 0 / 109 MC/DCmcdc 0.0% 0 / 60 Subroutinesub 0.0% 0 / 16 Podpod 0.0% 0 / 8 totaltotal 0.0% 0 / 555 CC 57 SCAR 56.5
CC
57
Cov
0%
_reset
552.0
changePwd
306.0
display
182.0
CRAP 283.5
1 package Lemonldap::NG::Portal::Plugins::MailPasswordReset;
2  
3 use strict;
4 use Encode;
5 use Mouse;
6 use POSIX qw(strftime);
7 use JSON;
8 use Lemonldap::NG::Common::FormEncode;
9 use Lemonldap::NG::Portal::Main::Constants qw(
10 PE_OK
11 PE_MAILOK
12 PE_NOTOKEN
13 PE_MAILERROR
14 PE_PASSWORD_OK
15 PE_BADMAILTOKEN
16 PE_CAPTCHAEMPTY
17 PE_CAPTCHAERROR
18 PE_MAILNOTFOUND
19 PE_TOKENEXPIRED
20 PE_USERNOTFOUND
21 PE_MAILCONFIRMOK
22 PE_MALFORMEDUSER
23 PE_MAILFORMEMPTY
24 PE_BADCREDENTIALS
25 PE_MAILFIRSTACCESS
26 PE_PASSWORDFORMEMPTY
27 PE_PASSWORD_MISMATCH
28 PE_PASSWORDFIRSTACCESS
29 PE_PP_PASSWORD_TOO_SHORT
30 PE_PP_PASSWORD_TOO_YOUNG
31 PE_PP_PASSWORD_IN_HISTORY
32 PE_MAILCONFIRMATION_ALREADY_SENT
33 PE_PP_INSUFFICIENT_PASSWORD_QUALITY
34 );
35  
36 our $VERSION = '2.19.0';
37  
38 extends qw(
39 Lemonldap::NG::Portal::Lib::SMTP
40 Lemonldap::NG::Portal::Main::Plugin
41 Lemonldap::NG::Portal::Lib::_tokenRule
42 );
43  
44 # PROPERTIES
45  
46 # Mail timeout token generator
47 # Form timout token generator (used even if requireToken is not set)
48 has ott => (
49 is => 'rw',
50 lazy => 1,
51 default => sub {
52 my $ott =
53 $_[0]->{p}->loadModule('Lemonldap::NG::Portal::Lib::OneTimeToken');
54 $ott->cache(0);
55 $ott->timeout( $_[0]->conf->{formTimeout} || $_[0]->conf->{timeout} );
56 return $ott;
57 }
58 );
59  
60 # Captcha generator
61 has captcha => ( is => 'rw' );
62  
63 # Password policy activation rule
64 has passwordPolicyActivationRule => ( is => 'rw', default => sub { 0 } );
65  
66 # INITIALIZATION
67  
68 sub init {
69 my ($self) = @_;
70  
71 # Declare REST route
72 $self->addUnauthRoute( resetpwd => 'resetPwd', [ 'POST', 'GET' ] );
73  
74 # Initialize Captcha if needed
75 $self->captcha(
76 $self->p->buildRule(
77 $self->conf->{captcha_mail_enabled},
78 'captchaMail'
79 )
80 );
81  
82 # Parse password policy activation rule
83 $self->passwordPolicyActivationRule(
84 $self->p->buildRule(
85 $self->conf->{passwordPolicyActivation},
86 'passwordPolicyActivation'
87 )
88 );
89  
90 return $self->passwordPolicyActivationRule ? 1 : 0;
91 }
92  
93 # RUNNIG METHODS
94  
95 # Handle reset requests
96 sub resetPwd {
97 my ( $self, $req ) = @_;
98  
99 $self->p->controlUrl($req);
100  
101 # Check parameters
102 $req->error( $self->_reset($req) );
103  
104 # Display form
105 my ( $tpl, $prms ) = $self->display($req);
106 return $self->p->sendHtml( $req, $tpl, params => $prms );
107 }
108  
109 sub searchUser {
110 my $self = shift;
111 my $req = shift;
112 my $searchByMail = shift;
113  
114 # Search user in database
115 $req->steps( [
116 'getUser', 'setSessionInfo',
117 $self->p->groupsAndMacros, 'setPersistentSessionInfo',
118 'setLocalGroups'
119 ]
120 );
121 if ( my $error = $self->p->process( $req, useMail => $searchByMail ) ) {
122 if ( $error == PE_USERNOTFOUND or $error == PE_BADCREDENTIALS ) {
123 $self->userLogger->warn(
124 'Reset asked for an invalid user (' . $req->{user} . ')' );
125  
126 # To avoid mail enumeration, return OK
127 # unless portalErrorOnMailNotFound is set
128  
129 if ( $self->conf->{portalErrorOnMailNotFound} ) {
130 $self->setSecurity($req);
131 return PE_MAILNOTFOUND;
132 }
133  
134 my $mailTimeout =
135 $self->conf->{mailTimeout} || $self->conf->{timeout};
136 my $expTimestamp = time() + $mailTimeout;
137 $req->data->{expMailDate} =
138 strftime( '%d/%m/%Y', localtime $expTimestamp );
139 $req->data->{expMailTime} =
140 strftime( '%H:%M', localtime $expTimestamp );
141 return PE_MAILCONFIRMOK;
142 }
143 return $error;
144 }
145 return PE_OK;
146 }
147  
148 sub createMailSession {
149 my $self = shift;
150 my $req = shift;
151  
152 # Create a new session
153 my $infos = {};
154  
155 # Set _utime for session autoremove
156 # Use default session timeout and mail session timeout to compute it
157 my $time = time();
158 my $timeout = $self->conf->{timeout};
159 my $mailTimeout = $self->conf->{mailTimeout} || $timeout;
160  
161 $infos->{_utime} = $time + ( $mailTimeout - $timeout );
162  
163 # Store expiration timestamp for further use
164 $infos->{mailSessionTimeoutTimestamp} = $time + $mailTimeout;
165  
166 # Store start timestamp for further use
167 $infos->{mailSessionStartTimestamp} = $time;
168  
169 # Store mail
170 $infos->{ $self->conf->{mailSessionKey} } =
171 $self->p->getFirstValue(
172 $req->{sessionInfo}->{ $self->conf->{mailSessionKey} } );
173  
174 # Store user
175 $infos->{user} = $req->{user};
176  
177 # Store type
178 $infos->{_type} = 'mail';
179  
180 # Store pdata
181 $infos->{_pdata} = $req->pdata;
182  
183 # create session
184 return $self->p->getApacheSession(
185 undef,
186 kind => "TOKEN",
187 info => $infos,
188 hashStore => 0,
189 );
190 }
191  
192 sub _reset {
193 my ( $self, $req ) = @_;
194 my $mailToken;
195  
196 # PASSWORD CHANGE FORM => changePwd()
197 return $self->changePwd($req)
198 if (
199 $req->method =~ /^POST$/i
200 and ( $req->param('newpassword')
201 or $req->param('confirmpassword')
202 or $req->param('reset') )
203 );
204  
205 # FIRST FORM
206 $mailToken = $req->data->{mailToken} = $req->param('mail_token');
207 unless ( $req->param('mail') || $mailToken ) {
208 $self->setSecurity($req);
209 return $req->method eq 'GET' ? PE_MAILFIRSTACCESS : PE_MAILFORMEMPTY;
210 }
211  
212 # OTHER FORMS
213 my $searchByMail = 1;
214 if ($mailToken) {
215 $self->logger->debug("Token given for password reset: $mailToken");
216  
217 # Check if token is valid
218 my $mailSession = $self->p->getApacheSession(
219 $mailToken,
220 kind => "TOKEN",
221 hashStore => 0,
222 );
223 unless ($mailSession) {
224 $self->userLogger->warn('Bad reset token');
225 return PE_BADMAILTOKEN;
226 }
227  
228 $req->{user} = $mailSession->data->{user};
229 $req->data->{mailAddress} =
230 $mailSession->data->{ $self->conf->{mailSessionKey} };
231 $self->logger->debug( 'User associated to: ' . $req->{user} );
232  
233 # Restore pdata if any
234 $req->pdata( $mailSession->data->{_pdata} || {} );
235 $searchByMail = 0 unless ( $req->{user} =~ /\@/ );
236 }
237  
238 # Check for values posted
239 else {
240  
241 # Use submitted value
242 $req->{user} = $req->param('mail');
243  
244 # Captcha for register form
245 if ( $self->captcha->( $req, {} ) ) {
246 my $result = $self->p->getService('captcha')->check_captcha($req);
247 if ($result) {
248 $self->logger->debug("Captcha code verified");
249 }
250 else {
251 $self->setSecurity($req);
252 $self->userLogger->warn("Captcha failed");
253 return PE_CAPTCHAERROR;
254 }
255 }
256 elsif ( $self->ottRule->( $req, {} ) ) {
257 my $token = $req->param('token');
258 unless ($token) {
259 $self->setSecurity($req);
260 $self->userLogger->warn('Reset try without token');
261 return PE_NOTOKEN;
262 }
263 unless ( $self->ott->getToken($token) ) {
264 $self->setSecurity($req);
265 $self->userLogger->warn('Reset try with expired/bad token');
266 return PE_TOKENEXPIRED;
267 }
268 }
269  
270 unless ( $req->{user} =~ /$self->{conf}->{userControl}/ ) {
271 $self->setSecurity($req);
272 return PE_MALFORMEDUSER;
273 }
274 }
275  
276 my $searchUserCode = $self->searchUser( $req, $searchByMail );
277 return $searchUserCode unless $searchUserCode == PE_OK;
278  
279 my $mailSession = $self->getMailSession( $req->{user} );
280 unless ( $mailSession or $mailToken ) {
281 $mailSession = $self->createMailSession( $req, $mailToken );
282 $req->id( $mailSession->id );
283 }
284 elsif ($mailSession) {
285 $self->logger->debug( 'Mail session found: ' . $mailSession->id );
286 $req->id( $mailSession->id );
287 $req->data->{mailAlreadySent} = 1;
288 }
289  
290 # Send confirmation mail
291 unless ($mailToken) {
292  
293 # Mail session expiration date
294 my $expTimestamp = $mailSession->data->{mailSessionTimeoutTimestamp};
295  
296 $self->logger->debug("Mail expiration timestamp: $expTimestamp");
297  
298 $req->data->{expMailDate} =
299 strftime( '%d/%m/%Y', localtime $expTimestamp );
300 $req->data->{expMailTime} =
301 strftime( '%H:%M', localtime $expTimestamp );
302  
303 # Mail session start date
304 my $startTimestamp = $mailSession->data->{mailSessionStartTimestamp};
305  
306 $self->logger->debug("Mail start timestamp: $startTimestamp");
307 $req->data->{startMailDate} =
308 strftime( '%d/%m/%Y', localtime $startTimestamp );
309 $req->data->{startMailTime} =
310 strftime( '%H:%M', localtime $startTimestamp );
311  
312 # Ask if user wants an another confirmation email
313 if ( $req->data->{mailAlreadySent}
314 and not $req->param('resendconfirmation') )
315 {
316 $self->userLogger->notice(
317 'Reset mail already sent to ' . $req->{user} );
318  
319 # Return mail already sent only if it is allowed at previous step
320 if ( $self->conf->{portalErrorOnMailNotFound} ) {
321 $self->setSecurity($req);
322 return PE_MAILCONFIRMATION_ALREADY_SENT;
323 }
324 }
325  
326 # Get mail address
327 $req->data->{mailAddress} ||=
328 $self->p->getFirstValue(
329 $req->{sessionInfo}->{ $self->conf->{mailSessionKey} } );
330 return PE_MAILERROR unless $req->data->{mailAddress};
331  
332 # Build confirmation url
333 my $req_url = $req->data->{_url};
334 my $skin = $self->p->getSkin($req);
335 my $url = $self->p->buildUrl(
336 ( $self->conf->{mailUrl} || ( $req->portal, "resetpwd" ) ),
337 {
338 mail_token => $req->{id},
339 skin => $skin,
340 ( $req_url ? ( url => $req_url ) : () ),
341 }
342 );
343  
344 $self->logger->info( "User "
345 . $req->data->{mailAddress}
346 . " is trying to reset his/her password" );
347  
348 # Send mail
349 $self->logger->debug('Unable to send reset mail')
350 unless (
351 $self->sendEmail(
352 $req,
353 subject => $self->conf->{mailConfirmSubject},
354 subject_trmsg => 'mailConfirmSubject',
355 body => $self->conf->{mailConfirmBody},
356 body_template => 'mail_confirm',
357 dest => $req->data->{mailAddress},
358 params => {
359 expMailDate => $req->data->{expMailDate},
360 expMailTime => $req->data->{expMailTime},
361 url => $url,
362 },
363 )
364 );
365  
366 # Do not return an error here to avoid enumeration
367 return PE_MAILCONFIRMOK;
368 }
369  
370 # User has a valid mailToken, allow to change password
371 # A token is required
372 $self->ott->setToken(
373 $req,
374 {
375 %{ $req->sessionInfo },
376 pwdAllowed => $self->conf->{passwordResetAllowedRetries}
377 }
378 );
379 return PE_PASSWORDFIRSTACCESS if ( $req->method eq 'GET' );
380 return PE_PASSWORDFORMEMPTY;
381 }
382  
383 sub changePwd {
384 my ( $self, $req ) = @_;
385 my %tplPrms;
386 $self->logger->debug('Change password form response');
387  
388 if ( my $token = $req->param('token') ) {
389 $req->sessionInfo( $self->ott->getToken($token) );
390 unless ( $req->sessionInfo ) {
391 $self->userLogger->warn(
392 'User tries to change password with an invalid or expired token'
393 );
394 return PE_NOTOKEN;
395 }
396 }
397  
398 # These 2 cases means that a user tries to change password without
399 # following valid links!!!
400 else {
401 $self->userLogger->error('User tries to change password without token');
402 return PE_NOTOKEN;
403 }
404  
405 unless ( $req->sessionInfo->{pwdAllowed}-- ) {
406 $self->userLogger->error(
407 'User tries to use another token to change a password');
408 return PE_NOTOKEN;
409 }
410  
411 # Remove the mail token session if mail token is provided
412 my $mailToken = $req->param('mail_token');
413 if ($mailToken) {
414 $self->logger->debug("Token given for password reset: $mailToken");
415  
416 # Check if token is valid
417 my $mailSession = $self->p->getApacheSession(
418 $mailToken,
419 kind => "TOKEN",
420 hashStore => 0,
421 );
422 unless ($mailSession) {
423 $self->userLogger->warn('Bad reset token');
424 return PE_BADMAILTOKEN;
425 }
426  
427 $self->logger->debug("Delete token $mailToken");
428 $mailSession->remove;
429 }
430  
431 # Check if user wants to generate the new password
432 if ( $req->param('reset') ) {
433 $self->logger->debug(
434 "Reset password request for $req->{sessionInfo}->{_user}");
435  
436 # Generate a complex password
437 my $pwdRegEx;
438 if ( $self->passwordPolicyActivationRule->( $req, $req->sessionInfo )
439 && !$self->conf->{randomPasswordRegexp} )
440 {
441 my $uppers = $self->conf->{passwordPolicyMinUpper} || 3;
442 my $lowers = $self->conf->{passwordPolicyMinLower} || 5;
443 my $digits = $self->conf->{passwordPolicyMinDigit} || 2;
444 my $chars =
445 $self->conf->{passwordPolicyMinSize} -
446 $self->conf->{passwordPolicyMinUpper} -
447 $self->conf->{passwordPolicyMinLower} -
448 $self->conf->{passwordPolicyMinDigit};
449 $chars = 1 if $chars < 1;
450 $pwdRegEx = "[A-Z]{$uppers}[a-z]{$lowers}\\d{$digits}";
451 $pwdRegEx .=
452 $self->conf->{passwordPolicySpecialChar} eq '__ALL__'
453 ? '\W{$chars}'
454 : "[$self->{conf}->{passwordPolicySpecialChar}]{$chars}";
455 $self->logger->debug("Generated password RegEx: $pwdRegEx");
456 }
457 else {
458 $pwdRegEx =
459 $self->conf->{randomPasswordRegexp} || '[A-Z]{3}[a-z]{5}.\d{2}';
460 $self->logger->debug("Used password RegEx: $pwdRegEx");
461 }
462 my $password = $self->gen_password($pwdRegEx);
463 $self->logger->debug("Generated password: $password");
464 $req->data->{newpassword} = $password;
465 $req->data->{confirmpassword} = $password;
466 $req->data->{forceReset} = 1;
467 $tplPrms{RESET} = 1;
468 }
469  
470 # Else a password is required in request
471 else {
472 $req->data->{newpassword} = $req->param('newpassword');
473 $req->data->{confirmpassword} = $req->param('confirmpassword');
474 unless ($req->data->{newpassword}
475 and $req->data->{confirmpassword}
476 and $req->data->{newpassword} eq $req->data->{confirmpassword} )
477 {
478 $self->ott->setToken( $req, $req->sessionInfo );
479 ( $req->data->{newpassword} && $req->data->{confirmpassword} )
480 ? return PE_PASSWORD_MISMATCH
481 : return PE_PASSWORDFORMEMPTY;
482  
483 }
484 }
485  
486 # Check password quality if enabled
487 require Lemonldap::NG::Portal::Plugins::BasePasswordPolicy;
488 my $cpq =
489 $self->passwordPolicyActivationRule->( $req, $req->sessionInfo )
490 ? $self
491 ->Lemonldap::NG::Portal::Plugins::BasePasswordPolicy::checkBasicPolicy(
492 $req->data->{newpassword} )
493 : PE_OK;
494 unless ( $cpq == PE_OK ) {
495 $self->ott->setToken( $req, $req->sessionInfo );
496 return $cpq;
497 }
498  
499 $req->user( $req->{sessionInfo}->{_user} );
500 my $result =
501 $self->p->_passwordDB->setNewPassword( $req,
502 $req->data->{newpassword}, 1 );
503 undef $req->{user};
504  
505 # Mail token can be used only one time, delete the session if all is ok
506 unless ( $result == PE_PASSWORD_OK or $result == PE_OK ) {
507 $self->ott->setToken( $req, $req->sessionInfo );
508 return $result;
509 }
510  
511 my $userlog = $req->sessionInfo->{ $self->conf->{whatToTrace} };
512 my $iplog = $req->sessionInfo->{ipAddr};
513 $self->userLogger->notice("Password changed for $userlog ($iplog)")
514 if ( defined $userlog and $iplog );
515  
516 # Send mail containing the new password
517 $req->data->{mailAddress} ||=
518 $self->p->getFirstValue(
519 $req->{sessionInfo}->{ $self->conf->{mailSessionKey} } );
520  
521 my $password = $req->data->{newpassword};
522  
523 # Send mail
524 return $self->sendEmail(
525 $req,
526 subject => $self->conf->{mailSubject},
527 subject_trmsg => 'mailSubject',
528 body => $self->conf->{mailBody},
529 body_template => 'mail_password',
530 dest => $req->data->{mailAddress},
531 params => {
532 %tplPrms, password => $password,
533 },
534 )
535 ? PE_MAILOK
536 : PE_MAILERROR;
537 }
538  
539 sub setSecurity {
540 my ( $self, $req ) = @_;
541 if ( $self->captcha->( $req, {} ) ) {
542 $self->p->getService('captcha')->init_captcha($req);
543 }
544 elsif ( $self->ottRule->( $req, {} ) ) {
545 $self->ott->setToken($req);
546 }
547 return 1;
548 }
549  
550 sub display {
551 my ( $self, $req ) = @_;
552 $self->logger->debug( 'Display called with code: ' . $req->error );
553  
554 my %tplPrm = (
555 $self->p->getErrorTplParams($req),
556 AUTH_URL => $req->data->{_url},
557 CHOICE_VALUE => $req->{_authChoice},
558 EXPMAILDATE => $req->data->{expMailDate},
559 EXPMAILTIME => $req->data->{expMailTime},
560 STARTMAILDATE => $req->data->{startMailDate},
561 STARTMAILTIME => $req->data->{startMailTime},
562 MAILALREADYSENT => $req->data->{mailAlreadySent},
563 (
564 $req->data->{customScript}
565 ? ( CUSTOM_SCRIPT => $req->data->{customScript} )
566 : ()
567 ),
568 MAIL => (
569 $self->p->checkXSSAttack( 'mail', $req->{user} ) ? ''
570 : $req->{user}
571 ),
572 DISPLAY_FORM => 0,
573 DISPLAY_RESEND_FORM => 0,
574 DISPLAY_CONFIRMMAILSENT => 0,
575 DISPLAY_MAILSENT => 0,
576 DISPLAY_PASSWORD_FORM => 0,
577 ENABLE_PASSWORD_DISPLAY => $self->conf->{portalEnablePasswordDisplay},
578 DONT_STORE_PASSWORD => $self->conf->{browsersDontStorePassword},
579 %{ $self->p->getPasswordPolicyTemplateVars },
580 PPOLICY_RULES => $self->p->getPpolicyRules,
581 DISPLAY_GENERATE_PASSWORD =>
582 $self->conf->{portalDisplayGeneratePassword},
583 );
584 if ( $req->data->{mailToken}
585 and
586 not $self->p->checkXSSAttack( 'mail_token', $req->data->{mailToken} ) )
587 {
588 $tplPrm{MAIL_TOKEN} = $req->data->{mailToken};
589 }
590  
591 # Display captcha if enabled
592 $tplPrm{CAPTCHA_HTML} = $req->captchaHtml if ( $req->captchaHtml );
593 $tplPrm{TOKEN} = $req->token if $req->token;
594  
595 # DEPRECATED: This is only used for compatibility with existing templates
596 if ( $req->captcha ) {
597 $tplPrm{CAPTCHA_SRC} = $req->captcha;
598 $tplPrm{CAPTCHA_SIZE} = $self->conf->{captcha_size};
599 }
600  
601 # Display form the first time
602 if ( (
603 $req->error == PE_MAILFORMEMPTY
604 or $req->error == PE_MAILFIRSTACCESS
605 or $req->error == PE_MAILNOTFOUND
606 or $req->error == PE_CAPTCHAERROR
607 or $req->error == PE_CAPTCHAEMPTY
608 )
609 and not $req->data->{mailToken}
610 )
611 {
612 $self->logger->debug('Display form');
613 $tplPrm{DISPLAY_FORM} = 1;
614 }
615  
616 # Display mail confirmation resent form
617 elsif ( $req->error == PE_MAILCONFIRMATION_ALREADY_SENT ) {
618 $self->logger->debug('Display resend form');
619 $tplPrm{DISPLAY_RESEND_FORM} = 1;
620 }
621  
622 # Display confirmation mail sent
623 elsif ( $req->error == PE_MAILCONFIRMOK ) {
624 $self->logger->debug('Display "confirm mail sent"');
625 $tplPrm{DISPLAY_CONFIRMMAILSENT} = 1;
626 }
627  
628 # Display mail sent
629 elsif ( $req->error == PE_MAILOK ) {
630 $self->logger->debug('Display "mail sent"');
631 $tplPrm{DISPLAY_MAILSENT} = 1;
632 }
633  
634 # Display password change form
635 elsif ( $req->data->{mailToken}
636 and $req->error != PE_MAILERROR
637 and $req->error != PE_BADMAILTOKEN
638 and $req->error != PE_MAILOK )
639 {
640 $self->logger->debug('Display password form');
641 $tplPrm{DISPLAY_PASSWORD_FORM} = 1;
642 }
643  
644 # Display password change form again
645 # - if passwords mismatch
646 # - if password quality check fail
647 elsif ($req->error == PE_PASSWORDFORMEMPTY
648 || $req->error == PE_PASSWORD_MISMATCH
649 || $req->error == PE_PP_INSUFFICIENT_PASSWORD_QUALITY
650 || $req->error == PE_PP_PASSWORD_TOO_SHORT
651 || $req->error == PE_PP_PASSWORD_TOO_YOUNG
652 || $req->error == PE_PP_PASSWORD_IN_HISTORY )
653 {
654 $self->logger->debug('Display password form');
655 $tplPrm{DISPLAY_PASSWORD_FORM} = $req->sessionInfo->{pwdAllowed};
656 }
657  
658 return 'mail', \%tplPrm;
659 }
660  
661 1;