_auth.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import { ref } from "vue"
  2. import { defineStore } from "pinia"
  3. import JwtService from "@/core/services/JwtService"
  4. import apis from "@/api"
  5. import storages from "@/core/utils/storages"
  6. import appStore from "."
  7. export interface User {
  8. userName: string
  9. userType: string
  10. orgId: string
  11. token: string
  12. }
  13. export const useAuthStore = defineStore("auth", () => {
  14. const USER_KEY = "user"
  15. const errors = ref({})
  16. const user = ref<User | null>(JSON.parse(storages.getItem(USER_KEY) ?? "{}"))
  17. const isAuthenticated = ref(!!JwtService.getToken())
  18. function setAuth(authUser: User) {
  19. isAuthenticated.value = true
  20. errors.value = {}
  21. user.value = authUser
  22. console.log("AUTHUSER", authUser)
  23. storages.setItem(USER_KEY, JSON.stringify(authUser))
  24. JwtService.saveToken(authUser.token)
  25. }
  26. function setError(error: any) {
  27. errors.value = { ...error }
  28. }
  29. function purgeAuth() {
  30. isAuthenticated.value = false
  31. user.value = null
  32. errors.value = []
  33. storages.removeItem(USER_KEY)
  34. appStore.menuStore.removeMenus()
  35. JwtService.destroyToken()
  36. }
  37. function login(userName: string, password: string) {
  38. purgeAuth()
  39. return new Promise<void>((resolve, reject) => {
  40. apis.authApi.login({ userName: userName, password: password }).then(({ data }) => {
  41. if (data) {
  42. const result = data
  43. setAuth({
  44. userName: result.authName || "",
  45. userType: result.userType || "0",
  46. orgId: result.enterpriseId || "",
  47. token: result.auth,
  48. })
  49. resolve(result.loginMsg)
  50. } else {
  51. setError(data.msg)
  52. reject(data)
  53. }
  54. })
  55. })
  56. }
  57. function logout() {
  58. purgeAuth()
  59. }
  60. function verifyAuth() {
  61. if (JwtService.getToken()) {
  62. //TODO
  63. } else {
  64. purgeAuth()
  65. }
  66. }
  67. return {
  68. errors,
  69. user,
  70. isAuthenticated,
  71. login,
  72. logout,
  73. verifyAuth,
  74. }
  75. })