xref: /webtrees/app/Http/RequestHandlers/PasswordRequestAction.php (revision 52209e2a0428fac097160b80768133667873b795)
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\Carbon;
24use Fisharebest\Webtrees\FlashMessages;
25use Fisharebest\Webtrees\I18N;
26use Fisharebest\Webtrees\Log;
27use Fisharebest\Webtrees\Services\EmailService;
28use Fisharebest\Webtrees\Services\RateLimitService;
29use Fisharebest\Webtrees\Services\UserService;
30use Fisharebest\Webtrees\SiteUser;
31use Fisharebest\Webtrees\Tree;
32use Fisharebest\Webtrees\User;
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 EmailService $email_service;
52
53    private RateLimitService $rate_limit_service;
54
55    private UserService $user_service;
56
57    /**
58     * PasswordRequestForm constructor.
59     *
60     * @param EmailService     $email_service
61     * @param RateLimitService $rate_limit_service
62     * @param UserService      $user_service
63     */
64    public function __construct(
65        EmailService $email_service,
66        RateLimitService $rate_limit_service,
67        UserService $user_service
68    ) {
69        $this->email_service      = $email_service;
70        $this->rate_limit_service = $rate_limit_service;
71        $this->user_service       = $user_service;
72    }
73
74    /**
75     * @param ServerRequestInterface $request
76     *
77     * @return ResponseInterface
78     */
79    public function handle(ServerRequestInterface $request): ResponseInterface
80    {
81        $tree = $request->getAttribute('tree');
82
83        $params = (array) $request->getParsedBody();
84
85        $email = $params['email'] ?? '';
86        $user  = $this->user_service->findByEmail($email);
87
88        if ($user instanceof User) {
89            $this->rate_limit_service->limitRateForUser($user, 5, 300, 'rate-limit-pw-reset');
90
91            $token  = Str::random(self::TOKEN_LENGTH);
92            $expire = (string) Carbon::now()->addHour()->getTimestamp();
93            $url    = route(PasswordResetPage::class, [
94                'token' => $token,
95                'tree'  => $tree instanceof Tree ? $tree->name() : null,
96            ]);
97
98            $user->setPreference('password-token', $token);
99            $user->setPreference('password-token-expire', $expire);
100
101            $this->email_service->send(
102                new SiteUser(),
103                $user,
104                new SiteUser(),
105                I18N::translate('Request a new password'),
106                view('emails/password-request-text', ['url' => $url, 'user' => $user]),
107                view('emails/password-request-html', ['url' => $url, 'user' => $user])
108            );
109
110            Log::addAuthenticationLog('Password request for user: ' . $user->userName());
111        } else {
112            // Email takes a few seconds to send.  An instant response would allow
113            // an attacker to use the speed of the response to infer whether an account exists.
114            usleep(random_int(500000, 2000000));
115        }
116
117        // For security, send a success message even when we fail.
118        $message1 = I18N::translate('A password reset link has been sent to “%s”.', e($email));
119        $message2 = I18N::translate('This link is valid for one hour.');
120        FlashMessages::addMessage($message1 . '<br>' . $message2, 'success');
121
122        return redirect(route(LoginPage::class, ['tree' => $tree instanceof Tree ? $tree->name() : null]));
123    }
124}
125