You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

guards.js 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import { currentProfile, authenticator } from '../services'
  2. import WaveUI from '../../node_modules/wave-ui/src/wave-ui/core'
  3. const DEV_MODE = import.meta.env.VITE_DEV == 'true'
  4. async function log(to) {
  5. if (DEV_MODE) {
  6. if (!currentProfile.isLoggedIn || !currentProfile.isComplete) {
  7. console.info(
  8. `[Guard Status debug]: Profile: ${currentProfile.id.value} | Login: ${currentProfile.isLoggedIn} | Complete: ${currentProfile.isComplete}`,
  9. )
  10. }
  11. console.info('[Guard Status debug]: being routed to:', to.fullPath)
  12. }
  13. }
  14. // TODO: move to utils/index.js and import to this file, OnboardingView.vue and VerifyView.vue
  15. const grabStoredCookie = cookieKey => {
  16. const cookies = document.cookie.split('; ').reduce((prev, current) => {
  17. const [name, ...value] = current.split('=')
  18. prev[name] = value.join('=')
  19. return prev
  20. }, {})
  21. const cookieVal = cookieKey in cookies ? cookies[`${cookieKey}`] : undefined
  22. return cookieVal
  23. }
  24. const verifySession = async () => {
  25. const hashedAccessToken = grabStoredCookie('siimee_access')
  26. if (!hashedAccessToken)
  27. return console.warn('WARNING :=> accessToken is not defined')
  28. const validatedToken = await authenticator.validateSession(
  29. hashedAccessToken,
  30. )
  31. if (validatedToken.error) {
  32. console.error('ERROR :=>', validatedToken.error)
  33. } else {
  34. return validatedToken
  35. }
  36. }
  37. const loginIfToken = async () => {
  38. const sessionData = await verifySession()
  39. if (
  40. sessionData?.profileId &&
  41. sessionData?.accessToken &&
  42. !currentProfile.isLoggedIn
  43. ) {
  44. await currentProfile.login(
  45. sessionData.profileId,
  46. // NOTE: probably not correct...
  47. WaveUI.notify,
  48. sessionData.accessToken,
  49. )
  50. }
  51. }
  52. const checkLoginStatus = async (destination, nextCb) => {
  53. await loginIfToken()
  54. log(destination)
  55. if (DEV_MODE) {
  56. nextCb()
  57. } else if (
  58. destination.meta.requiresCompleteProfile &&
  59. !currentProfile.isLoggedIn &&
  60. !currentProfile.isComplete
  61. ) {
  62. nextCb('onboarding')
  63. } else if (
  64. destination.meta.requiresCompleteProfile &&
  65. destination.meta.requiresAuth &&
  66. !currentProfile.isLoggedIn
  67. ) {
  68. nextCb('login')
  69. } else {
  70. nextCb()
  71. }
  72. }
  73. export { checkLoginStatus }