refactor: move login from function to middleware

This commit is contained in:
Kentai Radiquum 2025-03-22 01:15:48 +05:00
parent 19dbd69fd5
commit 0bf00b11e5
Signed by: Radiquum
GPG key ID: 858E8EE696525EED
5 changed files with 96 additions and 92 deletions

View file

@ -1,8 +1,11 @@
"use client";
import { useState, useEffect } from "react";
import { useUserStore } from "#/store/auth";
import { setJWT } from "#/api/utils";
import { setJWT, tryCatchAPI } from "#/api/utils";
import { useRouter, useSearchParams } from "next/navigation";
import { useThemeMode } from "flowbite-react";
import { toast } from "react-toastify";
import { ENDPOINTS } from "#/api/config";
export function LoginPage() {
const [login, setLogin] = useState("");
@ -12,37 +15,78 @@ export function LoginPage() {
const router = useRouter();
const searchParams = useSearchParams();
const redirect = searchParams.get("redirect") || null;
const theme = useThemeMode();
const [isSending, setIsSending] = useState(false);
function submit(e) {
async function submit(e) {
e.preventDefault();
fetch("/api/profile/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
login: login,
password: password,
}),
})
.then((response) => {
if (response.ok) {
return response.json();
} else {
alert("Ошибка получения пользователя.");
}
setIsSending(true);
const tid = toast.loading("Выполняем вход...", {
position: "bottom-center",
hideProgressBar: true,
closeOnClick: false,
pauseOnHover: false,
draggable: false,
theme: theme.mode == "light" ? "light" : "dark",
});
const { data, error } = await tryCatchAPI(
fetch(`${ENDPOINTS.user.auth}?login=${login}&password=${password}`, {
method: "POST",
headers: {
Sign: "9aa5c7af74e8cd70c86f7f9587bde23d",
"Content-Type": "application/x-www-form-urlencoded",
},
})
.then((data) => {
if (data.profileToken) {
userStore.login(data.profile, data.profileToken.token);
if (remember) {
setJWT(data.profile.id, data.profileToken.token);
}
router.push("/");
} else {
alert("Неверные данные.");
}
);
if (error) {
let message = `Ошибка получения пользователя, code: ${error.code}`
if (error.code == 2) {
message = "Такого пользователя не существует"
}
if (error.code == 3) {
message = "Неправильно указан логин и/или пароль"
}
toast.update(tid, {
render: message,
type: "error",
autoClose: 2500,
isLoading: false,
closeOnClick: true,
draggable: true,
});
setIsSending(false);
return;
}
if (!data.profileToken) {
toast.update(tid, {
render: "Не удалось войти в аккаунт",
type: "error",
autoClose: 2500,
isLoading: false,
closeOnClick: true,
draggable: true,
});
setIsSending(false);
return;
}
userStore.login(data.profile, data.profileToken.token);
if (remember) {
setJWT(data.profile.id, data.profileToken.token);
}
toast.update(tid, {
render: "Вход успешен!",
type: "success",
autoClose: 2500,
isLoading: false,
closeOnClick: true,
draggable: true,
});
}
useEffect(() => {
@ -53,7 +97,7 @@ export function LoginPage() {
}, [userStore.user]);
return (
<section className="bg-gray-50 dark:bg-gray-900">
<section>
<div className="flex flex-col items-center justify-center px-6 py-8 mx-auto md:h-screen lg:py-0">
<div className="w-full bg-white rounded-lg shadow dark:border md:mt-0 sm:max-w-md xl:p-0 dark:bg-gray-800 dark:border-gray-700">
<div className="p-6 space-y-4 md:space-y-6 sm:p-8">