This commit is contained in:
Vaica committed 2026-06-22 15:55:09 +08:00
1 parent a320ff2661
commit 310be913ef
2 files changed
+22 -6

No files matched your search

+13 -6
View File
@@ -9,9 +9,8 @@ self.addEventListener('fetch', e => {
const req = e.request;
const url = new URL(req.url);
// 登录页、静态资源、API 请求不拦截
// 登录页、静态资源不拦截
if (url.pathname === '/login' || url.pathname.startsWith('/_next/') ||
url.pathname.startsWith('/api/') ||
url.pathname.endsWith('.js') || url.pathname.endsWith('.css') ||
url.pathname.endsWith('.ico') || url.pathname.endsWith('.woff2')) {
e.respondWith(fetch(req));
@@ -21,18 +20,26 @@ self.addEventListener('fetch', e => {
e.respondWith((async () => {
const token = self.__auth_token;
const tokenTime = self.__auth_time || 0;
const isApi = url.pathname.startsWith('/api/');
// 无 token 且不是 API 请求 → 跳转登录
if (!token || (Date.now() - tokenTime > EXPIRE_MS)) {
self.__auth_token = null;
self.__auth_time = 0;
return Response.redirect(LOGIN, 302);
if (!isApi) {
self.__auth_token = null;
self.__auth_time = 0;
return Response.redirect(LOGIN, 302);
}
// API 请求无 token,直接发(让 API 自己返回 401)
return fetch(req);
}
// 添加认证头
const headers = new Headers(req.headers);
headers.set('X-Auth-User', token);
const res = await fetch(new Request(req, { headers }));
if (res.status === 401) {
// 非 API 请求 401 → 跳转登录
if (res.status === 401 && !isApi) {
self.__auth_token = null;
self.__auth_time = 0;
return Response.redirect(LOGIN, 302);
+9
View File
@@ -0,0 +1,9 @@
// 带认证的 fetch 封装
export async function authFetch(url: string, options: RequestInit = {}): Promise<Response> {
const token = localStorage.getItem("wauth_token");
const headers = new Headers(options.headers);
if (token) {
headers.set("X-Auth-User", token);
}
return fetch(url, { ...options, headers });
}