Projekt
This commit is contained in:
43
Pen&Paper Main/api/users.php
Normal file
43
Pen&Paper Main/api/users.php
Normal file
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
require "db.php";
|
||||
|
||||
//Gabriel,Jakob
|
||||
$action = $_GET['action'] ?? '';
|
||||
$b = body();
|
||||
|
||||
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_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 ($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]);
|
||||
$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_err('unknown action', 404);
|
Reference in New Issue
Block a user