feat: implement Phase 4 SvelteKit frontend + backend enhancements
Backend: - Add dashboard API (today stats, inbox count, law alerts, pipeline status) - Add /api/documents/tree endpoint for sidebar domain/sub_group tree - Migrate auth to HttpOnly cookie for refresh token (XSS defense) - Add /api/auth/logout endpoint (cookie cleanup) - Register dashboard router in main.py Frontend (SvelteKit + Tailwind CSS v4): - api.ts: fetch wrapper with refresh queue pattern, 401 single retry, forced logout on refresh failure - Auth store: login/logout/refresh with memory-based access token - UI store: toast system, sidebar state - Login page with TOTP support - Dashboard with 4 stat widgets + recent documents - Document list with hybrid search (debounce, URL query state, mode select) - Document detail with format-aware viewer (markdown/PDF/HWP/Synology/fallback) - Metadata panel (AI summary, tags, processing history) - Inbox triage UI (batch select, confirm dialog, domain override) - Settings page (password change, TOTP status) Infrastructure: - Enable frontend service in docker-compose - Caddy path routing (/api/* → fastapi, / → frontend) + gzip Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
133
frontend/src/lib/api.ts
Normal file
133
frontend/src/lib/api.ts
Normal file
@@ -0,0 +1,133 @@
|
||||
/**
|
||||
* API fetch 래퍼
|
||||
*
|
||||
* - access token: 메모리 변수
|
||||
* - refresh token: HttpOnly cookie (서버가 관리)
|
||||
* - refresh 중복 방지: isRefreshing 플래그 + 대기 큐
|
||||
* - 401 retry: 1회만, 실패 시 강제 logout
|
||||
*/
|
||||
|
||||
const API_BASE = '/api';
|
||||
|
||||
let accessToken: string | null = null;
|
||||
|
||||
// refresh 큐
|
||||
let isRefreshing = false;
|
||||
let refreshQueue: Array<{
|
||||
resolve: (token: string) => void;
|
||||
reject: (err: Error) => void;
|
||||
}> = [];
|
||||
|
||||
export function setAccessToken(token: string | null) {
|
||||
accessToken = token;
|
||||
}
|
||||
|
||||
export function getAccessToken(): string | null {
|
||||
return accessToken;
|
||||
}
|
||||
|
||||
async function refreshAccessToken(): Promise<string> {
|
||||
const res = await fetch(`${API_BASE}/auth/refresh`, {
|
||||
method: 'POST',
|
||||
credentials: 'include', // cookie 전송
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error('refresh failed');
|
||||
}
|
||||
const data = await res.json();
|
||||
accessToken = data.access_token;
|
||||
return data.access_token;
|
||||
}
|
||||
|
||||
function processRefreshQueue(error: Error | null, token: string | null) {
|
||||
refreshQueue.forEach(({ resolve, reject }) => {
|
||||
if (error) reject(error);
|
||||
else resolve(token!);
|
||||
});
|
||||
refreshQueue = [];
|
||||
}
|
||||
|
||||
async function handleTokenRefresh(): Promise<string> {
|
||||
if (isRefreshing) {
|
||||
return new Promise((resolve, reject) => {
|
||||
refreshQueue.push({ resolve, reject });
|
||||
});
|
||||
}
|
||||
|
||||
isRefreshing = true;
|
||||
try {
|
||||
const token = await refreshAccessToken();
|
||||
processRefreshQueue(null, token);
|
||||
return token;
|
||||
} catch (err) {
|
||||
const error = err instanceof Error ? err : new Error('refresh failed');
|
||||
processRefreshQueue(error, null);
|
||||
// 강제 logout
|
||||
accessToken = null;
|
||||
if (typeof window !== 'undefined') {
|
||||
window.location.href = '/login';
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
isRefreshing = false;
|
||||
}
|
||||
}
|
||||
|
||||
export type ApiError = {
|
||||
status: number;
|
||||
detail: string;
|
||||
};
|
||||
|
||||
export async function api<T = unknown>(
|
||||
path: string,
|
||||
options: RequestInit = {},
|
||||
): Promise<T> {
|
||||
const headers: Record<string, string> = {
|
||||
...(options.headers as Record<string, string> || {}),
|
||||
};
|
||||
|
||||
if (accessToken) {
|
||||
headers['Authorization'] = `Bearer ${accessToken}`;
|
||||
}
|
||||
|
||||
// FormData일 때는 Content-Type 자동 설정
|
||||
if (options.body && !(options.body instanceof FormData)) {
|
||||
headers['Content-Type'] = 'application/json';
|
||||
}
|
||||
|
||||
const res = await fetch(`${API_BASE}${path}`, {
|
||||
...options,
|
||||
headers,
|
||||
credentials: 'include',
|
||||
});
|
||||
|
||||
// 401 → refresh 1회 시도
|
||||
if (res.status === 401 && accessToken) {
|
||||
try {
|
||||
await handleTokenRefresh();
|
||||
headers['Authorization'] = `Bearer ${accessToken}`;
|
||||
const retryRes = await fetch(`${API_BASE}${path}`, {
|
||||
...options,
|
||||
headers,
|
||||
credentials: 'include',
|
||||
});
|
||||
if (!retryRes.ok) {
|
||||
const err = await retryRes.json().catch(() => ({ detail: 'Unknown error' }));
|
||||
throw { status: retryRes.status, detail: err.detail || retryRes.statusText };
|
||||
}
|
||||
return retryRes.json();
|
||||
} catch {
|
||||
throw { status: 401, detail: '인증이 만료되었습니다' };
|
||||
}
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({ detail: res.statusText }));
|
||||
throw { status: res.status, detail: err.detail || res.statusText } as ApiError;
|
||||
}
|
||||
|
||||
// 204 No Content
|
||||
if (res.status === 204) return {} as T;
|
||||
|
||||
return res.json();
|
||||
}
|
||||
55
frontend/src/lib/stores/auth.ts
Normal file
55
frontend/src/lib/stores/auth.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import { writable } from 'svelte/store';
|
||||
import { api, setAccessToken } from '$lib/api';
|
||||
|
||||
interface User {
|
||||
id: number;
|
||||
username: string;
|
||||
is_active: boolean;
|
||||
totp_enabled: boolean;
|
||||
last_login_at: string | null;
|
||||
}
|
||||
|
||||
export const user = writable<User | null>(null);
|
||||
export const isAuthenticated = writable(false);
|
||||
|
||||
export async function login(username: string, password: string, totp_code?: string) {
|
||||
const data = await api<{ access_token: string }>('/auth/login', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ username, password, totp_code: totp_code || undefined }),
|
||||
});
|
||||
setAccessToken(data.access_token);
|
||||
await fetchUser();
|
||||
}
|
||||
|
||||
export async function fetchUser() {
|
||||
try {
|
||||
const data = await api<User>('/auth/me');
|
||||
user.set(data);
|
||||
isAuthenticated.set(true);
|
||||
} catch {
|
||||
user.set(null);
|
||||
isAuthenticated.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
export async function logout() {
|
||||
try {
|
||||
await api('/auth/logout', { method: 'POST' });
|
||||
} catch { /* ignore */ }
|
||||
setAccessToken(null);
|
||||
user.set(null);
|
||||
isAuthenticated.set(false);
|
||||
}
|
||||
|
||||
export async function tryRefresh() {
|
||||
try {
|
||||
const data = await api<{ access_token: string }>('/auth/refresh', {
|
||||
method: 'POST',
|
||||
});
|
||||
setAccessToken(data.access_token);
|
||||
await fetchUser();
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
27
frontend/src/lib/stores/ui.ts
Normal file
27
frontend/src/lib/stores/ui.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { writable } from 'svelte/store';
|
||||
|
||||
export const sidebarOpen = writable(true);
|
||||
export const selectedDocId = writable<number | null>(null);
|
||||
|
||||
// Toast 시스템
|
||||
interface Toast {
|
||||
id: number;
|
||||
type: 'success' | 'error' | 'warning' | 'info';
|
||||
message: string;
|
||||
}
|
||||
|
||||
let toastId = 0;
|
||||
export const toasts = writable<Toast[]>([]);
|
||||
|
||||
export function addToast(type: Toast['type'], message: string, duration = 5000) {
|
||||
const id = ++toastId;
|
||||
toasts.update(t => [...t, { id, type, message }]);
|
||||
if (duration > 0) {
|
||||
setTimeout(() => removeToast(id), duration);
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
export function removeToast(id: number) {
|
||||
toasts.update(t => t.filter(toast => toast.id !== id));
|
||||
}
|
||||
Reference in New Issue
Block a user