| 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`; |
| } |
|
|