mirror of
https://github.com/woodchen-ink/Q58Connect.git
synced 2025-07-18 14:01:55 +08:00
refactor: 重构 SSO 登录流程,改进错误处理和状态管理
This commit is contained in:
parent
0d1228ec30
commit
99e833c84e
@ -10,11 +10,11 @@ const discourseHost = process.env.DISCOURSE_HOST as string;
|
|||||||
const clientSecret = process.env.DISCOURSE_SECRET as string;
|
const clientSecret = process.env.DISCOURSE_SECRET as string;
|
||||||
|
|
||||||
export async function POST(req: Request) {
|
export async function POST(req: Request) {
|
||||||
const nonce = WordArray.random(16).toString();
|
|
||||||
|
|
||||||
// 尝试从请求体中获取 OAuth 参数
|
|
||||||
let oauthParams = "";
|
|
||||||
try {
|
try {
|
||||||
|
const nonce = WordArray.random(16).toString();
|
||||||
|
|
||||||
|
// 尝试从请求体中获取 OAuth 参数
|
||||||
|
let oauthParams = "";
|
||||||
const body = await req.json();
|
const body = await req.json();
|
||||||
if (body.oauth_params) {
|
if (body.oauth_params) {
|
||||||
oauthParams = body.oauth_params;
|
oauthParams = body.oauth_params;
|
||||||
@ -22,27 +22,37 @@ export async function POST(req: Request) {
|
|||||||
cookies().set("oauth_params", oauthParams, {
|
cookies().set("oauth_params", oauthParams, {
|
||||||
maxAge: 60 * 10, // 10分钟过期
|
maxAge: 60 * 10, // 10分钟过期
|
||||||
path: "/",
|
path: "/",
|
||||||
|
httpOnly: true,
|
||||||
|
secure: process.env.NODE_ENV === "production",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 设置回调地址
|
||||||
|
const return_url = oauthParams
|
||||||
|
? `${hostUrl}/authorize?${oauthParams}` // OAuth流程:回到授权页面
|
||||||
|
: `${hostUrl}/dashboard`; // 普通登录:直接到仪表板
|
||||||
|
|
||||||
|
// 构建 SSO 参数
|
||||||
|
const ssoParams = new URLSearchParams();
|
||||||
|
ssoParams.set("nonce", nonce);
|
||||||
|
ssoParams.set("return_sso_url", return_url);
|
||||||
|
|
||||||
|
const sso = btoa(ssoParams.toString());
|
||||||
|
const sig = hmacSHA256(sso, clientSecret).toString(Hex);
|
||||||
|
|
||||||
|
// 保存 nonce 到 cookie
|
||||||
|
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) {
|
} catch (error) {
|
||||||
console.error("Failed to parse request body:", error);
|
console.error("SSO 处理错误:", error);
|
||||||
|
return Response.json({ error: "处理登录请求时发生错误" }, { status: 500 });
|
||||||
}
|
}
|
||||||
|
|
||||||
// 设置回调地址
|
|
||||||
const return_url = oauthParams
|
|
||||||
? `${hostUrl}/authorize?${oauthParams}` // OAuth流程:回到授权页面
|
|
||||||
: `${hostUrl}/dashboard`; // 普通登录:直接到仪表板
|
|
||||||
|
|
||||||
// 构建 SSO 参数
|
|
||||||
const ssoParams = new URLSearchParams();
|
|
||||||
ssoParams.set("nonce", nonce);
|
|
||||||
ssoParams.set("return_sso_url", return_url);
|
|
||||||
|
|
||||||
const sso = btoa(ssoParams.toString());
|
|
||||||
const sig = hmacSHA256(sso, clientSecret).toString(Hex);
|
|
||||||
|
|
||||||
cookies().set(AUTH_NONCE, nonce, { maxAge: 60 * 10 });
|
|
||||||
return Response.json({
|
|
||||||
sso_url: `${discourseHost}/session/sso_provider?sso=${sso}&sig=${sig}`,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
@ -21,55 +21,51 @@ export function UserAuthForm({
|
|||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
const searchParams = useSearchParams();
|
const searchParams = useSearchParams();
|
||||||
|
|
||||||
// 在组件挂载时保存 OAuth 参数
|
const signIn = async () => {
|
||||||
React.useEffect(() => {
|
if (isLoading) return;
|
||||||
if (searchParams?.toString()) {
|
|
||||||
localStorage.setItem("oauth_params", searchParams.toString());
|
|
||||||
}
|
|
||||||
}, [searchParams]);
|
|
||||||
|
|
||||||
const signIn = () => {
|
setIsLoading(true);
|
||||||
React.startTransition(async () => {
|
try {
|
||||||
try {
|
// 构建请求体,包含 OAuth 参数
|
||||||
setIsLoading(true);
|
const body: Record<string, any> = {};
|
||||||
// 构建请求体,包含 OAuth 参数
|
const currentParams = searchParams?.toString();
|
||||||
const body: Record<string, any> = {};
|
|
||||||
// 优先使用 URL 中的参数
|
|
||||||
if (searchParams?.toString()) {
|
|
||||||
body.oauth_params = searchParams.toString();
|
|
||||||
} else {
|
|
||||||
// 如果 URL 中没有参数,尝试从 localStorage 获取
|
|
||||||
const savedParams = localStorage.getItem("oauth_params");
|
|
||||||
if (savedParams) {
|
|
||||||
body.oauth_params = savedParams;
|
|
||||||
// 使用后清除存储的参数
|
|
||||||
localStorage.removeItem("oauth_params");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const response = await fetch("/api/auth/q58", {
|
if (currentParams) {
|
||||||
method: "POST",
|
body.oauth_params = currentParams;
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
body: JSON.stringify(body),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error(response.statusText);
|
|
||||||
}
|
|
||||||
|
|
||||||
const data: DiscourseData = await response.json();
|
|
||||||
router.push(data.sso_url);
|
|
||||||
} catch (error) {
|
|
||||||
setIsLoading(false);
|
|
||||||
toast({
|
|
||||||
variant: "destructive",
|
|
||||||
title: "内部服务异常",
|
|
||||||
description: error instanceof Error ? error.message : "未知错误",
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
const response = await fetch("/api/auth/q58", {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const errorText = await response.text();
|
||||||
|
throw new Error(errorText || response.statusText);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data: DiscourseData = await response.json();
|
||||||
|
|
||||||
|
// 在跳转之前确保保存当前的 OAuth 参数
|
||||||
|
if (currentParams) {
|
||||||
|
localStorage.setItem("oauth_params", currentParams);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 跳转到 SSO 登录页面
|
||||||
|
window.location.href = data.sso_url;
|
||||||
|
} catch (error) {
|
||||||
|
console.error("登录失败:", error);
|
||||||
|
setIsLoading(false);
|
||||||
|
toast({
|
||||||
|
variant: "destructive",
|
||||||
|
title: "登录失败",
|
||||||
|
description:
|
||||||
|
error instanceof Error ? error.message : "请求失败,请稍后重试",
|
||||||
|
});
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@ -77,10 +73,7 @@ export function UserAuthForm({
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className={cn(buttonVariants({ variant: "outline" }))}
|
className={cn(buttonVariants({ variant: "outline" }))}
|
||||||
onClick={() => {
|
onClick={signIn}
|
||||||
setIsLoading(true);
|
|
||||||
signIn();
|
|
||||||
}}
|
|
||||||
disabled={isLoading}
|
disabled={isLoading}
|
||||||
>
|
>
|
||||||
{isLoading ? (
|
{isLoading ? (
|
||||||
|
Loading…
x
Reference in New Issue
Block a user