lots of work done, dashboards added

This commit is contained in:
2026-11-20 01:03:35 +03:00
parent 2a5c9709e0
commit 9a987baa5c
19 changed files with 2712 additions and 785 deletions
+23 -34
View File
@@ -5,16 +5,10 @@ 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);
@@ -24,17 +18,19 @@ export function getStoredUser() {
}
}
/**
* Сохранить сессию (токен + данные пользователя)
*/
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';
}
}
/**
* Очистить сессию (Logout)
*/
export function clearSession() {
localStorage.removeItem(TOKEN_KEY);
localStorage.removeItem(USER_KEY);
@@ -42,19 +38,21 @@ export function clearSession() {
/**
* Защищённый Fetch wrapper.
* Автоматически добавляет Authorization header.
* При получении 401 очищает сессию и вызывает событие 'auth:unauthorized'.
*/
export async function apiFetch(path, options = {}) {
const token = getToken();
const headers = new Headers(options.headers || {});
if (token) {
headers.set("Authorization", `Bearer ${token}`);
// Критическая проверка: если токена нет, не идем на сервер
if (!token) {
console.warn(`⚠️ [AUTH] No token found for request: ${path}. Skipping.`);
throw new Error("Not authenticated");
}
// Если есть тело запроса и Content-Type не задан явно — ставим JSON
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");
}
@@ -66,23 +64,22 @@ export async function apiFetch(path, options = {}) {
headers,
});
} catch (e) {
// Сеть недоступна или другая ошибка транспорта
// Не логаутим автоматически, просто пробрасываем ошибку
console.error(`❌ [NETWORK] Failed to reach ${path}:`, e);
throw e;
}
// Если сервер ответил 401 Unauthorized — токен протух или неверный
// Если 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",
@@ -100,9 +97,6 @@ export async function login(username, password) {
return data.user;
}
/**
* Регистрация нового пользователя
*/
export async function register(username, password, role = "personal") {
const res = await fetch(`${API_BASE}/auth/register`, {
method: "POST",
@@ -120,18 +114,13 @@ export async function register(username, password, role = "personal") {
return data.user;
}
/**
* Проверка токена / получение текущего пользователя
*/
export async function me() {
// Используем apiFetch, чтобы автоматически добавить токен
const res = await apiFetch("/auth/me");
if (!res.ok) return null;
return await res.json();
}
/**
* Хелпер для парсинга ошибок FastAPI/Pydantic
*/
async function parseError(res, fallbackMessage) {
try {
const err = await res.json();