user.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { defineStore } from 'pinia'
  2. import { store } from '@/stores'
  3. interface UserState {
  4. access_token: string
  5. tokenExpiresAt: number
  6. tenant_id: string
  7. pushRecordId: string
  8. needFaceId: boolean
  9. }
  10. export const useUserStore = defineStore('user', {
  11. state: (): UserState => ({
  12. access_token: '',
  13. tokenExpiresAt: 0,
  14. tenant_id: '1',
  15. pushRecordId: '',
  16. needFaceId: false,
  17. }),
  18. actions: {
  19. setAccessToken(token: string, expiresIn?: number | string) {
  20. // expires_in 的单位为秒;未返回时使用后端约定的 12 小时。
  21. const seconds = expiresIn == null || expiresIn === '' ? NaN : Number(expiresIn)
  22. this.access_token = token
  23. this.tokenExpiresAt =
  24. Date.now() + (Number.isFinite(seconds) && seconds >= 0 ? seconds : 12 * 60 * 60) * 1000
  25. this.$persist()
  26. },
  27. hasValidSession() {
  28. if (!this.access_token) return false
  29. if (!Number.isFinite(this.tokenExpiresAt) || Date.now() >= this.tokenExpiresAt) {
  30. this.LogOut()
  31. return false
  32. }
  33. return true
  34. },
  35. setPushRecordId(id: string) {
  36. // 当前链接没有可核对的用户 ID,不能把旧业务的 token 用到另一条链接。
  37. if (id !== this.pushRecordId) this.LogOut()
  38. this.pushRecordId = id
  39. this.$persist()
  40. },
  41. setNeedFaceId(flag: boolean) {
  42. this.needFaceId = flag
  43. },
  44. LogOut() {
  45. this.access_token = ''
  46. this.tokenExpiresAt = 0
  47. this.needFaceId = false
  48. this.$persist()
  49. },
  50. },
  51. persist: {
  52. key: 'user-store',
  53. storage: localStorage,
  54. pick: ['access_token', 'tokenExpiresAt', 'needFaceId', 'tenant_id', 'pushRecordId'],
  55. },
  56. })
  57. export function useUserStoreWithOut() {
  58. return useUserStore(store)
  59. }