Implement authentification logic

This commit is contained in:
Иван 2025-12-14 14:09:47 +03:00
parent c51f26fccc
commit c592ba9eaf
2 changed files with 139 additions and 146 deletions

View File

@ -1,5 +1,6 @@
import { useMutation } from "@tanstack/react-query";
import useAuthStore from "@/stores/useAuthStore";
import useApiClient from "@/hooks/useApiClient";
interface AuthDataType {
email: string;
@ -7,35 +8,28 @@ interface AuthDataType {
rememberMe: boolean;
}
const useAuthentificate = (authData: AuthDataType) => {
const { rememberMe } = authData;
const useAuthentificate = () => {
const client = useApiClient();
const setToken = useAuthStore((state) => state.setToken);
return useMutation({
mutationKey: ["auth", authData.email],
mutationFn: async () => {
const response = await fetch("/api/auth/login/", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(authData),
});
mutationKey: ["auth"],
mutationFn: async (authData: AuthDataType) => {
const response = await client.post("/api/auth/login/", authData);
if (!response.ok) {
throw new Error("Ошибка авторизации");
}
const { access_token } = await response.json();
const { access_token } = await response.data;
if (!access_token) {
throw new Error("Не удалось получить токен авторизации");
}
setToken(access_token, rememberMe);
setToken(access_token, authData.rememberMe);
return access_token;
},
onError: () => {
throw new Error("Ошибка авторизации");
},
});
};

View File

@ -1,6 +1,6 @@
"use client";
import { useState } from "react";
import { useState, useEffect } from "react";
import {
Dialog,
DialogContent,
@ -12,6 +12,7 @@ import { Field, FieldContent } from "@/components/ui/field";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import Image from "next/image";
import useAuthentificate from "@/api/useAuthentificate";
interface AuthDialogProps {
isOpen: boolean;
@ -23,13 +24,19 @@ export default function AuthDialog({ isOpen, onClose }: AuthDialogProps) {
const [password, setPassword] = useState("");
const [rememberMe, setRememberMe] = useState(false);
const mutation = useAuthentificate();
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
// Здесь будет логика авторизации
console.log("Авторизация:", { email, password, rememberMe });
onClose();
mutation.mutate({ email, password, rememberMe });
};
useEffect(() => {
if (mutation.isSuccess) {
onClose();
}
}, [mutation.isSuccess]);
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="[&>button]:hidden max-w-4xl w-full h-[600px] rounded-[30px] bg-[#F8F8F8]">
@ -50,9 +57,7 @@ export default function AuthDialog({ isOpen, onClose }: AuthDialogProps) {
id="email"
type="email"
value={email}
onChange={(e) =>
setEmail(e.target.value)
}
onChange={(e) => setEmail(e.target.value)}
placeholder="Электронная почта"
className="w-full bg-white px-5 py-4 border border-gray-300 rounded-full focus:ring-2 focus:ring-[#008299] focus:border-transparent outline-none transition-colors"
required
@ -67,9 +72,7 @@ export default function AuthDialog({ isOpen, onClose }: AuthDialogProps) {
id="password"
type="password"
value={password}
onChange={(e) =>
setPassword(e.target.value)
}
onChange={(e) => setPassword(e.target.value)}
placeholder="Пароль"
className="w-full bg-white px-5 py-4 border border-gray-300 rounded-full focus:ring-2 focus:ring-[#008299] focus:border-transparent outline-none transition-colors"
required
@ -87,10 +90,7 @@ export default function AuthDialog({ isOpen, onClose }: AuthDialogProps) {
setRememberMe(checked as boolean)
}
/>
<Label
htmlFor="remember"
className="text-sm"
>
<Label htmlFor="remember" className="text-sm">
Запомнить меня
</Label>
</div>
@ -123,8 +123,7 @@ export default function AuthDialog({ isOpen, onClose }: AuthDialogProps) {
{/* Договор */}
<div className="mt-8 text-xs text-gray-400 text-center">
Входя в аккаунт или создавая новый, вы соглашаетесь
с нашими{" "}
Входя в аккаунт или создавая новый, вы соглашаетесь с нашими{" "}
<button className="text-primary hover:underline">
Правилами и условиями
</button>{" "}