File size: 2,029 Bytes
8d7950f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
67
68
69
70
/**
 * Auth Utility for LeadPilot
 * Handles secure storage and retrieval of authentication tokens and active workspace IDs.
 */

const TOKEN_KEY = "leadpilot_auth_token";
const WORKSPACE_KEY = "leadpilot_active_workspace";

export const auth = {
    getToken: (): string | null => {
        if (typeof window === "undefined") return null;
        return localStorage.getItem(TOKEN_KEY);
    },

    setToken: (token: string): void => {
        if (typeof window === "undefined") return;
        localStorage.setItem(TOKEN_KEY, token);
    },

    clearToken: (): void => {
        if (typeof window === "undefined") return;
        localStorage.removeItem(TOKEN_KEY);
    },

    getWorkspaceId: (): string | null => {
        if (typeof window === "undefined") return null;
        return localStorage.getItem(WORKSPACE_KEY);
    },

    setWorkspaceId: (id: string): void => {
        if (typeof window === "undefined") return;
        localStorage.setItem(WORKSPACE_KEY, id);
    },

    isAuthed: (): boolean => {
        return !!auth.getToken();
    },

    logout: (): void => {
        auth.clearToken();
        if (typeof window !== "undefined") {
            localStorage.removeItem(WORKSPACE_KEY);
            window.location.href = "/login";
        }
    },

    getDecodedToken: (): any | null => {
        const token = auth.getToken();
        if (!token) return null;
        try {
            const base64Url = token.split(".")[1];
            const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
            const jsonPayload = decodeURIComponent(
                atob(base64)
                    .split("")
                    .map((c) => "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2))
                    .join("")
            );
            return JSON.parse(jsonPayload);
        } catch (e) {
            return null;
        }
    },

    isImpersonating: (): boolean => {
        const decoded = auth.getDecodedToken();
        return !!decoded?.impersonated_by_admin_id;
    },
};