IntelliClass_FE/stores/loginState.ts
Timothy Yin b05f954923
feat: add authentication requirements to course preparation and resources pages
fix: update home page background image and remove unnecessary redirect code

chore: update pnpm lock file with new dependencies for auto-animate and svg spinners

delete: remove unused images from public directory

refactor: modify course and user types for better clarity and structure

feat: implement course API with CRUD operations and teacher team management

feat: create user authentication page with login functionality and validation

feat: add login state management with Pinia for user session handling

style: create reusable UI components for cards and tabs

chore: implement HTTP utility for API requests with error handling
2025-04-06 00:25:20 +08:00

63 lines
1.5 KiB
TypeScript

import { userProfile } from "~/api";
import type { IUser } from "~/types";
export const useLoginState = defineStore(
"loginState",
() => {
const isLoggedIn = ref(false);
const token = ref<string | null>(null);
const user = ref<IUser>({} as IUser);
const checkLogin = async (): Promise<IUser | false> => {
return new Promise((resolve, reject) => {
if (!token.value) {
user.value = {} as IUser;
isLoggedIn.value = false;
return reject(false);
}
userProfile()
.then((res) => {
if (res.code === 200) {
user.value = res.user;
isLoggedIn.value = true;
resolve(res.user);
} else {
user.value = {} as IUser;
isLoggedIn.value = false;
token.value = null;
reject(false);
}
})
.catch((_) => {
user.value = {} as IUser;
isLoggedIn.value = false;
token.value = null;
reject(false);
});
});
};
const logout = () => {
isLoggedIn.value = false;
token.value = null;
user.value = {} as IUser;
};
return {
isLoggedIn,
token,
user,
checkLogin,
logout,
};
},
{
persist: {
key: "xshic_user_state",
storage: piniaPluginPersistedstate.localStorage(),
pick: ["isLoggedIn", "token", "user"],
},
}
);