mirror of
https://github.com/woodchen-ink/Q58Connect.git
synced 2025-07-18 05:51:55 +08:00
refactor: Streamline OAuth and SSO authentication flow across multiple components
This commit is contained in:
parent
bcec776a00
commit
80e281f986
@ -5,22 +5,17 @@ import Link from "next/link";
|
|||||||
import { useRouter, useSearchParams } from "next/navigation";
|
import { useRouter, useSearchParams } from "next/navigation";
|
||||||
import { MessageCircleCode } from "lucide-react";
|
import { MessageCircleCode } from "lucide-react";
|
||||||
|
|
||||||
import { UserAuthorize } from "@/components/auth/user-authorize";
|
export default function AuthPage() {
|
||||||
|
|
||||||
type Props = {
|
|
||||||
searchParams: { [key: string]: string | string[] | undefined };
|
|
||||||
};
|
|
||||||
|
|
||||||
export default function AuthPage({ searchParams }: Props) {
|
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const urlSearchParams = useSearchParams();
|
const searchParams = useSearchParams();
|
||||||
const callbackUrl = urlSearchParams.get("callbackUrl");
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (callbackUrl) {
|
// 如果有 OAuth 参数,重定向回 /oauth/authorize
|
||||||
router.replace(callbackUrl);
|
if (searchParams.has("response_type") && searchParams.has("client_id")) {
|
||||||
|
router.replace(`/oauth/authorize?${searchParams.toString()}`);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
}, [callbackUrl, router]);
|
}, [router, searchParams]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[350px]">
|
<div className="mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[350px]">
|
||||||
@ -31,9 +26,6 @@ export default function AuthPage({ searchParams }: Props) {
|
|||||||
<span style={{ fontFamily: "Bahamas Bold" }}>Q58论坛</span>
|
<span style={{ fontFamily: "Bahamas Bold" }}>Q58论坛</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
|
||||||
<UserAuthorize data={searchParams} />
|
|
||||||
</div>
|
|
||||||
<p className="px-8 text-center text-sm text-muted-foreground">
|
<p className="px-8 text-center text-sm text-muted-foreground">
|
||||||
By clicking continue, you agree to our{" "}
|
By clicking continue, you agree to our{" "}
|
||||||
<Link
|
<Link
|
||||||
|
@ -21,17 +21,12 @@ export default async function OAuthAuthorization({
|
|||||||
// 检查用户是否已登录
|
// 检查用户是否已登录
|
||||||
const user = await getCurrentUser();
|
const user = await getCurrentUser();
|
||||||
if (!user?.id) {
|
if (!user?.id) {
|
||||||
// 构建当前 URL 作为回调地址
|
// 直接使用原始的 URL 参数进行重定向
|
||||||
const currentUrl = new URL(
|
const params = new URLSearchParams();
|
||||||
"/oauth/authorize",
|
|
||||||
process.env.NEXT_PUBLIC_HOST_URL,
|
|
||||||
);
|
|
||||||
Object.entries(searchParams).forEach(([key, value]) => {
|
Object.entries(searchParams).forEach(([key, value]) => {
|
||||||
if (value) currentUrl.searchParams.append(key, value.toString());
|
if (value) params.append(key, value);
|
||||||
});
|
});
|
||||||
redirect(
|
redirect(`/sign-in?${params.toString()}`);
|
||||||
`/sign-in?callbackUrl=${encodeURIComponent(currentUrl.toString())}`,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 验证必要的参数
|
// 验证必要的参数
|
||||||
|
@ -10,22 +10,31 @@ 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) {
|
||||||
|
console.log("开始处理 SSO 登录请求...");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const nonce = WordArray.random(16).toString();
|
const nonce = WordArray.random(16).toString();
|
||||||
let return_url = `${hostUrl}/authorize`;
|
let return_url = `${hostUrl}/authorize`;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const body = await req.json();
|
const body = await req.json();
|
||||||
|
console.log("收到请求体:", body);
|
||||||
|
|
||||||
if (body.return_url) {
|
if (body.return_url) {
|
||||||
return_url = body.return_url;
|
return_url = `${hostUrl}${body.return_url}`;
|
||||||
|
console.log("使用自定义 return_url:", return_url);
|
||||||
|
} else {
|
||||||
|
console.log("使用默认 return_url:", return_url);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Failed to parse request body:", error);
|
console.error("解析请求体失败:", error);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
console.log("生成 SSO 参数...");
|
||||||
const sso = btoa(`nonce=${nonce}&return_sso_url=${return_url}`);
|
const sso = btoa(`nonce=${nonce}&return_sso_url=${return_url}`);
|
||||||
const sig = hmacSHA256(sso, clientSecret).toString(Hex);
|
const sig = hmacSHA256(sso, clientSecret).toString(Hex);
|
||||||
|
|
||||||
|
console.log("设置 nonce cookie...");
|
||||||
cookies().set(AUTH_NONCE, nonce, {
|
cookies().set(AUTH_NONCE, nonce, {
|
||||||
maxAge: 60 * 10,
|
maxAge: 60 * 10,
|
||||||
path: "/",
|
path: "/",
|
||||||
@ -33,11 +42,21 @@ export async function POST(req: Request) {
|
|||||||
secure: process.env.NODE_ENV === "production",
|
secure: process.env.NODE_ENV === "production",
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const sso_url = `${discourseHost}/session/sso_provider?sso=${sso}&sig=${sig}`;
|
||||||
|
console.log("生成 SSO URL:", sso_url);
|
||||||
|
|
||||||
return Response.json({
|
return Response.json({
|
||||||
sso_url: `${discourseHost}/session/sso_provider?sso=${sso}&sig=${sig}`,
|
sso_url: sso_url,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("SSO 处理错误:", error);
|
console.error("SSO 处理错误:", error);
|
||||||
return Response.json({ error: "处理登录请求时发生错误" }, { status: 500 });
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||||
|
return Response.json(
|
||||||
|
{
|
||||||
|
error: "处理登录请求时发生错误",
|
||||||
|
details: errorMessage,
|
||||||
|
},
|
||||||
|
{ status: 500 },
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -24,30 +24,14 @@ export function UserAuthForm({
|
|||||||
async function signIn() {
|
async function signIn() {
|
||||||
try {
|
try {
|
||||||
const body: Record<string, any> = {};
|
const body: Record<string, any> = {};
|
||||||
const callbackUrl = searchParams?.get("callbackUrl");
|
|
||||||
|
|
||||||
console.log("Original callbackUrl:", callbackUrl);
|
// 如果有 OAuth 参数,作为 return_url 传递
|
||||||
|
if (searchParams.has("response_type") && searchParams.has("client_id")) {
|
||||||
// 如果是 OAuth 回调,则保留完整的 OAuth 参数
|
body.return_url = `/oauth/authorize?${searchParams.toString()}`;
|
||||||
if (callbackUrl?.includes("/oauth/authorize")) {
|
console.log("正在处理 OAuth 登录,return_url:", body.return_url);
|
||||||
try {
|
|
||||||
// 先解码一次 URL
|
|
||||||
const decodedUrl = decodeURIComponent(callbackUrl);
|
|
||||||
console.log("Decoded URL:", decodedUrl);
|
|
||||||
|
|
||||||
// 解析 URL 并保留所有参数
|
|
||||||
const url = new URL(decodedUrl);
|
|
||||||
if (url.pathname === "/oauth/authorize") {
|
|
||||||
body.return_url = `${window.location.origin}${url.pathname}${url.search}`;
|
|
||||||
console.log("Extracted return_url:", body.return_url);
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
console.error("URL 处理错误:", e);
|
|
||||||
body.return_url = `${window.location.origin}/authorize`;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log("发送请求体:", body);
|
console.log("发送登录请求...");
|
||||||
const response = await fetch("/api/auth/q58", {
|
const response = await fetch("/api/auth/q58", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
@ -57,20 +41,18 @@ export function UserAuthForm({
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const errorText = await response.text();
|
const errorData = await response.text();
|
||||||
console.error("服务器响应:", errorText);
|
console.error("登录请求失败:", errorData);
|
||||||
throw new Error(`登录请求失败: ${errorText}`);
|
throw new Error(`登录请求失败: ${errorData}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
console.log("收到 SSO URL:", data.sso_url);
|
console.log("获取到 SSO URL:", data.sso_url);
|
||||||
|
|
||||||
// 直接使用 window.location.href 跳转
|
|
||||||
window.location.href = data.sso_url;
|
window.location.href = data.sso_url;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("登录错误:", error);
|
console.error("登录错误:", error);
|
||||||
toast({
|
toast({
|
||||||
title: "错误",
|
title: "登录失败",
|
||||||
description:
|
description:
|
||||||
error instanceof Error
|
error instanceof Error
|
||||||
? error.message
|
? error.message
|
||||||
|
Loading…
x
Reference in New Issue
Block a user