aboutsummaryrefslogtreecommitdiffstats
path: root/src/app/Controllers/AuthController.php
blob: d1ac746a1117cd59facdd99298ee4347ea207056 (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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
<?php

declare(strict_types=1);
// Handles authentication: register, login, logout, email verification, and password reset.

namespace App\Controllers;

use App\Csrf;
use App\Flash;
use App\Mail;
use App\Models\User;
use App\RateLimiter;

class AuthController
{
    // 5 failed logins per 15 minutes per IP
    private const LOGIN_MAX_ATTEMPTS = 5;
    private const LOGIN_WINDOW = 900;
    // 3 password reset requests per 15 minutes per IP
    private const RESET_MAX_ATTEMPTS = 3;
    private const RESET_WINDOW = 900;

    private User $user;
    private RateLimiter $limiter;

    public function __construct()
    {
        $this->user = new User();
        $this->limiter = new RateLimiter();
    }

    public function registerForm(): void
    {
        $content = __DIR__ . '/../Views/auth/register.php';
        include __DIR__ . '/../Views/layouts/main.php';
    }

    public function register(): void
    {
        if (!Csrf::validate($_POST['csrf_token'] ?? '')) {
            Flash::set('error', 'Invalid CSRF token.');
            header('Location: /register');
            return;
        }

        $username = trim($_POST['username'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';
        $passwordConfirm = $_POST['password_confirm'] ?? '';

        // Validation
        $errors = [];

        if ($username === '' || $email === '' || $password === '') {
            $errors[] = 'All fields are required.';
        }
        if (!preg_match('/^[a-zA-Z0-9_]{3,20}$/', $username)) {
            $errors[] = 'Username must be 3-20 characters (letters, numbers, underscores).';
        }
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors[] = 'Invalid email address.';
        }
        if (\strlen($password) < 8) {
            $errors[] = 'Password must be at least 8 characters.';
        }
        if ($password !== $passwordConfirm) {
            $errors[] = 'Passwords do not match.';
        }
        if ($this->user->findByUsername($username)) {
            $errors[] = 'Username is already taken.';
        }
        if ($this->user->findByEmail($email)) {
            $errors[] = 'Email is already registered.';
        }

        if ($errors) {
            Flash::set('error', implode(' ', $errors));
            header('Location: /register');
            return;
        }

        $userId = $this->user->create($username, $email, $password);
        $token = $this->user->getVerificationToken($userId);
        Mail::sendVerification($email, $token);

        Flash::set('success', 'Account created! Check your email to verify.');
        header('Location: /login');
    }

    public function verify(): void
    {
        $token = $_GET['token'] ?? '';
        $user = $this->user->findByVerificationToken($token);

        if (!$user) {
            Flash::set('error', 'Invalid or expired verification link.');
            header('Location: /login');
            return;
        }

        $this->user->verify($user['id']);
        Flash::set('success', 'Email verified! You can now log in.');
        header('Location: /login');
    }

    public function loginForm(): void
    {
        $content = __DIR__ . '/../Views/auth/login.php';
        include __DIR__ . '/../Views/layouts/main.php';
    }

    public function login(): void
    {
        if (!Csrf::validate($_POST['csrf_token'] ?? '')) {
            Flash::set('error', 'Invalid CSRF token.');
            header('Location: /login');
            return;
        }

        $ip = $_SERVER['REMOTE_ADDR'] ?? '';

        if ($this->limiter->isLimited($ip, 'login', self::LOGIN_MAX_ATTEMPTS, self::LOGIN_WINDOW)) {
            Flash::set('error', 'Too many login attempts. Please try again later.');
            header('Location: /login');
            return;
        }

        $username = trim($_POST['username'] ?? '');
        $password = $_POST['password'] ?? '';

        $user = $this->user->findByUsername($username);

        // Use the same error message for wrong username or wrong password
        // to avoid revealing which usernames exist (user enumeration)
        if (!$user || !password_verify($password, $user['password_hash'])) {
            // Only record failed attempts — successful logins don't count
            $this->limiter->record($ip, 'login');
            Flash::set('error', 'Invalid username or password.');
            header('Location: /login');
            return;
        }

        if (!$user['is_verified']) {
            Flash::set('error', 'Please verify your email before logging in.');
            header('Location: /login');
            return;
        }

        // Regenerate session ID to prevent session fixation attacks
        session_regenerate_id(true);
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];

        header('Location: /');
    }

    public function logout(): void
    {
        session_destroy();
        header('Location: /');
    }

    public function forgotPasswordForm(): void
    {
        $content = __DIR__ . '/../Views/auth/forgot-password.php';
        include __DIR__ . '/../Views/layouts/main.php';
    }

    public function forgotPassword(): void
    {
        if (!Csrf::validate($_POST['csrf_token'] ?? '')) {
            Flash::set('error', 'Invalid CSRF token.');
            header('Location: /forgot-password');
            return;
        }

        $ip = $_SERVER['REMOTE_ADDR'] ?? '';

        if ($this->limiter->isLimited($ip, 'reset', self::RESET_MAX_ATTEMPTS, self::RESET_WINDOW)) {
            Flash::set('error', 'Too many reset requests. Please try again later.');
            header('Location: /forgot-password');
            return;
        }

        // Record every attempt — even for non-existent emails, to prevent
        // an attacker from probing email addresses at high speed
        $this->limiter->record($ip, 'reset');

        $email = trim($_POST['email'] ?? '');

        // Always show the same message whether the email exists or not
        // to prevent user enumeration
        Flash::set('success', 'If that email is registered, a reset link has been sent.');

        $user = $this->user->findByEmail($email);
        if ($user) {
            $token = $this->user->setResetToken($user['id']);
            Mail::sendPasswordReset($email, $token);
        }

        header('Location: /login');
    }

    public function resetPasswordForm(): void
    {
        $token = $_GET['token'] ?? '';
        $user = $this->user->findByResetToken($token);

        if (!$user) {
            Flash::set('error', 'Invalid or expired reset link.');
            header('Location: /login');
            return;
        }

        $content = __DIR__ . '/../Views/auth/reset-password.php';
        include __DIR__ . '/../Views/layouts/main.php';
    }

    public function resetPassword(): void
    {
        if (!Csrf::validate($_POST['csrf_token'] ?? '')) {
            Flash::set('error', 'Invalid CSRF token.');
            header('Location: /login');
            return;
        }

        $token = $_POST['token'] ?? '';
        $password = $_POST['password'] ?? '';
        $passwordConfirm = $_POST['password_confirm'] ?? '';

        $user = $this->user->findByResetToken($token);
        if (!$user) {
            Flash::set('error', 'Invalid or expired reset link.');
            header('Location: /login');
            return;
        }

        if (\strlen($password) < 8) {
            Flash::set('error', 'Password must be at least 8 characters.');
            header('Location: /reset-password?token=' . urlencode($token));
            return;
        }
        if ($password !== $passwordConfirm) {
            Flash::set('error', 'Passwords do not match.');
            header('Location: /reset-password?token=' . urlencode($token));
            return;
        }

        $this->user->updatePassword($user['id'], $password);
        Flash::set('success', 'Password updated! You can now log in.');
        header('Location: /login');
    }
}