This commit is contained in:
ariari04 2024-09-26 19:35:36 +06:00
parent 876555dc99
commit 165cab01ce
2 changed files with 121 additions and 115 deletions

View File

@ -1,3 +1,5 @@
"use client";
import { useState } from "react";
import { apiInstance } from "@/shared/config/apiConfig";
import { useSession } from "next-auth/react";
@ -7,7 +9,7 @@ import ChangePasswordInput from "./ChangePasswordInput/ChangePasswordInput";
import { Link } from "@/shared/config/navigation";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { FormProvider, useForm } from "react-hook-form";
interface IChangePasswordProps {
closeWindow: (bool: boolean) => void;
@ -17,23 +19,15 @@ const ChangePassword: React.FC<IChangePasswordProps> = ({
closeWindow,
}: IChangePasswordProps) => {
const session = useSession();
const [oldPassword, setOldPassword] = useState<string>("");
const [newPassword, setNewPassword] = useState<string>("");
const [confirmNewPassword, setConfirmNewPassword] = useState<string>("");
const [warningOldPassword, setWarningOldPassword] = useState<string>("");
const [warningNewPassword, setWarningNewPassword] = useState<string>("");
const [warningConfirmNewPassword, setWarningConfirmNewPassword] =
useState<string>("");
const [error, setError] = useState<string>("");
const [loader, setLoader] = useState<boolean>(false);
const [success, setSuccess] = useState<boolean>(false);
const changePasswordScheme = z
.object({
old_password: z.string().min(8, "Минимум 8 символов"),
new_password1: z.string().min(8, "Минимум 8 символов"),
new_password2: z.string().min(8, "Минимум 8 символов"),
old_password: z.string().min(8, { message: "Минимум 8 символов" }),
new_password1: z.string().min(8, { message: "Минимум 8 символов" }),
new_password2: z.string().min(8, { message: "Минимум 8 символов" }),
})
.refine((data) => data.new_password1 === data.new_password2, {
message: "Пароли не совпадают",
@ -41,40 +35,43 @@ const ChangePassword: React.FC<IChangePasswordProps> = ({
});
type FormFields = z.infer<typeof changePasswordScheme>;
const {
register,
handleSubmit,
formState: { errors },
} = useForm<FormFields>({
const form = useForm<FormFields>({
resolver: zodResolver(changePasswordScheme),
defaultValues: {
old_password: "",
new_password1: "",
new_password2: "",
},
});
const onSubmit = async (data: FormFields) => {
try {
setError("");
setLoader(true);
console.log(data);
// console.log("cfvgbhnj");
// setError("");
// setLoader(true);
const Authorization = `Bearer ${session.data?.access_token}`;
const config = {
headers: {
Authorization,
},
};
const res = await apiInstance.patch(
"/auth/password_change/",
data,
config
);
// const Authorization = `Bearer ${session.data?.access_token}`;
// const config = {
// headers: {
// Authorization,
// },
// };
// const res = await apiInstance.patch(
// "/auth/password_change/",
// data,
// config
// );
if ([200, 201].includes(res.status)) return setSuccess(true);
// if ([200, 201].includes(res.status)) return setSuccess(true);
} catch (error: unknown) {
if (error instanceof AxiosError) {
if (error.response?.status === 400) {
setError("Некорректный старый пароль или недопустимый новый пароль");
}
} else {
setError("Произошла непредвиденная ошибка");
}
// if (error instanceof AxiosError) {
// if (error.response?.status === 400) {
// setError("Некорректный старый пароль или недопустимый новый пароль");
// }
// } else {
// setError("Произошла непредвиденная ошибка");
// }
} finally {
setLoader(false);
}
@ -85,63 +82,59 @@ const ChangePassword: React.FC<IChangePasswordProps> = ({
onClick={() => closeWindow(false)}
className="w-full h-full fixed top-0 left-0 z-10 bg-gray-950 flex items-center justify-center"
>
<div
onClick={(e) => e.stopPropagation()}
className="flex w-full max-w-[400px] p-6 flex-col gap-4 rounded-md bg-white"
>
<form onSubmit={handleSubmit(onSubmit)}>
<h4 className="mb-2 text-[18px] font-bold leading-7 text-gray-900">
Изменить пароль
</h4>
<ChangePasswordInput
onChange={(e) => setOldPassword(e.target.value)}
value={oldPassword}
placeholder="Введите старый пароль"
label="Старый пароль"
error={warningOldPassword}
/>
<Link
href="/sign-in/forgot-password"
className="self-end leading-8 text-blue"
>
Забыли пароль?
</Link>
<ChangePasswordInput
onChange={(e) => setNewPassword(e.target.value)}
value={newPassword}
placeholder="Введите новый пароль"
label="Новый пароль"
error={warningNewPassword}
/>
<ChangePasswordInput
onChange={(e) => setConfirmNewPassword(e.target.value)}
value={confirmNewPassword}
placeholder="Повторите новый пароль"
label="Потвердить новый пароль"
error={warningConfirmNewPassword}
/>
{error ? <p className="text-red-500">{error}</p> : null}
{success ? (
<p className="text-light-blue">Вы успешно поменяли пароль!</p>
) : null}
<FormProvider {...form}>
<div
onClick={(e) => e.stopPropagation()}
className="flex w-full max-w-[400px] p-6 flex-col gap-4 rounded-md bg-white"
>
<form onSubmit={form.handleSubmit(onSubmit)}>
<h4 className="mb-2 text-[18px] font-bold leading-7 text-gray-900">
Изменить пароль
</h4>
<ChangePasswordInput
name="old_password"
placeholder="Введите старый пароль"
label="Старый пароль"
/>
<Link
href="/sign-in/forgot-password"
className="self-end leading-8 text-blue"
>
Забыли пароль?
</Link>
<ChangePasswordInput
name="new_password1"
placeholder="Введите новый пароль"
label="Новый пароль"
/>
<ChangePasswordInput
name="new_password2"
placeholder="Повторите новый пароль"
label="Потвердить новый пароль"
/>
{error ? <p className="text-red-500">{error}</p> : null}
{success ? (
<p className="text-light-blue">Вы успешно поменяли пароль!</p>
) : null}
<div className="mt-9 flex flex-col gap-3">
<button
type="button"
className="py-3 px-4 rounded-md font-bold leading-6 shadow-sm border border-blue bg-blue text-white"
>
{loader ? <Loader /> : "Сохранить"}
</button>
<button
className="py-3 px-4 rounded-md font-bold leading-6 shadow-md border border-gray-300 bg-slate-200 text-gray-500"
type="button"
onClick={() => closeWindow(false)}
>
Отмена
</button>
</div>
</form>
</div>
<div className="mt-9 flex flex-col gap-3">
<button
type="submit"
className="py-3 px-4 rounded-md font-bold leading-6 shadow-sm border border-blue bg-blue text-white"
>
{loader ? <Loader /> : "Сохранить"}
</button>
<button
className="py-3 px-4 rounded-md font-bold leading-6 shadow-md border border-gray-300 bg-slate-200 text-gray-500"
type="button"
onClick={() => closeWindow(false)}
>
Отмена
</button>
</div>
</form>
</div>
</FormProvider>
</div>
);
};

View File

@ -4,35 +4,48 @@ import Image from "next/image";
import { useState } from "react";
import eye_off from "./icons/eye-off.svg";
import eye_on from "./icons/eye-on.svg";
import { useFormContext } from "react-hook-form";
import { cn } from "@/lib/utils";
interface IChangePasswordInputProps
extends React.InputHTMLAttributes<HTMLInputElement> {
label: string;
error: string;
interface Props extends React.InputHTMLAttributes<HTMLInputElement> {
name: string;
label?: string;
required?: boolean;
className?: string;
}
const ChangePasswordInput: React.FC<IChangePasswordInputProps> = ({
label,
error,
placeholder,
const ChangePasswordInput: React.FC<Props> = ({
name,
onChange,
value,
}: IChangePasswordInputProps) => {
label,
required,
className,
...props
}) => {
const {
register,
formState: { errors },
} = useFormContext();
console.log(name);
const errorText = errors[name]?.message as string;
const [isOpen, setIsOpen] = useState<boolean>(false);
return (
<div className="flex flex-col gap-2">
<label className="font-bold leading-5 text-gray-700">{label}</label>
<div className={cn("flex flex-col gap-2", className)}>
{label && (
<label className="font-bold leading-5 text-gray-700">
{label}
{required && <span className="text-red-500">*</span>}
</label>
)}
<div
className={`py-[10px] px-[14px] flex items-center justify-between border border-gray-300 rounded-md shadow-sm bg-gray-200${
error ? "-with-error" : ""
errorText ? "-with-error" : ""
}`}
>
<input
onChange={onChange}
value={value}
name={name}
placeholder={placeholder}
{...register(name)}
{...props}
type={isOpen ? "text" : "password"}
className="w-full text-[14px] placeholder:leading-6 bg-gray-200"
/>
@ -40,9 +53,9 @@ const ChangePasswordInput: React.FC<IChangePasswordInputProps> = ({
<Image src={isOpen ? eye_on : eye_off} alt="Eye Icon" />
</button>
</div>
{error ? (
<p className="text-[14px] leading-5 text-red-500">{error}</p>
) : null}
{errorText && (
<p className="text-[14px] leading-5 text-red-500">{errorText}</p>
)}
</div>
);
};