wood chen 379fceb26b refactor: Improve SSO authentication flow with enhanced error handling and parameter processing
- Update Q58 route to handle dynamic OAuth parameters
- Add error handling and logging for SSO URL generation
- Modify UserAuthForm to preserve and pass OAuth parameters during authentication
- Implement more robust error handling in authentication process
2025-02-21 13:15:53 +08:00

48 lines
1.5 KiB
TypeScript

"use server";
import { cookies } from "next/headers";
import Hex from "crypto-js/enc-hex";
import hmacSHA256 from "crypto-js/hmac-sha256";
import WordArray from "crypto-js/lib-typedarrays";
import { AUTH_NONCE } from "@/lib/constants";
const hostUrl = process.env.NEXT_PUBLIC_HOST_URL as string;
const discourseHost = process.env.DISCOURSE_HOST as string;
const clientSecret = process.env.DISCOURSE_SECRET as string;
export async function POST(req: Request) {
try {
const nonce = WordArray.random(16).toString();
const url = new URL(req.url);
// 从请求中获取原始的 OAuth 参数
const searchParams = new URLSearchParams(await req.text());
const oauth = searchParams.get("oauth") || "";
// 构建回调 URL
const callbackUrl = new URL("/q58/callback", hostUrl);
if (oauth) {
callbackUrl.searchParams.set("oauth", oauth);
}
// 构建 SSO 参数
const ssoParams = new URLSearchParams();
ssoParams.set("nonce", nonce);
ssoParams.set("return_sso_url", callbackUrl.toString());
const sso = btoa(ssoParams.toString());
const sig = hmacSHA256(sso, clientSecret).toString(Hex);
// 设置 nonce cookie
cookies().set(AUTH_NONCE, nonce, { maxAge: 60 * 10 });
return Response.json({
sso_url: `${discourseHost}/session/sso_provider?sso=${sso}&sig=${sig}`,
});
} catch (error) {
console.error("SSO URL generation error:", error);
return Response.json({ error: "Internal server error" }, { status: 500 });
}
}