From 53ffc70812982b1ee53a7dd227df6bdc806bd680 Mon Sep 17 00:00:00 2001 From: tisachi Date: Sun, 11 Oct 2026 17:56:58 +0200 Subject: [PATCH] Panel admina: naglowek X-Client przy auth (wlasne ciastko refresh), upload zdjec i pobieranie dokumentow przez klient API ( FormData/blob, rotacja 401) --- admin/src/api/client.ts | 65 ++++++++++++++++++++++--- admin/src/components/AuthImage.tsx | 53 ++++++++++++++++++++ admin/src/pages/Verifications.tsx | 36 ++++++++------ admin/src/pages/gyms/GymDetail.tsx | 77 +++++++++++++++++------------- admin/src/pages/gyms/GymsList.tsx | 15 ++++-- admin/src/store/auth.ts | 2 + 6 files changed, 190 insertions(+), 58 deletions(-) create mode 100644 admin/src/components/AuthImage.tsx diff --git a/admin/src/api/client.ts b/admin/src/api/client.ts index 17659e2..5de051d 100644 --- a/admin/src/api/client.ts +++ b/admin/src/api/client.ts @@ -23,11 +23,16 @@ export function getAccessToken() { return accessToken; } +// Panel admina i SPA dzielą domenę (różne porty), a ciastka portów nie +// rozróżniają — nagłówek mówi API, by sięgało po ciastko `fitos_admin_refresh`. +const CLIENT_HEADER = { 'X-Client': 'admin' } as const; + async function tryRefresh(): Promise { if (!refreshing) { refreshing = fetch(`${API_BASE}/auth/refresh`, { method: 'POST', credentials: 'include', + headers: { ...CLIENT_HEADER }, }) .then(async (res) => { if (!res.ok) return false; @@ -43,21 +48,39 @@ async function tryRefresh(): Promise { return refreshing; } -export async function api(path: string, opts: { method?: string; body?: unknown } = {}): Promise { +async function fetchWithAuth( + path: string, + opts: { method?: string; body?: unknown } = {}, +): Promise { + const isFormData = typeof FormData !== 'undefined' && opts.body instanceof FormData; const doFetch = () => fetch(`${API_BASE}${path}`, { method: opts.method || 'GET', credentials: 'include', headers: { - 'Content-Type': 'application/json', + // FormData: przeglądarka sama stawia multipart boundary + ...(isFormData ? {} : { 'Content-Type': 'application/json' }), + ...CLIENT_HEADER, ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}), }, - body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined, + body: + opts.body === undefined + ? undefined + : isFormData + ? (opts.body as FormData) + : JSON.stringify(opts.body), }); let res = await doFetch(); - if (res.status === 401 && path !== '/auth/refresh' && path !== '/auth/login' && path !== '/auth/register') { + // Wylogowanie musi przejść nawet bez ważnego tokenu — odświeżanie/próba + // ponowna przy 401 zapętlają się (handler fitos:logout znowu woła /auth/logout). + const isAuthEntry = + path === '/auth/refresh' || + path === '/auth/login' || + path === '/auth/register' || + path === '/auth/logout'; + if (res.status === 401 && !isAuthEntry) { const ok = await tryRefresh(); if (ok) res = await doFetch(); else { @@ -65,7 +88,10 @@ export async function api(path: string, opts: { method?: string; body?: unkno window.dispatchEvent(new Event('fitos:logout')); } } + return res; +} +async function toApiError(res: Response): Promise { const text = await res.text(); let json: unknown = null; if (text) { @@ -75,9 +101,34 @@ export async function api(path: string, opts: { method?: string; body?: unkno // ciało nie-JSON (np. rate limiter, proxy) — traktujemy jako nieprzezroczysty błąd } } - if (!res.ok) { - const body = (json ?? (text ? { error: { code: `HTTP_${res.status}`, message: text } } : null)) as ApiErrorBody | null; - throw new ApiError(res.status, body); + const body = (json ?? + (text + ? { error: { code: `HTTP_${res.status}`, message: text } } + : null)) as ApiErrorBody | null; + return new ApiError(res.status, body); +} + +export async function api( + path: string, + opts: { method?: string; body?: unknown } = {}, +): Promise { + const res = await fetchWithAuth(path, opts); + if (!res.ok) throw await toApiError(res); + const text = await res.text(); + let json: unknown = null; + if (text) { + try { + json = JSON.parse(text); + } catch { + // pusty/nie-JSON 2xx (np. 204) — zwracamy null + } } return json as T; } + +/** Pobranie binarnych zasobów (zdjęcia, dokumenty weryfikacji) z bearerem i rotacją 401. */ +export async function apiBlob(path: string): Promise { + const res = await fetchWithAuth(path); + if (!res.ok) throw await toApiError(res); + return res.blob(); +} diff --git a/admin/src/components/AuthImage.tsx b/admin/src/components/AuthImage.tsx new file mode 100644 index 0000000..cd85698 --- /dev/null +++ b/admin/src/components/AuthImage.tsx @@ -0,0 +1,53 @@ +import { useEffect, useState } from 'react'; +import { apiBlob } from '../api/client'; + +// Obiekty URL trzymamy w buforze na czas życia karty — ten sam obraz potrafi +// pojawić się kilka razy (okładka na liście + w szczegółach). +const srcCache = new Map>(); + +function loadObjectUrl(url: string): Promise { + let pending = srcCache.get(url); + if (!pending) { + pending = apiBlob(url).then((blob) => URL.createObjectURL(blob)); + srcCache.set(url, pending); + pending.catch(() => srcCache.delete(url)); + } + return pending; +} + +interface AuthImageProps { + /** Ścieżka względna API (np. `/gyms/x/photos/y`). */ + src: string | null | undefined; + alt: string; + className?: string; +} + +/** + * Zdjęcia siłowni serwuje chroniony endpoint (Authorization), więc zwykły + * nie przejdzie — pobieramy blob przez `apiBlob` i wyświetlamy z + * URL.createObjectURL. Błąd poboru = pusty render (bez errorów w konsoli). + */ +export function AuthImage({ src, alt, className }: AuthImageProps) { + const [objectUrl, setObjectUrl] = useState(null); + + useEffect(() => { + if (!src) { + setObjectUrl(null); + return; + } + let active = true; + loadObjectUrl(src) + .then((url) => { + if (active) setObjectUrl(url); + }) + .catch(() => { + if (active) setObjectUrl(null); + }); + return () => { + active = false; + }; + }, [src]); + + if (!src || !objectUrl) return null; + return {alt}; +} diff --git a/admin/src/pages/Verifications.tsx b/admin/src/pages/Verifications.tsx index c640e72..5459c68 100644 --- a/admin/src/pages/Verifications.tsx +++ b/admin/src/pages/Verifications.tsx @@ -2,8 +2,7 @@ import { useState } from 'react'; import { Link, useNavigate, useParams } from 'react-router-dom'; import { useQuery, useQueryClient } from '@tanstack/react-query'; import { Download, ShieldCheck } from 'lucide-react'; -import { api, getAccessToken } from '../api/client'; -import { API_BASE } from '../config'; +import { api, apiBlob } from '../api/client'; import type { ClaimStatus, GymClaim } from '../api/types'; import { BackButton, @@ -45,14 +44,9 @@ function applicantName(claim: GymClaim) { return [firstName, lastName].filter(Boolean).join(' ') || email; } -/** Pobranie pliku po tokenie (nie po cookie): fetch + Bearer → blob → tymczasowy . */ +/** Pobranie pliku przez `apiBlob` (Bearer + rotacja 401) → tymczasowy . */ async function downloadFile(path: string, filename: string) { - const token = getAccessToken(); - const res = await fetch(`${API_BASE}${path}`, { - headers: token ? { Authorization: `Bearer ${token}` } : {}, - }); - if (!res.ok) throw new Error(`HTTP ${res.status}`); - const blob = await res.blob(); + const blob = await apiBlob(path); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; @@ -111,7 +105,9 @@ export default function VerificationsList() { meta={`${applicantName(c)} · ${new Date(c.createdAt).toLocaleDateString('pl-PL')}`} actions={ <> - {claimTypeLabel(c)} + + {claimTypeLabel(c)} + {c.documentCount ? {c.documentCount} dok. : null} {STATUS_META[c.status].label} @@ -124,7 +120,11 @@ export default function VerificationsList() { {!isLoading && !error && claims.length === 0 && ( - + )} @@ -216,7 +216,9 @@ export function VerificationDetail() { title={claimTitle(claim)} badge={ <> - {claimTypeLabel(claim)} + + {claimTypeLabel(claim)} + {STATUS_META[claim.status].label} } @@ -245,7 +247,9 @@ export function VerificationDetail() { <> {claim.gymName || '—'} {claim.gymLocation || '—'} - {formatAvailability(claim.gymAvailability) || '—'} + + {formatAvailability(claim.gymAvailability) || '—'} + {claim.gymCapacity ?? '—'} )} @@ -282,7 +286,11 @@ export function VerificationDetail() { key={d.id} title={d.originalName} actions={ - diff --git a/admin/src/pages/gyms/GymDetail.tsx b/admin/src/pages/gyms/GymDetail.tsx index fd74184..0d64ac9 100644 --- a/admin/src/pages/gyms/GymDetail.tsx +++ b/admin/src/pages/gyms/GymDetail.tsx @@ -3,8 +3,8 @@ import { useNavigate, useParams } from 'react-router-dom'; import { useQuery, useQueryClient } from '@tanstack/react-query'; import { ImagePlus, Star, X } from 'lucide-react'; import { useTopbar } from '../../topbar'; -import { api, getAccessToken } from '../../api/client'; -import { API_BASE } from '../../config'; +import { api } from '../../api/client'; +import { AuthImage } from '../../components/AuthImage'; import type { Equipment, Gym, GymException, GymPhoto } from '../../api/types'; import { formatEquipmentSpec, formatGymEquipment } from '../../lib/equipment'; import { @@ -35,10 +35,6 @@ function InfoItem({ label, children }: { label: string; children: React.ReactNod ); } -export function gymPhotoSrc(url: string): string { - return `${API_BASE}${url}`; -} - const PHOTO_MIME_TYPES = ['image/jpeg', 'image/png', 'image/webp']; const MAX_PHOTO_FILES = 10; const MAX_PHOTO_FILE_SIZE = 5 * 1024 * 1024; @@ -46,23 +42,7 @@ const MAX_PHOTO_FILE_SIZE = 5 * 1024 * 1024; async function uploadGymPhotos(gymId: string, files: File[]): Promise { const form = new FormData(); for (const file of files) form.append('photos', file); - const res = await fetch(`${API_BASE}/gyms/${gymId}/photos`, { - method: 'POST', - credentials: 'include', - headers: { Authorization: `Bearer ${getAccessToken()}` }, - body: form, - }); - const text = await res.text(); - let json: unknown = null; - if (text) { - try { - json = JSON.parse(text); - } catch { - // nie-JSON - } - } - if (!res.ok) throw new Error((json as { error?: { message?: string } })?.error?.message ?? `HTTP ${res.status}`); - return json; + return api(`/gyms/${gymId}/photos`, { method: 'POST', body: form }); } function GymEditForm({ gym, onSaved }: { gym: Gym; onSaved: () => void }) { @@ -103,13 +83,24 @@ function GymEditForm({ gym, onSaved }: { gym: Gym; onSaved: () => void }) {
- setForm({ ...form, name: e.target.value })} required /> + setForm({ ...form, name: e.target.value })} + required + /> - setForm({ ...form, location: e.target.value })} /> + setForm({ ...form, location: e.target.value })} + /> - setForm({ ...form, capacity: e.target.value })} /> + setForm({ ...form, capacity: e.target.value })} + />
@@ -131,7 +122,11 @@ export default function GymDetail() { const { id } = useParams(); const navigate = useNavigate(); const queryClient = useQueryClient(); - const { data: gym, isLoading, error } = useQuery({ + const { + data: gym, + isLoading, + error, + } = useQuery({ queryKey: ['gym', id], queryFn: () => api(`/admin/gyms/${id}`), enabled: !!id, @@ -139,7 +134,8 @@ export default function GymDetail() { const remove = async () => { if (!gym) return; - if (!confirm('Usunąć siłownię? Członkostwa zostaną usunięte, plany użytkowników zachowane.')) return; + if (!confirm('Usunąć siłownię? Członkostwa zostaną usunięte, plany użytkowników zachowane.')) + return; try { await api(`/admin/gyms/${gym.id}`, { method: 'DELETE' }); await queryClient.invalidateQueries({ queryKey: ['gyms'] }); @@ -185,7 +181,11 @@ export default function GymDetail() { {gym.coverPhoto && (
- {gym.name} +