diff options
| author | ilotterytea <iltsu@alright.party> | 2025-08-21 16:43:12 +0500 |
|---|---|---|
| committer | ilotterytea <iltsu@alright.party> | 2025-08-21 16:43:12 +0500 |
| commit | 86d7d3102489db9f592eea283161a3ed1c91ed76 (patch) | |
| tree | 8b98ea7d024423b961870f4899bc4b90240dd999 | |
| parent | d2580691d2441dab308ba624386a69c2f9a26b7b (diff) | |
feat: access tokens
| -rw-r--r-- | database.sql | 7 | ||||
| -rw-r--r-- | login.php | 22 |
2 files changed, 28 insertions, 1 deletions
diff --git a/database.sql b/database.sql index 27962fa..a339619 100644 --- a/database.sql +++ b/database.sql @@ -3,4 +3,11 @@ CREATE TABLE IF NOT EXISTS users ( username TEXT NOT NULL UNIQUE, `password` TEXT NOT NULL, joined_at TIMESTAMP NOT NULL DEFAULT UTC_TIMESTAMP +); + +CREATE TABLE IF NOT EXISTS tokens ( + id BIGINT PRIMARY KEY AUTO_INCREMENT, + user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + `hash` TEXT NOT NULL UNIQUE, + expires_at TIMESTAMP NOT NULL );
\ No newline at end of file @@ -26,9 +26,29 @@ if ($_SERVER['REQUEST_METHOD'] == 'POST') { exit(create_alert('/login.php', 401, 'Incorrect username or password.', null)); } + $now = date('Y-m-d H:i:s', time()); + $db->prepare('DELETE FROM tokens WHERE expires_at <= ? AND user_id = ?') + ->execute([$now, $user['id']]); + + $data = $user; + + if (IS_JSON_REQUEST) { + $expires_at = date('Y-m-d H:i:s', time() + 86400); + + $token = bin2hex(random_bytes(16)); + + $db->prepare('INSERT INTO tokens(user_id, hash, expires_at) VALUES (?, ?, ?)') + ->execute([$user['id'], hash('sha256', $token), $expires_at]); + + $data = [ + 'token' => $token, + 'id' => $user['id'] + ]; + } + $_SESSION['user'] = $user; - exit(create_alert('/', 200, null, $user)); + exit(create_alert('/', 200, null, $data)); } ?> <!DOCTYPE html> |
