This commit is contained in:
2025-09-12 09:58:27 +02:00
parent b7caa9be78
commit aa789dd5a7
9 changed files with 352 additions and 78 deletions

View File

@@ -1,26 +1,43 @@
<?php
require "db.php";
$a = $_GET['action'] ?? '';
//Gabriel,Jakob
$action = $_GET['action'] ?? '';
$b = body();
if ($a==="register") {
$u = trim($b["username"]??"");
$p = trim($b["password"]??"");
if ($u==""||$p=="") out(false,"username/password required",[],400);
$st=db()->prepare("SELECT 1 FROM users WHERE username=?");
function out_ok($arr = []) { echo json_encode(['ok'=>true] + $arr, JSON_UNESCAPED_UNICODE); exit; }
function out_err($msg, $code=400) { http_response_code($code); echo json_encode(['ok'=>false,'error'=>$msg], JSON_UNESCAPED_UNICODE); exit; }
if ($action === 'register') {
$u = trim($b['username'] ?? '');
$p = (string)($b['password'] ?? '');
if ($u === '' || $p === '') out_err('username/password required');
$st = db()->prepare("SELECT user_id FROM users WHERE username=?");
$st->execute([$u]);
if ($st->fetch()) out(false,"exists",[],409);
$hash=password_hash($p,PASSWORD_DEFAULT);
db()->prepare("INSERT INTO users(username,pass_hash) VALUES(?,?)")->execute([$u,$hash]);
out(true,"registered",["user_id"=>db()->lastInsertId()]);
if ($st->fetch()) out_err('username exists', 409);
$hash = password_hash($p, PASSWORD_DEFAULT);
$ins = db()->prepare("INSERT INTO users(username, pass_hash) VALUES(?, ?)");
$ins->execute([$u, $hash]);
out_ok(['user_id' => (int)db()->lastInsertId(), 'username' => $u]);
}
if ($a==="login") {
$u = trim($b["username"]??"");
$p = trim($b["password"]??"");
$st=db()->prepare("SELECT * FROM users WHERE username=?");
if ($action === 'login') {
$u = trim($b['username'] ?? '');
$p = (string)($b['password'] ?? '');
if ($u === '' || $p === '') out_err('username/password required');
$st = db()->prepare("SELECT user_id, pass_hash FROM users WHERE username=?");
$st->execute([$u]);
$r=$st->fetch();
if(!$r || !password_verify($p,$r["pass_hash"])) out(false,"invalid",[],401);
out(true,"ok",["user_id"=>$r["user_id"],"username"=>$u]);
$row = $st->fetch();
if (!$row) out_err('invalid credentials', 401);
if (!password_verify($p, $row['pass_hash'])) out_err('invalid credentials', 401);
out_ok(['user_id' => (int)$row['user_id'], 'username' => $u]);
}
out(false,"unknown action",[],404);
out_err('unknown action', 404);