Panel admina: naglowek X-Client przy auth (wlasne ciastko refresh), upload zdjec i pobieranie dokumentow przez klient API ( FormData/blob, rotacja 401)

This commit is contained in:
tisachi
2026-10-11 17:56:58 +02:00
parent d456a2af7e
commit 53ffc70812
6 changed files with 190 additions and 58 deletions

View File

@@ -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<boolean> {
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<boolean> {
return refreshing;
}
export async function api<T>(path: string, opts: { method?: string; body?: unknown } = {}): Promise<T> {
async function fetchWithAuth(
path: string,
opts: { method?: string; body?: unknown } = {},
): Promise<Response> {
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<T>(path: string, opts: { method?: string; body?: unkno
window.dispatchEvent(new Event('fitos:logout'));
}
}
return res;
}
async function toApiError(res: Response): Promise<ApiError> {
const text = await res.text();
let json: unknown = null;
if (text) {
@@ -75,9 +101,34 @@ export async function api<T>(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<T>(
path: string,
opts: { method?: string; body?: unknown } = {},
): Promise<T> {
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<Blob> {
const res = await fetchWithAuth(path);
if (!res.ok) throw await toApiError(res);
return res.blob();
}

View File

@@ -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<string, Promise<string>>();
function loadObjectUrl(url: string): Promise<string> {
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
* <img src> 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<string | null>(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 <img src={objectUrl} alt={alt} className={className} />;
}

View File

@@ -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 <a download>. */
/** Pobranie pliku przez `apiBlob` (Bearer + rotacja 401) → tymczasowy <a download>. */
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={
<>
<Badge color={c.type === 'verification' ? 'blue' : 'gray'}>{claimTypeLabel(c)}</Badge>
<Badge color={c.type === 'verification' ? 'blue' : 'gray'}>
{claimTypeLabel(c)}
</Badge>
{c.documentCount ? <Badge color="gray">{c.documentCount} dok.</Badge> : null}
<Badge color={STATUS_META[c.status].color}>{STATUS_META[c.status].label}</Badge>
</>
@@ -124,7 +120,11 @@ export default function VerificationsList() {
{!isLoading && !error && claims.length === 0 && (
<Card>
<EmptyState icon={ShieldCheck} title="Brak wniosków" description="Brak wniosków o siłownie." />
<EmptyState
icon={ShieldCheck}
title="Brak wniosków"
description="Brak wniosków o siłownie."
/>
</Card>
)}
</>
@@ -216,7 +216,9 @@ export function VerificationDetail() {
title={claimTitle(claim)}
badge={
<>
<Badge color={claim.type === 'verification' ? 'blue' : 'gray'}>{claimTypeLabel(claim)}</Badge>
<Badge color={claim.type === 'verification' ? 'blue' : 'gray'}>
{claimTypeLabel(claim)}
</Badge>
<Badge color={STATUS_META[claim.status].color}>{STATUS_META[claim.status].label}</Badge>
</>
}
@@ -245,7 +247,9 @@ export function VerificationDetail() {
<>
<InfoItem label="Nazwa siłowni">{claim.gymName || '—'}</InfoItem>
<InfoItem label="Lokalizacja">{claim.gymLocation || '—'}</InfoItem>
<InfoItem label="Dostępność">{formatAvailability(claim.gymAvailability) || '—'}</InfoItem>
<InfoItem label="Dostępność">
{formatAvailability(claim.gymAvailability) || '—'}
</InfoItem>
<InfoItem label="Pojemność">{claim.gymCapacity ?? '—'}</InfoItem>
</>
)}
@@ -282,7 +286,11 @@ export function VerificationDetail() {
key={d.id}
title={d.originalName}
actions={
<Button size="sm" variant="secondary" onClick={() => void download(d.id, d.originalName)}>
<Button
size="sm"
variant="secondary"
onClick={() => void download(d.id, d.originalName)}
>
<Download className="h-4 w-4" />
Pobierz
</Button>

View File

@@ -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<unknown> {
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 }) {
<form onSubmit={submit}>
<div className="grid grid-cols-1 gap-x-4 sm:grid-cols-2">
<Field label="Nazwa">
<Input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} required />
<Input
value={form.name}
onChange={(e) => setForm({ ...form, name: e.target.value })}
required
/>
</Field>
<Field label="Lokalizacja">
<Input value={form.location} onChange={(e) => setForm({ ...form, location: e.target.value })} />
<Input
value={form.location}
onChange={(e) => setForm({ ...form, location: e.target.value })}
/>
</Field>
<Field label="Ilość miejsc">
<Input type="number" value={form.capacity} onChange={(e) => setForm({ ...form, capacity: e.target.value })} />
<Input
type="number"
value={form.capacity}
onChange={(e) => setForm({ ...form, capacity: e.target.value })}
/>
</Field>
</div>
<Field label="Dostępność (dzień tygodnia + przedział godzin)">
@@ -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<Gym>(`/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 && (
<div className="relative mb-4 overflow-hidden rounded-[10px] border border-line shadow-card">
<img src={gymPhotoSrc(gym.coverPhoto)} alt={gym.name} className="h-44 w-full object-cover sm:h-56" />
<AuthImage
src={gym.coverPhoto}
alt={gym.name}
className="h-44 w-full object-cover sm:h-56"
/>
<div
aria-hidden="true"
className="absolute inset-0 bg-[linear-gradient(180deg,transparent_45%,rgb(0_0_0/0.55))]"
@@ -439,7 +439,9 @@ function ExceptionsSection({ gymId }: { gymId: string }) {
<Loading />
) : (
<div className="divide-y divide-line">
{exceptions.length === 0 && <span className="block text-[0.875rem] text-dim">Brak wyjątków.</span>}
{exceptions.length === 0 && (
<span className="block text-[0.875rem] text-dim">Brak wyjątków.</span>
)}
{exceptions.map((ex) => (
<ListRow
key={ex.id}
@@ -590,7 +592,11 @@ function GallerySection({ gym, onChanged }: { gym: Gym; onChanged: () => void })
)}
{photos.map((photo, i) => (
<div key={photo.id} className="relative overflow-hidden rounded-xl border border-line">
<img src={gymPhotoSrc(photo.url)} alt={`Zdjęcie ${i + 1}`} className="h-32 w-full object-cover" />
<AuthImage
src={photo.url}
alt={`Zdjęcie ${i + 1}`}
className="h-32 w-full object-cover"
/>
{i === 0 && (
<span className="absolute left-1.5 top-1.5 rounded-md bg-black/70 px-1.5 py-0.5 text-[0.7rem] font-semibold text-white">
Okładka
@@ -628,7 +634,14 @@ function GallerySection({ gym, onChanged }: { gym: Gym; onChanged: () => void })
<label className="inline-flex cursor-pointer items-center gap-1.5 rounded-xl border border-line px-3 py-1.5 text-[0.85rem] font-semibold text-dim hover:text-accent-text hover:border-accent">
<ImagePlus className="w-4 h-4" />
{busy ? 'Wgrywanie…' : 'Dodaj zdjęcia'}
<input type="file" accept={PHOTO_MIME_TYPES.join(',')} multiple hidden onChange={onPick} disabled={busy} />
<input
type="file"
accept={PHOTO_MIME_TYPES.join(',')}
multiple
hidden
onChange={onPick}
disabled={busy}
/>
</label>
</div>
{error && <ErrorText>{error}</ErrorText>}

View File

@@ -8,7 +8,7 @@ import { Badge, Card, EmptyState, ErrorText, Loading, MetaItem } from '../../com
import { formatAvailability } from '../../lib/availability';
import { useListSearch } from '../../store/list-search';
import { useTopbar } from '../../topbar';
import { gymPhotoSrc } from './GymDetail';
import { AuthImage } from '../../components/AuthImage';
export default function GymsList() {
useTopbar({
@@ -50,8 +50,8 @@ export default function GymsList() {
onClick={() => navigate(`/gyms/${g.id}`)}
>
{g.coverPhoto ? (
<img
src={gymPhotoSrc(g.coverPhoto)}
<AuthImage
src={g.coverPhoto}
alt={g.name}
className="h-28 w-full object-cover sm:h-32"
/>
@@ -78,7 +78,10 @@ export default function GymsList() {
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<Link to={`/gyms/${g.id}`} className="text-[1.05rem] font-semibold hover:text-accent-text">
<Link
to={`/gyms/${g.id}`}
className="text-[1.05rem] font-semibold hover:text-accent-text"
>
{g.name}
</Link>
<Badge color={g.kind === 'VIRTUAL' ? 'blue' : 'gray'}>
@@ -94,7 +97,9 @@ export default function GymsList() {
</div>
<div className="mt-3 flex flex-wrap gap-x-4 gap-y-1">
<MetaItem icon={Clock}>{formatAvailability(g.availability) || '—'}</MetaItem>
<MetaItem icon={Users}>{g.capacity != null ? `${g.capacity} miejsc` : '—'}</MetaItem>
<MetaItem icon={Users}>
{g.capacity != null ? `${g.capacity} miejsc` : '—'}
</MetaItem>
</div>
</div>
</div>

View File

@@ -43,6 +43,8 @@ export const useAuth = create<AuthState>((set) => ({
const refreshRes = await fetch(`${API_BASE}/auth/refresh`, {
method: 'POST',
credentials: 'include',
// bez nagłówka API sięgnęłoby po ciastko aplikacji użytkownika
headers: { 'X-Client': 'admin' },
});
if (refreshRes.ok) {
const data = await refreshRes.json();