archive-ccc8458/video/lib/auth.php
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
<?php
declare(strict_types=1);
require_once __DIR__ . '/config.php';
function load_password(): string {
if (!is_file(PASSWORD_FILE)) return '';
$p = require PASSWORD_FILE;
return is_string($p) ? $p : '';
}
function password_from_request(): ?string {
$h = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
if ($h === '' && function_exists('apache_request_headers')) {
foreach (apache_request_headers() as $k => $v) {
if (strcasecmp($k, 'Authorization') === 0) { $h = $v; break; }
}
}
if (stripos($h, 'Bearer ') === 0) return trim(substr($h, 7));
return null;
}
function verify_password(string $provided): bool {
$real = load_password();
if ($real === '') return false;
return hash_equals($real, $provided);
}
function client_ip(): string {
return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
}
function rl_file(): string {
return RATE_LIMIT_DIR . '/' . hash('sha256', client_ip()) . '.json';
}
function rate_limit_check(): bool {
if (!is_dir(RATE_LIMIT_DIR)) @mkdir(RATE_LIMIT_DIR, 0700, true);
$f = rl_file();
if (!is_file($f)) return true;
$j = json_decode((string) file_get_contents($f), true) ?: [];
return (int)($j['until'] ?? 0) <= time();
}
function rate_limit_fail(): void {
if (!is_dir(RATE_LIMIT_DIR)) @mkdir(RATE_LIMIT_DIR, 0700, true);
$f = rl_file();
$j = is_file($f) ? (json_decode((string) file_get_contents($f), true) ?: []) : [];
$j['count'] = (int)($j['count'] ?? 0) + 1;
if ($j['count'] >= RATE_LIMIT_MAX) {
$j['until'] = time() + RATE_LIMIT_WINDOW;
$j['count'] = 0;
}
file_put_contents($f, json_encode($j), LOCK_EX);
}
function rate_limit_reset(): void {
$f = rl_file();
if (is_file($f)) @unlink($f);
}
function require_https(): void {
$https = ($_SERVER['HTTPS'] ?? '') === 'on'
|| ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https'
|| (int)($_SERVER['SERVER_PORT'] ?? 80) === 443;
if (!$https) {
http_response_code(400);
header('Content-Type: application/json');
echo json_encode(['error' => 'https required']);
exit;
}
}