We are no longer offering accounts on this server. Consider https://gitlab.freedesktop.org/ as a place to host projects.

recoverpassword.php 16.4 KB
Newer Older
1 2
<?php
/*
3
 * StatusNet - the distributed open-source microblogging tool
4
 * Copyright (C) 2008, 2009, StatusNet, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

20
if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
21

22 23
# You have 24 hours to claim your password

Rasmus Lerdorf's avatar
Rasmus Lerdorf committed
24
define('MAX_RECOVERY_TIME', 24 * 60 * 60);
25

26 27
class RecoverpasswordAction extends Action
{
Evan Prodromou's avatar
Evan Prodromou committed
28 29 30
    var $mode = null;
    var $msg = null;
    var $success = null;
31

32 33
    function handle($args)
    {
34 35
        parent::handle($args);
        if (common_logged_in()) {
36
            // TRANS: Client error displayed trying to recover password while already logged in.
37
            $this->clientError(_('You are already logged in!'));
38 39
            return;
        } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
40
            if ($this->arg('recover')) {
Evan Prodromou's avatar
Evan Prodromou committed
41
                $this->recoverPassword();
42
            } else if ($this->arg('reset')) {
Evan Prodromou's avatar
Evan Prodromou committed
43
                $this->resetPassword();
44
            } else {
45
                // TRANS: Client error displayed when unexpected data is posted in the password recovery form.
46
                $this->clientError(_('Unexpected form submission.'));
47 48 49
            }
        } else {
            if ($this->trimmed('code')) {
Evan Prodromou's avatar
Evan Prodromou committed
50
                $this->checkCode();
51
            } else {
Evan Prodromou's avatar
Evan Prodromou committed
52
                $this->showForm();
53 54 55 56
            }
        }
    }

Evan Prodromou's avatar
Evan Prodromou committed
57
    function checkCode()
58
    {
59 60 61 62
        $code = $this->trimmed('code');
        $confirm = Confirm_address::staticGet('code', $code);

        if (!$confirm) {
63
            // TRANS: Client error displayed when password recovery code is not correct.
64
            $this->clientError(_('No such recovery code.'));
65 66 67
            return;
        }
        if ($confirm->address_type != 'recover') {
68
            // TRANS: Client error displayed when no proper password recovery code was submitted.
69
            $this->clientError(_('Not a recovery code.'));
70 71 72 73 74 75
            return;
        }

        $user = User::staticGet($confirm->user_id);

        if (!$user) {
76
            // TRANS: Server error displayed trying to recover password without providing a user.
77
            $this->serverError(_('Recovery code for unknown user.'));
78 79 80 81 82 83 84 85 86 87 88 89
            return;
        }

        $touched = strtotime($confirm->modified);
        $email = $confirm->address;

        # Burn this code

        $result = $confirm->delete();

        if (!$result) {
            common_log_db_error($confirm, 'DELETE', __FILE__);
90
            // TRANS: Server error displayed removing a password recovery code from the database.
91
            $this->serverError(_('Error with confirmation code.'));
92 93 94 95 96 97 98
            return;
        }

        # These should be reaped, but for now we just check mod time
        # Note: it's still deleted; let's avoid a second attempt!

        if ((time() - $touched) > MAX_RECOVERY_TIME) {
Evan Prodromou's avatar
Evan Prodromou committed
99
            common_log(LOG_WARNING,
100 101
                       'Attempted redemption on recovery code ' .
                       'that is ' . $touched . ' seconds old. ');
102
            // TRANS: Client error displayed trying to recover password with too old a recovery code.
103
            $this->clientError(_('This confirmation code is too old. ' .
104 105 106 107 108 109 110 111 112 113 114 115 116
                                   'Please start again.'));
            return;
        }

        # If we used an outstanding confirmation to send the email,
        # it's been confirmed at this point.

        if (!$user->email) {
            $orig = clone($user);
            $user->email = $email;
            $result = $user->updateKeys($orig);
            if (!$result) {
                common_log_db_error($user, 'UPDATE', __FILE__);
117
                // TRANS: Server error displayed when updating a user's e-mail address in the database fails while recovering a password.
118
                $this->serverError(_('Could not update user with confirmed email address.'));
119 120 121 122 123 124
                return;
            }
        }

        # Success!

Evan Prodromou's avatar
Evan Prodromou committed
125 126
        $this->setTempUser($user);
        $this->showPasswordForm();
127 128
    }

Evan Prodromou's avatar
Evan Prodromou committed
129
    function setTempUser(&$user)
130
    {
131 132 133 134
        common_ensure_session();
        $_SESSION['tempuser'] = $user->id;
    }

Evan Prodromou's avatar
Evan Prodromou committed
135
    function getTempUser()
136
    {
137 138 139 140 141 142 143 144
        common_ensure_session();
        $user_id = $_SESSION['tempuser'];
        if ($user_id) {
            $user = User::staticGet($user_id);
        }
        return $user;
    }

Evan Prodromou's avatar
Evan Prodromou committed
145
    function clearTempUser()
146
    {
147 148 149 150
        common_ensure_session();
        unset($_SESSION['tempuser']);
    }

Evan Prodromou's avatar
Evan Prodromou committed
151
    function showPageNotice()
152
    {
Evan Prodromou's avatar
Evan Prodromou committed
153 154
        if ($this->msg) {
            $this->element('div', ($this->success) ? 'success' : 'error', $this->msg);
155
        } else {
156
            $this->elementStart('div', 'instructions');
Evan Prodromou's avatar
Evan Prodromou committed
157 158
            if ($this->mode == 'recover') {
                $this->element('p', null,
159
                               // TRANS: Page notice for password recovery page.
160
                               _('If you have forgotten or lost your' .
Evan Prodromou's avatar
Evan Prodromou committed
161
                                 ' password, you can get a new one sent to' .
Ori Avtalion's avatar
Ori Avtalion committed
162
                                 ' the email address you have stored' .
Evan Prodromou's avatar
Evan Prodromou committed
163 164
                                 ' in your account.'));
            } else if ($this->mode == 'reset') {
165
                // TRANS: Page notice for password change page.
Evan Prodromou's avatar
Evan Prodromou committed
166
                $this->element('p', null,
167
                               _('You have been identified. Enter a' .
168
                                 ' new password below.'));
Evan Prodromou's avatar
Evan Prodromou committed
169
            }
170
            $this->elementEnd('div');
171 172 173
        }
    }

Evan Prodromou's avatar
Evan Prodromou committed
174
    function showForm($msg=null)
175
    {
Evan Prodromou's avatar
Evan Prodromou committed
176 177 178
        $this->msg = $msg;
        $this->mode = 'recover';
        $this->showPage();
179 180
    }

Evan Prodromou's avatar
Evan Prodromou committed
181
    function showContent()
182
    {
Evan Prodromou's avatar
Evan Prodromou committed
183 184 185 186 187 188
        if ($this->mode == 'recover') {
            $this->showRecoverForm();
        } else if ($this->mode == 'reset') {
            $this->showResetForm();
        }
    }
189

Evan Prodromou's avatar
Evan Prodromou committed
190 191
    function showRecoverForm()
    {
192
        $this->elementStart('form', array('method' => 'post',
193 194
                                           'id' => 'form_password_recover',
                                           'class' => 'form_settings',
195
                                           'action' => common_local_url('recoverpassword')));
196
        $this->elementStart('fieldset');
197
        // TRANS: Fieldset legend for password recovery page.
198
        $this->element('legend', null, _('Password recovery'));
199 200
        $this->elementStart('ul', 'form_data');
        $this->elementStart('li');
201
        // TRANS: Field label on password recovery page.
202
        $this->input('nicknameoremail', _('Nickname or email address'),
203
                     $this->trimmed('nicknameoremail'),
204
                     // TRANS: Title for field label on password recovery page.
205 206
                     _('Your nickname on this server, ' .
                        'or your registered email address.'));
207 208
        $this->elementEnd('li');
        $this->elementEnd('ul');
209 210
        $this->element('input', array('name' => 'recover',
                                      'type' => 'hidden',
211
                                      // TRANS: Field label on password recovery page.
212
                                      'value' => _('Recover')));
213 214
        // TRANS: Button text on password recovery page.
        $this->submit('recover', _m('BUTTON','Recover'));
215
        $this->elementEnd('fieldset');
216
        $this->elementEnd('form');
217 218
    }

Evan Prodromou's avatar
Evan Prodromou committed
219
    function title()
220
    {
Evan Prodromou's avatar
Evan Prodromou committed
221
        switch ($this->mode) {
222
         // TRANS: Title for password recovery page in password reset mode.
Evan Prodromou's avatar
Evan Prodromou committed
223
         case 'reset': return _('Reset password');
224
         // TRANS: Title for password recovery page in password recover mode.
Evan Prodromou's avatar
Evan Prodromou committed
225
         case 'recover': return _('Recover password');
226
         // TRANS: Title for password recovery page in email sent mode.
Evan Prodromou's avatar
Evan Prodromou committed
227
         case 'sent': return _('Password recovery requested');
228
         // TRANS: Title for password recovery page in password saved mode.
Evan Prodromou's avatar
Evan Prodromou committed
229 230
         case 'saved': return _('Password saved.');
         default:
231
            // TRANS: Title for password recovery page when an unknown action has been specified.
Evan Prodromou's avatar
Evan Prodromou committed
232 233 234
            return _('Unknown action');
        }
    }
235

Evan Prodromou's avatar
Evan Prodromou committed
236 237 238 239 240 241
    function showPasswordForm($msg=null)
    {
        $this->msg = $msg;
        $this->mode = 'reset';
        $this->showPage();
    }
242

Evan Prodromou's avatar
Evan Prodromou committed
243 244
    function showResetForm()
    {
245
        $this->elementStart('form', array('method' => 'post',
246 247
                                           'id' => 'form_password_change',
                                           'class' => 'form_settings',
248
                                           'action' => common_local_url('recoverpassword')));
249
        $this->elementStart('fieldset');
250
         // TRANS: Fieldset legend for password reset form.
251
        $this->element('legend', null, _('Password change'));
252
        $this->hidden('token', common_session_token());
253 254
        $this->elementStart('ul', 'form_data');
        $this->elementStart('li');
255
         // TRANS: Field label for password reset form.
256
        $this->password('newpassword', _('New password'),
257 258
                        // TRANS: Title for field label for password reset form.
                        _('6 or more characters, and do not forget it!'));
259 260
        $this->elementEnd('li');
        $this->elementStart('li');
261
         // TRANS: Field label for password reset form where the password has to be typed again.
262
        $this->password('confirm', _('Confirm'),
263 264
                        // TRANS: Ttile for field label for password reset form where the password has to be typed again.
                        _('Same as password above.'));
265 266
        $this->elementEnd('li');
        $this->elementEnd('ul');
267 268
         // TRANS: Button text for password reset form.
        $this->submit('reset', _m('BUTTON','Reset'));
269
        $this->elementEnd('fieldset');
270
        $this->elementEnd('form');
271 272
    }

Evan Prodromou's avatar
Evan Prodromou committed
273
    function recoverPassword()
274
    {
275 276
        $nore = $this->trimmed('nicknameoremail');
        if (!$nore) {
277
            // TRANS: Form instructions for password recovery form.
Evan Prodromou's avatar
Evan Prodromou committed
278
            $this->showForm(_('Enter a nickname or email address.'));
279 280 281 282 283 284 285 286 287 288 289 290
            return;
        }

        $user = User::staticGet('email', common_canonical_email($nore));

        if (!$user) {
            $user = User::staticGet('nickname', common_canonical_nickname($nore));
        }

        # See if it's an unconfirmed email address

        if (!$user) {
291 292 293 294 295 296 297 298
            // Warning: it may actually be legit to have multiple folks
            // who have claimed, but not yet confirmed, the same address.
            // We'll only send to the first one that comes up.
            $confirm_email = new Confirm_address();
            $confirm_email->address = common_canonical_email($nore);
            $confirm_email->address_type = 'email';
            $confirm_email->find();
            if ($confirm_email->fetch()) {
299
                $user = User::staticGet($confirm_email->user_id);
300 301
            } else {
                $confirm_email = null;
302
            }
303 304
        } else {
            $confirm_email = null;
305 306 307
        }

        if (!$user) {
308
            // TRANS: Information on password recovery form if no known username or e-mail address was specified.
Evan Prodromou's avatar
Evan Prodromou committed
309
            $this->showForm(_('No user with that email address or username.'));
310 311 312 313 314 315
            return;
        }

        # Try to get an unconfirmed email address if they used a user name

        if (!$user->email && !$confirm_email) {
316 317 318 319 320
            $confirm_email = new Confirm_address();
            $confirm_email->user_id = $user->id;
            $confirm_email->address_type = 'email';
            $confirm_email->find();
            if (!$confirm_email->fetch()) {
Evan Prodromou's avatar
Evan Prodromou committed
321
                $confirm_email = null;
322 323 324 325
            }
        }

        if (!$user->email && !$confirm_email) {
326
            // TRANS: Client error displayed on password recovery form if a user does not have a registered e-mail address.
327
            $this->clientError(_('No registered email address for that user.'));
328 329 330 331 332 333 334 335 336
            return;
        }

        # Success! We have a valid user and a confirmed or unconfirmed email address

        $confirm = new Confirm_address();
        $confirm->code = common_confirmation_code(128);
        $confirm->address_type = 'recover';
        $confirm->user_id = $user->id;
337
        $confirm->address = (!empty($user->email)) ? $user->email : $confirm_email->address;
338 339 340

        if (!$confirm->insert()) {
            common_log_db_error($confirm, 'INSERT', __FILE__);
341
            // TRANS: Server error displayed if e-mail address confirmation fails in the database on the password recovery form.
342
            $this->serverError(_('Error saving address confirmation.'));
343 344 345
            return;
        }

346
         // @todo FIXME: needs i18n.
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
        $body = "Hey, $user->nickname.";
        $body .= "\n\n";
        $body .= 'Someone just asked for a new password ' .
                 'for this account on ' . common_config('site', 'name') . '.';
        $body .= "\n\n";
        $body .= 'If it was you, and you want to confirm, use the URL below:';
        $body .= "\n\n";
        $body .= "\t".common_local_url('recoverpassword',
                                   array('code' => $confirm->code));
        $body .= "\n\n";
        $body .= 'If not, just ignore this message.';
        $body .= "\n\n";
        $body .= 'Thanks for your time, ';
        $body .= "\n";
        $body .= common_config('site', 'name');
        $body .= "\n";

364
        $headers = _mail_prepare_headers('recoverpassword', $user->nickname, $user->nickname);
365
        // TRANS: Subject for password recovery e-mail.
366
        mail_to_user($user, _('Password recovery requested'), $body, $headers, $confirm->address);
367

Evan Prodromou's avatar
Evan Prodromou committed
368
        $this->mode = 'sent';
369
        // TRANS: User notification after an e-mail with instructions was sent from the password recovery form.
Evan Prodromou's avatar
Evan Prodromou committed
370
        $this->msg = _('Instructions for recovering your password ' .
371
                          'have been sent to the email address registered to your ' .
Evan Prodromou's avatar
Evan Prodromou committed
372 373 374
                          'account.');
        $this->success = true;
        $this->showPage();
375 376
    }

Evan Prodromou's avatar
Evan Prodromou committed
377
    function resetPassword()
378
    {
379 380 381
        # CSRF protection
        $token = $this->trimmed('token');
        if (!$token || $token != common_session_token()) {
382
            // TRANS: Form validation error message.
Evan Prodromou's avatar
Evan Prodromou committed
383
            $this->showForm(_('There was a problem with your session token. Try again, please.'));
384 385 386
            return;
        }

Evan Prodromou's avatar
Evan Prodromou committed
387
        $user = $this->getTempUser();
388 389

        if (!$user) {
390
            // TRANS: Client error displayed when trying to reset as password without providing a user.
391
            $this->clientError(_('Unexpected password reset.'));
392 393 394 395 396 397 398
            return;
        }

        $newpassword = $this->trimmed('newpassword');
        $confirm = $this->trimmed('confirm');

        if (!$newpassword || strlen($newpassword) < 6) {
399
            // TRANS: Reset password form validation error message.
Siebrand Mazeland's avatar
Siebrand Mazeland committed
400
            $this->showPasswordForm(_('Password must be 6 characters or more.'));
401 402 403
            return;
        }
        if ($newpassword != $confirm) {
404
            // TRANS: Reset password form validation error message.
Evan Prodromou's avatar
Evan Prodromou committed
405
            $this->showPasswordForm(_('Password and confirmation do not match.'));
406 407 408 409 410 411 412 413 414 415 416
            return;
        }

        # OK, we're ready to go

        $original = clone($user);

        $user->password = common_munge_password($newpassword, $user->id);

        if (!$user->update($original)) {
            common_log_db_error($user, 'UPDATE', __FILE__);
417 418
            // TRANS: Reset password form validation error message.
            $this->serverError(_('Cannot save new password.'));
419 420 421
            return;
        }

Evan Prodromou's avatar
Evan Prodromou committed
422
        $this->clearTempUser();
423 424

        if (!common_set_user($user->nickname)) {
425
            // TRANS: Server error displayed when something does wrong with the user object during password reset.
426
            $this->serverError(_('Error setting user.'));
427 428 429 430 431
            return;
        }

        common_real_login(true);

Evan Prodromou's avatar
Evan Prodromou committed
432
        $this->mode = 'saved';
433
        // TRANS: Success message for user after password reset.
Evan Prodromou's avatar
Evan Prodromou committed
434 435 436 437
        $this->msg = _('New password successfully saved. ' .
                       'You are now logged in.');
        $this->success = true;
        $this->showPage();
438
    }
439
}