xref: /webtrees/app/Http/RequestHandlers/PasswordRequestAction.php (revision d97083fe315dad9b7d0a150d4fb5f563e57d1869)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2021 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Http\RequestHandlers;
21
22use Fig\Http\Message\StatusCodeInterface;
23use Fisharebest\Webtrees\FlashMessages;
24use Fisharebest\Webtrees\I18N;
25use Fisharebest\Webtrees\Log;
26use Fisharebest\Webtrees\Services\EmailService;
27use Fisharebest\Webtrees\Services\RateLimitService;
28use Fisharebest\Webtrees\Services\UserService;
29use Fisharebest\Webtrees\SiteUser;
30use Fisharebest\Webtrees\Tree;
31use Fisharebest\Webtrees\User;
32use Illuminate\Support\Str;
33use Psr\Http\Message\ResponseInterface;
34use Psr\Http\Message\ServerRequestInterface;
35use Psr\Http\Server\RequestHandlerInterface;
36
37use function e;
38use function random_int;
39use function redirect;
40use function route;
41use function view;
42
43/**
44 * Request a new password.
45 */
46class PasswordRequestAction implements RequestHandlerInterface, StatusCodeInterface
47{
48    private const TOKEN_LENGTH = 40;
49
50    private const TOKEN_VALIDITY_SECONDS = 3600;
51
52    private const RATE_LIMIT_REQUESTS = 5;
53
54    private const RATE_LIMIT_SECONDS = 300;
55
56    private EmailService $email_service;
57
58    private RateLimitService $rate_limit_service;
59
60    private UserService $user_service;
61
62    /**
63     * PasswordRequestForm constructor.
64     *
65     * @param EmailService     $email_service
66     * @param RateLimitService $rate_limit_service
67     * @param UserService      $user_service
68     */
69    public function __construct(
70        EmailService $email_service,
71        RateLimitService $rate_limit_service,
72        UserService $user_service
73    ) {
74        $this->email_service      = $email_service;
75        $this->rate_limit_service = $rate_limit_service;
76        $this->user_service       = $user_service;
77    }
78
79    /**
80     * @param ServerRequestInterface $request
81     *
82     * @return ResponseInterface
83     */
84    public function handle(ServerRequestInterface $request): ResponseInterface
85    {
86        $tree = $request->getAttribute('tree');
87
88        $params = (array) $request->getParsedBody();
89
90        $email = $params['email'] ?? '';
91        $user  = $this->user_service->findByEmail($email);
92
93        if ($user instanceof User) {
94            $this->rate_limit_service->limitRateForUser($user, self::RATE_LIMIT_REQUESTS, self::RATE_LIMIT_SECONDS, 'rate-limit-pw-reset');
95
96            $token  = Str::random(self::TOKEN_LENGTH);
97            $expire = (string) (time() + self::TOKEN_VALIDITY_SECONDS);
98            $url    = route(PasswordResetPage::class, [
99                'token' => $token,
100                'tree'  => $tree instanceof Tree ? $tree->name() : null,
101            ]);
102
103            $user->setPreference('password-token', $token);
104            $user->setPreference('password-token-expire', $expire);
105
106            $this->email_service->send(
107                new SiteUser(),
108                $user,
109                new SiteUser(),
110                I18N::translate('Request a new password'),
111                view('emails/password-request-text', ['url' => $url, 'user' => $user]),
112                view('emails/password-request-html', ['url' => $url, 'user' => $user])
113            );
114
115            Log::addAuthenticationLog('Password request for user: ' . $user->userName());
116        } else {
117            // Email takes a few seconds to send.  An instant response would allow
118            // an attacker to use the speed of the response to infer whether an account exists.
119            usleep(random_int(500000, 2000000));
120        }
121
122        // For security, send a success message even when we fail.
123        $message1 = I18N::translate('A password reset link has been sent to “%s”.', e($email));
124        $message2 = I18N::translate('This link is valid for one hour.');
125        FlashMessages::addMessage($message1 . '<br>' . $message2, 'success');
126
127        return redirect(route(LoginPage::class, ['tree' => $tree instanceof Tree ? $tree->name() : null]));
128    }
129}
130