Bug 18025 - Expired password recovery links cause sql crash
[koha.git] / opac / opac-password-recovery.pl
1 #!/usr/bin/perl
2
3 use Modern::Perl;
4 use CGI;
5
6 use C4::Auth;
7 use C4::Koha;
8 use C4::Output;
9 use C4::Context;
10 use Koha::Patron::Password::Recovery
11   qw(SendPasswordRecoveryEmail ValidateBorrowernumber GetValidLinkInfo CompletePasswordRecovery DeleteExpiredPasswordRecovery);
12 use Koha::Patrons;
13 use Koha::AuthUtils qw(hash_password);
14 use Koha::Patrons;
15 my $query = new CGI;
16 use HTML::Entities;
17
18 my ( $template, $dummy, $cookie ) = get_template_and_user(
19     {
20         template_name   => "opac-password-recovery.tt",
21         query           => $query,
22         type            => "opac",
23         authnotrequired => 1,
24         debug           => 1,
25     }
26 );
27
28 my $email          = $query->param('email') // q{};
29 my $password       = $query->param('password');
30 my $repeatPassword = $query->param('repeatPassword');
31 my $minPassLength  = C4::Context->preference('minPasswordLength');
32 my $id             = $query->param('id');
33 my $uniqueKey      = $query->param('uniqueKey');
34 my $username       = $query->param('username');
35 my $borrower_number;
36
37 #errors
38 my $hasError;
39
40 #email form error
41 my $errNoBorrowerFound;
42 my $errNoBorrowerEmail;
43 my $errAlreadyStartRecovery;
44 my $errTooManyEmailFound;
45 my $errBadEmail;
46
47 #new password form error
48 my $errLinkNotValid;
49 my $errPassNotMatch;
50 my $errPassTooShort;
51
52 if ( $query->param('sendEmail') || $query->param('resendEmail') ) {
53
54     #try with the main email
55     $email ||= '';    # avoid undef
56     my $borrower;
57     my $search_results = [];
58
59     # Find the borrower by his userid or email
60     if ($username) {
61         $search_results = [ Koha::Patrons->search( { userid => $username } ) ];
62     }
63     elsif ($email) {
64         $search_results = [ Koha::Patrons->search( { -or => { email => $email, emailpro => $email, B_email  => $email } } ) ];
65     }
66     if ( not $search_results || scalar @$search_results > 1 ) {
67         $hasError           = 1;
68         $errNoBorrowerFound = 1;
69     }
70     elsif ( $borrower = shift @$search_results ) {    # One matching borrower
71         $username ||= $borrower->userid;
72         my @emails = ( $borrower->email, $borrower->emailpro, $borrower->B_email );
73
74         my $firstNonEmptyEmail = '';
75         foreach my $address ( @emails ) {
76             $firstNonEmptyEmail = $address if length $address;
77             last if $firstNonEmptyEmail;
78         }
79
80         # Is the given email one of the borrower's ?
81         if ( $email && !( grep { $_ eq $email } @emails ) ) {
82             $hasError    = 1;
83             $errNoBorrowerFound = 1;
84         }
85
86 # If we dont have an email yet. Get one of the borrower's email or raise an error.
87         elsif ( !$email && !( $email = $firstNonEmptyEmail ) ) {
88             $hasError           = 1;
89             $errNoBorrowerEmail = 1;
90         }
91
92 # Check if a password reset already issued for this borrower AND we are not asking for a new email
93         elsif ( ValidateBorrowernumber( $borrower->borrowernumber )
94             && !$query->param('resendEmail') )
95         {
96             $hasError                = 1;
97             $errAlreadyStartRecovery = 1;
98         }
99         elsif ( !ValidateBorrowernumber($borrower->borrowernumber)
100             && !$query->param('resendEmail') )
101         {
102             DeleteExpiredPasswordRecovery($borrower->borrowernumber);
103         }
104     }
105     else {    # 0 matching borrower
106         $hasError           = 1;
107         $errNoBorrowerFound = 1;
108     }
109     if ($hasError) {
110         $template->param(
111             hasError                => 1,
112             errNoBorrowerFound      => $errNoBorrowerFound,
113             errTooManyEmailFound    => $errTooManyEmailFound,
114             errAlreadyStartRecovery => $errAlreadyStartRecovery,
115             errBadEmail             => $errBadEmail,
116             errNoBorrowerEmail      => $errNoBorrowerEmail,
117             password_recovery       => 1,
118             email                   => HTML::Entities::encode($email),
119             username                => $username
120         );
121     }
122     elsif ( SendPasswordRecoveryEmail( $borrower, $email, $query->param('resendEmail') ) ) {    # generate uuid and send recovery email
123         $template->param(
124             mail_sent => 1,
125             email     => $email
126         );
127     }
128     else {    # if it doesn't work....
129         $template->param(
130             password_recovery => 1,
131             sendmailError     => 1
132         );
133     }
134 }
135 elsif ( $query->param('passwordReset') ) {
136     ( $borrower_number, $username ) = GetValidLinkInfo($uniqueKey);
137
138     #validate password length & match
139     if (   ($borrower_number)
140         && ( $password eq $repeatPassword )
141         && ( length($password) >= $minPassLength ) )
142     {    #apply changes
143         Koha::Patrons->find($borrower_number)->update_password( $username, hash_password($password) );
144         CompletePasswordRecovery($uniqueKey);
145         $template->param(
146             password_reset_done => 1,
147             username            => $username
148         );
149     }
150     else {    #errors
151         if ( !$borrower_number ) {    #parameters not valid
152             $errLinkNotValid = 1;
153         }
154         elsif ( $password ne $repeatPassword ) {    #passwords does not match
155             $errPassNotMatch = 1;
156         }
157         elsif ( length($password) < $minPassLength ) {    #password too short
158             $errPassTooShort = 1;
159         }
160         $template->param(
161             new_password    => 1,
162             minPassLength   => $minPassLength,
163             email           => $email,
164             uniqueKey       => $uniqueKey,
165             errLinkNotValid => $errLinkNotValid,
166             errPassNotMatch => $errPassNotMatch,
167             errPassTooShort => $errPassTooShort,
168             hasError        => 1
169         );
170     }
171 }
172 elsif ($uniqueKey) {    #reset password form
173                         #check if the link is valid
174     ( $borrower_number, $username ) = GetValidLinkInfo($uniqueKey);
175
176     if ( !$borrower_number ) {
177         $errLinkNotValid = 1;
178     }
179
180     $template->param(
181         new_password    => 1,
182         minPassLength   => $minPassLength,
183         email           => $email,
184         uniqueKey       => $uniqueKey,
185         username        => $username,
186         errLinkNotValid => $errLinkNotValid,
187         hasError        => ( $errLinkNotValid ? 1 : 0 ),
188     );
189 }
190 else {    #password recovery form (to send email)
191     $template->param( password_recovery => 1 );
192 }
193
194 output_html_with_http_headers $query, $cookie, $template->output;