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 WaveUI from '../../node_modules/wave-ui/src/wave-ui/core'
  2. import { authenticator, currentProfile } from '../services'
  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 =
  29. await authenticator.validateSession(hashedAccessToken)
  30. if (validatedToken.error) {
  31. console.error('ERROR :=>', validatedToken.error)
  32. } else {
  33. return validatedToken
  34. }
  35. }
  36. const loginIfToken = async () => {
  37. const sessionData = await verifySession()
  38. if (
  39. sessionData?.profileId &&
  40. sessionData?.accessToken &&
  41. !currentProfile.isLoggedIn
  42. ) {
  43. await currentProfile.login(
  44. sessionData.profileId,
  45. // NOTE: probably not correct...
  46. WaveUI.notify,
  47. sessionData.accessToken,
  48. )
  49. }
  50. }
  51. const checkLoginStatus = async (destination, nextCb) => {
  52. await loginIfToken()
  53. log(destination)
  54. if (DEV_MODE) {
  55. nextCb()
  56. } else if (
  57. destination.meta.requiresCompleteProfile &&
  58. !currentProfile.isLoggedIn &&
  59. !currentProfile.isComplete
  60. ) {
  61. nextCb('onboarding')
  62. } else if (
  63. destination.meta.requiresCompleteProfile &&
  64. destination.meta.requiresAuth &&
  65. !currentProfile.isLoggedIn
  66. ) {
  67. nextCb('login')
  68. } else {
  69. nextCb()
  70. }
  71. }
  72. export { checkLoginStatus }