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.
71 lines
2.1 KiB
71 lines
2.1 KiB
import {
|
|
DEFAULT_AUTHENTICATED_LANDING_PATH,
|
|
isGuestOnlyRoute,
|
|
isPublicRoute,
|
|
normalizeSafeRedirect,
|
|
} from "@/utils/auth-routes";
|
|
import { useAuthSession } from "../composables/useAuthSession";
|
|
import { FRONTEND_LOGIN_PATH, FRONTEND_REGISTER_PATH } from "common/config"
|
|
|
|
export default defineNuxtRouteMiddleware(async (to) => {
|
|
if(to.path.startsWith("/__nuxt_error")) {
|
|
return
|
|
}
|
|
if(to.path.startsWith("/api")) {
|
|
return
|
|
}
|
|
if(to.path.startsWith("/public")) {
|
|
return
|
|
}
|
|
const { initialized, loggedIn, refresh } = useAuthSession();
|
|
if (!initialized.value) {
|
|
await refresh();
|
|
}
|
|
|
|
const currentPath = to.path;
|
|
const currentFullPath = to.fullPath;
|
|
const isLoggedIn = loggedIn.value;
|
|
|
|
// 管理员路由守卫:除仪表板外 /admin/* 需要管理员权限
|
|
const isAdminRoute = currentPath.startsWith("/admin");
|
|
const isDashboardOnly = currentPath === "/admin" || currentPath === "/admin/dashboard";
|
|
if (isLoggedIn && isAdminRoute && !isDashboardOnly) {
|
|
const { user } = useAuthSession();
|
|
if (user.value?.role !== "admin") {
|
|
const { $toast } = useNuxtApp();
|
|
$toast?.warning("需要管理员权限");
|
|
return navigateTo("/");
|
|
}
|
|
}
|
|
|
|
if (!isLoggedIn && !isPublicRoute(currentPath)) {
|
|
return navigateTo({
|
|
path: FRONTEND_LOGIN_PATH,
|
|
query: { redirect: currentFullPath },
|
|
});
|
|
}
|
|
|
|
if (!isLoggedIn && currentPath === FRONTEND_REGISTER_PATH) {
|
|
const { config: globalConfig } = useGlobalConfig();
|
|
if (globalConfig.value.allowRegister === false) {
|
|
const { $toast } = useNuxtApp();
|
|
$toast?.warning("当前已关闭注册");
|
|
return navigateTo(FRONTEND_LOGIN_PATH);
|
|
}
|
|
}
|
|
|
|
if (isLoggedIn && isGuestOnlyRoute(currentPath)) {
|
|
const redirectCandidate = Array.isArray(to.query.redirect)
|
|
? to.query.redirect[0]
|
|
: to.query.redirect;
|
|
const redirectTarget = normalizeSafeRedirect(
|
|
redirectCandidate,
|
|
DEFAULT_AUTHENTICATED_LANDING_PATH,
|
|
);
|
|
|
|
if (redirectTarget !== currentFullPath && redirectTarget !== currentPath) {
|
|
return navigateTo(redirectTarget);
|
|
}
|
|
return navigateTo(DEFAULT_AUTHENTICATED_LANDING_PATH);
|
|
}
|
|
});
|
|
|