File size: 2,131 Bytes
288c05b
32177e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
288c05b
 
 
 
 
32177e2
 
 
 
 
 
 
 
 
 
 
288c05b
 
 
32177e2
 
 
 
288c05b
32177e2
 
 
 
 
 
 
 
 
 
 
 
 
 
288c05b
 
32177e2
 
288c05b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32177e2
 
288c05b
32177e2
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
export const AUTH_TOKEN_KEY = 'sevima_raghub_auth_token';
const AUTH_USER_KEY = 'sevima_raghub_auth_user';

export type AuthRole = 'admin' | 'student' | 'lecturer';

export type AuthUser = {
    id: number;
    identity_number: string;
    name?: string;
    role: AuthRole;
    email: string;
    status: 'active' | 'inactive';
    created_at: string;
    updated_at: string;
};

export function getStoredAuthToken(): string | null {
    if (typeof window === 'undefined') {
        return null;
    }

    const rememberedToken = window.localStorage.getItem(AUTH_TOKEN_KEY);
    const sessionToken = window.sessionStorage.getItem(AUTH_TOKEN_KEY);
    const token = rememberedToken ?? sessionToken;

    return token ?? readCookie(AUTH_TOKEN_KEY);
}

export function getStoredAuthUser(): AuthUser | null {
    if (typeof window === 'undefined') {
        return null;
    }

    const rawUser =
        window.localStorage.getItem(AUTH_USER_KEY) ??
        window.sessionStorage.getItem(AUTH_USER_KEY);

    const storedUser = rawUser ?? readCookie(AUTH_USER_KEY);

    if (!storedUser) {
        return null;
    }

    try {
        return JSON.parse(storedUser) as AuthUser;
    } catch {
        return null;
    }
}

export function clearAuthSession(): void {
    if (typeof window === 'undefined') {
        return;
    }

    window.localStorage.removeItem(AUTH_TOKEN_KEY);
    window.localStorage.removeItem(AUTH_USER_KEY);
    window.sessionStorage.removeItem(AUTH_TOKEN_KEY);
    window.sessionStorage.removeItem(AUTH_USER_KEY);
    clearCookie(AUTH_TOKEN_KEY);
    clearCookie(AUTH_USER_KEY);
}

function readCookie(name: string): string | null {
    if (typeof document === 'undefined') {
        return null;
    }

    const cookie = document.cookie
        .split('; ')
        .find((item) => item.startsWith(`${name}=`));

    if (!cookie) {
        return null;
    }

    return decodeURIComponent(cookie.slice(name.length + 1));
}

function clearCookie(name: string): void {
    if (typeof document === 'undefined') {
        return;
    }

    document.cookie = `${name}=; Path=/; SameSite=Lax; Max-Age=0`;
}