Bug 18298: Add server-side checks and refactor stuffs
[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 $id             = $query->param('id');
32 my $uniqueKey      = $query->param('uniqueKey');
33 my $username       = $query->param('username');
34 my $borrower_number;
35
36 #errors
37 my $hasError;
38
39 #email form error
40 my $errNoBorrowerFound;
41 my $errNoBorrowerEmail;
42 my $errMultipleAccountsForEmail;
43 my $errAlreadyStartRecovery;
44 my $errTooManyEmailFound;
45 my $errBadEmail;
46
47 #new password form error
48 my $errLinkNotValid;
49
50 if ( $query->param('sendEmail') || $query->param('resendEmail') ) {
51
52     #try with the main email
53     $email ||= '';    # avoid undef
54     my $borrower;
55     my $search_results;
56
57     # Find the borrower by userid, card number, or email
58     if ($username) {
59         $search_results = Koha::Patrons->search( { -or => { userid => $username, cardnumber => $username } } );
60     }
61     elsif ($email) {
62         $search_results = Koha::Patrons->search( { -or => { email => $email, emailpro => $email, B_email  => $email } } );
63     }
64
65     if ( not $search_results || $search_results->count < 1) {
66         $hasError           = 1;
67         $errNoBorrowerFound = 1;
68     }
69     elsif ( $username && $search_results->count > 1) { # Multiple accounts for username
70         $hasError           = 1;
71         $errNoBorrowerFound = 1;
72     }
73     elsif ( $email && $search_results->count > 1) { # Muliple accounts for E-Mail
74         $hasError           = 1;
75         $errMultipleAccountsForEmail = 1;
76     }
77     elsif ( $borrower = $search_results->next() ) {    # One matching borrower
78         $username ||= $borrower->userid;
79         my @emails = ( $borrower->email, $borrower->emailpro, $borrower->B_email );
80
81         my $firstNonEmptyEmail = '';
82         foreach my $address ( @emails ) {
83             $firstNonEmptyEmail = $address if length $address;
84             last if $firstNonEmptyEmail;
85         }
86
87         # Is the given email one of the borrower's ?
88         if ( $email && !( grep { $_ eq $email } @emails ) ) {
89             $hasError    = 1;
90             $errNoBorrowerFound = 1;
91         }
92
93 # If we dont have an email yet. Get one of the borrower's email or raise an error.
94         elsif ( !$email && !( $email = $firstNonEmptyEmail ) ) {
95             $hasError           = 1;
96             $errNoBorrowerEmail = 1;
97         }
98
99 # Check if a password reset already issued for this borrower AND we are not asking for a new email
100         elsif ( not $query->param('resendEmail') ) {
101             if ( ValidateBorrowernumber( $borrower->borrowernumber ) ) {
102                 $hasError                = 1;
103                 $errAlreadyStartRecovery = 1;
104             }
105             else {
106                 DeleteExpiredPasswordRecovery( $borrower->borrowernumber );
107             }
108         }
109     }
110     else {    # 0 matching borrower
111         $hasError           = 1;
112         $errNoBorrowerFound = 1;
113     }
114     if ($hasError) {
115         $template->param(
116             hasError                => 1,
117             errNoBorrowerFound      => $errNoBorrowerFound,
118             errTooManyEmailFound    => $errTooManyEmailFound,
119             errAlreadyStartRecovery => $errAlreadyStartRecovery,
120             errBadEmail             => $errBadEmail,
121             errNoBorrowerEmail      => $errNoBorrowerEmail,
122             errMultipleAccountsForEmail => $errMultipleAccountsForEmail,
123             password_recovery       => 1,
124             email                   => HTML::Entities::encode($email),
125             username                => $username
126         );
127     }
128     elsif ( SendPasswordRecoveryEmail( $borrower, $email, $query->param('resendEmail') ) ) {    # generate uuid and send recovery email
129         $template->param(
130             mail_sent => 1,
131             email     => $email
132         );
133     }
134     else {    # if it doesn't work....
135         $template->param(
136             hasError          => 1,
137             password_recovery => 1,
138             sendmailError     => 1
139         );
140     }
141 }
142 elsif ( $query->param('passwordReset') ) {
143     ( $borrower_number, $username ) = GetValidLinkInfo($uniqueKey);
144
145     my $error;
146     if ( not $borrower_number ) {
147         $error = 'errLinkNotValid';
148     } elsif ( $password ne $repeatPassword ) {
149         $error = 'errPassNotMatch';
150     } else {
151         my ( $is_valid, $err) = Koha::AuthUtils::is_password_valid( $password );
152         unless ( $is_valid ) {
153             $error = 'password_too_short' if $err eq 'too_short';
154             $error = 'password_too_weak' if $err eq 'too_weak';
155             $error = 'password_has_whitespaces' if $err eq 'has_whitespaces';
156         } else {
157             Koha::Patrons->find($borrower_number)->update_password( $username, hash_password($password) );
158             CompletePasswordRecovery($uniqueKey);
159             $template->param(
160                 password_reset_done => 1,
161                 username            => $username
162             );
163         }
164     }
165     if ( $error ) {
166         $template->param(
167             new_password => 1,
168             email        => $email,
169             uniqueKey    => $uniqueKey,
170             hasError     => 1,
171             $error       => 1,
172         );
173     }
174 }
175 elsif ($uniqueKey) {    #reset password form
176                         #check if the link is valid
177     ( $borrower_number, $username ) = GetValidLinkInfo($uniqueKey);
178
179     if ( !$borrower_number ) {
180         $errLinkNotValid = 1;
181     }
182
183     $template->param(
184         new_password    => 1,
185         email           => $email,
186         uniqueKey       => $uniqueKey,
187         username        => $username,
188         errLinkNotValid => $errLinkNotValid,
189         hasError        => ( $errLinkNotValid ? 1 : 0 ),
190     );
191 }
192 else {    #password recovery form (to send email)
193     $template->param( password_recovery => 1 );
194 }
195
196 output_html_with_http_headers $query, $cookie, $template->output;