feat: implement login functionality with error handling and session management

This commit is contained in:
2026-07-13 10:40:40 +05:30
parent e0167caf85
commit 36302ff564
5 changed files with 162 additions and 16 deletions
+39
View File
@@ -0,0 +1,39 @@
import type { AuthUser, LoginResult } from "@/lib/api/auth"
const ACCESS_TOKEN_KEY = "hexa_erp_access_token"
const REFRESH_TOKEN_KEY = "hexa_erp_refresh_token"
const USER_KEY = "hexa_erp_user"
/** remember=true persists across browser restarts (localStorage); otherwise session-only. */
export function persistSession(result: LoginResult, remember: boolean) {
const store = remember ? window.localStorage : window.sessionStorage
const other = remember ? window.sessionStorage : window.localStorage
for (const key of [ACCESS_TOKEN_KEY, REFRESH_TOKEN_KEY, USER_KEY]) other.removeItem(key)
store.setItem(ACCESS_TOKEN_KEY, result.accessToken)
store.setItem(REFRESH_TOKEN_KEY, result.refreshToken)
store.setItem(USER_KEY, JSON.stringify(result.user))
}
export function getAccessToken(): string | null {
if (typeof window === "undefined") return null
return window.localStorage.getItem(ACCESS_TOKEN_KEY) ?? window.sessionStorage.getItem(ACCESS_TOKEN_KEY)
}
export function getStoredUser(): AuthUser | null {
if (typeof window === "undefined") return null
const raw = window.localStorage.getItem(USER_KEY) ?? window.sessionStorage.getItem(USER_KEY)
if (!raw) return null
try {
return JSON.parse(raw) as AuthUser
} catch {
return null
}
}
export function clearSession() {
for (const key of [ACCESS_TOKEN_KEY, REFRESH_TOKEN_KEY, USER_KEY]) {
window.localStorage.removeItem(key)
window.sessionStorage.removeItem(key)
}
}