mirror of
https://github.com/woodchen-ink/Q58Connect.git
synced 2025-07-18 05:51:55 +08:00
refactor: Simplify OAuth and SSO authentication error handling and component logic
This commit is contained in:
parent
465bf1dff5
commit
96804d59f8
@ -1,25 +1,11 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect } from "react";
|
||||
import Link from "next/link";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { MessageCircleCode } from "lucide-react";
|
||||
|
||||
import { UserAuthForm } from "@/components/auth/user-auth-form";
|
||||
|
||||
export default function AuthPage() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
useEffect(() => {
|
||||
// 如果有 OAuth 参数,重定向回 /oauth/authorize
|
||||
if (searchParams.has("response_type") && searchParams.has("client_id")) {
|
||||
console.log("检测到 OAuth 参数,准备重定向到 /oauth/authorize");
|
||||
router.replace(`/oauth/authorize?${searchParams.toString()}`);
|
||||
return;
|
||||
}
|
||||
}, [router, searchParams]);
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[350px]">
|
||||
<div className="flex flex-col space-y-2 text-center">
|
||||
|
@ -1,16 +1,11 @@
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
import { getClientByClientId } from "@/lib/dto/client";
|
||||
import { getCurrentUser } from "@/lib/session";
|
||||
import { Authorizing } from "@/components/auth/authorizing";
|
||||
import { ErrorCard } from "@/components/auth/error-card";
|
||||
|
||||
export interface AuthorizeParams {
|
||||
scope?: string;
|
||||
export interface AuthorizeParams extends Record<string, string> {
|
||||
scope: string;
|
||||
response_type: string;
|
||||
client_id: string;
|
||||
redirect_uri: string;
|
||||
state?: string;
|
||||
}
|
||||
|
||||
export default async function OAuthAuthorization({
|
||||
@ -18,98 +13,22 @@ export default async function OAuthAuthorization({
|
||||
}: {
|
||||
searchParams: AuthorizeParams;
|
||||
}) {
|
||||
// 检查用户是否已登录
|
||||
const user = await getCurrentUser();
|
||||
if (!user?.id) {
|
||||
// 直接使用原始的 URL 参数进行重定向
|
||||
const params = new URLSearchParams();
|
||||
Object.entries(searchParams).forEach(([key, value]) => {
|
||||
if (value) params.append(key, value);
|
||||
});
|
||||
redirect(`/sign-in?${params.toString()}`);
|
||||
}
|
||||
|
||||
// 验证必要的参数
|
||||
// params invalid
|
||||
if (
|
||||
!searchParams.response_type ||
|
||||
!searchParams.client_id ||
|
||||
!searchParams.redirect_uri
|
||||
) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center p-4">
|
||||
<ErrorCard
|
||||
title="参数错误"
|
||||
description="缺少必要的参数"
|
||||
redirectUri={searchParams.redirect_uri}
|
||||
error="invalid_request"
|
||||
errorDescription="缺少必要的参数"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
throw new Error("Params invalid");
|
||||
}
|
||||
|
||||
// 验证 response_type
|
||||
if (searchParams.response_type !== "code") {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center p-4">
|
||||
<ErrorCard
|
||||
title="参数错误"
|
||||
description="不支持的授权类型"
|
||||
redirectUri={searchParams.redirect_uri}
|
||||
error="unsupported_response_type"
|
||||
errorDescription="仅支持 code 授权类型"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 验证客户端
|
||||
// client invalid
|
||||
const client = await getClientByClientId(searchParams.client_id);
|
||||
if (!client) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center p-4">
|
||||
<ErrorCard
|
||||
title="应用不存在"
|
||||
description="您尝试访问的应用不存在或已被删除"
|
||||
redirectUri={searchParams.redirect_uri}
|
||||
error="invalid_client"
|
||||
errorDescription="应用不存在"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
if (!client || client.redirectUri !== searchParams.redirect_uri) {
|
||||
throw new Error("Client not found");
|
||||
}
|
||||
|
||||
// 检查应用是否被禁用
|
||||
if (!client.enabled) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center p-4">
|
||||
<ErrorCard
|
||||
title="应用已禁用"
|
||||
description="此应用已被管理员禁用,暂时无法使用"
|
||||
redirectUri={searchParams.redirect_uri}
|
||||
error="access_denied"
|
||||
errorDescription="此应用已被禁用"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 检查回调地址是否匹配
|
||||
if (client.redirectUri !== searchParams.redirect_uri) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center p-4">
|
||||
<ErrorCard
|
||||
title="回调地址不匹配"
|
||||
description="应用提供的回调地址与注册时不符"
|
||||
redirectUri={searchParams.redirect_uri}
|
||||
error="invalid_request"
|
||||
errorDescription="回调地址不匹配"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 使用原始的 Authorizing 组件处理授权流程
|
||||
// Authorizing ...
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-gray-50 p-4">
|
||||
<Authorizing />
|
||||
|
@ -10,31 +10,13 @@ const discourseHost = process.env.DISCOURSE_HOST as string;
|
||||
const clientSecret = process.env.DISCOURSE_SECRET as string;
|
||||
|
||||
export async function POST(req: Request) {
|
||||
console.log("开始处理 SSO 登录请求...");
|
||||
|
||||
try {
|
||||
const nonce = WordArray.random(16).toString();
|
||||
let return_url = `${hostUrl}/authorize`;
|
||||
const return_url = `${hostUrl}/authorize`;
|
||||
|
||||
try {
|
||||
const body = await req.json();
|
||||
console.log("收到请求体:", body);
|
||||
|
||||
if (body.return_url) {
|
||||
return_url = `${hostUrl}${body.return_url}`;
|
||||
console.log("使用自定义 return_url:", return_url);
|
||||
} else {
|
||||
console.log("使用默认 return_url:", return_url);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("解析请求体失败:", error);
|
||||
}
|
||||
|
||||
console.log("生成 SSO 参数...");
|
||||
const sso = btoa(`nonce=${nonce}&return_sso_url=${return_url}`);
|
||||
const sig = hmacSHA256(sso, clientSecret).toString(Hex);
|
||||
|
||||
console.log("设置 nonce cookie...");
|
||||
cookies().set(AUTH_NONCE, nonce, {
|
||||
maxAge: 60 * 10,
|
||||
path: "/",
|
||||
@ -43,18 +25,15 @@ export async function POST(req: Request) {
|
||||
});
|
||||
|
||||
const sso_url = `${discourseHost}/session/sso_provider?sso=${sso}&sig=${sig}`;
|
||||
console.log("生成 SSO URL:", sso_url);
|
||||
|
||||
return Response.json({
|
||||
sso_url: sso_url,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("SSO 处理错误:", error);
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
return Response.json(
|
||||
{
|
||||
error: "处理登录请求时发生错误",
|
||||
details: errorMessage,
|
||||
},
|
||||
{ status: 500 },
|
||||
);
|
||||
|
@ -5,7 +5,6 @@ import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { getDiscourseSSOUrl } from "@/actions/discourse-sso-url";
|
||||
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { ErrorCard } from "@/components/auth/error-card";
|
||||
|
||||
export function Authorizing() {
|
||||
const router = useRouter();
|
||||
|
@ -1,18 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Loader2, MessageCircleCode } from "lucide-react";
|
||||
import { signIn } from "next-auth/react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { buttonVariants } from "@/components/ui/button";
|
||||
|
||||
interface DiscourseData {
|
||||
sso_url: string;
|
||||
}
|
||||
|
||||
export function UserAuthForm({
|
||||
className,
|
||||
...props
|
||||
@ -20,61 +15,28 @@ export function UserAuthForm({
|
||||
const [isLoading, setIsLoading] = React.useState<boolean>(false);
|
||||
const router = useRouter();
|
||||
const { toast } = useToast();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
async function handleSignIn() {
|
||||
try {
|
||||
// 如果有 SSO 参数,使用 credentials provider 登录
|
||||
if (searchParams.has("sso") && searchParams.has("sig")) {
|
||||
console.log("检测到 SSO 参数,使用 credentials provider 登录");
|
||||
const result = await signIn("credentials", {
|
||||
sso: searchParams.get("sso"),
|
||||
sig: searchParams.get("sig"),
|
||||
redirect: false,
|
||||
});
|
||||
|
||||
if (result?.error) {
|
||||
throw new Error(result.error);
|
||||
}
|
||||
|
||||
// 登录成功后刷新页面
|
||||
router.refresh();
|
||||
return;
|
||||
}
|
||||
|
||||
// 如果有 OAuth 参数,发起 SSO 登录
|
||||
const body: Record<string, any> = {};
|
||||
if (searchParams.has("response_type") && searchParams.has("client_id")) {
|
||||
body.return_url = `/oauth/authorize?${searchParams.toString()}`;
|
||||
console.log("正在处理 OAuth 登录,return_url:", body.return_url);
|
||||
}
|
||||
|
||||
console.log("发送登录请求...");
|
||||
setIsLoading(true);
|
||||
const response = await fetch("/api/auth/q58", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.text();
|
||||
console.error("登录请求失败:", errorData);
|
||||
throw new Error(`登录请求失败: ${errorData}`);
|
||||
throw new Error("登录请求失败");
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
console.log("获取到 SSO URL:", data.sso_url);
|
||||
window.location.href = data.sso_url;
|
||||
} catch (error) {
|
||||
console.error("登录错误:", error);
|
||||
toast({
|
||||
title: "登录失败",
|
||||
description:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "登录过程中发生错误,请稍后重试",
|
||||
description: "登录过程中发生错误,请稍后重试",
|
||||
variant: "destructive",
|
||||
});
|
||||
setIsLoading(false);
|
||||
@ -86,10 +48,7 @@ export function UserAuthForm({
|
||||
<button
|
||||
type="button"
|
||||
className={cn(buttonVariants({ variant: "outline" }))}
|
||||
onClick={() => {
|
||||
setIsLoading(true);
|
||||
handleSignIn();
|
||||
}}
|
||||
onClick={handleSignIn}
|
||||
disabled={isLoading}
|
||||
>
|
||||
{isLoading ? (
|
||||
|
Loading…
x
Reference in New Issue
Block a user