summaryrefslogtreecommitdiff
path: root/app/Http/Controllers/Auth/LoginController.php
blob: 606d28e930ed5f635c4a7dfdd033d406edace6ae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
<?php
/**
 * webtrees: online genealogy
 * Copyright (C) 2018 webtrees development team
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
declare(strict_types=1);

namespace Fisharebest\Webtrees\Http\Controllers\Auth;

use Exception;
use Fisharebest\Webtrees\Auth;
use Fisharebest\Webtrees\Database;
use Fisharebest\Webtrees\DebugBar;
use Fisharebest\Webtrees\FlashMessages;
use Fisharebest\Webtrees\Functions\Functions;
use Fisharebest\Webtrees\Http\Controllers\AbstractBaseController;
use Fisharebest\Webtrees\I18N;
use Fisharebest\Webtrees\Log;
use Fisharebest\Webtrees\Session;
use Fisharebest\Webtrees\Site;
use Fisharebest\Webtrees\Tree;
use Fisharebest\Webtrees\User;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Controller for user login and logout.
 */
class LoginController extends AbstractBaseController
{
    /**
     * Show a login page.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function loginPage(Request $request): Response
    {
        /** @var Tree $tree */
        $tree = $request->attributes->get('tree');

        // Already logged in?
        if (Auth::check()) {
            $ged = $tree !== null ? $tree->getName() : '';

            return new RedirectResponse(route('user-page', ['ged' => $ged]));
        }

        $error    = $request->get('error', '');
        $url      = $request->get('url', '');
        $username = $request->get('username', '');

        $title = I18N::translate('Sign in');

        switch (Site::getPreference('WELCOME_TEXT_AUTH_MODE')) {
            case 1:
            default:
                $welcome = I18N::translate('Anyone with a user account can access this website.');
                break;
            case 2:
                $welcome = I18N::translate('You need to be an authorized user to access this website.');
                break;
            case 3:
                $welcome = I18N::translate('You need to be a family member to access this website.');
                break;
            case 4:
                $welcome = Site::getPreference('WELCOME_TEXT_AUTH_MODE_' . WT_LOCALE);
                break;
        }

        if (Site::getPreference('USE_REGISTRATION_MODULE') === '1') {
            $welcome .= ' ' . I18N::translate('You can apply for an account using the link below.');
        }

        $can_register = Site::getPreference('USE_REGISTRATION_MODULE') === '1';

        return $this->viewResponse('login-page', [
            'can_register' => $can_register,
            'error'        => $error,
            'title'        => $title,
            'url'          => $url,
            'username'     => $username,
            'welcome'      => $welcome,
        ]);
    }

    /**
     * Perform a login.
     *
     * @param Request $request
     *
     * @return RedirectResponse
     */
    public function loginAction(Request $request): RedirectResponse
    {
        /** @var Tree $tree */
        $tree = $request->attributes->get('tree');

        $username = $request->get('username', '');
        $password = $request->get('password', '');
        $url      = $request->get('url', '');

        try {
            $this->doLogin($username, $password);

            if (Auth::isAdmin()) {
                $this->doCheckForUpgrade();
            }

            // If there was no referring page, redirect to "my page".
            if ($url === '') {
                // Switch to a tree where we have a genealogy record (or keep to the current/default).
                $ged = Database::prepare("SELECT gedcom_name FROM `##gedcom` JOIN `##user_gedcom_setting` USING (gedcom_id)" . " WHERE setting_name = 'gedcomid' AND user_id = :user_id" . " ORDER BY gedcom_id = :tree_id DESC")->execute([
                    'user_id' => Auth::user()->getUserId(),
                    'tree_id' => $tree ? $tree->getTreeId() : 0,
                ])->fetchOne();

                $url = route('tree-page', ['ged' => $ged]);
            }

            // Redirect to the target URL
            return new RedirectResponse($url);
        } catch (Exception $ex) {
            // Failed to log in.
            DebugBar::addThrowable($ex);

            return new RedirectResponse(route('login', [
                'username' => $username,
                'url'      => $url,
                'error'    => $ex->getMessage(),
            ]));
        }
    }

    /**
     * Log in, if we can.  Throw an exception, if we can't.
     *
     * @param string $username
     * @param string $password
     *
     * @throws Exception
     */
    private function doLogin(string $username, string $password)
    {
        if (!$_COOKIE) {
            Log::addAuthenticationLog('Login failed (no session cookies): ' . $username);
            throw new Exception(I18N::translate('You cannot sign in because your browser does not accept cookies.'));
        }

        $user = User::findByIdentifier($username);

        if (!$user) {
            Log::addAuthenticationLog('Login failed (no such user/email): ' . $username);
            throw new Exception(I18N::translate('The username or password is incorrect.'));
        }

        if (!$user->checkPassword($password)) {
            Log::addAuthenticationLog('Login failed (incorrect password): ' . $username);
            throw new Exception(I18N::translate('The username or password is incorrect.'));
        }

        if (!$user->getPreference('verified')) {
            Log::addAuthenticationLog('Login failed (not verified by user): ' . $username);
            throw new Exception(I18N::translate('This account has not been verified. Please check your email for a verification message.'));
        }

        if (!$user->getPreference('verified_by_admin')) {
            Log::addAuthenticationLog('Login failed (not approved by admin): ' . $username);
            throw new Exception(I18N::translate('This account has not been approved. Please wait for an administrator to approve it.'));
        }

        Auth::login($user);
        Log::addAuthenticationLog('Login: ' . Auth::user()->getUserName() . '/' . Auth::user()->getRealName());
        Auth::user()->setPreference('sessiontime', WT_TIMESTAMP);

        Session::put('locale', Auth::user()->getPreference('language'));
        Session::put('theme_id', Auth::user()->getPreference('theme'));
        I18N::init(Auth::user()->getPreference('language'));
    }

    /**
     * Tell the user if a new version of webtrees exists.
     */
    private function doCheckForUpgrade()
    {
        $latest_version_txt = Functions::fetchLatestVersion();

        if (preg_match('/^[0-9.]+\|[0-9.]+\|/', $latest_version_txt)) {
            list($latest_version) = explode('|', $latest_version_txt);

            if (version_compare(WT_VERSION, $latest_version) < 0) {
                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">' . $latest_version . '</span>') . '</a>');
            }
        }
    }

    /**
     * Perform a logout.
     *
     * @param Request $request
     *
     * @return RedirectResponse
     */
    public function logoutAction(Request $request): RedirectResponse
    {
        /** @var Tree $tree */
        $tree = $request->attributes->get('tree');

        if (Auth::id()) {
            Log::addAuthenticationLog('Logout: ' . Auth::user()->getUserName() . '/' . Auth::user()->getRealName());
            Auth::logout();
            FlashMessages::addMessage(I18N::translate('You have signed out.'), 'info');
        }

        if ($tree === null) {
            return new RedirectResponse(route('tree-page'));
        } else {
            return new RedirectResponse(route('tree-page', ['ged' => $tree->getName()]));
        }
    }
}