Skip to content

A Q&A platform software for teams at any scales. Whether it's a community forum, help center, or knowledge management platform, you can always count on Apache Answer.

feat(admin/login): Forced login blocking development completed

haitao(lj)8acc3c937d98
diff --git a/ui/src/pages/Users/Suspended/index.tsx b/ui/src/pages/Users/Suspended/index.tsx
index c26071b1..20ed5f9b 100644
--- a/ui/src/pages/Users/Suspended/index.tsx
+++ b/ui/src/pages/Users/Suspended/index.tsx
@@ -1,18 +1,13 @@
import { useTranslation } from 'react-i18next';
import { usePageTags } from '@/hooks';
-import { loggedUserInfoStore } from '@/stores';
const Suspended = () => {
const { t } = useTranslation('translation', { keyPrefix: 'suspended' });
- const userInfo = loggedUserInfoStore((state) => state.user);
usePageTags({
title: t('account_suspended', { keyPrefix: 'page_title' }),
});
- if (userInfo.status !== 'forbidden') {
- window.location.replace('/');
- return null;
- }
+
return (
<div className="d-flex flex-column align-items-center mt-5 pt-3">
<h3 className="mb-5">{t('title')}</h3>
diff --git a/ui/src/router/RouteGuard.tsx b/ui/src/router/RouteGuard.tsx
new file mode 100644
index 00000000..3f4a17e1
--- /dev/null
+++ b/ui/src/router/RouteGuard.tsx
@@ -0,0 +1,39 @@
+import { FC, ReactNode, useEffect } from 'react';
+import { useLocation, useNavigate } from 'react-router-dom';
+
+import { floppyNavigation } from '@/utils';
+import { TGuardFunc } from '@/utils/guard';
+
+const Index: FC<{
+ children: ReactNode;
+ onEnter?: TGuardFunc;
+ path?: string;
+}> = ({
+ children,
+ onEnter,
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ path,
+}) => {
+ const navigate = useNavigate();
+ const location = useLocation();
+ useEffect(() => {
+ if (onEnter) {
+ const gr = onEnter();
+ const redirectUrl = gr.redirect;
+ if (redirectUrl) {
+ floppyNavigation.navigate(redirectUrl, () => {
+ navigate(redirectUrl, { replace: true });
+ });
+ }
+ }
+ }, [location]);
+
+ return (
+ <>
+ {/* Route Guard */}
+ {children}
+ </>
+ );
+};
+
+export default Index;
diff --git a/ui/src/router/index.tsx b/ui/src/router/index.tsx
index 6892f403..b7eeabff 100644
--- a/ui/src/router/index.tsx
+++ b/ui/src/router/index.tsx
@@ -1,48 +1,44 @@
-import React, { Suspense, lazy } from 'react';
-import { RouteObject, createBrowserRouter, redirect } from 'react-router-dom';
+import { Suspense, lazy } from 'react';
+import { RouteObject, createBrowserRouter } from 'react-router-dom';
import Layout from '@/pages/Layout';
import ErrorBoundary from '@/pages/50X';
import baseRoutes, { RouteNode } from '@/router/routes';
-import { floppyNavigation } from '@/utils';
+import RouteGuard from '@/router/RouteGuard';
const routes: RouteObject[] = [];
const routeWrapper = (routeNodes: RouteNode[], root: RouteObject[]) => {
routeNodes.forEach((rn) => {
if (rn.page === 'pages/Layout') {
- rn.element = <Layout />;
+ rn.element = rn.guard ? (
+ <RouteGuard onEnter={rn.guard} path={rn.path}>
+ <Layout />
+ </RouteGuard>
+ ) : (
+ <Layout />
+ );
rn.errorElement = <ErrorBoundary />;
} else {
/**
* cannot use a fully dynamic import statement
* ref: https://webpack.js.org/api/module-methods/#import-1
*/
- rn.page = rn.page.replace('pages/', '');
- const Ctrl = lazy(() => import(`@/pages/${rn.page}`));
+ const pagePath = rn.page.replace('pages/', '');
+ const Ctrl = lazy(() => import(`@/pages/${pagePath}`));
rn.element = (
<Suspense>
- <Ctrl />
+ {rn.guard ? (
+ <RouteGuard onEnter={rn.guard} path={rn.path}>
+ <Ctrl />
+ </RouteGuard>
+ ) : (
+ <Ctrl />
+ )}
</Suspense>
);
}
root.push(rn);
- if (rn.guard) {
- const refLoader = rn.loader;
- const refGuard = rn.guard;
- rn.loader = async (args) => {
- const gr = await refGuard(args);
- if (gr?.redirect && floppyNavigation.differentCurrent(gr.redirect)) {
- return redirect(gr.redirect);
- }
-
- let lr;
- if (typeof refLoader === 'function') {
- lr = await refLoader(args);
- }
- return lr;
- };
- }
const children = Array.isArray(rn.children) ? rn.children : null;
if (children) {
rn.children = [];
diff --git a/ui/src/router/routes.ts b/ui/src/router/routes.ts
index efe0ec87..a6ae53f3 100644
--- a/ui/src/router/routes.ts
+++ b/ui/src/router/routes.ts
@@ -1,7 +1,7 @@
-import { LoaderFunctionArgs, RouteObject } from 'react-router-dom';
+import { RouteObject } from 'react-router-dom';
import { guard } from '@/utils';
-import type { TGuardResult } from '@/utils/guard';
+import type { TGuardFunc } from '@/utils/guard';
export interface RouteNode extends RouteObject {
page: string;
@@ -13,14 +13,18 @@ export interface RouteNode extends RouteObject {
* if guard returned the `TGuardResult` has `redirect` field,
* then auto redirect route to the `redirect` target.
*/
- guard?: (args: LoaderFunctionArgs) => Promise<TGuardResult>;
+ guard?: TGuardFunc;
}
const routes: RouteNode[] = [
{
path: '/',
page: 'pages/Layout',
- guard: async () => {
+ guard: () => {
+ const gr = guard.shouldLoginRequired();
+ if (!gr.ok) {
+ return gr;
+ }
return guard.notForbidden();
},
children: [
@@ -36,7 +40,7 @@ const routes: RouteNode[] = [
{
path: 'questions/ask',
page: 'pages/Questions/Ask',
- guard: async () => {
+ guard: () => {
return guard.activated();
},
},
@@ -55,7 +59,7 @@ const routes: RouteNode[] = [
{
path: 'posts/:qid/edit',
page: 'pages/Questions/Ask',
- guard: async () => {
+ guard: () => {
return guard.activated();
},
},
@@ -83,7 +87,7 @@ const routes: RouteNode[] = [
{
path: 'tags/:tagId/edit',
page: 'pages/Tags/Edit',
- guard: async () => {
+ guard: () => {
return guard.activated();
},
},
@@ -99,7 +103,7 @@ const routes: RouteNode[] = [
{
path: 'users/settings',
page: 'pages/Users/Settings',
- guard: async () => {
+ guard: () => {
return guard.logged();
},
children: [
@@ -132,7 +136,7 @@ const routes: RouteNode[] = [
{
path: 'users/login',
page: 'pages/Users/Login',
- guard: async () => {
+ guard: () => {
const notLogged = guard.notLogged();
if (notLogged.ok) {
return notLogged;
@@ -143,7 +147,7 @@ const routes: RouteNode[] = [
{
path: 'users/register',
page: 'pages/Users/Register',
- guard: async () => {
+ guard: () => {
const allowNew = guard.allowNewRegistration();
if (!allowNew.ok) {
return allowNew;
@@ -154,7 +158,7 @@ const routes: RouteNode[] = [
{
path: 'users/account-recovery',
page: 'pages/Users/AccountForgot',
- guard: async () => {
+ guard: () => {
return guard.activated();
},
},
@@ -173,14 +177,14 @@ const routes: RouteNode[] = [
{
path: 'users/account-activation/success',
page: 'pages/Users/ActivationResult',
- guard: async () => {
+ guard: () => {
return guard.activated();
},
},
{
path: '/users/account-activation/failed',
page: 'pages/Users/ActivationResult',
- guard: async () => {
+ guard: () => {
return guard.notActivated();
},
},
@@ -191,28 +195,28 @@ const routes: RouteNode[] = [
{
path: '/users/account-suspended',
page: 'pages/Users/Suspended',
- guard: async () => {
+ guard: () => {
return guard.forbidden();
},
},
{
path: '/posts/:qid/timeline',
page: 'pages/Timeline',
- guard: async () => {
+ guard: () => {
return guard.logged();
},
},
{
path: '/posts/:qid/:aid/timeline',
page: 'pages/Timeline',
- guard: async () => {
+ guard: () => {
return guard.logged();
},
},
{
path: '/tags/:tid/timeline',
page: 'pages/Timeline',
- guard: async () => {
+ guard: () => {
return guard.logged();
},
},
@@ -220,8 +224,10 @@ const routes: RouteNode[] = [
{
path: 'admin',
page: 'pages/Admin',
- guard: async () => {
+ loader: async () => {
await guard.pullLoggedUser(true);
+ },
+ guard: () => {
return guard.admin();
},
children: [
diff --git a/ui/src/utils/guard.ts b/ui/src/utils/guard.ts
index c6228c4f..d494d132 100644
--- a/ui/src/utils/guard.ts
+++ b/ui/src/utils/guard.ts
@@ -26,6 +26,7 @@ export type TGuardResult = {
ok: boolean;
redirect?: string;
};
+export type TGuardFunc = () => TGuardResult;
export const deriveLoginState = (): TLoginState => {
const ls: TLoginState = {
@@ -55,10 +56,20 @@ export const deriveLoginState = (): TLoginState => {
if (ls.isNormal && user.is_admin === true) {
ls.isAdmin = true;
}
-
return ls;
};
+const isIgnoredPath = (ignoredPath: string | string[]) => {
+ if (!Array.isArray(ignoredPath)) {
+ ignoredPath = [ignoredPath];
+ }
+ const { pathname } = window.location;
+ const matchingPath = ignoredPath.find((_) => {
+ return pathname.indexOf(_) !== -1;
+ });
+ return !!matchingPath;
+};
+
let pullLock = false;
let dedupeTimestamp = 0;
export const pullLoggedUser = async (forceRePull = false) => {
@@ -129,7 +140,7 @@ export const activated = () => {
};
export const forbidden = () => {
- const gr = logged();
+ const gr: TGuardResult = { ok: true };
const us = deriveLoginState();
if (gr.ok && !us.isForbidden) {
gr.ok = false;
@@ -168,6 +179,34 @@ export const allowNewRegistration = () => {
return gr;
};
+export const shouldLoginRequired = () => {
+ const gr: TGuardResult = { ok: true };
+ const loginSetting = loginSettingStore.getState().login;
+ if (!loginSetting.login_required) {
+ return gr;
+ }
+ const us = deriveLoginState();
+ if (us.isLogged) {
+ return gr;
+ }
+ if (
+ isIgnoredPath([
+ RouteAlias.login,
+ RouteAlias.register,
+ '/users/account-recovery',
+ 'users/change-email',
+ 'users/account-activation/success',
+ '/users/account-activation/failed',
+ '/users/confirm-new-email',
+ ])
+ ) {
+ return gr;
+ }
+ gr.ok = false;
+ gr.redirect = RouteAlias.login;
+ return gr;
+};
+
/**
* try user was logged and all state ok
* @param canNavigate // if true, will navigate to login page if not logged
@@ -219,8 +258,7 @@ export const initAppSettingsStore = async () => {
};
export const shouldInitAppFetchData = () => {
- const { pathname } = window.location;
- if (pathname === '/install') {
+ if (isIgnoredPath('/install')) {
return false;
}
@@ -234,7 +272,6 @@ export const setupApp = async () => {
* 2. must pre init app settings for app render
*/
// TODO: optimize `initAppSettingsStore` by server render
-
if (shouldInitAppFetchData()) {
await Promise.allSettled([pullLoggedUser(), initAppSettingsStore()]);
setupAppLanguage();