feat: Improve OAuth authorization flow and redirect handling

- Update signIn action to support dynamic redirect after authentication
- Modify Q58 OAuth route to handle dynamic return URL with original parameters
- Refactor UserAuthorize component to support OAuth-specific redirect scenarios
- Add support for preserving and processing OAuth parameters during login
This commit is contained in:
wood chen 2025-02-21 13:08:42 +08:00
parent f7d32436b5
commit 1e519738ea
3 changed files with 29 additions and 23 deletions

View File

@ -1,7 +1,10 @@
"use server";
import { redirect } from "next/navigation";
import { signIn as nextSignIn } from "@/auth";
export async function signIn(data: Record<string, any>) {
return nextSignIn("credentials", data);
const { redirectTo, ...credentials } = data;
await nextSignIn("credentials", credentials);
redirect(redirectTo || "/dashboard");
}

View File

@ -9,10 +9,12 @@ 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) {
export async function POST(req: Request) {
const nonce = WordArray.random(16).toString();
const return_url = `${hostUrl}/authorize`;
const sso = btoa(`nonce=${nonce}&return_sso_url=${return_url}`);
const url = new URL(req.url);
const originalParams = url.searchParams.toString();
const return_url = `${hostUrl}/q58/callback?${originalParams}`;
const sso = btoa(`nonce=${nonce}&return_sso_url=${encodeURI(return_url)}`);
const sig = hmacSHA256(sso, clientSecret).toString(Hex);
cookies().set(AUTH_NONCE, nonce, { maxAge: 60 * 10 });

View File

@ -1,8 +1,7 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { signIn as nextAuthSignIn, useSession } from "next-auth/react";
import { signIn } from "@/actions/user-authorize";
interface UserAuthorizeProps extends React.HTMLAttributes<HTMLDivElement> {
data: Record<string, any>;
@ -15,8 +14,6 @@ export function UserAuthorize({
}: UserAuthorizeProps) {
const [isLoading, setIsLoading] = useState<boolean>(false);
const [error, setError] = useState<Error | unknown>(null);
const { update } = useSession();
const router = useRouter();
const signInCallback = useCallback(async () => {
if (isLoading) {
@ -24,28 +21,32 @@ export function UserAuthorize({
}
setIsLoading(true);
try {
const result = await nextAuthSignIn("credentials", {
...data,
redirect: false,
});
// 检查是否有 OAuth 参数
const searchParams = new URLSearchParams(data);
const sso = searchParams.get("sso");
const sig = searchParams.get("sig");
const oauth = searchParams.get("oauth");
if (result?.error) {
setError(result.error);
} else {
// 更新 session
await update();
// 重定向回OAuth授权页面
router.push(`/oauth/authorize${window.location.search}`);
let redirectTo = "/dashboard";
if (sso && sig && oauth) {
// 如果是从Q58论坛回调使用原始的OAuth参数
const oauthParams = new URLSearchParams(atob(oauth));
redirectTo = `/oauth/authorize?${oauthParams.toString()}`;
}
await signIn({ ...data, redirectTo });
setIsLoading(false);
} catch (error) {
setError(error);
} finally {
setIsLoading(false);
}
}, [data, isLoading, update, router]);
}, [data, isLoading]);
useEffect(() => {
signInCallback();
const timer = setTimeout(signInCallback, 5);
return () => {
clearTimeout(timer);
};
}, [signInCallback]);
return (
@ -53,7 +54,7 @@ export function UserAuthorize({
{error ? (
<p className="text-center"></p>
) : (
<p className="text-center">...</p>
<p className="text-center">...</p>
)}
</>
);