xref: /webtrees/app/Http/RequestHandlers/LoginAction.php (revision f507cef925e69f3dc0d47102f965899785571595)
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 Exception;
23use Fisharebest\Webtrees\Auth;
24use Fisharebest\Webtrees\Contracts\UserInterface;
25use Fisharebest\Webtrees\FlashMessages;
26use Fisharebest\Webtrees\I18N;
27use Fisharebest\Webtrees\Log;
28use Fisharebest\Webtrees\Services\UpgradeService;
29use Fisharebest\Webtrees\Services\UserService;
30use Fisharebest\Webtrees\Session;
31use Fisharebest\Webtrees\Tree;
32use Fisharebest\Webtrees\Validator;
33use Psr\Http\Message\ResponseInterface;
34use Psr\Http\Message\ServerRequestInterface;
35use Psr\Http\Server\RequestHandlerInterface;
36
37use function route;
38use function time;
39
40/**
41 * Perform a login.
42 */
43class LoginAction implements RequestHandlerInterface
44{
45    private UpgradeService $upgrade_service;
46
47    private UserService $user_service;
48
49    /**
50     * LoginController constructor.
51     *
52     * @param UpgradeService $upgrade_service
53     * @param UserService    $user_service
54     */
55    public function __construct(UpgradeService $upgrade_service, UserService $user_service)
56    {
57        $this->upgrade_service = $upgrade_service;
58        $this->user_service    = $user_service;
59    }
60
61    /**
62     * Perform a login.
63     *
64     * @param ServerRequestInterface $request
65     *
66     * @return ResponseInterface
67     */
68    public function handle(ServerRequestInterface $request): ResponseInterface
69    {
70        $tree        = Validator::attributes($request)->treeOptional();
71        $default_url = route(HomePage::class);
72        $username    = Validator::parsedBody($request)->string('username');
73        $password    = Validator::parsedBody($request)->string('password');
74        $url         = Validator::parsedBody($request)->isLocalUrl()->string('url', $default_url);
75
76        try {
77            $this->doLogin($username, $password);
78
79            if (Auth::isAdmin() && $this->upgrade_service->isUpgradeAvailable()) {
80                FlashMessages::addMessage(I18N::translate('A new version of webtrees is available.') . ' <a class="alert-link" href="' . e(route(UpgradeWizardPage::class)) . '">' . I18N::translate('Upgrade to webtrees %s.', '<span dir="ltr">' . $this->upgrade_service->latestVersion() . '</span>') . '</a>');
81            }
82
83            // Redirect to the target URL
84            return redirect($url);
85        } catch (Exception $ex) {
86            // Failed to log in.
87            FlashMessages::addMessage($ex->getMessage(), 'danger');
88
89            return redirect(route(LoginPage::class, [
90                'tree'     => $tree instanceof Tree ? $tree->name() : null,
91                'username' => $username,
92                'url'      => $url,
93            ]));
94        }
95    }
96
97    /**
98     * Log in, if we can.  Throw an exception, if we can't.
99     *
100     * @param string $username
101     * @param string $password
102     *
103     * @return void
104     * @throws Exception
105     */
106    private function doLogin(string $username, string $password): void
107    {
108        if ($_COOKIE === []) {
109            Log::addAuthenticationLog('Login failed (no session cookies): ' . $username);
110            throw new Exception(I18N::translate('You cannot sign in because your browser does not accept cookies.'));
111        }
112
113        $user = $this->user_service->findByIdentifier($username);
114
115        if ($user === null) {
116            Log::addAuthenticationLog('Login failed (no such user/email): ' . $username);
117            throw new Exception(I18N::translate('The username or password is incorrect.'));
118        }
119
120        if (!$user->checkPassword($password)) {
121            Log::addAuthenticationLog('Login failed (incorrect password): ' . $username);
122            throw new Exception(I18N::translate('The username or password is incorrect.'));
123        }
124
125        if ($user->getPreference(UserInterface::PREF_IS_EMAIL_VERIFIED) !== '1') {
126            Log::addAuthenticationLog('Login failed (not verified by user): ' . $username);
127            throw new Exception(I18N::translate('This account has not been verified. Please check your email for a verification message.'));
128        }
129
130        if ($user->getPreference(UserInterface::PREF_IS_ACCOUNT_APPROVED) !== '1') {
131            Log::addAuthenticationLog('Login failed (not approved by admin): ' . $username);
132            throw new Exception(I18N::translate('This account has not been approved. Please wait for an administrator to approve it.'));
133        }
134
135        Auth::login($user);
136        Log::addAuthenticationLog('Login: ' . Auth::user()->userName() . '/' . Auth::user()->realName());
137        Auth::user()->setPreference(UserInterface::PREF_TIMESTAMP_ACTIVE, (string) time());
138
139        Session::put('language', Auth::user()->getPreference(UserInterface::PREF_LANGUAGE));
140        Session::put('theme', Auth::user()->getPreference(UserInterface::PREF_THEME));
141        I18N::init(Auth::user()->getPreference(UserInterface::PREF_LANGUAGE));
142    }
143}
144