about summary refs log tree commit diff stats
path: root/classes/Handler/LoginHandler.php
blob: 7b6fabbccb0554c240d7e4aa24dddc97cc252b0f (plain) (blame)
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
<?php

namespace Handler;

use Config;
use Jumbojett\OpenIDConnectClient;
use ORM;
use Request;
use RequestHandlerInterface;
use Response;

class LoginHandler implements RequestHandlerInterface
{
    const USER_NOT_FOUND = 1;
    const USER_RATE_LIMITED = 2;
    const USER_WRONG_PASSWORD = 3;
    const USER_AUTH_SUCCESS = 4;

    private function isRateLimited(object $user): bool
    {
        // Skip rate limiting during integration tests or schema is older than required
        if (getenv('IS_INTEGRATION_TESTING') || Config::get_schema_version() < 3) {
            return false;
        }

        $windowSeconds = 60;
        $lastAttempt   = $user->last_auth_attempt;

        if ($lastAttempt !== null && is_numeric($lastAttempt) && (int) $lastAttempt > 0) {
            if ((time() - (int) $lastAttempt) < $windowSeconds) {

                // Bump login attempt timestamp
                $user->last_auth_attempt = time();
                $user->save();

                return true;
            }
        }

        return false;
    }

    /**
     * Record a failed authentication attempt for rate limiting purposes.
     */
    private function recordFailedAttempt(object $user): void
    {
        if (Config::get_schema_version() >= 3) {
            $user->last_auth_attempt = time();
            $user->save();
        }
    }

    /** @return array{array{result: string, user: string, csrf_token: string}|null, int} */
    private function doLocalLogin(string $username, string $password): array
    {
        $user = ORM::for_table('epube_users')
            ->where('username', $username)
            ->find_one();

        if (!$user) {
            return [null, self::USER_NOT_FOUND];
        }

        // Check rate limit against the *previous* attempt before updating.
        // This avoids blocking the first attempt in any window.
        if ($this->isRateLimited($user)) {
            return [null, self::USER_RATE_LIMITED];
        }

        // Verify password against stored hash (legacy or modern)
        $legacy = str_starts_with($user->pass, 'SHA256:');
        $valid  = $legacy
            ? hash_equals($user->pass, 'SHA256:' . hash('sha256', "$username:$password"))
            : password_verify($password, $user->pass);

        if (!$valid) {
            $this->recordFailedAttempt($user);
            return [null, self::USER_WRONG_PASSWORD];
        }

        // Upgrade legacy hash to bcrypt
        if ($legacy) {
            $this->upgradePassword($user, $password);
        }

        // Reset last login attempt on successful login
        if (Config::get_schema_version() >= 3) {
            $user->last_auth_attempt = 0;
            $user->save();
        }

        // Set up session
        if (session_status() != PHP_SESSION_ACTIVE) {
            session_start();
        }

        session_regenerate_id(true);

        $_SESSION["owner"] = $username;
        $_SESSION["pass_hash"] = sha1($user->pass);
        $_SESSION["csrf_token"] = bin2hex(random_bytes(16));

        setcookie("epube_csrf_token", $_SESSION["csrf_token"], time() + Config::get(Config::SESSION_LIFETIME),
            "/", "", Config::is_server_https());

        return [["result" => "ok", "user" => $username, "csrf_token" => $_SESSION["csrf_token"]], self::USER_AUTH_SUCCESS];
    }

    /**
     * Upgrade a legacy SHA256 password hash to bcrypt.
     * Called after successful verification — the plaintext password is already known.
     */
    private function upgradePassword(object $user, string $password): void
    {
        $newHash = password_hash($password, PASSWORD_BCRYPT);
        $user->pass = $newHash;
        $user->save();
    }

    private function doOidcLogin(): void
    {
        $oidc = new OpenIDConnectClient(
            Config::get(Config::OIDC_URL),
            Config::get(Config::OIDC_CLIENT_ID),
            Config::get(Config::OIDC_CLIENT_SECRET)
        );

        $oidc->setRedirectURL(Config::get_self_url() . "/backend.php?op=oidc-login-callback");
        $oidc->addScope(['openid', 'profile', 'email']);
        $oidc->authenticate();
    }

    /** @return array<string, string> */
    private function handleOidcCallback(): array
    {
        $oidc = new OpenIDConnectClient(
            Config::get(Config::OIDC_URL),
            Config::get(Config::OIDC_CLIENT_ID),
            Config::get(Config::OIDC_CLIENT_SECRET)
        );

        $oidc->setRedirectURL(Config::get_self_url() . "/backend.php?op=oidc-login-callback");
        $oidc->addScope(['openid', 'profile', 'email']);

        try {
            $oidc->authenticate();

            $username = trim(mb_strtolower($oidc->requestUserInfo("preferred_username")));

            if (!$username) {
                return ["error" => "No username received from OIDC provider."];
            }

            $user = ORM::for_table('epube_users')
                ->where('username', $username)
                ->find_one();

            if (!$user) {
                return ["error" => "User not found: $username"];
            }

            if (session_status() != PHP_SESSION_ACTIVE) {
                session_start();
            }

            session_regenerate_id(true);

            $_SESSION["access_token"] = $oidc->getAccessToken();
            $_SESSION["access_token_last_check"] = time();
            $_SESSION["owner"] = $username;
            $_SESSION["pass_hash"] = sha1($user->pass);
            $_SESSION["csrf_token"] = bin2hex(random_bytes(16));

            setcookie("epube_csrf_token", $_SESSION["csrf_token"], time() + Config::get(Config::SESSION_LIFETIME),
                "/", "", Config::is_server_https());

            return ["result" => "ok", "user" => $username, "csrf_token" => $_SESSION["csrf_token"]];

        } catch (\Exception $e) {
            return ["error" => "OIDC Error: " . $e->getMessage()];
        }
    }

    public function handle(Request $request): Response
    {
        $op = $request->getString('op', '');

        // Redirect to OIDC provider
        if ($op === "perform-oidc-login") {
            if (empty(Config::get(Config::OIDC_URL))) {
                return (new Response())
                    ->withStatus(400)
                    ->withBody(json_encode(["error" => "OIDC is not configured."]));
            }

            $this->doOidcLogin();

            // unreachable - authenticate() redirects
            return new Response();
        }

        // OIDC callback
        if ($op === "oidc-login-callback") {
            if (empty(Config::get(Config::OIDC_URL))) {
                return (new Response())
                    ->withStatus(400)
                    ->withBody(json_encode(["error" => "OIDC is not configured."]));
            }

            $result = $this->handleOidcCallback();

            if (isset($result["error"])) {
                // Logout any partial session state
                if (function_exists('logout_user')) {
                    logout_user();
                }
                return (new Response())
                    ->withStatus(401)
                    ->withBody(json_encode($result));
            }

            return (new Response())
                ->withHeader("Location", Config::get_self_url() . "/index.html")
                ->withBody(json_encode($result));
        }

        // Local username/password login
        if ($op === "perform-login") {
            $username = trim(mb_strtolower($request->getString('user', '')));
            $password = $request->getString('password', '');

            if (!$username || !$password) {
                return (new Response())
                    ->withStatus(400)
                    ->withBody(json_encode(["error" => "Username and password are required."]));
            }

            [$result, $status] = $this->doLocalLogin($username, $password);

            if (!$result) {
                if ($status === self::USER_RATE_LIMITED) {
                    return (new Response())
                        ->withStatus(429)
                        ->withBody(json_encode(["error" => "Too many login attempts."]));
                } else {
                    return (new Response())
                        ->withStatus(401)
                        ->withBody(json_encode(["error" => "Incorrect username or password."]));
                }
            }

            return (new Response())
                ->withBody(json_encode($result));
        }

        return (new Response())
            ->withStatus(404)
            ->withBody(json_encode(["error" => "Not found."]));
    }
}