1555
This commit is contained in:
1 parent
a320ff2661
commit
310be913ef
2 files changed
+19
-3
No files matched your search
@@ -9,9 +9,8 @@ self.addEventListener('fetch', e => {
|
|||||||
const req = e.request;
|
const req = e.request;
|
||||||
const url = new URL(req.url);
|
const url = new URL(req.url);
|
||||||
|
|
||||||
// 登录页、静态资源、API 请求不拦截
|
// 登录页、静态资源不拦截
|
||||||
if (url.pathname === '/login' || url.pathname.startsWith('/_next/') ||
|
if (url.pathname === '/login' || url.pathname.startsWith('/_next/') ||
|
||||||
url.pathname.startsWith('/api/') ||
|
|
||||||
url.pathname.endsWith('.js') || url.pathname.endsWith('.css') ||
|
url.pathname.endsWith('.js') || url.pathname.endsWith('.css') ||
|
||||||
url.pathname.endsWith('.ico') || url.pathname.endsWith('.woff2')) {
|
url.pathname.endsWith('.ico') || url.pathname.endsWith('.woff2')) {
|
||||||
e.respondWith(fetch(req));
|
e.respondWith(fetch(req));
|
||||||
@@ -21,18 +20,26 @@ self.addEventListener('fetch', e => {
|
|||||||
e.respondWith((async () => {
|
e.respondWith((async () => {
|
||||||
const token = self.__auth_token;
|
const token = self.__auth_token;
|
||||||
const tokenTime = self.__auth_time || 0;
|
const tokenTime = self.__auth_time || 0;
|
||||||
|
const isApi = url.pathname.startsWith('/api/');
|
||||||
|
|
||||||
|
// 无 token 且不是 API 请求 → 跳转登录
|
||||||
if (!token || (Date.now() - tokenTime > EXPIRE_MS)) {
|
if (!token || (Date.now() - tokenTime > EXPIRE_MS)) {
|
||||||
|
if (!isApi) {
|
||||||
self.__auth_token = null;
|
self.__auth_token = null;
|
||||||
self.__auth_time = 0;
|
self.__auth_time = 0;
|
||||||
return Response.redirect(LOGIN, 302);
|
return Response.redirect(LOGIN, 302);
|
||||||
}
|
}
|
||||||
|
// API 请求无 token,直接发(让 API 自己返回 401)
|
||||||
|
return fetch(req);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 添加认证头
|
||||||
const headers = new Headers(req.headers);
|
const headers = new Headers(req.headers);
|
||||||
headers.set('X-Auth-User', token);
|
headers.set('X-Auth-User', token);
|
||||||
const res = await fetch(new Request(req, { headers }));
|
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_token = null;
|
||||||
self.__auth_time = 0;
|
self.__auth_time = 0;
|
||||||
return Response.redirect(LOGIN, 302);
|
return Response.redirect(LOGIN, 302);
|
||||||
|
|||||||
@@ -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 });
|
||||||
|
}
|
||||||
Reference in new issue
Block a user