feat: new route guards for the new setup flow

This commit is contained in:
Joel Jacob Stephen
2024-02-23 20:11:14 +05:30
parent 041eeab4d2
commit ae9e32b427
2 changed files with 61 additions and 14 deletions

View File

@@ -244,7 +244,7 @@ export const auth = {
getFirstTimeInfraSetupStatus: async (): Promise<boolean> => {
try {
const res = await authQuery.getFirstTimeInfraSetupStatus();
return res.data?.value;
return res.data?.value === 'true' ? true : false;
} catch (err) {
// Setup is not done
return true;

View File

@@ -1,14 +1,19 @@
import { auth } from '~/helpers/auth';
import { HoppModule } from '.';
const isAdmin = () => {
const user = auth.getCurrentUser();
return user ? user.isAdmin : false;
const isSetupRoute = (to: unknown) => to === 'setup';
const isGuestRoute = (to: unknown) => ['index', 'enter'].includes(to as string);
const getAdminStatus = async () => {
const user = await auth.checkCurrentUser();
return !!user?.isAdmin;
};
const GUEST_ROUTES = ['index', 'enter'];
const isGuestRoute = (to: unknown) => GUEST_ROUTES.includes(to as string);
const getFirstTimeInfraSetupStatus = async () => {
const isInfraNotSetup = await auth.getFirstTimeInfraSetupStatus();
return isInfraNotSetup;
};
/**
* @module routers
@@ -24,13 +29,55 @@ const isGuestRoute = (to: unknown) => GUEST_ROUTES.includes(to as string);
*/
export default <HoppModule>{
onBeforeRouteChange(to, from, next) {
if (!isGuestRoute(to.name) && !isAdmin()) {
next({ name: 'index' });
} else if (isGuestRoute(to.name) && isAdmin()) {
next({ name: 'dashboard' });
} else {
next();
async onBeforeRouteChange(to, _from, next) {
const isAdmin = await getAdminStatus();
if (!isAdmin) {
auth.signOutUser();
}
// Route Guards
if (!isGuestRoute(to.name) && !isAdmin) {
/**
* Reroutes the user to the login page if user is not logged in
* and is not an admin
*/
return next({ name: 'index' });
}
if (isAdmin) {
// This block applies to the case where the user is logged in successfully and validated as an admin
const isInfraNotSetup = await getFirstTimeInfraSetupStatus();
/**
* Reroutes the user to the dashboard homepage if they have setup the infra already
* Else, the Setup page
*/
if (isGuestRoute(to.name)) {
console.log('hi');
const name = isInfraNotSetup ? 'setup' : 'dashboard';
return next({ name });
}
/**
* Reroutes the user to the dashboard homepage if they have setup the infra already
* and are trying to access the setup page
*/
if (isSetupRoute(to.name) && !isInfraNotSetup) {
return next({ name: 'dashboard' });
}
/**
* Reroutes the user to the setup page if they have not setup the infra yet
* and tries to access a valid route which is not a guest route
*/
if (isInfraNotSetup && !isSetupRoute(to.name)) {
return next({ name: 'setup' });
}
}
next();
},
};