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.
47 lines
1.4 KiB
47 lines
1.4 KiB
import { UNAUTHORIZED_MESSAGE } from "#server/constants/auth";
|
|
import { isAllowlistedApiPath, isFrontendPageAllowed } from "#server/utils/auth-api-routes";
|
|
import { getCurrentUser } from "#server/utils/context";
|
|
import { FRONTEND_LOGIN_PATH, FRONTEND_PAGE_GUEST_ONLY } from "common/config"
|
|
import { normalizePath } from "common/utils/path";
|
|
|
|
export default eventHandler(async (event) => {
|
|
const path = event.path;
|
|
|
|
// ====================== API 路径保护 ======================
|
|
if (path.startsWith("/api/")) {
|
|
if (path.startsWith("/api/_nuxt_icon")) {
|
|
return;
|
|
}
|
|
|
|
if (isAllowlistedApiPath(path, event.method)) {
|
|
return;
|
|
}
|
|
|
|
const user = await getCurrentUser(event);
|
|
if (user) {
|
|
return;
|
|
}
|
|
|
|
throw createError({
|
|
statusCode: 401,
|
|
statusMessage: UNAUTHORIZED_MESSAGE,
|
|
});
|
|
}
|
|
|
|
// ====================== 前端页面访问限制 ======================
|
|
// 非白名单的前端页面需要登录才能直接访问
|
|
if (isFrontendPageAllowed(path)) {
|
|
return;
|
|
}
|
|
|
|
const user = await getCurrentUser(event);
|
|
if (!user) {
|
|
// 未登录且页面不在白名单,重定向到登录页
|
|
return sendRedirect(event, FRONTEND_LOGIN_PATH, 302);
|
|
}
|
|
|
|
// 已登录用户访问登录/注册页面,重定向到首页
|
|
if (FRONTEND_PAGE_GUEST_ONLY.has(normalizePath(path))) {
|
|
return sendRedirect(event, "/", 302);
|
|
}
|
|
});
|