| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- import { ref } from "vue"
- import { defineStore } from "pinia"
- import JwtService from "@/core/services/JwtService"
- import apis from "@/api"
- import storages from "@/core/utils/storages"
- import appStore from "."
- export interface User {
- userName: string
- userType: string
- orgId: string
- token: string
- }
- export const useAuthStore = defineStore("auth", () => {
- const USER_KEY = "user"
- const user = ref<User | null>(JSON.parse(storages.getItem(USER_KEY) ?? "{}"))
- const isAuthenticated = ref(!!JwtService.getToken())
- function setAuth(authUser: User) {
- isAuthenticated.value = true
- user.value = authUser
- console.log("AUTHUSER", authUser)
- storages.setItem(USER_KEY, JSON.stringify(authUser))
- JwtService.saveToken(authUser.token)
- }
- function purgeAuth() {
- isAuthenticated.value = false
- user.value = null
- storages.removeItem(USER_KEY)
- appStore.menuStore.removeMenus()
- appStore.bodyConfigStore.clearThemeMode()
- JwtService.destroyToken()
- }
- function login(userName: string, password: string) {
- purgeAuth()
- //console.log("LOGIN")
- return new Promise<void>((resolve, reject) => {
- apis.authApi
- .login({ userName: userName, password: password })
- .then(({ data }) => {
- if (data) {
- const result = data
- setAuth({
- userName: result.authName || "",
- userType: result.userType || "0",
- orgId: result.enterpriseId || "",
- token: result.auth,
- })
- resolve(result.loginMsg)
- } else {
- reject(data.msg)
- }
- })
- .catch(() => {
- //console.log("ERROR_LOGIN", e)
- reject("用户名或密码错误!")
- })
- })
- }
- function logout() {
- purgeAuth()
- }
- function verifyAuth() {
- if (JwtService.getToken()) {
- //TODO
- } else {
- purgeAuth()
- }
- }
- return {
- user,
- isAuthenticated,
- login,
- logout,
- verifyAuth,
- }
- })
|