1555
This commit is contained in:
1 parent
a320ff2661
commit
310be913ef
2 files changed
+22
-6
No files matched your search
@@ -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);
|
||||
|
||||
Reference in new issue
Block a user