Files
ai-contract-platform/frontend/src/stores/auth.store.ts
T
2026-04-24 13:44:17 +08:00

83 lines
2.3 KiB
TypeScript

import { create } from "zustand";
import { persist } from "zustand/middleware";
import type { CurrentUser } from "@/types/api";
type AuthState = {
accessToken: string | null;
currentUser: CurrentUser | null;
setAccessToken: (token: string | null) => void;
setCurrentUser: (user: CurrentUser | null) => void;
clear: () => void;
};
const ACCESS_TOKEN_STORAGE_KEY = "access_token";
const AUTH_STORE_STORAGE_KEY = "auth-store";
export const useAuthStore = create<AuthState>()(
persist(
(set) => ({
accessToken: null,
currentUser: null,
setAccessToken: (token) => set({ accessToken: token }),
setCurrentUser: (user) => set({ currentUser: user }),
clear: () => set({ accessToken: null, currentUser: null }),
}),
{
name: AUTH_STORE_STORAGE_KEY,
},
),
);
function persistSessionSnapshot(accessToken: string | null, currentUser: CurrentUser | null) {
if (typeof window === "undefined") {
return;
}
if (accessToken) {
window.localStorage.setItem(ACCESS_TOKEN_STORAGE_KEY, accessToken);
} else {
window.localStorage.removeItem(ACCESS_TOKEN_STORAGE_KEY);
}
if (accessToken || currentUser) {
window.localStorage.setItem(AUTH_STORE_STORAGE_KEY, JSON.stringify({ state: { accessToken, currentUser }, version: 0 }));
} else {
window.localStorage.removeItem(AUTH_STORE_STORAGE_KEY);
}
}
export function getStoredAccessToken() {
if (typeof window === "undefined") {
return null;
}
return window.localStorage.getItem(ACCESS_TOKEN_STORAGE_KEY);
}
export function syncSession(accessToken: string, currentUser: CurrentUser | null) {
useAuthStore.setState({ accessToken, currentUser });
persistSessionSnapshot(accessToken, currentUser);
}
export function syncCurrentUser(currentUser: CurrentUser | null) {
const accessToken = useAuthStore.getState().accessToken ?? getStoredAccessToken();
useAuthStore.setState({ accessToken, currentUser });
persistSessionSnapshot(accessToken, currentUser);
}
export function clearSession() {
useAuthStore.getState().clear();
persistSessionSnapshot(null, null);
}
export function handleSessionExpired() {
clearSession();
if (typeof window === "undefined" || window.location.pathname === "/login") {
return;
}
window.location.replace("/login");
}