first commit
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
import {create, type StateCreator} from 'zustand';
|
||||
import {createJSONStorage, devtools, persist} from "zustand/middleware";
|
||||
import {info, type InfoResponse, type LoginParams, logout} from "@/api/system/sys_user.ts";
|
||||
import {login} from "@/api/system/sys_user";
|
||||
import type {AuthStore, AuthStoreState, AuthStoreActions} from "./types";
|
||||
|
||||
const authState: AuthStoreState = {
|
||||
userinfo: {},
|
||||
access: [],
|
||||
};
|
||||
|
||||
const authAction: StateCreator<AuthStore, [], [], AuthStoreActions> = (set, get) => ({
|
||||
userId: () => get().userinfo.id,
|
||||
setAccess: (access) => set({access}),
|
||||
login: async (credentials: LoginParams) => {
|
||||
const { data } = await login(credentials);
|
||||
localStorage.setItem("token", data.data!.token);
|
||||
},
|
||||
logout: async () => {
|
||||
await logout();
|
||||
localStorage.removeItem("token");
|
||||
set(authState);
|
||||
},
|
||||
info: async () => {
|
||||
const result = await info();
|
||||
const data: InfoResponse = result.data.data!;
|
||||
set({
|
||||
userinfo: data.info,
|
||||
access: data.access,
|
||||
});
|
||||
},
|
||||
})
|
||||
|
||||
const useUserStore = create<AuthStore>()(
|
||||
devtools(
|
||||
persist(
|
||||
(...args) => ({
|
||||
...authState,
|
||||
...authAction(...args),
|
||||
}),
|
||||
{
|
||||
name: 'auth-storage',
|
||||
storage: createJSONStorage(() => localStorage),
|
||||
}
|
||||
),
|
||||
{ name: 'XinAdmin-Auth' }
|
||||
)
|
||||
);
|
||||
|
||||
export type {AuthStore, AuthStoreState, AuthStoreActions};
|
||||
export default useUserStore;
|
||||
@@ -0,0 +1,16 @@
|
||||
import type {LoginParams} from "@/api/system/sys_user";
|
||||
|
||||
export interface AuthStoreState {
|
||||
userinfo: any;
|
||||
access: any[];
|
||||
}
|
||||
|
||||
export interface AuthStoreActions {
|
||||
login: (credentials: LoginParams) => Promise<void>;
|
||||
logout: () => Promise<void>;
|
||||
userId: () => number;
|
||||
info: () => Promise<void>;
|
||||
setAccess: (assess: string[]) => void;
|
||||
}
|
||||
|
||||
export type AuthStore = AuthStoreState & AuthStoreActions;
|
||||
Reference in New Issue
Block a user