xref: /webtrees/app/Http/RequestHandlers/PasswordRequestAction.php (revision ac71572d8462e396ed5a307f05b29381e49f9e6e)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2022 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     * PasswordRequestForm constructor.
65     *
66     * @param EmailService     $email_service
67     * @param RateLimitService $rate_limit_service
68     * @param UserService      $user_service
69     */
70    public function __construct(
71        EmailService $email_service,
72        RateLimitService $rate_limit_service,
73        UserService $user_service
74    ) {
75        $this->email_service      = $email_service;
76        $this->rate_limit_service = $rate_limit_service;
77        $this->user_service       = $user_service;
78    }
79
80    /**
81     * @param ServerRequestInterface $request
82     *
83     * @return ResponseInterface
84     */
85    public function handle(ServerRequestInterface $request): ResponseInterface
86    {
87        $tree  = Validator::attributes($request)->treeOptional();
88        $email = Validator::parsedBody($request)->string('email');
89        $user  = $this->user_service->findByEmail($email);
90
91        if ($user instanceof User) {
92            $this->rate_limit_service->limitRateForUser($user, self::RATE_LIMIT_REQUESTS, self::RATE_LIMIT_SECONDS, 'rate-limit-pw-reset');
93
94            $token  = Str::random(self::TOKEN_LENGTH);
95            $expire = (string) (time() + self::TOKEN_VALIDITY_SECONDS);
96            $url    = route(PasswordResetPage::class, [
97                'token' => $token,
98                'tree'  => $tree instanceof Tree ? $tree->name() : null,
99            ]);
100
101            $user->setPreference('password-token', $token);
102            $user->setPreference('password-token-expire', $expire);
103
104            $this->email_service->send(
105                new SiteUser(),
106                $user,
107                new SiteUser(),
108                I18N::translate('Request a new password'),
109                view('emails/password-request-text', ['url' => $url, 'user' => $user]),
110                view('emails/password-request-html', ['url' => $url, 'user' => $user])
111            );
112
113            Log::addAuthenticationLog('Password request for user: ' . $user->userName());
114        } else {
115            // Email takes a few seconds to send.  An instant response would allow
116            // an attacker to use the speed of the response to infer whether an account exists.
117            usleep(random_int(500000, 2000000));
118        }
119
120        // For security, send a success message even when we fail.
121        $message1 = I18N::translate('A password reset link has been sent to “%s”.', e($email));
122        $message2 = I18N::translate('This link is valid for one hour.');
123        FlashMessages::addMessage($message1 . '<br>' . $message2, 'success');
124
125        return redirect(route(LoginPage::class, ['tree' => $tree instanceof Tree ? $tree->name() : null]));
126    }
127}
128