feat: api client and natural login and logoff

This commit is contained in:
2025-05-05 16:53:18 +03:00
parent db73f498f6
commit 0055e09806
5 changed files with 215 additions and 26 deletions

View File

@@ -3,6 +3,7 @@ import Input from "@/components/ui/Input";
import { withTitle } from "@/constructors/Component";
import { UrlsTitle } from "@/enums/urls";
import { useAppContext } from "@/providers/AuthProvider";
import apiClient from "@/services/api";
import { FunctionComponent } from "preact";
import { useLocation } from "preact-iso";
import "preact/debug";
@@ -10,10 +11,6 @@ import { Controller, SubmitHandler, useForm } from "react-hook-form";
import { ILoginForm } from "./login.dto";
import classes from "./login.module.scss";
const testUser = {
login: "test",
password: "test",
};
const LoginPage: FunctionComponent = () => {
const { isLoggedIn } = useAppContext();
const { route } = useLocation();
@@ -25,15 +22,35 @@ const LoginPage: FunctionComponent = () => {
mode: "onChange",
});
const login: SubmitHandler<ILoginForm> = async (data) => {
console.log(data);
if (data.login !== testUser.login || data.password !== testUser.password) {
setError("login", { message: "Неверный логин или пароль" });
setError("password", { message: "Неверный логин или пароль" });
return;
try {
const response = await apiClient<{ success: boolean; user?: any; error?: string }>(
"/api/login/",
{
method: "POST",
body: JSON.stringify({ username: data.login, password: data.password }),
needsCsrf: true,
},
isLoggedIn
);
if (response.success) {
isLoggedIn.value = true;
localStorage.setItem("loggedIn", "true");
route("/profile/tasks", true);
} else {
const errorMessage = response.error || "Неверный логин или пароль";
setError("login", { message: errorMessage });
setError("password", { message: " " });
}
} catch (error: any) {
console.error("Login failed:", error);
const errorMessage =
error.message.includes("Authentication failed") || error.message.includes("Invalid credentials")
? "Неверный логин или пароль"
: "Ошибка входа. Попробуйте позже.";
setError("login", { message: errorMessage });
setError("password", { message: " " });
}
isLoggedIn.value = true;
localStorage.setItem("loggedIn", "true");
route("/profile/tasks", true);
};
if (isLoggedIn.value) route("/profile/tasks", true);
return !isLoggedIn.value ? (

View File

@@ -6,8 +6,16 @@ import ids from "./profile.module.scss";
const ProfilePage: FunctionComponent = () => {
const { route } = useLocation();
const { isLoggedIn } = useAppContext();
if (!isLoggedIn.value) route("/login", true);
const { isLoggedIn, isCheckingAuth } = useAppContext(); // Получаем новый сигнал
if (isCheckingAuth.value) {
return <div class="flex h-screen items-center justify-center">Проверка авторизации...</div>;
}
if (!isLoggedIn.value) {
route("/login", true);
return <p>Redirecting...</p>; // Заглушка на время редиректа
}
return isLoggedIn.value ? (
<div id={ids.main_container}>
<div id={ids.router_container}>

View File

@@ -2,6 +2,7 @@ import Button from "@/components/ui/Button";
import { withTitle } from "@/constructors/Component";
import { UrlsTitle } from "@/enums/urls";
import { useAppContext } from "@/providers/AuthProvider";
import apiClient from "@/services/api";
import { cn } from "@/utils/class-merge";
import { calculatePoints, getCurrentStatus } from "@/utils/status-system";
import { ArrowRightStartOnRectangleIcon, Cog8ToothIcon } from "@heroicons/react/24/outline";
@@ -38,6 +39,18 @@ const ProfileSettings: FunctionComponent = () => {
return () => window.removeEventListener("storage", handleStorage);
}, []);
const handleLogout = async () => {
try {
await apiClient("/api/logout/", { method: "POST", needsCsrf: true }, isLoggedIn);
isLoggedIn.value = false;
localStorage.removeItem("loggedIn");
localStorage.removeItem("user");
route("/login", true);
} catch (error) {
console.error("Logout failed:", error);
}
};
return (
<div class={classes.container}>
<div class="flex w-full flex-col items-center rounded-[4rem] bg-[linear-gradient(180.00deg,rgb(251,194,199),rgba(206,232,251,0.72)_100%)] px-7 py-5 shadow-[0px_4px_4px_0px_rgba(0,0,0,0.25)] md:flex-row">
@@ -64,11 +77,7 @@ const ProfileSettings: FunctionComponent = () => {
</Button>
<Button
className="flex flex-row items-center justify-center gap-2 bg-[linear-gradient(180.00deg,rgba(246,255,211,0.7),rgba(195,229,253,0.7)_100%)]"
onClick={() => {
isLoggedIn.value = false;
localStorage.setItem("loggedIn", "false");
route("/login", true);
}}
onClick={handleLogout}
>
<ArrowRightStartOnRectangleIcon class="size-8" /> Выйти
</Button>