diff options
| author | ilotterytea <iltsu@alright.party> | 2025-04-20 18:02:22 +0500 |
|---|---|---|
| committer | ilotterytea <iltsu@alright.party> | 2025-04-20 18:02:22 +0500 |
| commit | ac515bdb95db1b3628381a7356dbae1d2715e0a8 (patch) | |
| tree | 53265887dfb1c95abda309c549f28fb8bf4bf538 | |
| parent | 99e2edb45abd9987c6526ba9be3ac301e03af713 (diff) | |
feat: check Authorization header in authorize_user()
| -rw-r--r-- | src/accounts.php | 38 |
1 files changed, 34 insertions, 4 deletions
diff --git a/src/accounts.php b/src/accounts.php index 330ad3c..1580fa5 100644 --- a/src/accounts.php +++ b/src/accounts.php @@ -1,32 +1,62 @@ <?php include_once "config.php"; -function authorize_user() +function authorize_user(bool $required = false): bool { session_start(); - if (!isset($_COOKIE["secret_key"])) { + if (!isset($_COOKIE["secret_key"]) && !isset($_SERVER["HTTP_AUTHORIZATION"])) { if (isset($_SESSION["user_id"])) { session_unset(); } - return; + if ($required) { + if (isset($_SERVER["HTTP_ACCEPT"]) && $_SERVER["HTTP_ACCEPT"] == "application/json") { + http_response_code(401); + echo json_encode([ + "status_code" => 401, + "message" => "Unauthorized", + "data" => null + ]); + } else { + header("Location: /account"); + } + } + + return false; } include_once "config.php"; $db = new PDO(DB_URL, DB_USER, DB_PASS); + $key = $_SERVER["HTTP_AUTHORIZATION"] ?? $_COOKIE["secret_key"]; + $stmt = $db->prepare("SELECT id, username FROM users WHERE secret_key = ?"); - $stmt->execute([$_COOKIE["secret_key"]]); + $stmt->execute([$key]); if ($row = $stmt->fetch()) { $_SESSION["user_id"] = $row["id"]; $_SESSION["user_name"] = $row["username"]; } else { session_regenerate_id(); + session_unset(); setcookie("secret_key", "", time() - 1000); + + if ($required) { + if (isset($_SERVER["HTTP_ACCEPT"]) && $_SERVER["HTTP_ACCEPT"] == "application/json") { + http_response_code(401); + echo json_encode([ + "status_code" => 401, + "message" => "Unauthorized", + "data" => null + ]); + } else { + header("Location: /account"); + } + } } $db = null; + return isset($_SESSION["user_name"]); }
\ No newline at end of file |
