-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.php
More file actions
434 lines (360 loc) · 9.67 KB
/
auth.php
File metadata and controls
434 lines (360 loc) · 9.67 KB
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
<?php
/**
* Authentication Endpoint for PAN
*
* Handles login, logout, token refresh, and session management
*
* Security Features:
* ✓ Password hashing with bcrypt
* ✓ HttpOnly cookies for session/JWT
* ✓ CSRF protection
* ✓ Rate limiting
* ✓ Secure session configuration
*/
// Security headers
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');
header('Referrer-Policy: strict-origin-when-cross-origin');
// CORS - Whitelist specific origins
$allowedOrigins = [
'https://cdr2.com',
'https://www.cdr2.com',
'https://localhost:8443',
'http://localhost:8080',
];
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (in_array($origin, $allowedOrigins) || strpos($origin, 'http://localhost:') === 0) {
header("Access-Control-Allow-Origin: $origin");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, X-CSRF-Token');
}
// Handle OPTIONS preflight
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(204);
exit;
}
// Secure session configuration
ini_set('session.cookie_httponly', 1);
ini_set('session.cookie_secure', 1); // Requires HTTPS
ini_set('session.cookie_samesite', 'Strict');
ini_set('session.use_strict_mode', 1);
session_start();
// Generate CSRF token
if (!isset($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
// Rate limiting
function checkRateLimit($action, $limit = 5, $window = 300) {
$key = "ratelimit_{$action}";
$ip = $_SERVER['REMOTE_ADDR'];
$now = time();
if (!isset($_SESSION[$key])) {
$_SESSION[$key] = [$ip => ['count' => 0, 'reset' => $now + $window]];
}
if (!isset($_SESSION[$key][$ip])) {
$_SESSION[$key][$ip] = ['count' => 0, 'reset' => $now + $window];
}
$data = $_SESSION[$key][$ip];
// Reset if window expired
if ($now > $data['reset']) {
$_SESSION[$key][$ip] = ['count' => 1, 'reset' => $now + $window];
return true;
}
// Check limit
if ($data['count'] >= $limit) {
http_response_code(429);
sendJSON(['ok' => false, 'error' => 'Too many attempts. Please try again later.']);
exit;
}
$_SESSION[$key][$ip]['count']++;
return true;
}
// Validate CSRF token
function validateCSRF() {
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$token = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? $_POST['csrf_token'] ?? '';
$sessionToken = $_SESSION['csrf_token'] ?? '';
if (!$token || !$sessionToken || !hash_equals($sessionToken, $token)) {
http_response_code(403);
sendJSON(['ok' => false, 'error' => 'CSRF token invalid']);
exit;
}
}
}
// Get JSON body
function getJSONBody() {
$raw = file_get_contents('php://input');
if ($raw === false || $raw === '') return null;
$json = json_decode($raw, true);
return is_array($json) ? $json : null;
}
// Send JSON response
function sendJSON($data) {
header('Content-Type: application/json');
echo json_encode($data);
exit;
}
// JWT encoding (simple implementation - use a library like firebase/php-jwt in production)
function createJWT($payload, $secret, $expiresIn = 3600) {
$header = ['alg' => 'HS256', 'typ' => 'JWT'];
$payload['iat'] = time();
$payload['exp'] = time() + $expiresIn;
$base64Header = base64_encode(json_encode($header));
$base64Payload = base64_encode(json_encode($payload));
$signature = hash_hmac('sha256', "$base64Header.$base64Payload", $secret, true);
$base64Signature = base64_encode($signature);
return "$base64Header.$base64Payload.$base64Signature";
}
function verifyJWT($token, $secret) {
$parts = explode('.', $token);
if (count($parts) !== 3) return null;
[$base64Header, $base64Payload, $base64Signature] = $parts;
// Verify signature
$expectedSignature = base64_encode(
hash_hmac('sha256', "$base64Header.$base64Payload", $secret, true)
);
if (!hash_equals($expectedSignature, $base64Signature)) {
return null;
}
// Decode payload
$payload = json_decode(base64_decode($base64Payload), true);
// Check expiration
if (isset($payload['exp']) && $payload['exp'] < time()) {
return null;
}
return $payload;
}
// Load environment
$env = loadEnvironment('.env');
// JWT secret (store securely in production)
$JWT_SECRET = $env['security']['jwt_secret'] ?? 'change-this-secret-in-production';
// Connect to database
try {
$link = new mysqli(
$env['db']['host'],
$env['db']['user'],
$env['db']['pass'],
$env['db']['db']
);
if ($link->connect_error) {
throw new Exception('Database connection failed');
}
$link->set_charset('utf8mb4');
} catch (Exception $e) {
http_response_code(500);
sendJSON(['ok' => false, 'error' => 'Service unavailable']);
exit;
}
// Route request
$action = $_GET['action'] ?? $_POST['action'] ?? '';
switch ($action) {
case 'login':
handleLogin();
break;
case 'logout':
handleLogout();
break;
case 'refresh':
handleRefresh();
break;
case 'check':
handleCheck();
break;
case 'csrf':
// Return CSRF token
sendJSON([
'ok' => true,
'csrf_token' => $_SESSION['csrf_token']
]);
break;
default:
http_response_code(400);
sendJSON(['ok' => false, 'error' => 'Invalid action']);
}
/**
* Handle login
*/
function handleLogin() {
global $link, $JWT_SECRET;
// Rate limiting: 5 attempts per 5 minutes
checkRateLimit('login', 5, 300);
// Validate CSRF
validateCSRF();
// Get credentials
$body = getJSONBody();
$email = $body['email'] ?? $_POST['email'] ?? '';
$password = $body['password'] ?? $_POST['password'] ?? '';
if (!$email || !$password) {
http_response_code(400);
sendJSON(['ok' => false, 'error' => 'Email and password required']);
}
// Query user (use prepared statement)
$stmt = $link->prepare("SELECT userID, username, email, password_hash FROM users WHERE email = ? LIMIT 1");
$stmt->bind_param('s', $email);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
$stmt->close();
// Verify password
if (!$user || !password_verify($password, $user['password_hash'])) {
// Use same error message to prevent user enumeration
http_response_code(401);
sendJSON(['ok' => false, 'error' => 'Invalid credentials']);
}
// Create session
$_SESSION['authenticated'] = true;
$_SESSION['user_id'] = $user['userID'];
$_SESSION['username'] = $user['username'];
$_SESSION['email'] = $user['email'];
// Regenerate session ID to prevent session fixation
session_regenerate_id(true);
// Create JWT token
$token = createJWT([
'sub' => $user['userID'],
'username' => $user['username'],
'email' => $user['email'],
], $JWT_SECRET, 900); // 15 minutes
// Create refresh token (longer expiry)
$refreshToken = createJWT([
'sub' => $user['userID'],
'type' => 'refresh',
], $JWT_SECRET, 604800); // 7 days
// Set tokens as HttpOnly cookies
setcookie('jwt', $token, [
'expires' => time() + 900,
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Strict',
]);
setcookie('refresh_jwt', $refreshToken, [
'expires' => time() + 604800,
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Strict',
]);
// Return success (token also in response for backward compatibility)
sendJSON([
'ok' => true,
'user' => [
'id' => $user['userID'],
'username' => $user['username'],
'email' => $user['email'],
],
'token' => $token,
'refresh_token' => $refreshToken,
]);
}
/**
* Handle logout
*/
function handleLogout() {
// Clear session
$_SESSION = [];
// Delete cookies
setcookie('jwt', '', [
'expires' => time() - 3600,
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Strict',
]);
setcookie('refresh_jwt', '', [
'expires' => time() - 3600,
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Strict',
]);
// Destroy session
session_destroy();
sendJSON(['ok' => true]);
}
/**
* Handle token refresh
*/
function handleRefresh() {
global $JWT_SECRET;
// Get refresh token from cookie
$refreshToken = $_COOKIE['refresh_jwt'] ?? '';
if (!$refreshToken) {
http_response_code(401);
sendJSON(['ok' => false, 'error' => 'No refresh token']);
}
// Verify refresh token
$payload = verifyJWT($refreshToken, $JWT_SECRET);
if (!$payload || ($payload['type'] ?? '') !== 'refresh') {
http_response_code(401);
sendJSON(['ok' => false, 'error' => 'Invalid refresh token']);
}
// Create new access token
$token = createJWT([
'sub' => $payload['sub'],
], $JWT_SECRET, 900); // 15 minutes
// Set new token cookie
setcookie('jwt', $token, [
'expires' => time() + 900,
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Strict',
]);
sendJSON([
'ok' => true,
'token' => $token,
]);
}
/**
* Handle auth check
*/
function handleCheck() {
if (isset($_SESSION['authenticated']) && $_SESSION['authenticated'] === true) {
sendJSON([
'ok' => true,
'authenticated' => true,
'user' => [
'id' => $_SESSION['user_id'] ?? null,
'username' => $_SESSION['username'] ?? null,
'email' => $_SESSION['email'] ?? null,
],
'csrf_token' => $_SESSION['csrf_token'],
]);
} else {
sendJSON([
'ok' => true,
'authenticated' => false,
'csrf_token' => $_SESSION['csrf_token'],
]);
}
}
/**
* Load environment configuration
*/
function loadEnvironment($file) {
$file = basename($file);
if ($file !== '.env') {
die('Invalid configuration file');
}
if (!file_exists($file)) {
die('Configuration file not found');
}
$txt = file_get_contents($file);
$lines = preg_split("/\n/", $txt);
$out = [];
$section = '';
foreach ($lines as $line) {
if (preg_match("/\[(\w+)\]/", $line, $m)) {
$section = $m[1];
$out[$section] = [];
} else {
$parts = preg_split("/\s*=\s*/", $line, 2);
if (count($parts) == 2) {
$out[$section][$parts[0]] = $parts[1];
}
}
}
return $out;
}