From 967be9e750221ab2ab783f95df79bb26d290a45e Mon Sep 17 00:00:00 2001 From: Martial Simon Date: Mon, 15 Sep 2025 01:07:58 +0200 Subject: add: added projects --- ping/frontend/src/lib/stores/auth.ts | 66 ++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 ping/frontend/src/lib/stores/auth.ts (limited to 'ping/frontend/src/lib/stores/auth.ts') diff --git a/ping/frontend/src/lib/stores/auth.ts b/ping/frontend/src/lib/stores/auth.ts new file mode 100644 index 0000000..97acaf2 --- /dev/null +++ b/ping/frontend/src/lib/stores/auth.ts @@ -0,0 +1,66 @@ +import { error } from "@sveltejs/kit"; +import { get, writable } from "svelte/store"; + +export interface IUser { + id: string; + login: string; + displayName: string; + avatar: string; + isAdmin: boolean; +} + +export const user = writable(null); + +export async function getUser() { + const userVal = get(user); + if (userVal) { + return userVal; + } + return getUpdatedUser(); +} + +export async function getUpdatedUser() { + const token = localStorage.getItem("token"); + if (!token) { + localStorage.clear(); + window.location.replace("/login"); + throw new Error("Pas de token"); + } + try { + const userId = JSON.parse(atob(token.split(".")[1])).sub; + + const res = await authFetch(`/api/user/${userId}`); + if (!res.ok) { + throw error(res.status, "Erreur lors de la récupération de l'utilisateur"); + } + const data = await res.json(); + user.set({ ...data }); + return data; + } + catch (e) { + console.error("Erreur lors de la récupération de l'ID utilisateur depuis le token", e); + localStorage.clear(); + window.location.replace("/login"); + throw new Error("Token invalide " + e); + } +} + +// place files you want to import through the `$lib` alias in this folder. +export function authFetch(url: string | URL, options: RequestInit = {}) { + const token = localStorage.getItem("token"); + if (!token) { + localStorage.clear(); + window.location.replace("/login"); + throw new Error("Pas de token"); + } + + const mergedOptions: RequestInit = { + ...options, + headers: { + Authorization: `Bearer ${token}`, + ...(options.headers ?? {}) + } + }; + + return fetch(url, mergedOptions); +} \ No newline at end of file -- cgit v1.2.3