Merge pull request #81 from hamster1963/fix-auth

fix: auth
This commit is contained in:
仓鼠 2024-10-21 13:52:15 +08:00 committed by GitHub
commit b6980c9daa
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1,8 +1,8 @@
"use client";
import { getCsrfToken, signIn } from "next-auth/react";
import { getCsrfToken } from "next-auth/react";
import { useTranslations } from "next-intl";
import { useRouter, useSearchParams } from "next/navigation";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { Loader } from "./loading/Loader";
@ -11,20 +11,11 @@ export function SignIn() {
const t = useTranslations("SignIn");
const [csrfToken, setCsrfToken] = useState("");
const [errorState, setErrorState] = useState(false);
const [loading, setLoading] = useState(false);
const [successState, setSuccessState] = useState(false);
const [errorState, setErrorState] = useState(false);
const search = useSearchParams();
const error = search.get("error");
const router = useRouter();
useEffect(() => {
if (error) {
setErrorState(true);
}
}, [error]);
useEffect(() => {
async function loadProviders() {
const csrf = await getCsrfToken();
@ -37,20 +28,32 @@ export function SignIn() {
e.preventDefault();
setLoading(true);
const formData = new FormData(e.currentTarget);
const password = formData.get("password");
const res = await signIn("credentials", {
password,
redirect: false,
// 直接构建 URL 编码的字符串
const urlEncodedData = [
`csrfToken=${encodeURIComponent(csrfToken)}`,
`redirect=false`,
`password=${encodeURIComponent(formData.get('password') as string)}`,
].join('&');
const res = await fetch("/api/auth/callback/credentials", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: urlEncodedData,
});
if (res?.error) {
setErrorState(true);
if (res.url.includes("error")) {
setLoading(false)
setErrorState(true)
} else {
setErrorState(false);
setSuccessState(true);
setLoading(false)
setErrorState(false)
}
router.push("/");
router.refresh();
}
setLoading(false);
};
return (
@ -66,11 +69,6 @@ export function SignIn() {
{t("ErrorMessage")}
</p>
)}
{successState && (
<p className="text-green-500 text-sm font-semibold">
{t("SuccessMessage")}
</p>
)}
<p className="text-base font-semibold">{t("SignInMessage")}</p>
<input
className="px-1 border-[1px] rounded-[5px]"