Skip to content

Commit

Permalink
refactor: simplify loginGuard logic
Browse files Browse the repository at this point in the history
  • Loading branch information
ferferga authored Aug 9, 2024
1 parent b884466 commit 9fcec08
Showing 1 changed file with 24 additions and 20 deletions.
44 changes: 24 additions & 20 deletions frontend/src/plugins/router/middlewares/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ import { getJSONConfig } from '@/utils/external-config';
const serverAddUrl = '/server/add';
const serverSelectUrl = '/server/select';
const serverLoginUrl = '/server/login';
const routes = new Set([serverAddUrl, serverSelectUrl, serverLoginUrl]);
const serverRoutes = new Set([serverAddUrl, serverSelectUrl]);
const routes = new Set(...serverRoutes, serverLoginUrl);

/**
* Redirects to login page if there's no user logged in.
Expand All @@ -22,28 +23,31 @@ export async function loginGuard(
let destinationRoute: RouteLocationPathRaw | undefined;
const jsonConfig = await getJSONConfig();

if (!isNil(remote.auth.currentServer) && !isNil(remote.auth.currentUser) && !isNil(remote.auth.currentUserToken) && routes.has(to.path)) {
destinationRoute = { path: '/', replace: true };
} else if (to.path === serverAddUrl && remote.auth.servers.length > 0 || to.path === serverSelectUrl) {
if (!jsonConfig.allowServerSelection) {
destinationRoute = { path: serverLoginUrl, replace: true };
}
if (jsonConfig.defaultServerURLs.length && isNil(remote.auth.currentServer)) {
await until(() => remote.auth.currentServer).toBeTruthy({ flush: 'pre' });
}

if (remote.auth.servers.length <= 0 && jsonConfig.defaultServerURLs.length <= 0) {
destinationRoute = { path: serverAddUrl, replace: true };
} else if (!routes.has(to.path)) {
if (isNil(remote.auth.currentServer)) {
if (jsonConfig.allowServerSelection) {
destinationRoute = { path: serverSelectUrl, replace: true };
} else {
await until(() => remote.auth.currentServer).toBeTruthy({ flush: 'pre' });
if (
(
!jsonConfig.allowServerSelection
&& serverRoutes.has(to.path)
)
|| (
!isNil(remote.auth.currentServer)
&& !isNil(remote.auth.currentUser)
&& !isNil(remote.auth.currentUserToken)
&& routes.has(to.path)
)
) {
return { path: '/', replace: true };
}

return loginGuard(to);
}
} else if (isNil(remote.auth.currentUser)) {
destinationRoute = { path: serverLoginUrl, replace: true };
}
if (!remote.auth.servers.length) {
destinationRoute = { path: serverAddUrl, replace: true };
} else if (isNil(remote.auth.currentServer)) {
destinationRoute = { path: serverSelectUrl, replace: true };
} else if (isNil(remote.auth.currentUser)) {
destinationRoute = { path: serverLoginUrl, replace: true };
}

return destinationRoute && to.path !== destinationRoute.path
Expand Down

0 comments on commit 9fcec08

Please sign in to comment.