xref: /webtrees/app/Http/RequestHandlers/PasswordRequestAction.php (revision 72d49ceedf256aedf1b97871f100dc61df3fd16b)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2023 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 Fisharebest\Webtrees\Validator;
33use Illuminate\Support\Str;
34use Psr\Http\Message\ResponseInterface;
35use Psr\Http\Message\ServerRequestInterface;
36use Psr\Http\Server\RequestHandlerInterface;
37
38use function e;
39use function random_int;
40use function redirect;
41use function route;
42use function view;
43
44/**
45 * Request a new password.
46 */
47class PasswordRequestAction implements RequestHandlerInterface, StatusCodeInterface
48{
49    private const TOKEN_LENGTH = 40;
50
51    private const TOKEN_VALIDITY_SECONDS = 3600;
52
53    private const RATE_LIMIT_REQUESTS = 5;
54
55    private const RATE_LIMIT_SECONDS = 300;
56
57    private EmailService $email_service;
58
59    private RateLimitService $rate_limit_service;
60
61    private UserService $user_service;
62
63    /**
64     * @param EmailService     $email_service
65     * @param RateLimitService $rate_limit_service
66     * @param UserService      $user_service
67     */
68    public function __construct(
69        EmailService $email_service,
70        RateLimitService $rate_limit_service,
71        UserService $user_service
72    ) {
73        $this->email_service      = $email_service;
74        $this->rate_limit_service = $rate_limit_service;
75        $this->user_service       = $user_service;
76    }
77
78    /**
79     * @param ServerRequestInterface $request
80     *
81     * @return ResponseInterface
82     */
83    public function handle(ServerRequestInterface $request): ResponseInterface
84    {
85        $tree  = Validator::attributes($request)->treeOptional();
86        $email = Validator::parsedBody($request)->string('email');
87        $user  = $this->user_service->findByEmail($email);
88
89        if ($user instanceof User) {
90            $this->rate_limit_service->limitRateForUser($user, self::RATE_LIMIT_REQUESTS, self::RATE_LIMIT_SECONDS, 'rate-limit-pw-reset');
91
92            $token  = Str::random(self::TOKEN_LENGTH);
93            $expire = (string) (time() + self::TOKEN_VALIDITY_SECONDS);
94            $url    = route(PasswordResetPage::class, [
95                'token' => $token,
96                'tree'  => $tree?->name(),
97            ]);
98
99            $user->setPreference('password-token', $token);
100            $user->setPreference('password-token-expire', $expire);
101
102            $this->email_service->send(
103                new SiteUser(),
104                $user,
105                new SiteUser(),
106                I18N::translate('Request a new password'),
107                view('emails/password-request-text', ['url' => $url, 'user' => $user]),
108                view('emails/password-request-html', ['url' => $url, 'user' => $user])
109            );
110
111            Log::addAuthenticationLog('Password request for user: ' . $user->userName());
112        } else {
113            // Email takes a few seconds to send.  An instant response would allow
114            // an attacker to use the speed of the response to infer whether an account exists.
115            usleep(random_int(500000, 2000000));
116        }
117
118        // For security, send a success message even when we fail.
119        $message1 = I18N::translate('A password reset link has been sent to “%s”.', e($email));
120        $message2 = I18N::translate('This link is valid for one hour.');
121        FlashMessages::addMessage($message1 . '<br>' . $message2, 'success');
122
123        return redirect(route(LoginPage::class, ['tree' => $tree?->name()]));
124    }
125}
126