refactor: Simplify user authorization action and component with direct sign-in method

This commit is contained in:
wood chen 2025-02-21 18:56:27 +08:00
parent 4254098b53
commit a3e43bf9e1
2 changed files with 7 additions and 42 deletions

View File

@ -1,27 +1,7 @@
"use server";
import { redirect } from "next/navigation";
import { signIn as nextSignIn } from "@/auth";
export async function signIn(data: Record<string, any>) {
const { sso, sig } = data;
try {
// 进行 SSO 登录
await nextSignIn("credentials", { sso, sig });
// 从 sso 参数中获取 return_sso_url
const params = new URLSearchParams(atob(sso));
const returnSsoUrl = params.get("return_sso_url");
if (!returnSsoUrl) {
redirect("/dashboard");
}
// 重定向到 return_sso_url
redirect(returnSsoUrl);
} catch (error) {
console.error("登录失败:", error);
redirect("/sign-in?error=AuthenticationError");
}
return nextSignIn("credentials", data);
}

View File

@ -1,7 +1,6 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { signIn } from "@/actions/user-authorize";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
@ -17,7 +16,6 @@ export function UserAuthorize({
}: UserAuthorizeProps) {
const [isLoading, setIsLoading] = useState<boolean>(false);
const [error, setError] = useState<Error | unknown>(null);
const router = useRouter();
const signInCallback = useCallback(async () => {
if (isLoading) {
@ -25,33 +23,20 @@ export function UserAuthorize({
}
setIsLoading(true);
try {
// 从 URL 中获取 sso 和 sig 参数
const url = new URL(window.location.href);
const sso = url.searchParams.get("sso");
const sig = url.searchParams.get("sig");
if (!sso || !sig) {
throw new Error("缺少必要的认证参数");
}
// 传递 SSO 参数
await signIn({
sso,
sig,
});
// 登录成功后刷新路由状态
router.refresh();
await signIn(data);
setIsLoading(false);
} catch (error) {
console.error("登录过程出错:", error);
setError(error);
setIsLoading(false);
}
}, [isLoading, router]);
}, [data, isLoading]);
useEffect(() => {
signInCallback();
const timer = setTimeout(signInCallback, 5);
return () => {
clearTimeout(timer);
};
}, [signInCallback]);
if (error) {