From 4c2500797b1e4da1e83ae6e1b598297a0d30ca52 Mon Sep 17 00:00:00 2001 From: dbildhauer Date: Sun, 25 Oct 2026 10:00:44 +0100 Subject: [PATCH] =?UTF-8?q?feat:=20frontend=20f=C3=BCr=20login,=20konto=20?= =?UTF-8?q?und=20benutzerverwaltung?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Login-Seite, Auth-Store und Router-Guard mit Weiterleitung nach dem Login - API-Client sendet X-CSRF-Token und reagiert auf 401 - Konto: Passwort ändern, angemeldete Geräte anzeigen und widerrufen - Benutzerverwaltung für Admins: anlegen, Rolle, aktiv, Passwort-Reset, löschen Co-Authored-By: Claude Opus 5.5 --- frontend/src/App.vue | 6 + frontend/src/api/client.ts | 61 +++++++- frontend/src/api/types.ts | 19 +++ frontend/src/assets/main.css | 117 +++++++++++++++ frontend/src/components/AppHeader.vue | 66 +++++++++ frontend/src/main.ts | 10 ++ frontend/src/router/index.ts | 42 +++++- frontend/src/stores/auth.ts | 46 ++++++ frontend/src/stores/health.ts | 4 +- frontend/src/utils/format.ts | 38 +++++ frontend/src/views/AccountView.vue | 190 ++++++++++++++++++++++++ frontend/src/views/AdminUsersView.vue | 199 ++++++++++++++++++++++++++ frontend/src/views/HomeView.vue | 57 +------- frontend/src/views/LoginView.vue | 81 +++++++++++ 14 files changed, 873 insertions(+), 63 deletions(-) create mode 100644 frontend/src/api/types.ts create mode 100644 frontend/src/components/AppHeader.vue create mode 100644 frontend/src/stores/auth.ts create mode 100644 frontend/src/utils/format.ts create mode 100644 frontend/src/views/AccountView.vue create mode 100644 frontend/src/views/AdminUsersView.vue create mode 100644 frontend/src/views/LoginView.vue diff --git a/frontend/src/App.vue b/frontend/src/App.vue index a78fb6f..e073f29 100644 --- a/frontend/src/App.vue +++ b/frontend/src/App.vue @@ -1,7 +1,13 @@ diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts index c64e49a..c9afdf6 100644 --- a/frontend/src/api/client.ts +++ b/frontend/src/api/client.ts @@ -7,13 +7,60 @@ export class ApiError extends Error { } } -export async function apiGet(path: string): Promise { - const response = await fetch(`/api${path}`, { - credentials: 'same-origin', - headers: { Accept: 'application/json' }, - }) - if (!response.ok) { - throw new ApiError(response.status, `${response.status} ${response.statusText}`) +type UnauthorizedHandler = () => void + +let onUnauthorized: UnauthorizedHandler | null = null + +/** Called on 401 responses (except for the login request itself). */ +export function setUnauthorizedHandler(handler: UnauthorizedHandler): void { + onUnauthorized = handler +} + +function readCookie(name: string): string | null { + const match = document.cookie.split('; ').find((c) => c.startsWith(`${name}=`)) + return match ? decodeURIComponent(match.slice(name.length + 1)) : null +} + +async function errorMessage(response: Response): Promise { + try { + const data: unknown = await response.json() + if (data && typeof data === 'object' && 'detail' in data) { + const detail = (data as { detail: unknown }).detail + if (typeof detail === 'string') return detail + if (Array.isArray(detail)) return 'Ungültige Eingabe.' + } + } catch { + // body is not JSON } + return `${response.status} ${response.statusText}` +} + +export async function apiRequest(method: string, path: string, body?: unknown): Promise { + const headers: Record = { Accept: 'application/json' } + if (body !== undefined) headers['Content-Type'] = 'application/json' + if (method !== 'GET') { + const csrf = readCookie('lc_csrf') + if (csrf) headers['X-CSRF-Token'] = csrf + } + + const response = await fetch(`/api${path}`, { + method, + headers, + credentials: 'same-origin', + body: body === undefined ? undefined : JSON.stringify(body), + }) + + if (!response.ok) { + if (response.status === 401 && path !== '/auth/login') onUnauthorized?.() + throw new ApiError(response.status, await errorMessage(response)) + } + if (response.status === 204) return undefined as T return (await response.json()) as T } + +export const api = { + get: (path: string) => apiRequest('GET', path), + post: (path: string, body?: unknown) => apiRequest('POST', path, body), + patch: (path: string, body?: unknown) => apiRequest('PATCH', path, body), + delete: (path: string) => apiRequest('DELETE', path), +} diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.ts new file mode 100644 index 0000000..98bd798 --- /dev/null +++ b/frontend/src/api/types.ts @@ -0,0 +1,19 @@ +export type Role = 'admin' | 'user' + +export interface User { + id: number + username: string + role: Role + is_active: boolean + created_at: string +} + +export interface SessionInfo { + id: number + created_at: string + last_seen_at: string + expires_at: string + ip: string | null + user_agent: string | null + current: boolean +} diff --git a/frontend/src/assets/main.css b/frontend/src/assets/main.css index 93c8f5c..8e42a05 100644 --- a/frontend/src/assets/main.css +++ b/frontend/src/assets/main.css @@ -36,3 +36,120 @@ body { padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left); } + +/* --- Shared building blocks ------------------------------------------------ */ + +.page { + max-width: 48rem; + margin: 0 auto; + padding: 1.25rem 1rem 3rem; +} + +.page > h1 { + font-size: 1.5rem; + margin: 0 0 1rem; +} + +.card { + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius); + padding: 1rem 1.25rem; + margin-bottom: 1rem; +} + +.card > h2 { + font-size: 1.1rem; + margin: 0 0 0.75rem; +} + +.form { + display: grid; + gap: 0.75rem; +} + +.form label { + display: grid; + gap: 0.25rem; + color: var(--muted); + font-size: 0.9rem; +} + +input, +select { + min-height: 44px; + width: 100%; + padding: 0 0.75rem; + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--bg); + color: var(--text); + /* 16px prevents iOS Safari from zooming into focused inputs */ + font: inherit; + font-size: 16px; +} + +input:focus, +select:focus { + outline: 2px solid var(--accent); + outline-offset: 1px; +} + +button { + min-height: 44px; + padding: 0 1rem; + border: 1px solid var(--accent); + border-radius: var(--radius); + background: transparent; + color: var(--accent); + font: inherit; + cursor: pointer; +} + +button.primary { + background: var(--accent); + color: var(--bg); + font-weight: 600; +} + +button.danger { + border-color: var(--error); + color: var(--error); +} + +button.small { + min-height: 36px; + padding: 0 0.75rem; + font-size: 0.9rem; +} + +button:disabled { + opacity: 0.5; + cursor: default; +} + +.ok { + color: var(--ok); +} + +.error { + color: var(--error); +} + +.muted { + color: var(--muted); +} + +.badge { + display: inline-block; + padding: 0 0.5rem; + border: 1px solid var(--border); + border-radius: 999px; + font-size: 0.8rem; + color: var(--muted); +} + +.badge.accent { + border-color: var(--accent); + color: var(--accent); +} diff --git a/frontend/src/components/AppHeader.vue b/frontend/src/components/AppHeader.vue new file mode 100644 index 0000000..248089a --- /dev/null +++ b/frontend/src/components/AppHeader.vue @@ -0,0 +1,66 @@ + + + + + diff --git a/frontend/src/main.ts b/frontend/src/main.ts index c486c90..c5f68f3 100644 --- a/frontend/src/main.ts +++ b/frontend/src/main.ts @@ -3,12 +3,22 @@ import './assets/main.css' import { createPinia } from 'pinia' import { createApp } from 'vue' +import { setUnauthorizedHandler } from './api/client' import App from './App.vue' import router from './router' +import { useAuthStore } from './stores/auth' const app = createApp(App) app.use(createPinia()) app.use(router) +// Session expired or revoked elsewhere: drop local state and go to the login page +setUnauthorizedHandler(() => { + useAuthStore().clear() + if (router.currentRoute.value.name !== 'login') { + void router.push({ name: 'login', query: { redirect: router.currentRoute.value.fullPath } }) + } +}) + app.mount('#app') diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts index 9af22db..2a12909 100644 --- a/frontend/src/router/index.ts +++ b/frontend/src/router/index.ts @@ -1,10 +1,50 @@ import { createRouter, createWebHistory } from 'vue-router' +import { useAuthStore } from '@/stores/auth' import HomeView from '@/views/HomeView.vue' +declare module 'vue-router' { + interface RouteMeta { + public?: boolean + admin?: boolean + } +} + const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), - routes: [{ path: '/', name: 'home', component: HomeView }], + routes: [ + { path: '/', name: 'home', component: HomeView }, + { + path: '/login', + name: 'login', + component: () => import('@/views/LoginView.vue'), + meta: { public: true }, + }, + { path: '/account', name: 'account', component: () => import('@/views/AccountView.vue') }, + { + path: '/admin/users', + name: 'admin-users', + component: () => import('@/views/AdminUsersView.vue'), + meta: { admin: true }, + }, + { path: '/:pathMatch(.*)*', redirect: '/' }, + ], +}) + +router.beforeEach(async (to) => { + const auth = useAuthStore() + await auth.ensureLoaded() + + if (to.meta.public) { + return auth.user && to.name === 'login' ? { name: 'home' } : true + } + if (!auth.user) { + return { name: 'login', query: to.fullPath !== '/' ? { redirect: to.fullPath } : {} } + } + if (to.meta.admin && !auth.isAdmin) { + return { name: 'home' } + } + return true }) export default router diff --git a/frontend/src/stores/auth.ts b/frontend/src/stores/auth.ts new file mode 100644 index 0000000..f685973 --- /dev/null +++ b/frontend/src/stores/auth.ts @@ -0,0 +1,46 @@ +import { defineStore } from 'pinia' +import { computed, ref } from 'vue' + +import { ApiError, api } from '@/api/client' +import type { User } from '@/api/types' + +export const useAuthStore = defineStore('auth', () => { + const user = ref(null) + const loaded = ref(false) + + const isAdmin = computed(() => user.value?.role === 'admin') + + async function fetchMe(): Promise { + try { + user.value = await api.get('/auth/me') + } catch (e) { + if (!(e instanceof ApiError) || e.status !== 401) throw e + user.value = null + } finally { + loaded.value = true + } + } + + async function ensureLoaded(): Promise { + if (!loaded.value) await fetchMe() + } + + async function login(username: string, password: string): Promise { + user.value = await api.post('/auth/login', { username, password }) + loaded.value = true + } + + async function logout(): Promise { + try { + await api.post('/auth/logout') + } finally { + clear() + } + } + + function clear(): void { + user.value = null + } + + return { user, loaded, isAdmin, fetchMe, ensureLoaded, login, logout, clear } +}) diff --git a/frontend/src/stores/health.ts b/frontend/src/stores/health.ts index 7484a57..0b8cc52 100644 --- a/frontend/src/stores/health.ts +++ b/frontend/src/stores/health.ts @@ -1,7 +1,7 @@ import { defineStore } from 'pinia' import { ref } from 'vue' -import { apiGet } from '@/api/client' +import { api } from '@/api/client' export interface Health { status: 'ok' | 'error' @@ -18,7 +18,7 @@ export const useHealthStore = defineStore('health', () => { loading.value = true error.value = null try { - health.value = await apiGet('/health') + health.value = await api.get('/health') } catch (e) { health.value = null error.value = e instanceof Error ? e.message : String(e) diff --git a/frontend/src/utils/format.ts b/frontend/src/utils/format.ts new file mode 100644 index 0000000..a702484 --- /dev/null +++ b/frontend/src/utils/format.ts @@ -0,0 +1,38 @@ +const dateTimeFormat = new Intl.DateTimeFormat('de-DE', { + dateStyle: 'medium', + timeStyle: 'short', +}) + +export function formatDateTime(iso: string): string { + return dateTimeFormat.format(new Date(iso)) +} + +// Order matters: iPad/iPhone before macOS, Edge/Chrome before Safari +const DEVICES: [RegExp, string][] = [ + [/iPad/, 'iPad'], + [/iPhone/, 'iPhone'], + [/Android/, 'Android'], + [/Windows/, 'Windows'], + [/Mac OS X|Macintosh/, 'macOS'], + [/Linux/, 'Linux'], +] + +const BROWSERS: [RegExp, string][] = [ + [/Edg\//, 'Edge'], + [/Firefox\/|FxiOS/, 'Firefox'], + [/Chrome\/|CriOS/, 'Chrome'], + [/Safari\//, 'Safari'], +] + +function firstMatch(ua: string, table: [RegExp, string][]): string | null { + return table.find(([pattern]) => pattern.test(ua))?.[1] ?? null +} + +/** Short human-readable device description from a User-Agent string. */ +export function describeUserAgent(ua: string | null): string { + if (!ua) return 'Unbekanntes Gerät' + const device = firstMatch(ua, DEVICES) + const browser = firstMatch(ua, BROWSERS) + if (device && browser) return `${browser} auf ${device}` + return device ?? browser ?? ua.slice(0, 40) +} diff --git a/frontend/src/views/AccountView.vue b/frontend/src/views/AccountView.vue new file mode 100644 index 0000000..48fa623 --- /dev/null +++ b/frontend/src/views/AccountView.vue @@ -0,0 +1,190 @@ + + + + + diff --git a/frontend/src/views/AdminUsersView.vue b/frontend/src/views/AdminUsersView.vue new file mode 100644 index 0000000..774b2df --- /dev/null +++ b/frontend/src/views/AdminUsersView.vue @@ -0,0 +1,199 @@ + + + + + diff --git a/frontend/src/views/HomeView.vue b/frontend/src/views/HomeView.vue index c4ccac4..59070cf 100644 --- a/frontend/src/views/HomeView.vue +++ b/frontend/src/views/HomeView.vue @@ -1,16 +1,18 @@ diff --git a/frontend/src/views/LoginView.vue b/frontend/src/views/LoginView.vue new file mode 100644 index 0000000..7a01f3e --- /dev/null +++ b/frontend/src/views/LoginView.vue @@ -0,0 +1,81 @@ + + + + +