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

View File

@ -1,152 +1,151 @@
"use client"; "use client";
import { useState } from "react"; import { useState, useEffect } from "react";
import { import {
Dialog, Dialog,
DialogContent, DialogContent,
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
} from "@/components/ui/dialog"; } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Field, FieldContent } from "@/components/ui/field"; import { Field, FieldContent } from "@/components/ui/field";
import { Checkbox } from "@/components/ui/checkbox"; import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
import Image from "next/image"; import Image from "next/image";
import useAuthentificate from "@/api/useAuthentificate";
interface AuthDialogProps { interface AuthDialogProps {
isOpen: boolean; isOpen: boolean;
onClose: () => void; onClose: () => void;
} }
export default function AuthDialog({ isOpen, onClose }: AuthDialogProps) { export default function AuthDialog({ isOpen, onClose }: AuthDialogProps) {
const [email, setEmail] = useState(""); const [email, setEmail] = useState("");
const [password, setPassword] = useState(""); const [password, setPassword] = useState("");
const [rememberMe, setRememberMe] = useState(false); const [rememberMe, setRememberMe] = useState(false);
const handleSubmit = (e: React.FormEvent) => { const mutation = useAuthentificate();
e.preventDefault();
// Здесь будет логика авторизации
console.log("Авторизация:", { email, password, rememberMe });
onClose();
};
return ( const handleSubmit = (e: React.FormEvent) => {
<Dialog open={isOpen} onOpenChange={onClose}> e.preventDefault();
<DialogContent className="[&>button]:hidden max-w-4xl w-full h-[600px] rounded-[30px] bg-[#F8F8F8]"> mutation.mutate({ email, password, rememberMe });
<div className="flex h-full gap-10"> };
{/* Левая часть - форма */}
<div className="flex-1 rounded-l-[10px] py-8 pl-1 flex flex-col justify-center">
<DialogHeader className="text-left mb-8">
<DialogTitle className="text-2xl font-bold text-gray-800 mb-2">
Авторизация
</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-6"> useEffect(() => {
{/* Поле email */} if (mutation.isSuccess) {
<Field> onClose();
<FieldContent> }
<input }, [mutation.isSuccess]);
id="email"
type="email"
value={email}
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
/>
</FieldContent>
</Field>
{/* Поле пароля */} return (
<Field> <Dialog open={isOpen} onOpenChange={onClose}>
<FieldContent> <DialogContent className="[&>button]:hidden max-w-4xl w-full h-[600px] rounded-[30px] bg-[#F8F8F8]">
<input <div className="flex h-full gap-10">
id="password" {/* Левая часть - форма */}
type="password" <div className="flex-1 rounded-l-[10px] py-8 pl-1 flex flex-col justify-center">
value={password} <DialogHeader className="text-left mb-8">
onChange={(e) => <DialogTitle className="text-2xl font-bold text-gray-800 mb-2">
setPassword(e.target.value) Авторизация
} </DialogTitle>
placeholder="Пароль" </DialogHeader>
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
/>
</FieldContent>
</Field>
{/* Чекбокс и ссылка */} <form onSubmit={handleSubmit} className="space-y-6">
<div className="flex items-center justify-between"> {/* Поле email */}
<div className="flex items-center space-x-2"> <Field>
<Checkbox <FieldContent>
id="remember" <input
checked={rememberMe} id="email"
onCheckedChange={(checked) => type="email"
setRememberMe(checked as boolean) value={email}
} onChange={(e) => setEmail(e.target.value)}
/> placeholder="Электронная почта"
<Label 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"
htmlFor="remember" required
className="text-sm" />
> </FieldContent>
Запомнить меня </Field>
</Label>
</div>
<button
type="button"
className="text-sm hover:text-[#008299] transition-colors"
>
Забыли пароль?
</button>
</div>
{/* Кнопка входа */} {/* Поле пароля */}
<Button <Field>
type="submit" <FieldContent>
className="w-full h-[56px] bg-brand px-5 py-4 hover:bg-brand-hover text-white rounded-full font-semibold transition-colors" <input
> id="password"
Войти type="password"
</Button> value={password}
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
/>
</FieldContent>
</Field>
{/* Ссылка на регистрацию */} {/* Чекбокс и ссылка */}
<div className="text-center"> <div className="flex items-center justify-between">
<button <div className="flex items-center space-x-2">
type="button" <Checkbox
className="hover:text-brand font-bold transition-colors" id="remember"
> checked={rememberMe}
Создать аккаунт onCheckedChange={(checked) =>
</button> setRememberMe(checked as boolean)
</div> }
</form> />
<Label htmlFor="remember" className="text-sm">
{/* Договор */} Запомнить меня
<div className="mt-8 text-xs text-gray-400 text-center"> </Label>
Входя в аккаунт или создавая новый, вы соглашаетесь
с нашими{" "}
<button className="text-primary hover:underline">
Правилами и условиями
</button>{" "}
и{" "}
<button className="text-primary hover:underline">
Положением о конфиденциальности
</button>
</div>
</div>
{/* Правая часть - изображение */}
<div className="hidden md:block flex-1 relative overflow-hidden rounded-[20px]">
{/* Изображение яхт */}
<Image
src="/images/auth.jpg"
alt="Яхты"
fill
className="object-cover rounded-lg"
/>
</div>
</div> </div>
</DialogContent> <button
</Dialog> type="button"
); className="text-sm hover:text-[#008299] transition-colors"
>
Забыли пароль?
</button>
</div>
{/* Кнопка входа */}
<Button
type="submit"
className="w-full h-[56px] bg-brand px-5 py-4 hover:bg-brand-hover text-white rounded-full font-semibold transition-colors"
>
Войти
</Button>
{/* Ссылка на регистрацию */}
<div className="text-center">
<button
type="button"
className="hover:text-brand font-bold transition-colors"
>
Создать аккаунт
</button>
</div>
</form>
{/* Договор */}
<div className="mt-8 text-xs text-gray-400 text-center">
Входя в аккаунт или создавая новый, вы соглашаетесь с нашими{" "}
<button className="text-primary hover:underline">
Правилами и условиями
</button>{" "}
и{" "}
<button className="text-primary hover:underline">
Положением о конфиденциальности
</button>
</div>
</div>
{/* Правая часть - изображение */}
<div className="hidden md:block flex-1 relative overflow-hidden rounded-[20px]">
{/* Изображение яхт */}
<Image
src="/images/auth.jpg"
alt="Яхты"
fill
className="object-cover rounded-lg"
/>
</div>
</div>
</DialogContent>
</Dialog>
);
} }