2 Commits

Author SHA1 Message Date
restitux aa2d92a7ae frontend: add admin panel for user and permission management
Admin-only page at /admin with:
- Create user form (username, password, admin toggle)
- User list table with edit and delete actions
- Inline user editing (change password, toggle admin role)
- Inline permission editor with per-app checkboxes grouped by server
- Access guarded by checking is_admin from /api/auth/me

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-16 15:36:29 +00:00
restitux 786579a7d8 frontend: attach auth credentials to all API requests
Add Authorization Bearer header to all fetch calls (apps, stream
start). Handle 401 responses by clearing token and redirecting to
login. Pass stream_token from the stream start response through to
the WebTransport URL as a query parameter for proxy authentication.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-16 15:36:29 +00:00
7 changed files with 571 additions and 11 deletions
+1
View File
@@ -25,6 +25,7 @@
streamStore.CertHash = streamData.CertHash;
streamStore.Width = streamData.Width;
streamStore.Height = streamData.Height;
streamStore.StreamToken = streamData.StreamToken;
console.log(`Stream data retrieved. Navigating to /stream.`);
await goto('/stream');
+535
View File
@@ -0,0 +1,535 @@
<script lang="ts">
import { onMount } from 'svelte';
import { goto } from '$app/navigation';
import { getToken, handleUnauthorized } from '../stores/authStore.svelte';
import { fetchApps, type App } from '../apps';
interface User {
id: string;
username: string;
is_admin: boolean;
created_at: string;
}
interface AppPermission {
server: string;
app_id: number;
}
let users: User[] = $state([]);
let allApps: Record<string, App[]> = $state({});
let loading = $state(true);
let error = $state('');
// Create user form
let newUsername = $state('');
let newPassword = $state('');
let newIsAdmin = $state(false);
let createError = $state('');
// Edit permissions
let editingUserId: string | null = $state(null);
let editingPermissions: Set<string> = $state(new Set());
// Edit user
let editingUserDetails: string | null = $state(null);
let editPassword = $state('');
let editIsAdmin = $state(false);
let editError = $state('');
function authHeaders(): Record<string, string> {
return {
'Authorization': `Bearer ${getToken()}`,
'Content-Type': 'application/json'
};
}
async function authFetch(url: string, options: RequestInit = {}) {
const response = await fetch(url, {
...options,
headers: { ...authHeaders(), ...(options.headers || {}) }
});
if (response.status === 401) {
handleUnauthorized();
throw new Error('Unauthorized');
}
return response;
}
async function loadUsers() {
const response = await authFetch('/api/admin/users');
if (response.ok) {
users = await response.json();
}
}
async function loadApps() {
try {
const data = await fetchApps();
allApps = data.apps;
} catch {
// Apps may fail if no servers paired, that's ok
}
}
onMount(async () => {
try {
// Verify admin access
const meResp = await authFetch('/api/auth/me');
if (!meResp.ok) return;
const me = await meResp.json();
if (!me.is_admin) {
await goto('/');
return;
}
await Promise.all([loadUsers(), loadApps()]);
} catch (e) {
error = 'Failed to load admin data';
} finally {
loading = false;
}
});
async function createUser() {
createError = '';
if (!newUsername || !newPassword) {
createError = 'Username and password are required';
return;
}
try {
const response = await authFetch('/api/admin/users', {
method: 'POST',
body: JSON.stringify({
username: newUsername,
password: newPassword,
is_admin: newIsAdmin
})
});
if (!response.ok) {
const data = await response.json().catch(() => null);
createError = data?.description || 'Failed to create user';
return;
}
newUsername = '';
newPassword = '';
newIsAdmin = false;
await loadUsers();
} catch {
createError = 'Connection error';
}
}
async function deleteUser(userId: string, username: string) {
if (!confirm(`Delete user "${username}"? This cannot be undone.`)) return;
await authFetch(`/api/admin/users/${userId}`, { method: 'DELETE' });
await loadUsers();
}
function startEditUser(user: User) {
editingUserDetails = user.id;
editPassword = '';
editIsAdmin = user.is_admin;
editError = '';
}
function cancelEditUser() {
editingUserDetails = null;
}
async function saveEditUser() {
if (!editingUserDetails) return;
editError = '';
const body: Record<string, unknown> = {};
if (editPassword) body.password = editPassword;
body.is_admin = editIsAdmin;
try {
const response = await authFetch(`/api/admin/users/${editingUserDetails}`, {
method: 'PUT',
body: JSON.stringify(body)
});
if (!response.ok) {
const data = await response.json().catch(() => null);
editError = data?.description || 'Failed to update user';
return;
}
editingUserDetails = null;
await loadUsers();
} catch {
editError = 'Connection error';
}
}
async function startEditPermissions(userId: string) {
editingUserId = userId;
const response = await authFetch(`/api/admin/users/${userId}/permissions`);
if (response.ok) {
const perms: AppPermission[] = await response.json();
editingPermissions = new Set(perms.map(p => `${p.server}:${p.app_id}`));
}
}
function cancelEditPermissions() {
editingUserId = null;
editingPermissions = new Set();
}
function togglePermission(server: string, appId: number) {
const key = `${server}:${appId}`;
const next = new Set(editingPermissions);
if (next.has(key)) {
next.delete(key);
} else {
next.add(key);
}
editingPermissions = next;
}
async function savePermissions() {
if (!editingUserId) return;
const permissions: AppPermission[] = Array.from(editingPermissions).map(key => {
const [server, appId] = key.split(':');
return { server, app_id: parseInt(appId) };
});
await authFetch(`/api/admin/users/${editingUserId}/permissions`, {
method: 'PUT',
body: JSON.stringify({ permissions })
});
editingUserId = null;
editingPermissions = new Set();
}
function permKey(server: string, appId: number): string {
return `${server}:${appId}`;
}
</script>
<svelte:head>
<title>Admin</title>
</svelte:head>
<div class="admin-container">
<h1>User Management</h1>
{#if loading}
<p class="loading">Loading...</p>
{:else if error}
<p class="error">{error}</p>
{:else}
<!-- Create User -->
<div class="section">
<h2>Create User</h2>
<form class="create-form" onsubmit={(e) => { e.preventDefault(); createUser(); }}>
<input type="text" placeholder="Username" bind:value={newUsername} />
<input type="password" placeholder="Password" bind:value={newPassword} />
<label class="checkbox-label">
<input type="checkbox" bind:checked={newIsAdmin} />
Admin
</label>
<button type="submit">Create</button>
</form>
{#if createError}
<p class="error">{createError}</p>
{/if}
</div>
<!-- User List -->
<div class="section">
<h2>Users</h2>
<table>
<thead>
<tr>
<th>Username</th>
<th>Role</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{#each users as user}
<tr>
<td>{user.username}</td>
<td>
<span class="role-badge" class:admin={user.is_admin}>
{user.is_admin ? 'Admin' : 'User'}
</span>
</td>
<td class="actions">
<button class="btn-sm" onclick={() => startEditUser(user)}>Edit</button>
<button class="btn-sm" onclick={() => startEditPermissions(user.id)}>Permissions</button>
<button class="btn-sm btn-danger" onclick={() => deleteUser(user.id, user.username)}>Delete</button>
</td>
</tr>
<!-- Edit User Inline -->
{#if editingUserDetails === user.id}
<tr class="edit-row">
<td colspan="3">
<div class="edit-form">
<div class="field-row">
<label>New Password (leave blank to keep)</label>
<input type="password" bind:value={editPassword} placeholder="New password" />
</div>
<div class="field-row">
<label class="checkbox-label">
<input type="checkbox" bind:checked={editIsAdmin} />
Admin
</label>
</div>
{#if editError}
<p class="error">{editError}</p>
{/if}
<div class="button-row">
<button class="btn-sm" onclick={saveEditUser}>Save</button>
<button class="btn-sm" onclick={cancelEditUser}>Cancel</button>
</div>
</div>
</td>
</tr>
{/if}
<!-- Edit Permissions Inline -->
{#if editingUserId === user.id}
<tr class="edit-row">
<td colspan="3">
<div class="permissions-editor">
<h3>App Permissions for {user.username}</h3>
{#if Object.keys(allApps).length === 0}
<p class="muted">No servers paired. Pair a server first to manage app permissions.</p>
{:else}
{#each Object.entries(allApps) as [serverName, apps]}
<div class="server-group">
<h4>{serverName}</h4>
{#each apps as app}
<label class="perm-checkbox">
<input
type="checkbox"
checked={editingPermissions.has(permKey(serverName, app.id))}
onchange={() => togglePermission(serverName, app.id)}
/>
{app.title}
</label>
{/each}
</div>
{/each}
{/if}
<div class="button-row">
<button class="btn-sm" onclick={savePermissions}>Save Permissions</button>
<button class="btn-sm" onclick={cancelEditPermissions}>Cancel</button>
</div>
</div>
</td>
</tr>
{/if}
{/each}
</tbody>
</table>
</div>
{/if}
</div>
<style>
.admin-container {
max-width: 800px;
margin: 2rem auto;
padding: 0 1rem;
}
h1 {
color: #e0e0e0;
font-size: 1.5rem;
margin-bottom: 1.5rem;
}
h2 {
color: #ccc;
font-size: 1.1rem;
margin-bottom: 0.8rem;
}
h3 {
color: #ccc;
font-size: 1rem;
margin: 0 0 0.5rem 0;
}
h4 {
color: #aaa;
font-size: 0.9rem;
margin: 0.5rem 0 0.3rem 0;
}
.section {
margin-bottom: 2rem;
}
.loading, .error {
color: #aaa;
}
.error {
color: #ff4444;
font-size: 0.85rem;
}
.muted {
color: #666;
font-size: 0.85rem;
}
.create-form {
display: flex;
gap: 0.5rem;
align-items: center;
flex-wrap: wrap;
}
.create-form input[type="text"],
.create-form input[type="password"] {
padding: 0.4rem 0.6rem;
border: 1px solid #444;
border-radius: 4px;
background-color: #0f0f23;
color: #e0e0e0;
font-size: 0.9rem;
}
.create-form button {
padding: 0.4rem 1rem;
border: none;
border-radius: 4px;
background-color: #00aaff;
color: white;
cursor: pointer;
font-size: 0.9rem;
}
.create-form button:hover {
background-color: #0088cc;
}
.checkbox-label {
display: flex;
align-items: center;
gap: 0.3rem;
color: #ccc;
font-size: 0.9rem;
cursor: pointer;
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: 0.6rem 0.8rem;
text-align: left;
border-bottom: 1px solid #333;
}
th {
color: #888;
font-size: 0.8rem;
text-transform: uppercase;
font-weight: normal;
}
td {
color: #ddd;
font-size: 0.9rem;
}
.role-badge {
padding: 0.15rem 0.5rem;
border-radius: 3px;
font-size: 0.8rem;
background-color: #2a2a4e;
color: #aaa;
}
.role-badge.admin {
background-color: #1a3a2a;
color: #4ade80;
}
.actions {
display: flex;
gap: 0.3rem;
}
.btn-sm {
padding: 0.25rem 0.6rem;
border: 1px solid #444;
border-radius: 3px;
background-color: transparent;
color: #ccc;
cursor: pointer;
font-size: 0.8rem;
}
.btn-sm:hover {
background-color: #2a2a4e;
}
.btn-danger {
border-color: #662222;
color: #ff6666;
}
.btn-danger:hover {
background-color: #331111;
}
.edit-row td {
background-color: #111122;
border-bottom: 1px solid #333;
}
.edit-form, .permissions-editor {
padding: 0.5rem 0;
}
.field-row {
margin-bottom: 0.5rem;
}
.field-row label {
display: block;
color: #888;
font-size: 0.8rem;
margin-bottom: 0.2rem;
}
.field-row input[type="password"] {
padding: 0.3rem 0.5rem;
border: 1px solid #444;
border-radius: 4px;
background-color: #0f0f23;
color: #e0e0e0;
font-size: 0.85rem;
}
.button-row {
display: flex;
gap: 0.3rem;
margin-top: 0.5rem;
}
.server-group {
margin-bottom: 0.5rem;
}
.perm-checkbox {
display: flex;
align-items: center;
gap: 0.3rem;
color: #ccc;
font-size: 0.85rem;
padding: 0.15rem 0;
cursor: pointer;
}
</style>
+11 -1
View File
@@ -1,3 +1,5 @@
import { getToken, handleUnauthorized } from './stores/authStore.svelte';
export interface App {
title: string;
id: number;
@@ -12,7 +14,15 @@ export interface AppsResponse {
export async function fetchApps() {
console.log('Getting apps');
const response = await fetch('/api/apps');
const response = await fetch('/api/apps', {
headers: { 'Authorization': `Bearer ${getToken()}` }
});
if (response.status === 401) {
handleUnauthorized();
throw new Error('Unauthorized');
}
console.log(response);
const data = (await response.json()) as AppsResponse;
console.log(data);
+16 -5
View File
@@ -1,8 +1,11 @@
import { getToken, handleUnauthorized } from './stores/authStore.svelte';
type StreamData = {
Url: string,
CertHash: Array<number>,
Width: number,
Height: number,
StreamToken: string,
}
export async function getStreamData(appId: number, server_name: string): Promise<StreamData> {
@@ -34,10 +37,16 @@ export async function getStreamData(appId: number, server_name: string): Promise
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${getToken()}`,
},
body: JSON.stringify(payload)
});
if (response.status === 401) {
handleUnauthorized();
throw new Error('Unauthorized');
}
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}: ${await response.text()}`);
}
@@ -45,15 +54,17 @@ export async function getStreamData(appId: number, server_name: string): Promise
const streamDataResp = await response.json();
console.log('Stream started:', streamDataResp);
let streamData: StreamData = { Url: streamDataResp.url, CertHash: streamDataResp.cert_hash, Width: width, Height: height };
let streamData: StreamData = {
Url: streamDataResp.url,
CertHash: streamDataResp.cert_hash,
Width: width,
Height: height,
StreamToken: streamDataResp.stream_token,
};
return streamData;
} catch (error) {
console.error('Error getting stream data: ', error);
throw new Error('Failed to start stream: ' + error);
}
}
@@ -3,4 +3,5 @@ export const streamStore = $state({
CertHash: [0],
Width: 0,
Height: 0,
StreamToken: '',
});
+2 -3
View File
@@ -6,6 +6,7 @@
$: certHash = streamStore.CertHash;
$: width = streamStore.Width;
$: height = streamStore.Height;
$: streamToken = streamStore.StreamToken;
</script>
<svelte:head>
@@ -13,9 +14,7 @@
<meta name="description" content="Streaming game" />
</svelte:head>
<!--<section>
</section>-->
<Stream {url} {certHash} {width} {height} />
<Stream {url} {certHash} {width} {height} {streamToken} />
<style>
section {
+5 -2
View File
@@ -8,17 +8,20 @@
certHash: Array<number>;
width: number;
height: number;
streamToken: string;
}
let { url, certHash, width, height }: Props = $props();
let { url, certHash, width, height, streamToken }: Props = $props();
let loading = $state(true);
let fullscreen = $state(false);
let gameplayView: HTMLDivElement;
let gameplayCanvas: HTMLCanvasElement;
async function startStream() {
// Append stream token to URL for proxy authentication
const authenticatedUrl = url + (url.includes('?') ? '&' : '?') + 'token=' + encodeURIComponent(streamToken);
await startWebtransportStream(
url,
authenticatedUrl,
certHash,
width,
height,