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";
|
"use client";
|
||||||
|
|
||||||
import { useEffect } from "react";
|
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { useRouter, useSearchParams } from "next/navigation";
|
|
||||||
import { MessageCircleCode } from "lucide-react";
|
import { MessageCircleCode } from "lucide-react";
|
||||||
|
|
||||||
import { UserAuthForm } from "@/components/auth/user-auth-form";
|
import { UserAuthForm } from "@/components/auth/user-auth-form";
|
||||||
|
|
||||||
export default function AuthPage() {
|
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 (
|
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]">
|
||||||
<div className="flex flex-col space-y-2 text-center">
|
<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 { getClientByClientId } from "@/lib/dto/client";
|
||||||
import { getCurrentUser } from "@/lib/session";
|
|
||||||
import { Authorizing } from "@/components/auth/authorizing";
|
import { Authorizing } from "@/components/auth/authorizing";
|
||||||
import { ErrorCard } from "@/components/auth/error-card";
|
|
||||||
|
|
||||||
export interface AuthorizeParams {
|
export interface AuthorizeParams extends Record<string, string> {
|
||||||
scope?: string;
|
scope: string;
|
||||||
response_type: string;
|
response_type: string;
|
||||||
client_id: string;
|
client_id: string;
|
||||||
redirect_uri: string;
|
redirect_uri: string;
|
||||||
state?: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export default async function OAuthAuthorization({
|
export default async function OAuthAuthorization({
|
||||||
@ -18,98 +13,22 @@ export default async function OAuthAuthorization({
|
|||||||
}: {
|
}: {
|
||||||
searchParams: AuthorizeParams;
|
searchParams: AuthorizeParams;
|
||||||
}) {
|
}) {
|
||||||
// 检查用户是否已登录
|
// params invalid
|
||||||
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()}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 验证必要的参数
|
|
||||||
if (
|
if (
|
||||||
!searchParams.response_type ||
|
!searchParams.response_type ||
|
||||||
!searchParams.client_id ||
|
!searchParams.client_id ||
|
||||||
!searchParams.redirect_uri
|
!searchParams.redirect_uri
|
||||||
) {
|
) {
|
||||||
return (
|
throw new Error("Params invalid");
|
||||||
<div className="flex min-h-screen items-center justify-center p-4">
|
|
||||||
<ErrorCard
|
|
||||||
title="参数错误"
|
|
||||||
description="缺少必要的参数"
|
|
||||||
redirectUri={searchParams.redirect_uri}
|
|
||||||
error="invalid_request"
|
|
||||||
errorDescription="缺少必要的参数"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 验证 response_type
|
// client invalid
|
||||||
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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 验证客户端
|
|
||||||
const client = await getClientByClientId(searchParams.client_id);
|
const client = await getClientByClientId(searchParams.client_id);
|
||||||
if (!client) {
|
if (!client || client.redirectUri !== searchParams.redirect_uri) {
|
||||||
return (
|
throw new Error("Client not found");
|
||||||
<div className="flex min-h-screen items-center justify-center p-4">
|
|
||||||
<ErrorCard
|
|
||||||
title="应用不存在"
|
|
||||||
description="您尝试访问的应用不存在或已被删除"
|
|
||||||
redirectUri={searchParams.redirect_uri}
|
|
||||||
error="invalid_client"
|
|
||||||
errorDescription="应用不存在"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 检查应用是否被禁用
|
// Authorizing ...
|
||||||
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 组件处理授权流程
|
|
||||||
return (
|
return (
|
||||||
<div className="flex min-h-screen items-center justify-center bg-gray-50 p-4">
|
<div className="flex min-h-screen items-center justify-center bg-gray-50 p-4">
|
||||||
<Authorizing />
|
<Authorizing />
|
||||||
|
@ -10,31 +10,13 @@ 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`;
|
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 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: "/",
|
||||||
@ -43,18 +25,15 @@ export async function POST(req: Request) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const sso_url = `${discourseHost}/session/sso_provider?sso=${sso}&sig=${sig}`;
|
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: sso_url,
|
sso_url: sso_url,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("SSO 处理错误:", error);
|
console.error("SSO 处理错误:", error);
|
||||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
||||||
return Response.json(
|
return Response.json(
|
||||||
{
|
{
|
||||||
error: "处理登录请求时发生错误",
|
error: "处理登录请求时发生错误",
|
||||||
details: errorMessage,
|
|
||||||
},
|
},
|
||||||
{ status: 500 },
|
{ status: 500 },
|
||||||
);
|
);
|
||||||
|
@ -5,7 +5,6 @@ import { useRouter, useSearchParams } from "next/navigation";
|
|||||||
import { getDiscourseSSOUrl } from "@/actions/discourse-sso-url";
|
import { getDiscourseSSOUrl } from "@/actions/discourse-sso-url";
|
||||||
|
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import { ErrorCard } from "@/components/auth/error-card";
|
|
||||||
|
|
||||||
export function Authorizing() {
|
export function Authorizing() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
@ -1,18 +1,13 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import * as React from "react";
|
import * as React from "react";
|
||||||
import { useRouter, useSearchParams } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { Loader2, MessageCircleCode } from "lucide-react";
|
import { Loader2, MessageCircleCode } from "lucide-react";
|
||||||
import { signIn } from "next-auth/react";
|
|
||||||
|
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { useToast } from "@/hooks/use-toast";
|
import { useToast } from "@/hooks/use-toast";
|
||||||
import { buttonVariants } from "@/components/ui/button";
|
import { buttonVariants } from "@/components/ui/button";
|
||||||
|
|
||||||
interface DiscourseData {
|
|
||||||
sso_url: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function UserAuthForm({
|
export function UserAuthForm({
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
@ -20,61 +15,28 @@ export function UserAuthForm({
|
|||||||
const [isLoading, setIsLoading] = React.useState<boolean>(false);
|
const [isLoading, setIsLoading] = React.useState<boolean>(false);
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
const searchParams = useSearchParams();
|
|
||||||
|
|
||||||
async function handleSignIn() {
|
async function handleSignIn() {
|
||||||
try {
|
try {
|
||||||
// 如果有 SSO 参数,使用 credentials provider 登录
|
setIsLoading(true);
|
||||||
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("发送登录请求...");
|
|
||||||
const response = await fetch("/api/auth/q58", {
|
const response = await fetch("/api/auth/q58", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
},
|
},
|
||||||
body: JSON.stringify(body),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const errorData = await response.text();
|
throw new Error("登录请求失败");
|
||||||
console.error("登录请求失败:", errorData);
|
|
||||||
throw new Error(`登录请求失败: ${errorData}`);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
console.log("获取到 SSO URL:", data.sso_url);
|
|
||||||
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.message
|
|
||||||
: "登录过程中发生错误,请稍后重试",
|
|
||||||
variant: "destructive",
|
variant: "destructive",
|
||||||
});
|
});
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
@ -86,10 +48,7 @@ export function UserAuthForm({
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className={cn(buttonVariants({ variant: "outline" }))}
|
className={cn(buttonVariants({ variant: "outline" }))}
|
||||||
onClick={() => {
|
onClick={handleSignIn}
|
||||||
setIsLoading(true);
|
|
||||||
handleSignIn();
|
|
||||||
}}
|
|
||||||
disabled={isLoading}
|
disabled={isLoading}
|
||||||
>
|
>
|
||||||
{isLoading ? (
|
{isLoading ? (
|
||||||
|
Loading…
x
Reference in New Issue
Block a user