44 lines
1.1 KiB
TypeScript
44 lines
1.1 KiB
TypeScript
import { create } from 'zustand';
|
|
import { AuthAPI, AuthUser } from '../api';
|
|
|
|
interface AuthState {
|
|
user: AuthUser | null;
|
|
loading: boolean;
|
|
/** 启动时调用:从后端拉当前登录态 */
|
|
bootstrap: () => Promise<void>;
|
|
login: (email: string, password: string) => Promise<void>;
|
|
register: (p: { email: string; password: string; name: string; inviteCode?: string }) => Promise<void>;
|
|
logout: () => Promise<void>;
|
|
}
|
|
|
|
export const useAuth = create<AuthState>((set) => ({
|
|
user: null,
|
|
loading: false,
|
|
bootstrap: async () => {
|
|
set({ loading: false });
|
|
},
|
|
login: async (email, password) => {
|
|
const ok = await AuthAPI.verify(email, password);
|
|
if (!ok) throw new Error('身份验证失败');
|
|
set({
|
|
user: {
|
|
id: 'mock',
|
|
email,
|
|
name: email.split('@')[0] || 'User',
|
|
role: 'user'
|
|
}
|
|
});
|
|
},
|
|
register: async (p) => {
|
|
const u = await AuthAPI.register(p);
|
|
set({ user: u });
|
|
},
|
|
logout: async () => {
|
|
try {
|
|
await AuthAPI.logout();
|
|
} catch {
|
|
}
|
|
set({ user: null });
|
|
}
|
|
}));
|