// frontend/js/auth.js import { API_BASE } from "./config.js"; const TOKEN_KEY = "gym_auth_token"; const USER_KEY = "gym_auth_user"; export function getToken() { return localStorage.getItem(TOKEN_KEY); } export function getStoredUser() { try { const raw = localStorage.getItem(USER_KEY); return raw ? JSON.parse(raw) : null; } catch { return null; } } export function setSession(token, user) { // Гарантируем, что данные записаны синхронно localStorage.setItem(TOKEN_KEY, token); localStorage.setItem(USER_KEY, JSON.stringify(user)); // Принудительно обновляем UI статус, если элемент существует const statusEl = document.getElementById('sync-status'); if (statusEl) { statusEl.textContent = '● Авторизовано'; statusEl.className = 'sync-status synced'; } } export function clearSession() { localStorage.removeItem(TOKEN_KEY); localStorage.removeItem(USER_KEY); } /** * Защищённый Fetch wrapper. */ export async function apiFetch(path, options = {}) { const token = getToken(); // Критическая проверка: если токена нет, не идем на сервер if (!token) { console.warn(`⚠️ [AUTH] No token found for request: ${path}. Skipping.`); throw new Error("Not authenticated"); } const headers = new Headers(options.headers || {}); // Всегда добавляем Authorization, перезаписывая любые существующие headers.set("Authorization", `Bearer ${token}`); if (options.body && !headers.has("Content-Type")) { headers.set("Content-Type", "application/json"); } let res; try { res = await fetch(`${API_BASE}${path}`, { ...options, headers, }); } catch (e) { console.error(`❌ [NETWORK] Failed to reach ${path}:`, e); throw e; } // Если 401 — очищаем сессию и кидаем событие if (res.status === 401) { console.error(`❌ [AUTH] Received 401 Unauthorized for ${path}. Clearing session.`); clearSession(); window.dispatchEvent(new Event("auth:unauthorized")); // Пробрасываем ошибку, чтобы вызывающий код знал, что произошло throw new Error("Unauthorized"); } return res; } export async function login(username, password) { const res = await fetch(`${API_BASE}/auth/login`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username, password }), }); if (!res.ok) { const err = await parseError(res, "Login failed"); throw new Error(err); } const data = await res.json(); setSession(data.access_token, data.user); return data.user; } export async function register(username, password, role = "personal") { const res = await fetch(`${API_BASE}/auth/register`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username, password, role }), }); if (!res.ok) { const err = await parseError(res, "Register failed"); throw new Error(err); } const data = await res.json(); setSession(data.access_token, data.user); return data.user; } export async function me() { // Используем apiFetch, чтобы автоматически добавить токен const res = await apiFetch("/auth/me"); if (!res.ok) return null; return await res.json(); } async function parseError(res, fallbackMessage) { try { const err = await res.json(); if (typeof err.detail === "string") return err.detail; if (Array.isArray(err.detail)) { return err.detail .map((d) => `${d.loc?.join(".") || ""}: ${d.msg || ""}`.trim()) .join("; "); } return JSON.stringify(err.detail || err); } catch { return fallbackMessage || res.statusText; } }