prepare( 'INSERT INTO api_tokens (user_id, name, prefix, token_hash, created_at) VALUES (?, ?, ?, ?, ?)' ); $stmt->execute([ $userId, mb_substr($name !== '' ? $name : 'App', 0, 64, 'UTF-8'), $prefix, hash('sha256', $token), utc_now(), ]); $tokenId = (int) db()->lastInsertId(); audit('token.create', 'token', $tokenId, $name, $userId); return ['token' => $token, 'prefix' => $prefix, 'id' => $tokenId]; } function tokens_list(int $userId): array { $stmt = db()->prepare( 'SELECT id, name, prefix, created_at, last_used_at, expires_at, revoked_at FROM api_tokens WHERE user_id = ? ORDER BY created_at DESC' ); $stmt->execute([$userId]); return $stmt->fetchAll(); } function token_revoke(int $tokenId, int $userId): bool { $stmt = db()->prepare( 'UPDATE api_tokens SET revoked_at = ? WHERE id = ? AND user_id = ? AND revoked_at IS NULL' ); $stmt->execute([utc_now(), $tokenId, $userId]); return $stmt->rowCount() === 1; } function bearer_token(): string { $header = (string) ($_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? ''); if ($header === '' && function_exists('apache_request_headers')) { $headers = apache_request_headers(); foreach ($headers as $name => $value) { if (strtolower((string) $name) === 'authorization') { $header = (string) $value; break; } } } if (preg_match('/^Bearer\s+(\S+)$/i', trim($header), $matches) === 1) { return $matches[1]; } return ''; } function token_user(string $token): ?array { if (!str_starts_with($token, 'rhub_') || strlen($token) !== 69) { return null; } $stmt = db()->prepare( 'SELECT t.id AS token_id, t.prefix AS token_prefix, t.last_used_at AS token_last_used, u.* FROM api_tokens t JOIN users u ON u.id = t.user_id WHERE t.token_hash = ? AND t.revoked_at IS NULL AND (t.expires_at IS NULL OR t.expires_at > ?) AND u.status = ? LIMIT 1' ); $stmt->execute([hash('sha256', $token), utc_now(), 'active']); $row = $stmt->fetch(); if (!$row) { return null; } $lastUsed = $row['token_last_used']; if ($lastUsed === null || strtotime($lastUsed . ' UTC') < time() - 60) { db()->prepare('UPDATE api_tokens SET last_used_at = ? WHERE id = ?') ->execute([utc_now(), (int) $row['token_id']]); } $row['id'] = (int) $row['id']; $row['auth_epoch'] = (int) $row['auth_epoch']; $row['must_change_password'] = (int) $row['must_change_password']; $row['token_id'] = (int) $row['token_id']; return $row; } function api_require_user(): array { $token = bearer_token(); if ($token === '') { abort_api(401, 'unauthorized', t('api.bearer_missing')); } $user = token_user($token); if ($user === null) { abort_api(401, 'invalid_token', t('api.token_invalid')); } if ($user['must_change_password'] === 1) { abort_api(403, 'password_change_required', t('api.change_password_web')); } return $user; }