Mosijiu 9285fc1822
Some checks failed
Lint / build (20) (push) Has been cancelled
Playwright Tests / test (push) Has been cancelled
钉钉登录支持配置多组织
2025-12-18 22:12:03 +08:00

52 lines
1.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { NextResponse } from "next/server";
import { getAuthSettings } from "@/lib/db/queries";
export async function GET(request: Request) {
const settings = await getAuthSettings();
if (!settings.isDingTalkEnabled) {
return NextResponse.json(
{ error: "DingTalk login is not enabled" },
{ status: 400 },
);
}
const urlObj = new URL(request.url);
const orgName = urlObj.searchParams.get("org");
const organizations = settings.dingTalkOrganizations ?? [];
const selectedOrg = orgName
? organizations.find((org) => org.name === orgName)
: organizations[0];
const appKey = selectedOrg?.appKey ?? settings.dingTalkAppKey;
if (!appKey) {
return NextResponse.json(
{ error: "DingTalk appKey is not configured" },
{ status: 400 },
);
}
// 动态构建回调地址
const host = request.headers.get("host");
const protocol = request.headers.get("x-forwarded-proto") || "http";
const baseUrl = `${protocol}://${host}`;
const redirectUri = `${baseUrl}/dingtalk-callback.html`;
// 使用组织名称作为 state,便于回调时选择对应的配置
const state = orgName || selectedOrg?.name || "default";
// 钉钉 OAuth 2.0 授权地址
const url =
`https://login.dingtalk.com/oauth2/auth?` +
`redirect_uri=${encodeURIComponent(redirectUri)}&` +
`response_type=code&` +
`client_id=${encodeURIComponent(appKey)}&` +
`scope=openid&` +
`state=${encodeURIComponent(state)}&` +
`prompt=consent`;
return NextResponse.redirect(url);
}