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