multi-tenant relay und card-push to user
This commit is contained in:
1 parent
7219bae655
commit
5b18c46ac2
22 files changed
+7453
-519
No files matched your search
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
// Account routes — every logged-in user manages their own client secret
|
||||
// here. The admin never sees or sets it.
|
||||
//
|
||||
// GET /api/account/secret show plaintext (decrypted via master key)
|
||||
// POST /api/account/secret set/replace (body: {secret} or {generate:true})
|
||||
// DELETE /api/account/secret clear (disconnects all clients)
|
||||
|
||||
if (!defined('RELAY_BOOTSTRAPPED')) { http_response_code(404); exit; }
|
||||
|
||||
// $sessionTenant comes from routes/public.php earlier in the chain
|
||||
|
||||
if ($route === '/api/account/secret' && $method === 'GET') {
|
||||
if (!$sessionTenant) jsonResponse(['error' => 'not logged in'], 401);
|
||||
if (empty($sessionTenant['secret_encrypted'])) {
|
||||
jsonResponse(['has_secret' => false]);
|
||||
}
|
||||
$plain = masterDecrypt($sessionTenant['secret_encrypted'], $MASTER_KEY);
|
||||
jsonResponse(['has_secret' => true, 'secret' => $plain]);
|
||||
}
|
||||
|
||||
if ($route === '/api/account/secret' && $method === 'POST') {
|
||||
if (!$sessionTenant) jsonResponse(['error' => 'not logged in'], 401);
|
||||
$input = json_decode(file_get_contents('php://input'), true) ?: [];
|
||||
|
||||
// Either accept a user-supplied secret OR generate a random one
|
||||
if (!empty($input['generate'])) {
|
||||
$secret = bin2hex(random_bytes(24)); // 48-char hex
|
||||
} else {
|
||||
$secret = (string)($input['secret'] ?? '');
|
||||
if (strlen($secret) < 8) {
|
||||
jsonResponse(['error' => 'secret must be at least 8 chars'], 400);
|
||||
}
|
||||
}
|
||||
|
||||
$db->prepare('UPDATE tenants SET secret_hash = :sh, secret_encrypted = :se WHERE id = :id')
|
||||
->execute([
|
||||
'sh' => password_hash($secret, PASSWORD_BCRYPT),
|
||||
'se' => masterEncrypt($secret, $MASTER_KEY),
|
||||
'id' => $sessionTenant['id'],
|
||||
]);
|
||||
|
||||
jsonResponse(['ok' => true, 'secret' => $secret]);
|
||||
}
|
||||
|
||||
if ($route === '/api/account/secret' && $method === 'DELETE') {
|
||||
if (!$sessionTenant) jsonResponse(['error' => 'not logged in'], 401);
|
||||
$db->prepare('UPDATE tenants SET secret_hash = NULL, secret_encrypted = NULL WHERE id = :id')
|
||||
->execute(['id' => $sessionTenant['id']]);
|
||||
jsonResponse(['ok' => true]);
|
||||
}
|
||||
|
||||
if ($route === '/api/account/password' && $method === 'POST') {
|
||||
if (!$sessionTenant) jsonResponse(['error' => 'not logged in'], 401);
|
||||
$input = json_decode(file_get_contents('php://input'), true) ?: [];
|
||||
$current = (string)($input['current'] ?? '');
|
||||
$new = (string)($input['new'] ?? '');
|
||||
|
||||
if (strlen($new) < 4) jsonResponse(['error' => 'new password must be at least 4 chars'], 400);
|
||||
if (!password_verify($current, $sessionTenant['password_hash'])) {
|
||||
jsonResponse(['error' => 'current password is wrong'], 401);
|
||||
}
|
||||
if ($current === $new) {
|
||||
jsonResponse(['error' => 'new password must differ from current'], 400);
|
||||
}
|
||||
|
||||
$db->prepare('UPDATE tenants SET password_hash = :p, password_changed = 1 WHERE id = :id')
|
||||
->execute([
|
||||
'p' => password_hash($new, PASSWORD_BCRYPT),
|
||||
'id' => $sessionTenant['id'],
|
||||
]);
|
||||
jsonResponse(['ok' => true]);
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
<?php
|
||||
// Admin-only routes (session + is_admin):
|
||||
// GET /api/users
|
||||
// POST /api/users
|
||||
// PATCH /api/users/{id}
|
||||
// DELETE /api/users/{id}
|
||||
//
|
||||
// Plus the tenant directory available to any logged-in user:
|
||||
// GET /api/tenants
|
||||
|
||||
if (!defined('RELAY_BOOTSTRAPPED')) { http_response_code(404); exit; }
|
||||
|
||||
// $sessionTenant is set by routes/public.php earlier in the chain
|
||||
|
||||
if ($route === '/api/users' && $method === 'GET') {
|
||||
if (!$sessionTenant || !$sessionTenant['is_admin']) jsonResponse(['error' => 'admin only'], 403);
|
||||
$rows = $db->query('SELECT id, username, is_admin, created_at FROM tenants ORDER BY id ASC')->fetchAll();
|
||||
jsonResponse(['users' => $rows]);
|
||||
}
|
||||
|
||||
if ($route === '/api/users' && $method === 'POST') {
|
||||
if (!$sessionTenant || !$sessionTenant['is_admin']) jsonResponse(['error' => 'admin only'], 403);
|
||||
$input = json_decode(file_get_contents('php://input'), true) ?: [];
|
||||
$username = trim((string)($input['username'] ?? ''));
|
||||
$password = (string)($input['password'] ?? '');
|
||||
$isAdmin = !empty($input['is_admin']) ? 1 : 0;
|
||||
|
||||
if (!preg_match('/^[a-zA-Z0-9_-]{2,32}$/', $username)) {
|
||||
jsonResponse(['error' => 'username must be 2-32 chars: letters, digits, _ or -'], 400);
|
||||
}
|
||||
if (strlen($password) < 4) jsonResponse(['error' => 'password must be at least 4 chars'], 400);
|
||||
if (getTenantByUsername($db, $username)) jsonResponse(['error' => 'username already exists'], 409);
|
||||
|
||||
// No client secret — the new user sets that themselves after first login
|
||||
// via the account view. password_hash is bcrypted; secret columns stay NULL.
|
||||
// password_changed = 0 forces a password change on first login (the
|
||||
// admin-supplied password is meant as a temporary credential).
|
||||
// Admin-flagged users still need to change because the admin set it.
|
||||
$db->prepare('INSERT INTO tenants (username, password_hash, is_admin, password_changed) VALUES (:u, :p, :a, 0)')
|
||||
->execute([
|
||||
'u' => $username,
|
||||
'p' => password_hash($password, PASSWORD_BCRYPT),
|
||||
'a' => $isAdmin,
|
||||
]);
|
||||
jsonResponse(['ok' => true, 'id' => (int)$db->lastInsertId()]);
|
||||
}
|
||||
|
||||
if (preg_match('#^/api/users/(\d+)$#', $route, $m) && $method === 'PATCH') {
|
||||
if (!$sessionTenant || !$sessionTenant['is_admin']) jsonResponse(['error' => 'admin only'], 403);
|
||||
$id = (int)$m[1];
|
||||
$target = getTenantById($db, $id);
|
||||
if (!$target) jsonResponse(['error' => 'user not found'], 404);
|
||||
$input = json_decode(file_get_contents('php://input'), true) ?: [];
|
||||
$fields = []; $params = ['id' => $id];
|
||||
if (!empty($input['password'])) {
|
||||
if (strlen($input['password']) < 4) jsonResponse(['error' => 'password too short'], 400);
|
||||
$fields[] = 'password_hash = :pw';
|
||||
$params['pw'] = password_hash($input['password'], PASSWORD_BCRYPT);
|
||||
}
|
||||
if (array_key_exists('is_admin', $input)) {
|
||||
if (!$input['is_admin'] && $target['is_admin'] && adminCount($db) <= 1) {
|
||||
jsonResponse(['error' => 'cannot demote the last admin'], 400);
|
||||
}
|
||||
$fields[] = 'is_admin = :ad';
|
||||
$params['ad'] = $input['is_admin'] ? 1 : 0;
|
||||
}
|
||||
// Note: client secret is set by the user themselves via /api/account/secret,
|
||||
// not by the admin. Admins can only reset password and toggle admin flag.
|
||||
if (!$fields) jsonResponse(['ok' => true]);
|
||||
$db->prepare('UPDATE tenants SET ' . implode(', ', $fields) . ' WHERE id = :id')->execute($params);
|
||||
jsonResponse(['ok' => true]);
|
||||
}
|
||||
|
||||
if (preg_match('#^/api/users/(\d+)$#', $route, $m) && $method === 'DELETE') {
|
||||
if (!$sessionTenant || !$sessionTenant['is_admin']) jsonResponse(['error' => 'admin only'], 403);
|
||||
$id = (int)$m[1];
|
||||
$target = getTenantById($db, $id);
|
||||
if (!$target) jsonResponse(['error' => 'user not found'], 404);
|
||||
if ($target['is_admin'] && adminCount($db) <= 1) {
|
||||
jsonResponse(['error' => 'cannot delete the last admin'], 400);
|
||||
}
|
||||
if ($id === (int)$sessionTenant['id']) {
|
||||
jsonResponse(['error' => 'cannot delete yourself'], 400);
|
||||
}
|
||||
$db->prepare('DELETE FROM tenants WHERE id = :id')->execute(['id' => $id]);
|
||||
jsonResponse(['ok' => true]);
|
||||
}
|
||||
|
||||
// ── Tenant directory (visible to all authenticated tenants) ──────
|
||||
// Accepts both UI session auth and client API headers, so hyprcrd
|
||||
// instances can fetch the list to populate their recipient picker.
|
||||
|
||||
if ($route === '/api/tenants' && $method === 'GET') {
|
||||
$authedTenant = $sessionTenant ?: authClient($db);
|
||||
if (!$authedTenant) jsonResponse(['error' => 'unauthorized'], 401);
|
||||
$rows = $db->query('SELECT id, username FROM tenants ORDER BY username ASC')->fetchAll();
|
||||
jsonResponse(['tenants' => $rows, 'self' => $authedTenant['username']]);
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
<?php
|
||||
// Message + attachment routes:
|
||||
// POST /api/messages (UI session: server encrypts)
|
||||
// POST /api/messages (client API: decrypt-reencrypt hop)
|
||||
// GET /api/messages (client API: re-encrypt for recipient)
|
||||
// DELETE /api/messages/{id} (own only)
|
||||
// POST /api/attachments (client API)
|
||||
// GET /api/attachments (client API)
|
||||
|
||||
if (!defined('RELAY_BOOTSTRAPPED')) { http_response_code(404); exit; }
|
||||
|
||||
// $sessionTenant comes from routes/public.php earlier in the chain
|
||||
|
||||
// ── UI compose path: server encrypts plaintext with inter-tenant key ──
|
||||
|
||||
if ($route === '/api/messages' && $method === 'POST' && $sessionTenant && empty($_SERVER['HTTP_X_RELAY_KEY'])) {
|
||||
$input = json_decode(file_get_contents('php://input'), true) ?: [];
|
||||
$title = (string)($input['title'] ?? '');
|
||||
$body = (string)($input['body'] ?? '');
|
||||
$recipientName = trim((string)($input['recipient'] ?? $sessionTenant['username']));
|
||||
if ($body === '') jsonResponse(['error' => 'body required'], 400);
|
||||
|
||||
$recipient = getTenantByUsername($db, $recipientName);
|
||||
if (!$recipient) jsonResponse(['error' => "no such user: $recipientName"], 404);
|
||||
|
||||
$interKey = getInterTenantKey($db, $MASTER_KEY);
|
||||
if (!$interKey) jsonResponse(['error' => 'relay super-shared key not set'], 500);
|
||||
$storedTitle = clientEncrypt($title, $interKey);
|
||||
$storedBody = clientEncrypt($body, $interKey);
|
||||
|
||||
$db->prepare('INSERT INTO messages (recipient_id, sender_id, sender_username, title, body, color, tags, relay_uid) VALUES (:r, :s, :sn, :t, :b, :c, :tg, :uid)')
|
||||
->execute([
|
||||
'r' => $recipient['id'],
|
||||
's' => $sessionTenant['id'],
|
||||
'sn' => $sessionTenant['username'],
|
||||
't' => $storedTitle,
|
||||
'b' => $storedBody,
|
||||
'c' => $input['color'] ?? '#38bdf8',
|
||||
'tg' => $input['tags'] ?? '',
|
||||
'uid' => $input['relay_uid'] ?? null,
|
||||
]);
|
||||
jsonResponse(['ok' => true, 'id' => (int)$db->lastInsertId(), 'recipient' => $recipientName]);
|
||||
}
|
||||
|
||||
// ── Client API auth (X-Relay-User + X-Relay-Key) ──
|
||||
|
||||
$clientTenant = authClient($db);
|
||||
|
||||
if ($route === '/api/messages' && $method === 'POST') {
|
||||
if (!$clientTenant) jsonResponse(['error' => 'unauthorized'], 401);
|
||||
|
||||
$input = json_decode(file_get_contents('php://input'), true) ?: [];
|
||||
$encryptedTitle = (string)($input['title'] ?? '');
|
||||
$encryptedBody = (string)($input['body'] ?? '');
|
||||
$recipientName = trim((string)($input['recipient'] ?? $clientTenant['username']));
|
||||
if ($encryptedBody === '') jsonResponse(['error' => 'body required'], 400);
|
||||
|
||||
$recipient = getTenantByUsername($db, $recipientName);
|
||||
if (!$recipient) jsonResponse(['error' => "no such user: $recipientName"], 404);
|
||||
|
||||
// Decrypt with sender's secret
|
||||
if (empty($clientTenant['secret_encrypted'])) {
|
||||
jsonResponse(['error' => 'sender has no client secret set — log into the relay UI and configure one in your account'], 400);
|
||||
}
|
||||
$senderSecret = masterDecrypt($clientTenant['secret_encrypted'], $MASTER_KEY);
|
||||
if (!$senderSecret) jsonResponse(['error' => 'sender secret unavailable'], 500);
|
||||
$plainTitle = clientDecrypt($encryptedTitle, $senderSecret);
|
||||
$plainBody = clientDecrypt($encryptedBody, $senderSecret);
|
||||
|
||||
// Re-encrypt with the inter-tenant (super-shared) key for at-rest storage
|
||||
$interKey = getInterTenantKey($db, $MASTER_KEY);
|
||||
if (!$interKey) jsonResponse(['error' => 'relay super-shared key not set — admin must complete setup'], 500);
|
||||
$storedTitle = clientEncrypt($plainTitle, $interKey);
|
||||
$storedBody = clientEncrypt($plainBody, $interKey);
|
||||
|
||||
$db->prepare('INSERT INTO messages (recipient_id, sender_id, sender_username, title, body, color, tags, relay_uid) VALUES (:r, :s, :sn, :t, :b, :c, :tg, :uid)')
|
||||
->execute([
|
||||
'r' => $recipient['id'],
|
||||
's' => $clientTenant['id'],
|
||||
'sn' => $clientTenant['username'],
|
||||
't' => $storedTitle,
|
||||
'b' => $storedBody,
|
||||
'c' => $input['color'] ?? '#38bdf8',
|
||||
'tg' => $input['tags'] ?? '',
|
||||
'uid' => $input['relay_uid'] ?? null,
|
||||
]);
|
||||
jsonResponse(['ok' => true, 'id' => (int)$db->lastInsertId(), 'recipient' => $recipientName]);
|
||||
}
|
||||
|
||||
if ($route === '/api/messages' && $method === 'GET') {
|
||||
if (!$clientTenant) jsonResponse(['error' => 'unauthorized'], 401);
|
||||
if (empty($clientTenant['secret_encrypted'])) {
|
||||
jsonResponse(['error' => 'no client secret set — log into the relay UI and configure one in your account'], 400);
|
||||
}
|
||||
|
||||
$since = $_GET['since'] ?? null;
|
||||
if ($since) {
|
||||
$stmt = $db->prepare("SELECT * FROM messages WHERE recipient_id = :r AND created_at > :s ORDER BY created_at ASC");
|
||||
$stmt->execute(['r' => $clientTenant['id'], 's' => $since]);
|
||||
} else {
|
||||
$stmt = $db->prepare("SELECT * FROM messages WHERE recipient_id = :r ORDER BY created_at ASC");
|
||||
$stmt->execute(['r' => $clientTenant['id']]);
|
||||
}
|
||||
$msgs = $stmt->fetchAll();
|
||||
|
||||
// Decrypt with inter-tenant key, re-encrypt with recipient's secret
|
||||
$interKey = getInterTenantKey($db, $MASTER_KEY);
|
||||
if (!$interKey) jsonResponse(['error' => 'relay super-shared key not set'], 500);
|
||||
$recipientSecret = masterDecrypt($clientTenant['secret_encrypted'], $MASTER_KEY);
|
||||
if (!$recipientSecret) jsonResponse(['error' => 'recipient secret unavailable'], 500);
|
||||
|
||||
$out = [];
|
||||
foreach ($msgs as $msg) {
|
||||
$plainTitle = clientDecrypt($msg['title'] ?? '', $interKey);
|
||||
$plainBody = clientDecrypt($msg['body'] ?? '', $interKey);
|
||||
$msg['title'] = clientEncrypt($plainTitle, $recipientSecret);
|
||||
$msg['body'] = clientEncrypt($plainBody, $recipientSecret);
|
||||
$out[] = $msg;
|
||||
}
|
||||
$db->prepare("UPDATE messages SET fetched = 1 WHERE recipient_id = :r AND fetched = 0")
|
||||
->execute(['r' => $clientTenant['id']]);
|
||||
jsonResponse($out);
|
||||
}
|
||||
|
||||
if (preg_match('#^/api/messages/(\d+)$#', $route, $m) && $method === 'DELETE') {
|
||||
$tenant = $clientTenant ?: $sessionTenant;
|
||||
if (!$tenant) jsonResponse(['error' => 'unauthorized'], 401);
|
||||
$id = (int)$m[1];
|
||||
$db->prepare('DELETE FROM messages WHERE id = :id AND recipient_id = :r')
|
||||
->execute(['id' => $id, 'r' => $tenant['id']]);
|
||||
jsonResponse(['ok' => true]);
|
||||
}
|
||||
|
||||
if ($route === '/api/attachments' && $method === 'POST') {
|
||||
if (!$clientTenant) jsonResponse(['error' => 'unauthorized'], 401);
|
||||
$input = json_decode(file_get_contents('php://input'), true) ?: [];
|
||||
$relayUid = (string)($input['relay_uid'] ?? '');
|
||||
$filename = (string)($input['filename'] ?? '');
|
||||
$data = (string)($input['data'] ?? '');
|
||||
$recipientName = trim((string)($input['recipient'] ?? $clientTenant['username']));
|
||||
if (!$relayUid || !$filename || !$data) jsonResponse(['error' => 'relay_uid, filename, and data required'], 400);
|
||||
|
||||
$recipient = getTenantByUsername($db, $recipientName);
|
||||
if (!$recipient) jsonResponse(['error' => "no such user: $recipientName"], 404);
|
||||
|
||||
$db->prepare('DELETE FROM attachments WHERE recipient_id = :r AND relay_uid = :uid AND filename = :fn')
|
||||
->execute(['r' => $recipient['id'], 'uid' => $relayUid, 'fn' => $filename]);
|
||||
$db->prepare('INSERT INTO attachments (recipient_id, relay_uid, filename, data) VALUES (:r, :uid, :fn, :data)')
|
||||
->execute(['r' => $recipient['id'], 'uid' => $relayUid, 'fn' => $filename, 'data' => $data]);
|
||||
jsonResponse(['ok' => true, 'id' => (int)$db->lastInsertId()]);
|
||||
}
|
||||
|
||||
if ($route === '/api/attachments' && $method === 'GET') {
|
||||
if (!$clientTenant) jsonResponse(['error' => 'unauthorized'], 401);
|
||||
$relayUid = $_GET['relay_uid'] ?? '';
|
||||
if (!$relayUid) jsonResponse(['error' => 'relay_uid required'], 400);
|
||||
$stmt = $db->prepare('SELECT id, relay_uid, filename, data, created_at FROM attachments WHERE recipient_id = :r AND relay_uid = :uid');
|
||||
$stmt->execute(['r' => $clientTenant['id'], 'uid' => $relayUid]);
|
||||
jsonResponse($stmt->fetchAll());
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
<?php
|
||||
// Public + UI session routes:
|
||||
// GET /api/status
|
||||
// POST /api/setup
|
||||
// POST /api/login
|
||||
// POST /api/logout
|
||||
// GET /api/me
|
||||
//
|
||||
// Each handler exits on match. Falls through to other route files if
|
||||
// none of these matched.
|
||||
|
||||
if (!defined('RELAY_BOOTSTRAPPED')) { http_response_code(404); exit; }
|
||||
|
||||
// ── Public: status ─────────────────────────────────────────────────
|
||||
|
||||
if ($route === '/api/status' && $method === 'GET') {
|
||||
$data = [
|
||||
'setup' => $isSetup,
|
||||
'has_admin' => adminCount($db) > 0,
|
||||
'has_super_secret' => hasInterTenantKey($db),
|
||||
];
|
||||
$sessionTenant = getSessionTenant($db);
|
||||
if ($sessionTenant) {
|
||||
$cnt = $db->prepare('SELECT COUNT(*) FROM messages WHERE recipient_id = :r AND fetched = 0');
|
||||
$cnt->execute(['r' => $sessionTenant['id']]);
|
||||
$data['logged_in'] = true;
|
||||
$data['username'] = $sessionTenant['username'];
|
||||
$data['is_admin'] = (bool)$sessionTenant['is_admin'];
|
||||
$data['inbox_count'] = (int)$cnt->fetchColumn();
|
||||
$data['has_secret'] = !empty($sessionTenant['secret_hash']);
|
||||
$data['password_changed'] = (bool)$sessionTenant['password_changed'];
|
||||
} else {
|
||||
$data['logged_in'] = false;
|
||||
}
|
||||
jsonResponse($data);
|
||||
}
|
||||
|
||||
// ── Public: setup (only when no tenants exist) ────────────────────
|
||||
|
||||
if ($route === '/api/setup' && $method === 'POST') {
|
||||
if (isRateLimited($db, 'setup', 5)) jsonResponse(['error' => 'too many attempts'], 429);
|
||||
if (!$isSetup) jsonResponse(['error' => 'already configured'], 403);
|
||||
|
||||
$input = json_decode(file_get_contents('php://input'), true) ?: [];
|
||||
$username = trim((string)($input['username'] ?? ''));
|
||||
$password = (string)($input['password'] ?? '');
|
||||
$superSecret = (string)($input['super_secret'] ?? '');
|
||||
|
||||
if (!preg_match('/^[a-zA-Z0-9_-]{2,32}$/', $username)) {
|
||||
jsonResponse(['error' => 'username must be 2-32 chars: letters, digits, _ or -'], 400);
|
||||
}
|
||||
if (strlen($password) < 4) jsonResponse(['error' => 'password must be at least 4 chars'], 400);
|
||||
if (strlen($superSecret) < 12) jsonResponse(['error' => 'super-shared secret must be at least 12 chars'], 400);
|
||||
|
||||
// Create the admin tenant. NO client secret yet — the admin (and every
|
||||
// user) sets that themselves later via the account view.
|
||||
$passHash = password_hash($password, PASSWORD_BCRYPT);
|
||||
$db->prepare('INSERT INTO tenants (username, password_hash, is_admin) VALUES (:u, :p, 1)')
|
||||
->execute([
|
||||
'u' => $username,
|
||||
'p' => $passHash,
|
||||
]);
|
||||
|
||||
// Set the relay-wide super-shared key. This is the cross-tenant
|
||||
// routing key — used by the relay to re-encrypt messages at rest.
|
||||
setInterTenantKey($db, $MASTER_KEY, $superSecret);
|
||||
|
||||
$tenantId = (int)$db->lastInsertId();
|
||||
$token = makeSession($db, $tenantId);
|
||||
setSessionCookie($token);
|
||||
jsonResponse(['ok' => true, 'username' => $username, 'is_admin' => true]);
|
||||
}
|
||||
|
||||
// ── Public: login (UI session) ────────────────────────────────────
|
||||
|
||||
if ($route === '/api/login' && $method === 'POST') {
|
||||
if (isRateLimited($db, 'login', 5)) jsonResponse(['error' => 'too many attempts'], 429);
|
||||
$input = json_decode(file_get_contents('php://input'), true) ?: [];
|
||||
$username = trim((string)($input['username'] ?? ''));
|
||||
$password = (string)($input['password'] ?? '');
|
||||
$tenant = getTenantByUsername($db, $username);
|
||||
if (!$tenant || !password_verify($password, $tenant['password_hash'])) {
|
||||
jsonResponse(['error' => 'wrong username or password'], 401);
|
||||
}
|
||||
$token = makeSession($db, (int)$tenant['id']);
|
||||
setSessionCookie($token);
|
||||
jsonResponse([
|
||||
'ok' => true,
|
||||
'username' => $tenant['username'],
|
||||
'is_admin' => (bool)$tenant['is_admin'],
|
||||
]);
|
||||
}
|
||||
|
||||
if ($route === '/api/logout' && $method === 'POST') {
|
||||
destroySession($db);
|
||||
jsonResponse(['ok' => true]);
|
||||
}
|
||||
|
||||
// ── Session-authenticated: /api/me ────────────────────────────────
|
||||
|
||||
$sessionTenant = getSessionTenant($db);
|
||||
|
||||
if ($route === '/api/me' && $method === 'GET') {
|
||||
if (!$sessionTenant) jsonResponse(['error' => 'not logged in'], 401);
|
||||
jsonResponse([
|
||||
'username' => $sessionTenant['username'],
|
||||
'is_admin' => (bool)$sessionTenant['is_admin'],
|
||||
'created_at' => $sessionTenant['created_at'],
|
||||
]);
|
||||
}
|
||||
Reference in new issue
Block a user