authStore.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import { create } from 'zustand'
  2. import { getCookie, setCookie, removeCookie } from '@/lib/cookies'
  3. const ACCESS_TOKEN = 'thisisjustarandomstring'
  4. interface AuthUser {
  5. accountNo: string
  6. email: string
  7. role: string[]
  8. exp: number
  9. }
  10. interface AuthState {
  11. auth: {
  12. user: AuthUser | null
  13. setUser: (user: AuthUser | null) => void
  14. accessToken: string
  15. setAccessToken: (accessToken: string) => void
  16. resetAccessToken: () => void
  17. reset: () => void
  18. }
  19. }
  20. export const useAuthStore = create<AuthState>()((set) => {
  21. const cookieState = getCookie(ACCESS_TOKEN)
  22. const initToken = cookieState ? JSON.parse(cookieState) : ''
  23. return {
  24. auth: {
  25. user: null,
  26. setUser: (user) =>
  27. set((state) => ({ ...state, auth: { ...state.auth, user } })),
  28. accessToken: initToken,
  29. setAccessToken: (accessToken) =>
  30. set((state) => {
  31. setCookie(ACCESS_TOKEN, JSON.stringify(accessToken))
  32. return { ...state, auth: { ...state.auth, accessToken } }
  33. }),
  34. resetAccessToken: () =>
  35. set((state) => {
  36. removeCookie(ACCESS_TOKEN)
  37. return { ...state, auth: { ...state.auth, accessToken: '' } }
  38. }),
  39. reset: () =>
  40. set((state) => {
  41. removeCookie(ACCESS_TOKEN)
  42. return {
  43. ...state,
  44. auth: { ...state.auth, user: null, accessToken: '' },
  45. }
  46. }),
  47. },
  48. }
  49. })