完成设置密码逻辑

This commit is contained in:
sijinhui 2024-05-25 14:37:12 +08:00
parent 4f71182fd6
commit 94b7ac8550
2 changed files with 137 additions and 30 deletions

View File

@ -0,0 +1,70 @@
import { NextRequest, NextResponse } from "next/server";
import prisma from "@/lib/prisma";
import { hashPassword, comparePassword } from "@/lib/utils";
import { getSession } from "@/lib/auth";
async function handle(
req: NextRequest,
{ params }: { params: { path: string } },
) {
// 判断网址和请求方法
const method = req.method;
// const url = req.url;
const { pathname, searchParams } = new URL(req.url);
const searchText = searchParams.get("search");
// 校验仅当前用户支持访问
const session = await getSession();
if (params.path !== session?.user?.id) {
// return NextResponse.json({ error: "无权限" }, { status: 402 });
}
const new_password_d = await req.json();
// 旧密码校验
// @ts-expect-error
if (session?.user?.hasPassword) {
const user = await prisma.user.findUnique({
where: {
id: params.path,
},
});
if (
!(
new_password_d["user[old_password]"] &&
comparePassword(
new_password_d["user[old_password]"],
user?.password ?? "",
)
)
) {
return NextResponse.json({ error: "密码校验失败" }, { status: 401 });
}
}
// 校验新密码规则
if (
new_password_d["user[password]"].length < 6 ||
new_password_d["user[password]"] !==
new_password_d["user[password_confirmation]"]
) {
return NextResponse.json({ error: "密码校验失败" }, { status: 401 });
}
await prisma.user.update({
where: {
id: params.path,
},
data: {
password: hashPassword(new_password_d["user[password]"]),
},
});
return NextResponse.json({ result: "ok" });
// return NextResponse.json({ error: "未知错误" }, { status: 500 });
// return NextResponse.json({ error: "当前方法不支持" }, { status: 405 });
}
// export const GET = handle;
// export const POST = handle;
export const PUT = handle;
// export const DELETE = handle;

View File

@ -2,55 +2,92 @@
import { redirect } from "next/navigation";
// import { getSession } from "@/lib/auth";
import { useSession } from "next-auth/react";
import { Button, Checkbox, Form, Input } from "antd";
import { Button, Checkbox, Form, FormProps, Input } from "antd";
import { LockOutlined } from "@ant-design/icons";
import React from "react";
import React, { useState } from "react";
import { signOut } from "next-auth/react";
type LoginType = "phone" | "account";
export default function SetPasswordPage() {
const [loading, setLoading] = useState(false);
const { data: session, status } = useSession();
const [showOldPassword, setShowOldPassword] = useState<Boolean>(true);
const [setPasswordForm] = Form.useForm();
// if (typeof window !== "undefined" && loading) return null;
// console.log("2222222", session);
// @ts-expect-error
if (!session?.user?.hasPassword) {
}
// else {
// redirect("/")
// @ ts-expect-error
// if (!session?.user?.hasPassword) {
// setShowOldPassword(false);
// }
// if (status === "authenticated") {
// console.log('55555,', session, status)
// // @ts-expect-error
// if (session?.user?.hasPassword) {
// setShowOldPassword(false);
// }
// }
// console.log('---', session)
type FieldType = {
"user[old_password]"?: string;
"user[password]"?: string;
"user[password_confirmation]"?: string;
};
const onFinish: FormProps<FieldType>["onFinish"] = (values) => {
setLoading(true);
// console.log('-------------', values)
// @ts-expect-error
fetch(`/api/user/${session?.user?.id}`, {
method: "PUT",
credentials: "include",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(values),
})
.then((response) => response.json())
.then((result) => {
if (result["result"] == "ok") {
signOut({ redirect: true, callbackUrl: "/login" });
}
console.log("--------", result);
});
};
return (
<>
{/*<p>Signed in as {}</p>*/}
{/*<div>需要设置一个密码</div>*/}
<div className="mx-auto mt-4 w-11/12 max-w-xs sm:w-full">
<Form
autoComplete="off"
form={setPasswordForm}
id="set-password-form"
layout="vertical"
onFinish={onFinish}
>
<Form.Item
name="user[old_password]"
label="Old password"
rules={[
{
validator: async (_, value) => {
if (!value) {
return Promise.reject(new Error("请填写该字段"));
}
},
},
]}
>
<Input
prefix={<LockOutlined className="site-form-item-icon" />}
type="password"
autoComplete="current-password"
id="user_old_password"
/>
</Form.Item>
{
// @ts-expect-error
status === "authenticated" && session?.user?.hasPassword && (
<Form.Item
name="user[old_password]"
label="Old password"
rules={[
{
validator: async (_, value) => {
if (!value) {
return Promise.reject(new Error("请填写该字段"));
}
},
},
]}
>
<Input
prefix={<LockOutlined className="site-form-item-icon" />}
type="password"
autoComplete="current-password"
id="user_old_password"
/>
</Form.Item>
)
}
<Form.Item
name="user[password]"
label="New password"