From 3c32d4ce3cb5c5d9a9c053d579082995f3cb61c7 Mon Sep 17 00:00:00 2001 From: huangzhuang_3rd Date: Wed, 12 Aug 2026 13:31:23 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20AI=20Worker=20=E5=B9=B3=E5=8F=B0=20MVP?= =?UTF-8?q?=20v1.0.0=20-=20=E5=A4=9A=E7=A7=9F=E6=88=B7/=E9=A1=B9=E7=9B=AE?= =?UTF-8?q?=E7=AE=A1=E7=90=86/AI=20Worker/=E4=BB=BB=E5=8A=A1=E7=BC=96?= =?UTF-8?q?=E6=8E=92/HITL=E5=AE=A1=E6=A0=B8/=E6=88=90=E6=9C=AC=E6=B2=BB?= =?UTF-8?q?=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/src/stores/auth.ts | 87 +++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 frontend/src/stores/auth.ts diff --git a/frontend/src/stores/auth.ts b/frontend/src/stores/auth.ts new file mode 100644 index 0000000..08037dc --- /dev/null +++ b/frontend/src/stores/auth.ts @@ -0,0 +1,87 @@ +import { create } from 'zustand'; +import { persist } from 'zustand/middleware'; +import type { User, LoginPayload, RegisterPayload } from '@/types'; +import { authApi } from '@/api'; + +interface AuthState { + token: string | null; + user: User | null; + loading: boolean; + isAuthenticated: boolean; + + login: (data: LoginPayload) => Promise; + register: (data: RegisterPayload) => Promise; + fetchMe: () => Promise; + logout: () => void; + setUser: (user: User | null) => void; +} + +export const useAuthStore = create()( + persist( + (set) => ({ + token: null, + user: null, + loading: false, + isAuthenticated: false, + + login: async (data: LoginPayload) => { + set({ loading: true }); + try { + const res = await authApi.login(data); + localStorage.setItem('access_token', res.access_token); + set({ + token: res.access_token, + user: res.user, + isAuthenticated: true, + loading: false, + }); + } catch { + set({ loading: false }); + throw new Error('登录失败,请检查邮箱和密码'); + } + }, + + register: async (data: RegisterPayload) => { + set({ loading: true }); + try { + const res = await authApi.register(data); + localStorage.setItem('access_token', res.access_token); + set({ + token: res.access_token, + user: res.user, + isAuthenticated: true, + loading: false, + }); + } catch { + set({ loading: false }); + throw new Error('注册失败,请检查输入信息'); + } + }, + + fetchMe: async () => { + try { + const user = await authApi.me(); + set({ user, isAuthenticated: true, loading: false }); + } catch { + set({ loading: false }); + throw new Error('获取用户信息失败'); + } + }, + + logout: () => { + localStorage.removeItem('access_token'); + set({ token: null, user: null, isAuthenticated: false }); + }, + + setUser: (user: User | null) => set({ user }), + }), + { + name: 'auth-storage', + partialize: (state) => ({ + token: state.token, + user: state.user, + isAuthenticated: state.isAuthenticated, + }), + } + ) +);