This commit is contained in:
22
frontend/app/composables/three-scene.ts
Normal file
22
frontend/app/composables/three-scene.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
// Helpers to keep heavy WebGL scene setup off the page's critical path.
|
||||
|
||||
// Runs fn once the main thread is idle (falling back to a short timeout),
|
||||
// returning a cancel handle so an early unmount never leaks a scheduled init.
|
||||
export const scheduleIdle = (fn: () => void, timeout = 1500): (() => void) => {
|
||||
const ric = (window as any).requestIdleCallback as
|
||||
| ((cb: () => void, opts?: { timeout: number }) => number)
|
||||
| undefined
|
||||
if (typeof ric === 'function') {
|
||||
const id = ric(fn, { timeout })
|
||||
return () => (window as any).cancelIdleCallback?.(id)
|
||||
}
|
||||
const id = setTimeout(fn, 200)
|
||||
return () => clearTimeout(id)
|
||||
}
|
||||
|
||||
// Calls cb whenever tab visibility changes, returning an unsubscribe function.
|
||||
export const onVisibility = (cb: (hidden: boolean) => void): (() => void) => {
|
||||
const handler = () => cb(document.hidden)
|
||||
document.addEventListener('visibilitychange', handler)
|
||||
return () => document.removeEventListener('visibilitychange', handler)
|
||||
}
|
||||
@@ -1,6 +1,16 @@
|
||||
// composables/useApi.js
|
||||
import { ref } from 'vue'
|
||||
|
||||
export const ADMIN_TOKEN_COOKIE = 'admin_token'
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number
|
||||
constructor(message: string, status: number) {
|
||||
super(message)
|
||||
this.status = status
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeUrl(url: string): string {
|
||||
return url.replace(/\/+$/, '')
|
||||
}
|
||||
@@ -12,7 +22,7 @@ export default function useApi() {
|
||||
// Generic GET request
|
||||
const get = async (endpoint) => {
|
||||
const res = await fetch(`${baseUrl}${endpoint}`)
|
||||
if (!res.ok) throw new Error(`API GET ${endpoint} failed`)
|
||||
if (!res.ok) throw new ApiError(`API GET ${endpoint} failed`, res.status)
|
||||
return res.json()
|
||||
}
|
||||
|
||||
@@ -23,9 +33,31 @@ export default function useApi() {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload)
|
||||
})
|
||||
if (!res.ok) throw new Error(`API POST ${endpoint} failed`)
|
||||
if (!res.ok) throw new ApiError(`API POST ${endpoint} failed`, res.status)
|
||||
return res.json()
|
||||
}
|
||||
|
||||
return { get, post }
|
||||
// Authenticated requests (JWT stored in cookie by useAuth)
|
||||
const authHeaders = (): Record<string, string> => {
|
||||
const token = useCookie<string | null>(ADMIN_TOKEN_COOKIE).value
|
||||
return token ? { Authorization: `Bearer ${token}` } : {}
|
||||
}
|
||||
|
||||
const getAuth = async (endpoint) => {
|
||||
const res = await fetch(`${baseUrl}${endpoint}`, { headers: authHeaders() })
|
||||
if (!res.ok) throw new ApiError(`API GET ${endpoint} failed`, res.status)
|
||||
return res.json()
|
||||
}
|
||||
|
||||
const postAuth = async (endpoint, payload) => {
|
||||
const res = await fetch(`${baseUrl}${endpoint}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...authHeaders() },
|
||||
body: JSON.stringify(payload)
|
||||
})
|
||||
if (!res.ok) throw new ApiError(`API POST ${endpoint} failed`, res.status)
|
||||
return res.json()
|
||||
}
|
||||
|
||||
return { get, post, getAuth, postAuth }
|
||||
}
|
||||
62
frontend/app/composables/useAuth.ts
Normal file
62
frontend/app/composables/useAuth.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import { ADMIN_TOKEN_COOKIE, ApiError } from './useApi'
|
||||
|
||||
export interface AdminUser {
|
||||
username: string
|
||||
}
|
||||
|
||||
const TOKEN_TTL_SECONDS = 60 * 60 * 12
|
||||
|
||||
export default function useAuth() {
|
||||
const config = useRuntimeConfig()
|
||||
const baseUrl = `${config.public.apiBaseUrl.replace(/\/+$/, '')}/api`
|
||||
|
||||
const token = useCookie<string | null>(ADMIN_TOKEN_COOKIE, {
|
||||
maxAge: TOKEN_TTL_SECONDS,
|
||||
sameSite: 'lax',
|
||||
path: '/',
|
||||
default: () => null
|
||||
})
|
||||
const user = useState<AdminUser | null>('admin-user', () => null)
|
||||
|
||||
const isAuthenticated = computed(() => !!token.value)
|
||||
|
||||
const login = async (username: string, password: string) => {
|
||||
const res = await fetch(`${baseUrl}/auth/login`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password })
|
||||
})
|
||||
const data = await res.json().catch(() => ({}))
|
||||
if (!res.ok) throw new ApiError(data.error || 'Login failed', res.status)
|
||||
token.value = data.token
|
||||
user.value = { username: data.username }
|
||||
return data
|
||||
}
|
||||
|
||||
const logout = () => {
|
||||
token.value = null
|
||||
user.value = null
|
||||
}
|
||||
|
||||
// Validates the stored token against the backend; logs out on failure.
|
||||
const fetchMe = async () => {
|
||||
if (!token.value) return null
|
||||
try {
|
||||
const res = await fetch(`${baseUrl}/auth/me`, {
|
||||
headers: { Authorization: `Bearer ${token.value}` }
|
||||
})
|
||||
if (res.status === 401) {
|
||||
logout()
|
||||
return null
|
||||
}
|
||||
if (!res.ok) throw new Error('auth check failed')
|
||||
const data = await res.json()
|
||||
user.value = { username: data.username }
|
||||
return data
|
||||
} catch (e) {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
return { token, user, isAuthenticated, login, logout, fetchMe }
|
||||
}
|
||||
Reference in New Issue
Block a user