MCPcopy Create free account
hub / github.com/AntiHub-Project/AntiHub / GET

Function GET

app/api/auth/github/callback/route.ts:11–104  ·  view source on GitHub ↗
(request: NextRequest)

Source from the content-addressed store, hash-verified

9 * 转发给后端 API 完成认证,然后重定向到前端
10 */
11export async function GET(request: NextRequest) {
12 const searchParams = request.nextUrl.searchParams;
13 const code = searchParams.get('code');
14 const state = searchParams.get('state');
15 const error = searchParams.get('error');
16
17 // 如果有错误,重定向到登录页并显示错误
18 if (error) {
19 return NextResponse.redirect(
20 new URL(`/auth?error=${encodeURIComponent(error)}`, FRONTEND_URL)
21 );
22 }
23
24 // 如果缺少必要参数,返回错误
25 if (!code || !state) {
26 return NextResponse.redirect(
27 new URL('/auth?error=missing_oauth_params', FRONTEND_URL)
28 );
29 }
30
31 try {
32 // 调用后端 API 完成 GitHub OAuth 流程
33 const response = await fetch(
34 `${API_BASE_URL}/api/auth/github/callback`,
35 {
36 method: 'POST',
37 headers: {
38 'Content-Type': 'application/json',
39 },
40 body: JSON.stringify({ code, state }),
41 }
42 );
43
44 if (!response.ok) {
45 const errorData = await response.json().catch(() => ({}));
46 const errorMessage = errorData.detail || 'GitHub 认证失败';
47 throw new Error(errorMessage);
48 }
49
50 const data = await response.json();
51 const { access_token, refresh_token, expires_in, user } = data;
52
53 // 创建重定向 URL,包含用户信息用于 localStorage 同步
54 const redirectUrl = new URL('/dashboard', FRONTEND_URL);
55 redirectUrl.searchParams.set('login', 'success');
56 redirectUrl.searchParams.set('token', access_token);
57 redirectUrl.searchParams.set('user', encodeURIComponent(JSON.stringify(user)));
58
59 // 添加 refresh_token 和 expires_in 参数
60 if (refresh_token) {
61 redirectUrl.searchParams.set('refresh_token', refresh_token);
62 }
63 if (expires_in) {
64 redirectUrl.searchParams.set('expires_in', String(expires_in));
65 }
66
67 const redirectResponse = NextResponse.redirect(redirectUrl);
68

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected