summaryrefslogtreecommitdiff
path: root/ping/frontend/src/lib/stores/auth.ts
blob: 97acaf2870c90b3f2a5f73f61e7377a129f025ce (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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<IUser | null>(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);
}