admin.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { auth } from '~/helpers/auth';
  2. import { UNAUTHORIZED } from '~/helpers/errors';
  3. import { HoppModule } from '.';
  4. const isSetupRoute = (to: unknown) => to === 'setup';
  5. const isGuestRoute = (to: unknown) => ['index', 'enter'].includes(to as string);
  6. const getFirstTimeInfraSetupStatus = async () => {
  7. const isInfraNotSetup = await auth.getFirstTimeInfraSetupStatus();
  8. return isInfraNotSetup;
  9. };
  10. /**
  11. * @module routers
  12. */
  13. /**
  14. * @function
  15. * @name onBeforeRouteChange
  16. * @param {object} to
  17. * @param {object} from
  18. * @param {function} next
  19. * @returns {void}
  20. */
  21. export default <HoppModule>{
  22. async onBeforeRouteChange(to, _from, next) {
  23. const res = await auth.getUserDetails();
  24. // Allow performing the silent refresh flow for an invalid access token state
  25. if (res.errors?.[0].message === UNAUTHORIZED) {
  26. return next();
  27. }
  28. const isAdmin = res.data?.me.isAdmin;
  29. // Route Guards
  30. if (!isGuestRoute(to.name) && !isAdmin) {
  31. /**
  32. * Reroutes the user to the login page if user is not logged in
  33. * and is not an admin
  34. */
  35. return next({ name: 'index' });
  36. }
  37. if (isAdmin) {
  38. // These route guards applies to the case where the user is logged in successfully and validated as an admin
  39. const isInfraNotSetup = await getFirstTimeInfraSetupStatus();
  40. /**
  41. * Reroutes the user to the dashboard homepage if they have setup the infra already
  42. * Else, the Setup page
  43. */
  44. if (isGuestRoute(to.name)) {
  45. const name = isInfraNotSetup ? 'setup' : 'dashboard';
  46. return next({ name });
  47. }
  48. /**
  49. * Reroutes the user to the dashboard homepage if they have setup the infra already
  50. * and are trying to access the setup page
  51. */
  52. if (isSetupRoute(to.name) && !isInfraNotSetup) {
  53. return next({ name: 'dashboard' });
  54. }
  55. /**
  56. * Reroutes the user to the setup page if they have not setup the infra yet
  57. * and tries to access a valid route which is not a guest route
  58. */
  59. if (isInfraNotSetup && !isSetupRoute(to.name)) {
  60. return next({ name: 'setup' });
  61. }
  62. }
  63. next();
  64. },
  65. };