Skip to content

Commit 2fd1ba2

Browse files
authored
auth change (#139)
1 parent d01608a commit 2fd1ba2

File tree

2 files changed

+30
-13
lines changed

2 files changed

+30
-13
lines changed

app/api/auth/[...nextauth]/route.ts

Lines changed: 29 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,25 +2,45 @@ import { handlers } from "@/app/auth"
22
import { NextResponse } from 'next/server'
33
import { NextRequest } from 'next/server'
44
import { getProxyConfig } from "@/proxy-config"
5+
import { HttpsProxyAgent } from "https-proxy-agent"
56

67
const TIMEOUT_DURATION = 60000;
78

9+
// 扩展 RequestInit 类型以包含 Node.js 特定选项
10+
interface ExtendedRequestInit extends RequestInit {
11+
agent?: HttpsProxyAgent;
12+
timeout?: number;
13+
}
14+
815
// 定义超时 Promise 的类型
916
type TimeoutPromise = Promise<never>
1017

1118
export async function GET(request: NextRequest): Promise<Response> {
1219
try {
13-
const { isEnabled } = getProxyConfig();
20+
const { isEnabled, httpsAgent } = getProxyConfig();
1421

15-
if (isEnabled) {
16-
// 使用超时机制
17-
const timeoutPromise: TimeoutPromise = new Promise((_, reject) =>
18-
setTimeout(() => reject(new Error('Request timeout')), TIMEOUT_DURATION)
19-
);
20-
const response = await Promise.race([handlers.GET(request), timeoutPromise]);
21-
return response instanceof Response ? response : NextResponse.json(response);
22+
// 只在认证请求时使用代理
23+
if (isEnabled && request.url.includes('/api/auth')) {
24+
console.log('originalFetch!!!!!!!!!!:', global.fetch);
25+
const originalFetch = global.fetch;
26+
global.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
27+
const extendedInit: ExtendedRequestInit = {
28+
...init,
29+
agent: httpsAgent,
30+
timeout: TIMEOUT_DURATION,
31+
};
32+
return originalFetch(input, extendedInit);
33+
};
34+
35+
try {
36+
const response = await handlers.GET(request);
37+
return response instanceof Response ? response : NextResponse.json(response);
38+
} finally {
39+
// 请求完成后恢复原始的 fetch
40+
global.fetch = originalFetch;
41+
}
2242
} else {
23-
// 不使用超时机制
43+
// 非认证请求使用普通 fetch
2444
const response = await handlers.GET(request);
2545
return response instanceof Response ? response : NextResponse.json(response);
2646
}

app/auth.ts

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,6 @@
11
import NextAuth from "next-auth"
22
import GitHub from "next-auth/providers/github"
3-
import { setupGlobalFetch } from "@/proxy-config"
4-
5-
// 设置全局代理(如果启用)
6-
setupGlobalFetch();
3+
// import { getProxyConfig } from "@/proxy-config"
74

85
// 打印环境变量(开发环境调试用)
96
console.log('Environment Config:', {

0 commit comments

Comments
 (0)