mirror of
https://github.com/woodchen-ink/Q58Connect.git
synced 2025-07-18 14:01:55 +08:00
44 lines
1.4 KiB
TypeScript
44 lines
1.4 KiB
TypeScript
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();
|
|
let return_url = `${hostUrl}/dashboard`; // 默认重定向到仪表板
|
|
|
|
try {
|
|
const body = await req.json();
|
|
if (body.oauth_params) {
|
|
return_url = `${hostUrl}/oauth/authorize?${body.oauth_params}`;
|
|
}
|
|
} catch (error) {
|
|
console.error("Failed to parse request body:", error);
|
|
}
|
|
|
|
const sso = btoa(`nonce=${nonce}&return_sso_url=${return_url}`);
|
|
const sig = hmacSHA256(sso, clientSecret).toString(Hex);
|
|
|
|
cookies().set(AUTH_NONCE, nonce, {
|
|
maxAge: 60 * 10,
|
|
path: "/",
|
|
httpOnly: true,
|
|
secure: process.env.NODE_ENV === "production",
|
|
});
|
|
|
|
return Response.json({
|
|
sso_url: `${discourseHost}/session/sso_provider?sso=${sso}&sig=${sig}`,
|
|
});
|
|
} catch (error) {
|
|
console.error("SSO 处理错误:", error);
|
|
return Response.json({ error: "处理登录请求时发生错误" }, { status: 500 });
|
|
}
|
|
}
|