feat(auth): add Zustand store for authentication management

- Implemented a Zustand store to manage authentication state.
- Added user information handling, including user roles and organization switching.
- Integrated toast notifications for user feedback on actions.
- Included initialization logic to check for local user and token.
This commit is contained in:
2026-02-22 01:18:28 +08:00
parent 8349e1ca4c
commit ce38fd6dad
4 changed files with 2913 additions and 7 deletions

65
src/pages/auth/store.ts Normal file
View File

@@ -0,0 +1,65 @@
import { queryLogin } from '@/modules/query';
import { create } from 'zustand';
import { toast } from 'sonner';
type UserInfo = {
id?: string;
username?: string;
nickname?: string | null;
needChangePassword?: boolean;
description?: string | null;
type?: 'user' | 'org';
orgs?: string[];
avatar?: string;
};
export type LayoutStore = {
open: boolean;
setOpen: (open: boolean) => void;
openUser: boolean;
setOpenUser: (openUser: boolean) => void;
me?: UserInfo;
setMe: (me: UserInfo) => void;
getMe: () => Promise<void>;
switchOrg: (username?: string) => Promise<void>;
isAdmin: boolean;
setIsAdmin: (isAdmin: boolean) => void
init: () => Promise<void>;
};
export const useLayoutStore = create<LayoutStore>((set, get) => ({
open: false,
setOpen: (open) => set({ open }),
openUser: false,
setOpenUser: (openUser) => set({ openUser }),
me: undefined,
setMe: (me) => set({ me }),
getMe: async () => {
const res = await queryLogin.getMe();
if (res.code === 200) {
set({ me: res.data });
set({ isAdmin: res.data.orgs?.includes?.('admin') || false });
}
},
switchOrg: async (username?: string) => {
const res = await queryLogin.switchUser(username || '');
if (res.code === 200) {
toast.success('切换成功');
setTimeout(() => {
window.location.reload();
}, 1000);
} else {
toast.error(res.message || '请求失败');
}
},
isAdmin: false,
setIsAdmin: (isAdmin) => set({ isAdmin }),
init: async () => {
const token = await queryLogin.getToken()
if (token) {
const user = await queryLogin.checkLocalUser() as UserInfo;
if (user) {
set({ me: user });
set({ isAdmin: user.orgs?.includes?.('admin') || false });
}
}
}
}));