| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- 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 errors = ref({})
- const user = ref<User | null>(JSON.parse(storages.getItem(USER_KEY) ?? "{}"))
- const isAuthenticated = ref(!!JwtService.getToken())
- function setAuth(authUser: User) {
- isAuthenticated.value = true
- errors.value = {}
- user.value = authUser
- console.log("AUTHUSER", authUser)
- storages.setItem(USER_KEY, JSON.stringify(authUser))
- JwtService.saveToken(authUser.token)
- }
- function setError(error: any) {
- errors.value = { ...error }
- }
- function purgeAuth() {
- isAuthenticated.value = false
- user.value = null
- errors.value = []
- storages.removeItem(USER_KEY)
- appStore.menuStore.removeMenus()
- JwtService.destroyToken()
- }
- function login(userName: string, password: string) {
- purgeAuth()
- 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 {
- setError(data.msg)
- reject(data)
- }
- })
- })
- }
- function logout() {
- purgeAuth()
- }
- function verifyAuth() {
- if (JwtService.getToken()) {
- //TODO
- } else {
- purgeAuth()
- }
- }
- return {
- errors,
- user,
- isAuthenticated,
- login,
- logout,
- verifyAuth,
- }
- })
|