From 2f848af557cf9677f82d862c57e1f2a42bc1bd68 Mon Sep 17 00:00:00 2001 From: wood chen Date: Fri, 21 Feb 2025 18:27:55 +0800 Subject: [PATCH] refactor: Improve OAuth and SSO authorization flow with enhanced loading and error handling --- src/actions/user-authorize.ts | 8 ++-- src/components/auth/user-authorize.tsx | 51 ++++++++++---------------- 2 files changed, 24 insertions(+), 35 deletions(-) diff --git a/src/actions/user-authorize.ts b/src/actions/user-authorize.ts index 1aa2df6..2388466 100644 --- a/src/actions/user-authorize.ts +++ b/src/actions/user-authorize.ts @@ -26,7 +26,7 @@ export async function signIn(data: Record) { const state = params.get("state"); const scope = params.get("scope") || "read_profile"; - // 重新构建授权页面 URL + // 重新构建授权页面 URL,使用相对路径 const authParams = new URLSearchParams({ response_type: "code", client_id: clientId || "", @@ -37,14 +37,16 @@ export async function signIn(data: Record) { authParams.set("state", state); } - // 重定向到授权页面 + // 重定向到授权页面,使用相对路径 redirect(`/oauth/authorize?${authParams.toString()}`); + return; } // 如果没有 OAuth 参数,重定向到仪表板 redirect("/dashboard"); } catch (error) { console.error("登录失败:", error); - redirect("/sign-in?error=AuthenticationError"); + // 添加时间戳防止循环 + redirect(`/sign-in?error=AuthenticationError&t=${Date.now()}`); } } diff --git a/src/components/auth/user-authorize.tsx b/src/components/auth/user-authorize.tsx index e1c9510..1a52493 100644 --- a/src/components/auth/user-authorize.tsx +++ b/src/components/auth/user-authorize.tsx @@ -20,22 +20,22 @@ export function UserAuthorize({ const router = useRouter(); const searchParams = useSearchParams(); + // 检查是否是 OAuth 授权页面 + const isOAuthFlow = + searchParams?.has("client_id") && searchParams?.has("redirect_uri"); + // 检查是否是 SSO 回调 + const isSSOCallback = searchParams?.has("sso") && searchParams?.has("sig"); + const signInCallback = useCallback(async () => { - if (isLoading) { - return; - } - - // 检查是否是 SSO 回调 - const sso = searchParams?.get("sso"); - const sig = searchParams?.get("sig"); - - // 如果没有 SSO 参数,说明这是 OAuth 授权页面,不需要处理 - if (!sso || !sig) { + if (isLoading || !isSSOCallback || isOAuthFlow) { return; } setIsLoading(true); try { + const sso = searchParams?.get("sso"); + const sig = searchParams?.get("sig"); + // 传递 SSO 参数 await signIn({ sso, @@ -50,31 +50,12 @@ export function UserAuthorize({ } finally { setIsLoading(false); } - }, [isLoading, router, searchParams]); + }, [isLoading, isSSOCallback, isOAuthFlow, router, searchParams]); useEffect(() => { signInCallback(); }, [signInCallback]); - // 如果没有 SSO 参数,显示正在处理授权的界面 - if (!searchParams?.get("sso")) { - return ( - - -
-
-
- 正在处理授权 -
- -

- 请稍候,我们正在处理您的授权请求 -

-
-
- ); - } - if (error) { return ( @@ -103,11 +84,17 @@ export function UserAuthorize({
- 正在处理登录 + + {isOAuthFlow ? "正在处理授权" : "正在处理登录"} +

- {isLoading ? "请稍候,我们正在处理您的登录请求" : "正在跳转..."} + {isOAuthFlow + ? "请稍候,我们正在处理您的授权请求" + : isLoading + ? "请稍候,我们正在处理您的登录请求" + : "正在跳转..."}