settings + reinvite players to lobby

This commit is contained in:
2026-02-28 05:49:56 +01:00
parent f4b94597c7
commit 90396b5338
32 changed files with 1000 additions and 268 deletions

11
src/app.d.ts vendored
View File

@@ -1,15 +1,18 @@
// src/app.d.ts
import type { User, Session } from 'better-auth/minimal';
// See https://svelte.dev/docs/kit/types#app.d.ts
// for information about these interfaces
declare global {
namespace App {
interface Locals {
user?: User;
user?: User & { role: string };
session?: Session;
}
// interface Error {}
interface Error {
message: string;
code?: string;
}
// interface PageData {}
// interface PageState {}
// interface Platform {}

View File

@@ -1,14 +1,27 @@
// src/hooks.server.ts
import type { Handle } from '@sveltejs/kit';
import { building } from '$app/environment';
import { auth } from '$lib/server/auth';
import { svelteKitHandler } from 'better-auth/svelte-kit';
import { db } from '$lib/server/db';
import { user as userTable } from '$lib/server/db/auth.schema';
import { eq } from 'drizzle-orm';
const handleBetterAuth: Handle = async ({ event, resolve }) => {
const session = await auth.api.getSession({ headers: event.request.headers });
if (session) {
event.locals.session = session.session;
event.locals.user = session.user;
// Load fresh role from DB (better-auth doesn't include custom columns)
const dbUser = await db.query.user.findFirst({
where: eq(userTable.id, session.user.id)
});
event.locals.user = {
...session.user,
role: dbUser?.role ?? 'player'
};
}
return svelteKitHandler({ event, resolve, auth, building });

View File

@@ -1,7 +1,15 @@
<script lang="ts">
import { page } from '$app/state';
import { enhance } from '$app/forms';
const user = $derived(page.data?.user);
const roleBadge: Record<string, { label: string; color: string }> = {
referee: { label: 'REF', color: 'bg-yellow-500/20 text-yellow-400' },
admin: { label: 'ADMIN', color: 'bg-red-500/20 text-red-400' }
};
const badge = $derived(user?.role ? roleBadge[user.role] : null);
</script>
<header
@@ -12,14 +20,27 @@
<div class="flex items-center gap-4">
{#if user}
<div class="flex items-center gap-3">
{#if badge}
<span class="rounded px-1.5 py-0.5 text-[10px] font-700 {badge.color}">
{badge.label}
</span>
{/if}
{#if user.image}
<img src={user.image} alt={user.name} class="h-7 w-7 rounded-full" />
{/if}
<span class="font-500 text-sm text-text-primary">{user.name}</span>
<form method="post" action="/settings?/logout" use:enhance>
<button
type="submit"
class="rounded-md border border-border px-2.5 py-1 text-xs text-text-secondary transition-colors hover:border-red-500/30 hover:text-red-400"
>
Logout
</button>
</form>
</div>
{:else}
<a
href="/api/auth/osu/login"
href="/login"
class="font-600 rounded-md bg-accent px-3.5 py-1.5 text-sm text-surface-900 transition-colors hover:bg-accent-hover"
>
Sign in with osu!

View File

@@ -1,6 +1,8 @@
<script lang="ts">
import { page } from '$app/state';
const user = $derived(page.data?.user);
const nav = [
{ href: '/', label: 'Dashboard', icon: '⌂' },
{ href: '/matches', label: 'Matches', icon: '⚔' },
@@ -12,6 +14,9 @@
if (href === '/') return page.url.pathname === '/';
return page.url.pathname.startsWith(href);
}
const isStaff = $derived(user?.role === 'referee' || user?.role === 'admin');
const isAdmin = $derived(user?.role === 'admin');
</script>
<aside
@@ -42,13 +47,34 @@
{item.label}
</a>
{/each}
{#if isAdmin}
<div class="mt-4 mb-1 px-3">
<p class="text-[10px] font-600 text-text-secondary uppercase tracking-widest">Staff</p>
</div>
<a
href="/admin"
class="font-500 flex items-center gap-3 rounded-md px-3 py-2 text-sm transition-colors {isActive(
'/admin'
)
? 'bg-red-500/10 text-red-400'
: 'text-text-secondary hover:bg-surface-700 hover:text-text-primary'}"
>
<span class="text-base">⚡</span>
Admin
</a>
{/if}
</nav>
<!-- Bottom -->
<div class="border-t border-border p-3">
<a
href="/settings"
class="font-500 flex items-center gap-3 rounded-md px-3 py-2 text-sm text-text-secondary transition-colors hover:bg-surface-700 hover:text-text-primary"
class="font-500 flex items-center gap-3 rounded-md px-3 py-2 text-sm text-text-secondary transition-colors hover:bg-surface-700 hover:text-text-primary {isActive(
'/settings'
)
? 'bg-accent-dim text-accent'
: ''}"
>
<span class="text-base">⚙</span>
Settings

View File

@@ -1,3 +1,4 @@
// src/lib/server/auth.ts
import { betterAuth } from 'better-auth/minimal';
import { drizzleAdapter } from 'better-auth/adapters/drizzle';
import { sveltekitCookies } from 'better-auth/svelte-kit';
@@ -48,7 +49,8 @@ export const auth = betterAuth({
scopes: ['identify', 'public'],
pkce: false,
authentication: 'post',
redirectURI: 'http://localhost:5173/api/auth/oauth2/callback/osu',
// ── FIX: Use ORIGIN env var instead of hardcoded localhost ──
redirectURI: `${env.ORIGIN}/api/auth/oauth2/callback/osu`,
getToken: async ({ code, redirectURI }) => {
const res = await fetch('https://osu.ppy.sh/oauth/token', {
method: 'POST',
@@ -87,6 +89,6 @@ export const auth = betterAuth({
}
]
}),
sveltekitCookies(getRequestEvent) // make sure this is the last plugin in the array
sveltekitCookies(getRequestEvent) // must be last
]
});

View File

@@ -1,93 +1,96 @@
import { relations } from "drizzle-orm";
import { pgTable, text, timestamp, boolean, index } from "drizzle-orm/pg-core";
// src/lib/server/db/auth.schema.ts
import { relations } from 'drizzle-orm';
import { pgTable, text, timestamp, boolean, index } from 'drizzle-orm/pg-core';
export const user = pgTable("user", {
id: text("id").primaryKey(),
name: text("name").notNull(),
email: text("email").notNull().unique(),
emailVerified: boolean("email_verified").default(false).notNull(),
image: text("image"),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at")
export const user = pgTable('user', {
id: text('id').primaryKey(),
name: text('name').notNull(),
email: text('email').notNull().unique(),
emailVerified: boolean('email_verified').default(false).notNull(),
image: text('image'),
// ── Staff role: 'player' | 'referee' | 'admin' ──
role: text('role').default('player').notNull(),
createdAt: timestamp('created_at').defaultNow().notNull(),
updatedAt: timestamp('updated_at')
.defaultNow()
.$onUpdate(() => /* @__PURE__ */ new Date())
.notNull(),
.$onUpdate(() => new Date())
.notNull()
});
export const session = pgTable(
"session",
'session',
{
id: text("id").primaryKey(),
expiresAt: timestamp("expires_at").notNull(),
token: text("token").notNull().unique(),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at")
.$onUpdate(() => /* @__PURE__ */ new Date())
id: text('id').primaryKey(),
expiresAt: timestamp('expires_at').notNull(),
token: text('token').notNull().unique(),
createdAt: timestamp('created_at').defaultNow().notNull(),
updatedAt: timestamp('updated_at')
.$onUpdate(() => new Date())
.notNull(),
ipAddress: text("ip_address"),
userAgent: text("user_agent"),
userId: text("user_id")
ipAddress: text('ip_address'),
userAgent: text('user_agent'),
userId: text('user_id')
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
.references(() => user.id, { onDelete: 'cascade' })
},
(table) => [index("session_userId_idx").on(table.userId)],
(table) => [index('session_userId_idx').on(table.userId)]
);
export const account = pgTable(
"account",
'account',
{
id: text("id").primaryKey(),
accountId: text("account_id").notNull(),
providerId: text("provider_id").notNull(),
userId: text("user_id")
id: text('id').primaryKey(),
accountId: text('account_id').notNull(),
providerId: text('provider_id').notNull(),
userId: text('user_id')
.notNull()
.references(() => user.id, { onDelete: 'cascade' }),
accessToken: text('access_token'),
refreshToken: text('refresh_token'),
idToken: text('id_token'),
accessTokenExpiresAt: timestamp('access_token_expires_at'),
refreshTokenExpiresAt: timestamp('refresh_token_expires_at'),
scope: text('scope'),
password: text('password'),
createdAt: timestamp('created_at').defaultNow().notNull(),
updatedAt: timestamp('updated_at')
.$onUpdate(() => new Date())
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
accessToken: text("access_token"),
refreshToken: text("refresh_token"),
idToken: text("id_token"),
accessTokenExpiresAt: timestamp("access_token_expires_at"),
refreshTokenExpiresAt: timestamp("refresh_token_expires_at"),
scope: text("scope"),
password: text("password"),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at")
.$onUpdate(() => /* @__PURE__ */ new Date())
.notNull(),
},
(table) => [index("account_userId_idx").on(table.userId)],
(table) => [index('account_userId_idx').on(table.userId)]
);
export const verification = pgTable(
"verification",
'verification',
{
id: text("id").primaryKey(),
identifier: text("identifier").notNull(),
value: text("value").notNull(),
expiresAt: timestamp("expires_at").notNull(),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at")
id: text('id').primaryKey(),
identifier: text('identifier').notNull(),
value: text('value').notNull(),
expiresAt: timestamp('expires_at').notNull(),
createdAt: timestamp('created_at').defaultNow().notNull(),
updatedAt: timestamp('updated_at')
.defaultNow()
.$onUpdate(() => /* @__PURE__ */ new Date())
.notNull(),
.$onUpdate(() => new Date())
.notNull()
},
(table) => [index("verification_identifier_idx").on(table.identifier)],
(table) => [index('verification_identifier_idx').on(table.identifier)]
);
export const userRelations = relations(user, ({ many }) => ({
sessions: many(session),
accounts: many(account),
accounts: many(account)
}));
export const sessionRelations = relations(session, ({ one }) => ({
user: one(user, {
fields: [session.userId],
references: [user.id],
}),
references: [user.id]
})
}));
export const accountRelations = relations(account, ({ one }) => ({
user: one(user, {
fields: [account.userId],
references: [user.id],
}),
references: [user.id]
})
}));

View File

@@ -1,3 +1,8 @@
// src/lib/server/db/schema.ts
//
// CHANGE: Add `role` column to user table in auth.schema.ts (see that file).
// This file adds the permission helper utilities.
import {
pgTable,
integer,

View File

@@ -1,12 +1,13 @@
// src/lib/server/osu/api.ts
import { env } from '$env/dynamic/private';
import { db } from '$lib/server/db';
import { and, eq } from 'drizzle-orm';
import { account } from '$lib/server/db/auth.schema';
import { getCached, setCache } from './cache';
let clientToken: string | null = null;
let clientTokenExpiresAt = 0;
// Client credentials token (no user needed, for public endpoints)
async function getClientToken(): Promise<string> {
if (clientToken && Date.now() < clientTokenExpiresAt - 60_000) {
return clientToken;
@@ -36,7 +37,6 @@ async function getClientToken(): Promise<string> {
return clientToken!;
}
// Get a user's access token (for user-scoped endpoints)
async function getUserToken(userId: string): Promise<string | null> {
const acc = await db.query.account.findFirst({
where: and(eq(account.userId, userId), eq(account.providerId, 'osu'))
@@ -44,7 +44,6 @@ async function getUserToken(userId: string): Promise<string | null> {
if (!acc?.accessToken) return null;
// Check if expired and refresh if needed
if (acc.accessTokenExpiresAt && acc.accessTokenExpiresAt < new Date()) {
if (!acc.refreshToken) return null;
@@ -94,18 +93,36 @@ async function osuFetch(path: string, token?: string) {
return res.json();
}
// ── Public API ──────────────────────────────────────────────────────────
// ── Public API (with caching) ───────────────────────────────────────────
export async function getBeatmap(beatmapId: string | number) {
return osuFetch(`/beatmaps/${beatmapId}`);
const cacheKey = `beatmap:${beatmapId}`;
const cached = getCached(cacheKey);
if (cached) return cached;
const data = await osuFetch(`/beatmaps/${beatmapId}`);
setCache(cacheKey, data);
return data;
}
export async function getBeatmapset(beatmapsetId: string | number) {
return osuFetch(`/beatmapsets/${beatmapsetId}`);
const cacheKey = `beatmapset:${beatmapsetId}`;
const cached = getCached(cacheKey);
if (cached) return cached;
const data = await osuFetch(`/beatmapsets/${beatmapsetId}`);
setCache(cacheKey, data);
return data;
}
export async function getUser(userId: string | number) {
return osuFetch(`/users/${userId}`);
const cacheKey = `osu_user:${userId}`;
const cached = getCached(cacheKey);
if (cached) return cached;
const data = await osuFetch(`/users/${userId}`);
setCache(cacheKey, data, 5 * 60 * 1000); // 5 min for user data
return data;
}
export async function getUserScores(

View File

@@ -0,0 +1,42 @@
// src/lib/server/osu/cache.ts
//
// Simple in-memory cache for osu! beatmap metadata.
// TTL: 10 minutes. Max entries: 500.
// Avoids hammering the osu! API on every page load.
interface CacheEntry<T> {
data: T;
expiresAt: number;
}
const CACHE_TTL = 10 * 60 * 1000; // 10 minutes
const MAX_ENTRIES = 500;
const cache = new Map<string, CacheEntry<any>>();
export function getCached<T>(key: string): T | null {
const entry = cache.get(key);
if (!entry) return null;
if (Date.now() > entry.expiresAt) {
cache.delete(key);
return null;
}
return entry.data as T;
}
export function setCache<T>(key: string, data: T, ttl = CACHE_TTL): void {
// Evict oldest entries if at capacity
if (cache.size >= MAX_ENTRIES) {
const firstKey = cache.keys().next().value;
if (firstKey) cache.delete(firstKey);
}
cache.set(key, { data, expiresAt: Date.now() + ttl });
}
export function invalidateCache(key: string): void {
cache.delete(key);
}
export function clearCache(): void {
cache.clear();
}

View File

@@ -0,0 +1,56 @@
// src/lib/server/permissions.ts
import { error } from '@sveltejs/kit';
import { db } from '$lib/server/db';
import { user } from '$lib/server/db/auth.schema';
import { eq } from 'drizzle-orm';
export type UserRole = 'player' | 'referee' | 'admin';
const ROLE_HIERARCHY: Record<UserRole, number> = {
player: 0,
referee: 1,
admin: 2
};
/**
* Check if a role meets the minimum required level.
*/
export function hasRole(userRole: string | undefined, minRole: UserRole): boolean {
const level = ROLE_HIERARCHY[userRole as UserRole] ?? 0;
const required = ROLE_HIERARCHY[minRole];
return level >= required;
}
/**
* Throw 403 if user doesn't have the required role.
* Use in +page.server.ts load/actions.
*/
export function requireRole(
locals: App.Locals,
minRole: UserRole,
message = 'Insufficient permissions'
) {
if (!locals.user) {
error(401, 'Not logged in');
}
if (!hasRole(locals.user.role, minRole)) {
error(403, message);
}
}
/**
* Promote/demote a user's global role. Only admins can do this.
*/
export async function setUserRole(userId: string, role: UserRole) {
await db.update(user).set({ role }).where(eq(user.id, userId));
}
/**
* Get a user's role from the database (for fresh reads).
*/
export async function getUserRole(userId: string): Promise<UserRole> {
const u = await db.query.user.findFirst({
where: eq(user.id, userId)
});
return (u?.role as UserRole) ?? 'player';
}

View File

@@ -1,7 +1,16 @@
import type { LayoutServerLoad } from "./$types";
// src/routes/(app)/+layout.server.ts
import type { LayoutServerLoad } from './$types';
export const load: LayoutServerLoad = async ({ locals }) => {
return {
user: locals.user ?? null
user: locals.user
? {
id: locals.user.id,
name: locals.user.name,
email: locals.user.email,
image: locals.user.image,
role: locals.user.role ?? 'player'
}
: null
};
};

View File

@@ -2,11 +2,16 @@
import './layout.css';
import Sidebar from '$lib/components/Sidebar.svelte';
import Header from '$lib/components/Header.svelte';
import { page } from '$app/state';
let { children } = $props();
const user = $derived(page.data?.user);
</script>
<div class="flex min-h-dvh">
{#if user}
<!-- Authenticated layout with sidebar -->
<div class="flex min-h-dvh">
<Sidebar />
<div class="ml-56 flex flex-1 flex-col">
<Header />
@@ -14,4 +19,30 @@
{@render children()}
</main>
</div>
</div>
</div>
{:else}
<!-- Unauthenticated: clean layout, no sidebar -->
<div class="min-h-dvh">
<header
class="flex h-14 items-center justify-between border-b border-border bg-surface-900/80 px-6 backdrop-blur-md"
>
<a href="/" class="flex items-center gap-2.5">
<div
class="font-800 flex h-8 w-8 items-center justify-center rounded-md bg-accent text-sm text-surface-900"
>
V
</div>
<span class="font-700 text-base tracking-tight text-text-primary">Vash Esports</span>
</a>
<a
href="/login"
class="font-600 rounded-md bg-accent px-3.5 py-1.5 text-sm text-surface-900 transition-colors hover:bg-accent-hover"
>
Sign in with osu!
</a>
</header>
<main class="p-6">
{@render children()}
</main>
</div>
{/if}

View File

@@ -1,26 +1,32 @@
// src/routes/(app)/+page.server.ts
import { db } from '$lib/server/db';
import { match, team, mappool } from '$lib/server/db/schema';
import { eq, desc, count, and, inArray } from 'drizzle-orm';
import { redirect } from '@sveltejs/kit';
import { eq, desc, count, inArray } from 'drizzle-orm';
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ locals }) => {
if (!locals.user) redirect(302, '/');
// ── NOT LOGGED IN → landing page (no redirect loop!) ──
if (!locals.user) {
return {
authenticated: false as const,
recentMatches: [],
liveMatches: [],
stats: { matches: 0, finished: 0, teams: 0, mappools: 0 }
};
}
// Recent matches (last 5)
// ── LOGGED IN → dashboard data ──
const recentMatches = await db.query.match.findMany({
with: { participants: { with: { team: true } } },
orderBy: desc(match.createdAt),
limit: 5
});
// Live matches
const liveMatches = await db.query.match.findMany({
with: { participants: { with: { team: true } } },
where: inArray(match.state, ['LOBBY', 'ROLLING', 'PICKING', 'PLAYING'])
});
// Counts
const [matchCount] = await db.select({ count: count() }).from(match);
const [teamCount] = await db.select({ count: count() }).from(team);
const [poolCount] = await db.select({ count: count() }).from(mappool);
@@ -30,6 +36,7 @@ export const load: PageServerLoad = async ({ locals }) => {
.where(eq(match.state, 'FINISHED'));
return {
authenticated: true as const,
recentMatches,
liveMatches,
stats: {

View File

@@ -26,21 +26,44 @@
}
</script>
<div class="mx-auto max-w-5xl">
<!-- Welcome -->
<!-- ── LANDING PAGE (not logged in) ── -->
{#if !data.user}
<div class="flex min-h-[70vh] flex-col items-center justify-center text-center">
<div
class="font-800 mb-6 flex h-16 w-16 items-center justify-center rounded-xl bg-accent text-2xl text-surface-900"
>
V
</div>
<h1 class="text-4xl font-800 tracking-tight">
Welcome to <span class="text-accent">Vash Esports</span>
</h1>
<p class="mt-3 max-w-md text-text-secondary">
Automated tournament match management for osu! — lobbies, mappools, picks, bans, and
ELO tracking all in one place.
</p>
<a
href="/login"
class="font-600 mt-8 rounded-lg bg-accent px-6 py-3 text-surface-900 transition-colors hover:bg-accent-hover"
>
Sign in with osu!
</a>
<p class="mt-4 text-xs text-text-secondary">
Uses your osu! account. No extra registration needed.
</p>
</div>
<!-- ── DASHBOARD (logged in) ── -->
{:else}
<div class="mx-auto max-w-5xl">
<div>
<h1 class="text-2xl font-700 tracking-tight">
{#if data.user}
Welcome back, <span class="text-accent">{data.user.name}</span>
{:else}
Welcome to <span class="text-accent">VASH</span>
{/if}
</h1>
<p class="mt-1 text-sm text-text-secondary">Automated esports match management for osu!</p>
</div>
<!-- Stats -->
<div class="mt-6 grid grid-cols-4 gap-3">
<div class="mt-6 grid grid-cols-2 gap-3 sm:grid-cols-4">
<div class="rounded-lg border border-border bg-surface-800 p-4">
<p class="text-2xl font-800 tabular-nums text-text-primary">{data.stats.matches}</p>
<p class="mt-1 text-xs text-text-secondary">Total Matches</p>
@@ -107,16 +130,18 @@
</div>
{/if}
<div class="mt-8 grid grid-cols-3 gap-4">
<div class="mt-8 grid gap-4 lg:grid-cols-3">
<!-- Quick Actions -->
<div class="col-span-1">
<div class="lg:col-span-1">
<h2 class="text-sm font-600">Quick Actions</h2>
<div class="mt-3 flex flex-col gap-2">
<a
href="/matches"
class="flex items-center gap-3 rounded-lg border border-border bg-surface-800 p-3 transition-colors hover:border-accent/40 hover:bg-surface-700"
>
<span class="flex h-8 w-8 items-center justify-center rounded-md bg-accent/10 text-accent">⚔</span>
<span class="flex h-8 w-8 items-center justify-center rounded-md bg-accent/10 text-accent"
>⚔</span
>
<div>
<p class="text-sm font-600">New Match</p>
<p class="text-xs text-text-secondary">Start a 1v1</p>
@@ -126,7 +151,10 @@
href="/mappools"
class="flex items-center gap-3 rounded-lg border border-border bg-surface-800 p-3 transition-colors hover:border-accent/40 hover:bg-surface-700"
>
<span class="flex h-8 w-8 items-center justify-center rounded-md bg-purple-500/10 text-purple-400">♫</span>
<span
class="flex h-8 w-8 items-center justify-center rounded-md bg-purple-500/10 text-purple-400"
>♫</span
>
<div>
<p class="text-sm font-600">Mappools</p>
<p class="text-xs text-text-secondary">Build a pool</p>
@@ -136,7 +164,10 @@
href="/teams"
class="flex items-center gap-3 rounded-lg border border-border bg-surface-800 p-3 transition-colors hover:border-accent/40 hover:bg-surface-700"
>
<span class="flex h-8 w-8 items-center justify-center rounded-md bg-blue-500/10 text-blue-400">⚑</span>
<span
class="flex h-8 w-8 items-center justify-center rounded-md bg-blue-500/10 text-blue-400"
>⚑</span
>
<div>
<p class="text-sm font-600">Teams</p>
<p class="text-xs text-text-secondary">Manage rosters</p>
@@ -146,7 +177,7 @@
</div>
<!-- Recent Activity -->
<div class="col-span-2">
<div class="lg:col-span-2">
<h2 class="text-sm font-600">Recent Matches</h2>
<div class="mt-3 flex flex-col gap-2">
{#each data.recentMatches as m}
@@ -162,9 +193,17 @@
<div class="flex items-center gap-2">
<span class="text-sm font-600">{p1?.team.name ?? '?'}</span>
{#if m.state === 'FINISHED'}
<span class="text-xs font-700 tabular-nums {(p1?.score ?? 0) > (p2?.score ?? 0) ? 'text-green-400' : 'text-text-secondary'}">{p1?.score ?? 0}</span>
<span
class="text-xs font-700 tabular-nums {(p1?.score ?? 0) > (p2?.score ?? 0)
? 'text-green-400'
: 'text-text-secondary'}">{p1?.score ?? 0}</span
>
<span class="text-xs text-text-secondary">-</span>
<span class="text-xs font-700 tabular-nums {(p2?.score ?? 0) > (p1?.score ?? 0) ? 'text-green-400' : 'text-text-secondary'}">{p2?.score ?? 0}</span>
<span
class="text-xs font-700 tabular-nums {(p2?.score ?? 0) > (p1?.score ?? 0)
? 'text-green-400'
: 'text-text-secondary'}">{p2?.score ?? 0}</span
>
{:else}
<span class="text-xs text-text-secondary">vs</span>
{/if}
@@ -185,10 +224,13 @@
</a>
{:else}
<div class="rounded-lg border border-dashed border-border py-8 text-center">
<p class="text-sm text-text-secondary">No matches yet. <a href="/matches" class="text-accent hover:underline">Create one</a></p>
<p class="text-sm text-text-secondary">
No matches yet. <a href="/matches" class="text-accent hover:underline">Create one</a>
</p>
</div>
{/each}
</div>
</div>
</div>
</div>
</div>
{/if}

View File

@@ -0,0 +1,61 @@
// src/routes/(app)/admin/+page.server.ts
import { db } from '$lib/server/db';
import { user } from '$lib/server/db/auth.schema';
import { playerRating } from '$lib/server/db/schema';
import { eq, desc } from 'drizzle-orm';
import { redirect, error } from '@sveltejs/kit';
import { requireRole, setUserRole } from '$lib/server/permissions';
import type { PageServerLoad, Actions } from './$types';
export const load: PageServerLoad = async ({ locals }) => {
requireRole(locals, 'admin');
const users = await db.query.user.findMany({
orderBy: desc(user.createdAt)
});
// Fetch ratings for all users
const usersWithRatings = await Promise.all(
users.map(async (u) => {
const rating = await db.query.playerRating.findFirst({
where: eq(playerRating.userId, u.id)
});
return {
id: u.id,
name: u.name,
email: u.email,
image: u.image,
role: u.role ?? 'player',
createdAt: u.createdAt,
elo: rating?.elo ?? 1000,
wins: rating?.wins ?? 0,
losses: rating?.losses ?? 0
};
})
);
return { users: usersWithRatings };
};
export const actions: Actions = {
setRole: async ({ request, locals }) => {
requireRole(locals, 'admin');
const form = await request.formData();
const userId = form.get('userId')?.toString();
const role = form.get('role')?.toString();
if (!userId || !role) return { error: 'User ID and role are required' };
if (!['player', 'referee', 'admin'].includes(role)) {
return { error: 'Invalid role' };
}
// Prevent demoting yourself
if (userId === locals.user!.id && role !== 'admin') {
return { error: "You can't demote yourself" };
}
await setUserRole(userId, role as any);
return { success: true };
}
};

View File

@@ -0,0 +1,103 @@
<script lang="ts">
import { enhance } from '$app/forms';
let { data } = $props();
let actionError = $state('');
const roleBadge: Record<string, { label: string; color: string }> = {
player: { label: 'Player', color: 'bg-surface-600 text-text-secondary border-border' },
referee: {
label: 'Referee',
color: 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30'
},
admin: { label: 'Admin', color: 'bg-red-500/20 text-red-400 border-red-500/30' }
};
</script>
<div class="mx-auto max-w-4xl">
<div>
<h1 class="text-2xl font-700 tracking-tight">Admin Panel</h1>
<p class="mt-1 text-sm text-text-secondary">
{data.users.length} registered user{data.users.length !== 1 ? 's' : ''}
</p>
</div>
{#if actionError}
<p class="mt-3 text-sm text-red-400">{actionError}</p>
{/if}
<!-- Users Table -->
<div class="mt-6 rounded-lg border border-border bg-surface-800">
<div class="grid grid-cols-[auto_1fr_auto_auto_auto] gap-4 border-b border-border px-4 py-3">
<span class="text-xs font-600 text-text-secondary">Avatar</span>
<span class="text-xs font-600 text-text-secondary">User</span>
<span class="text-xs font-600 text-text-secondary">ELO</span>
<span class="text-xs font-600 text-text-secondary">W/L</span>
<span class="text-xs font-600 text-text-secondary">Role</span>
</div>
{#each data.users as u}
{@const badge = roleBadge[u.role] ?? roleBadge.player}
<div
class="grid grid-cols-[auto_1fr_auto_auto_auto] items-center gap-4 border-b border-border/50 px-4 py-3 last:border-b-0"
>
<!-- Avatar -->
{#if u.image}
<img src={u.image} alt="" class="h-8 w-8 rounded-full" />
{:else}
<div
class="flex h-8 w-8 items-center justify-center rounded-full bg-surface-600 text-xs font-700 text-text-secondary"
>
{u.name.charAt(0).toUpperCase()}
</div>
{/if}
<!-- Name -->
<div class="min-w-0">
<p class="truncate text-sm font-500">{u.name}</p>
<p class="truncate text-xs text-text-secondary">{u.email}</p>
</div>
<!-- ELO -->
<span class="text-sm font-600 tabular-nums text-text-primary">{u.elo}</span>
<!-- W/L -->
<span class="text-xs tabular-nums text-text-secondary">
<span class="text-green-400">{u.wins}W</span> /
<span class="text-red-400">{u.losses}L</span>
</span>
<!-- Role selector -->
<form
method="post"
action="?/setRole"
use:enhance={() => {
actionError = '';
return async ({ result }) => {
if (
result.type === 'failure' ||
(result.type === 'success' && (result.data as any)?.error)
) {
actionError = (result.data as any)?.error ?? 'Failed to update role';
}
};
}}
class="flex items-center gap-2"
>
<input type="hidden" name="userId" value={u.id} />
<select
name="role"
value={u.role}
onchange={(e) => e.currentTarget.form?.requestSubmit()}
class="rounded-md border px-2 py-1 text-xs font-500 {badge.color} cursor-pointer bg-transparent focus:outline-none"
>
<option value="player" class="bg-surface-800 text-text-primary">Player</option>
<option value="referee" class="bg-surface-800 text-text-primary">Referee</option>
<option value="admin" class="bg-surface-800 text-text-primary">Admin</option>
</select>
</form>
</div>
{/each}
</div>
</div>

View File

@@ -67,9 +67,11 @@
action="?/createMatch"
use:enhance={() => {
createError = '';
return async ({ result }) => {
return async ({ result, update }) => {
if (result.type === 'failure' || (result.type === 'success' && (result.data as any)?.error)) {
createError = (result.data as any)?.error ?? 'Failed to create match';
} else {
await update();
}
};
}}

View File

@@ -1,9 +1,13 @@
import { user } from '$lib/server/db/schema';
import { db } from '$lib/server/db';
import { getMatchFull, submitRoll, pickMap, cancelMatch } from '$lib/server/match/engine';
import { playPickedMap, closeLobby, forceStartGame } from '$lib/server/match/orchestrator';
import { getLobby } from '$lib/server/bancho/client';
import { error, redirect } from '@sveltejs/kit';
import { getBeatmap } from '$lib/server/osu/api';
import type { PageServerLoad, Actions } from './$types';
import { eq } from 'drizzle-orm';
export const load: PageServerLoad = async ({ params, locals }) => {
if (!locals.user) redirect(302, '/');
@@ -41,6 +45,28 @@ export const load: PageServerLoad = async ({ params, locals }) => {
};
export const actions: Actions = {
reinvite: async ({ params, locals }) => {
if (!locals.user) redirect(302, '/');
const lobby = getLobby(params.id);
if (!lobby) return { error: 'No active IRC lobby for this match' };
const m = await getMatchFull(params.id);
const invited: string[] = [];
for (const p of m.participants) {
for (const pl of p.players) {
const u = await db.query.user.findFirst({ where: eq(user.id, pl.userId) });
if (u?.name) {
await lobby.invite(u.name);
invited.push(u.name);
}
}
}
return { reinvited: invited };
},
roll: async ({ params, locals }) => {
if (!locals.user) redirect(302, '/');

View File

@@ -136,6 +136,27 @@
</div>
{/if}
<!-- Re-invite players -->
{#if ['LOBBY', 'ROLLING', 'PICKING', 'PLAYING'].includes(m.state)}
<div class="mt-3 flex justify-center">
<form method="post" action="?/reinvite" use:enhance={() => {
return async ({ result, update }) => {
if (result.type === 'success' && (result.data as any)?.reinvited) {
// Brief visual feedback — just reload
await update();
}
};
}}>
<button
type="submit"
class="rounded-md border border-border px-3 py-1.5 text-xs text-text-secondary transition-colors hover:border-accent/40 hover:text-accent"
>
📨 Re-invite players to lobby
</button>
</form>
</div>
{/if}
<!-- ROLLING MODAL -->
{#if m.state === 'ROLLING'}
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm">

View File

@@ -0,0 +1,46 @@
// src/routes/(app)/settings/+page.server.ts
import { redirect } from '@sveltejs/kit';
import { auth } from '$lib/server/auth';
import { db } from '$lib/server/db';
import { playerRating } from '$lib/server/db/schema';
import { account } from '$lib/server/db/auth.schema';
import { eq, and } from 'drizzle-orm';
import type { PageServerLoad, Actions } from './$types';
export const load: PageServerLoad = async ({ locals }) => {
if (!locals.user) redirect(302, '/');
// Get player rating
const rating = await db.query.playerRating.findFirst({
where: eq(playerRating.userId, locals.user.id)
});
// Get linked osu! account info
const osuAccount = await db.query.account.findFirst({
where: and(eq(account.userId, locals.user.id), eq(account.providerId, 'osu'))
});
return {
profile: {
id: locals.user.id,
name: locals.user.name,
email: locals.user.email,
image: locals.user.image,
role: locals.user.role ?? 'player',
createdAt: locals.user.createdAt
},
rating: rating
? { elo: rating.elo, wins: rating.wins, losses: rating.losses }
: { elo: 1000, wins: 0, losses: 0 },
hasOsuLinked: !!osuAccount
};
};
export const actions: Actions = {
logout: async (event) => {
await auth.api.signOut({
headers: event.request.headers
});
redirect(302, '/');
}
};

View File

@@ -0,0 +1,114 @@
<script lang="ts">
import { enhance } from '$app/forms';
let { data } = $props();
const roleBadge: Record<string, { label: string; color: string }> = {
player: { label: 'Player', color: 'bg-surface-600 text-text-secondary' },
referee: { label: 'Referee', color: 'bg-yellow-500/20 text-yellow-400' },
admin: { label: 'Admin', color: 'bg-red-500/20 text-red-400' }
};
const badge = $derived(roleBadge[data.profile.role] ?? roleBadge.player);
const winRate = $derived(
data.rating.wins + data.rating.losses > 0
? ((data.rating.wins / (data.rating.wins + data.rating.losses)) * 100).toFixed(1)
: '—'
);
</script>
<div class="mx-auto max-w-2xl">
<h1 class="text-2xl font-700 tracking-tight">Settings</h1>
<p class="mt-1 text-sm text-text-secondary">Your profile and account settings</p>
<!-- Profile Card -->
<div class="mt-6 rounded-lg border border-border bg-surface-800 p-6">
<div class="flex items-center gap-4">
{#if data.profile.image}
<img src={data.profile.image} alt={data.profile.name} class="h-16 w-16 rounded-full" />
{:else}
<div
class="flex h-16 w-16 items-center justify-center rounded-full bg-surface-600 text-xl font-700 text-text-secondary"
>
{data.profile.name.charAt(0).toUpperCase()}
</div>
{/if}
<div class="flex-1">
<div class="flex items-center gap-2">
<h2 class="text-lg font-700">{data.profile.name}</h2>
<span class="rounded px-2 py-0.5 text-xs font-600 {badge.color}">
{badge.label}
</span>
</div>
<p class="mt-0.5 text-sm text-text-secondary">{data.profile.email}</p>
</div>
</div>
<!-- Connected Accounts -->
<div class="mt-6 border-t border-border pt-4">
<h3 class="text-xs font-600 text-text-secondary uppercase tracking-wider">Connected Accounts</h3>
<div class="mt-3 flex items-center gap-3 rounded-md bg-surface-700 px-4 py-3">
<span class="text-lg">🎮</span>
<div class="flex-1">
<p class="text-sm font-500">osu!</p>
<p class="text-xs text-text-secondary">
{#if data.hasOsuLinked}
Connected as {data.profile.name}
{:else}
Not connected
{/if}
</p>
</div>
{#if data.hasOsuLinked}
<span class="rounded bg-green-500/20 px-2 py-0.5 text-xs font-500 text-green-400">Linked</span>
{:else}
<a
href="/api/auth/osu/login"
class="rounded bg-accent px-3 py-1 text-xs font-600 text-surface-900 hover:bg-accent-hover"
>
Connect
</a>
{/if}
</div>
</div>
</div>
<!-- Stats Card -->
<div class="mt-4 rounded-lg border border-border bg-surface-800 p-6">
<h3 class="text-xs font-600 text-text-secondary uppercase tracking-wider">Ranked Stats</h3>
<div class="mt-4 grid grid-cols-4 gap-4">
<div>
<p class="text-2xl font-800 tabular-nums text-accent">{data.rating.elo}</p>
<p class="mt-1 text-xs text-text-secondary">ELO Rating</p>
</div>
<div>
<p class="text-2xl font-800 tabular-nums text-green-400">{data.rating.wins}</p>
<p class="mt-1 text-xs text-text-secondary">Wins</p>
</div>
<div>
<p class="text-2xl font-800 tabular-nums text-red-400">{data.rating.losses}</p>
<p class="mt-1 text-xs text-text-secondary">Losses</p>
</div>
<div>
<p class="text-2xl font-800 tabular-nums text-text-primary">{winRate}{winRate !== '—' ? '%' : ''}</p>
<p class="mt-1 text-xs text-text-secondary">Win Rate</p>
</div>
</div>
</div>
<!-- Danger Zone -->
<div class="mt-4 rounded-lg border border-border bg-surface-800 p-6">
<h3 class="text-xs font-600 text-red-400 uppercase tracking-wider">Account</h3>
<div class="mt-4">
<form method="post" action="?/logout" use:enhance>
<button
type="submit"
class="rounded-md border border-red-500/30 px-4 py-2 text-sm font-500 text-red-400 transition-colors hover:bg-red-500/10"
>
Sign Out
</button>
</form>
</div>
</div>
</div>

29
src/routes/+error.svelte Normal file
View File

@@ -0,0 +1,29 @@
<script lang="ts">
import { page } from '$app/state';
</script>
<div class="flex min-h-dvh items-center justify-center bg-surface-900">
<div class="text-center">
<p class="text-6xl font-800 text-accent">{page.status}</p>
<h1 class="mt-4 text-xl font-700 text-text-primary">
{#if page.status === 404}
Page not found
{:else if page.status === 403}
Access denied
{:else if page.status === 401}
Not logged in
{:else}
Something went wrong
{/if}
</h1>
<p class="mt-2 text-sm text-text-secondary">
{page.error?.message ?? 'An unexpected error occurred.'}
</p>
<a
href="/"
class="mt-6 inline-block rounded-md bg-accent px-5 py-2.5 text-sm font-600 text-surface-900 transition-colors hover:bg-accent-hover"
>
Back to Dashboard
</a>
</div>
</div>

View File

@@ -0,0 +1,27 @@
// src/routes/api/health/+server.ts
import { json } from '@sveltejs/kit';
import { db } from '$lib/server/db';
import { sql } from 'drizzle-orm';
import type { RequestHandler } from './$types';
export const GET: RequestHandler = async () => {
try {
// Check DB connectivity
await db.execute(sql`SELECT 1`);
return json({
status: 'ok',
timestamp: new Date().toISOString(),
uptime: process.uptime()
});
} catch (e: any) {
return json(
{
status: 'error',
error: 'Database connection failed',
timestamp: new Date().toISOString()
},
{ status: 503 }
);
}
};

View File

@@ -1,3 +1,4 @@
// src/routes/api/matches/+server.ts
import { json, error } from '@sveltejs/kit';
import { db } from '$lib/server/db';
import { createMatch } from '$lib/server/match/engine';
@@ -35,7 +36,7 @@ export const POST: RequestHandler = async ({ request, locals }) => {
createdBy: locals.user.id
});
return json(result, { status: 201 });
} catch (e) {
} catch (e: any) {
error(400, e.message);
}
};

View File

@@ -1,3 +1,4 @@
// src/routes/api/matches/[id]/+server.ts
import { json, error } from '@sveltejs/kit';
import { getMatchFull, cancelMatch } from '$lib/server/match/engine';
import type { RequestHandler } from './$types';
@@ -8,7 +9,7 @@ export const GET: RequestHandler = async ({ params, locals }) => {
try {
const m = await getMatchFull(params.id);
return json(m);
} catch (e) {
} catch (e: any) {
error(404, e.message);
}
};
@@ -19,7 +20,7 @@ export const DELETE: RequestHandler = async ({ params, locals }) => {
try {
const m = await cancelMatch(params.id);
return json(m);
} catch (e) {
} catch (e: any) {
error(400, e.message);
}
};

View File

@@ -1,3 +1,4 @@
// src/routes/api/matches/[id]/lobby/+server.ts
import { json, error } from '@sveltejs/kit';
import { moveToLobby } from '$lib/server/match/engine';
import type { RequestHandler } from './$types';
@@ -10,7 +11,7 @@ export const POST: RequestHandler = async ({ params, request, locals }) => {
try {
const m = await moveToLobby(params.id, body.osuLobbyId);
return json(m);
} catch (e) {
} catch (e: any) {
error(400, e.message);
}
};

View File

@@ -1,3 +1,4 @@
// src/routes/api/matches/[id]/pick/+server.ts
import { json, error } from '@sveltejs/kit';
import { pickMap } from '$lib/server/match/engine';
import type { RequestHandler } from './$types';
@@ -13,7 +14,7 @@ export const POST: RequestHandler = async ({ params, request, locals }) => {
try {
const game = await pickMap(params.id, participantId, mappoolSlotId);
return json(game);
} catch (e) {
} catch (e: any) {
error(400, e.message);
}
};

View File

@@ -1,3 +1,4 @@
// src/routes/api/matches/[id]/roll/+server.ts
import { json, error } from '@sveltejs/kit';
import { submitRoll } from '$lib/server/match/engine';
import type { RequestHandler } from './$types';
@@ -13,7 +14,7 @@ export const POST: RequestHandler = async ({ params, request, locals }) => {
try {
const m = await submitRoll(params.id, participantId, value);
return json(m);
} catch (e) {
} catch (e: any) {
error(400, e.message);
}
};

View File

@@ -1,3 +1,4 @@
// src/routes/api/matches/[id]/rolling/+server.ts
import { json, error } from '@sveltejs/kit';
import { moveToRolling } from '$lib/server/match/engine';
import type { RequestHandler } from './$types';
@@ -8,7 +9,7 @@ export const POST: RequestHandler = async ({ params, locals }) => {
try {
const m = await moveToRolling(params.id);
return json(m);
} catch (e) {
} catch (e: any) {
error(400, e.message);
}
};

View File

@@ -1,3 +1,4 @@
// src/routes/api/matches/[id]/score/+server.ts
import { json, error } from '@sveltejs/kit';
import { submitGameScores } from '$lib/server/match/engine';
import type { RequestHandler } from './$types';
@@ -13,7 +14,7 @@ export const POST: RequestHandler = async ({ request, locals }) => {
try {
const m = await submitGameScores(matchGameId, scores);
return json(m);
} catch (e) {
} catch (e: any) {
error(400, e.message);
}
};

View File

@@ -1,8 +1,9 @@
// src/routes/api/queue/+server.ts
import { json, error } from '@sveltejs/kit';
import { joinQueue, leaveQueue, getQueueStatus } from '$lib/server/match/engine';
import { db } from '$lib/server/db';
import { team, teamMember } from '$lib/server/db/schema';
import { eq, and } from 'drizzle-orm';
import { teamMember } from '$lib/server/db/schema';
import { eq } from 'drizzle-orm';
import type { RequestHandler } from './$types';
export const GET: RequestHandler = async ({ locals }) => {
@@ -29,7 +30,7 @@ export const POST: RequestHandler = async ({ locals }) => {
try {
const result = await joinQueue(locals.user.id, personalTeam.id);
return json({ matched: !!result, match: result });
} catch (e) {
} catch (e: any) {
error(400, e.message);
}
};

View File

@@ -0,0 +1,18 @@
import { redirect } from '@sveltejs/kit';
import { auth } from '$lib/server/auth';
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async (event) => {
if (event.locals.user) redirect(302, '/');
const result = await auth.api.signInSocial({
body: {
provider: 'osu',
callbackURL: '/'
}
});
if (result.url) redirect(302, result.url);
return {};
};