_auth.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 user = ref<User | null>(JSON.parse(storages.getItem(USER_KEY) ?? "{}"))
  16. const isAuthenticated = ref(!!JwtService.getToken())
  17. function setAuth(authUser: User) {
  18. isAuthenticated.value = true
  19. user.value = authUser
  20. console.log("AUTHUSER", authUser)
  21. storages.setItem(USER_KEY, JSON.stringify(authUser))
  22. JwtService.saveToken(authUser.token)
  23. }
  24. function purgeAuth() {
  25. isAuthenticated.value = false
  26. user.value = null
  27. storages.removeItem(USER_KEY)
  28. appStore.menuStore.removeMenus()
  29. appStore.bodyConfigStore.clearThemeMode()
  30. JwtService.destroyToken()
  31. }
  32. function login(userName: string, password: string) {
  33. purgeAuth()
  34. //console.log("LOGIN")
  35. return new Promise<void>((resolve, reject) => {
  36. apis.authApi
  37. .login({ userName: userName, password: password })
  38. .then(({ data }) => {
  39. if (data) {
  40. const result = data
  41. setAuth({
  42. userName: result.authName || "",
  43. userType: result.userType || "0",
  44. orgId: result.enterpriseId || "",
  45. token: result.auth,
  46. })
  47. resolve(result.loginMsg)
  48. } else {
  49. reject(data.msg)
  50. }
  51. })
  52. .catch(() => {
  53. //console.log("ERROR_LOGIN", e)
  54. reject("用户名或密码错误!")
  55. })
  56. })
  57. }
  58. function logout() {
  59. purgeAuth()
  60. }
  61. function verifyAuth() {
  62. if (JwtService.getToken()) {
  63. //TODO
  64. } else {
  65. purgeAuth()
  66. }
  67. }
  68. return {
  69. user,
  70. isAuthenticated,
  71. login,
  72. logout,
  73. verifyAuth,
  74. }
  75. })