feat: api client and natural login and logoff
This commit is contained in:
@@ -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: " " });
|
||||
}
|
||||
};
|
||||
if (isLoggedIn.value) route("/profile/tasks", true);
|
||||
return !isLoggedIn.value ? (
|
||||
|
||||
@@ -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}>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -1,20 +1,75 @@
|
||||
import { stringToBoolean } from "@/utils/converter";
|
||||
import apiClient from "@/services/api";
|
||||
import { signal, Signal } from "@preact/signals";
|
||||
import { createContext, JSX } from "preact";
|
||||
import { useContext } from "preact/hooks";
|
||||
import { useContext, useEffect } from "preact/hooks";
|
||||
|
||||
interface UserData {
|
||||
id: number;
|
||||
username: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
interface AuthStatusResponse {
|
||||
isAuthenticated: boolean;
|
||||
user?: UserData;
|
||||
}
|
||||
|
||||
interface AppContextValue {
|
||||
isLoggedIn: Signal<boolean>;
|
||||
isCheckingAuth: Signal<boolean>;
|
||||
currentUser: Signal<UserData | null>;
|
||||
checkAuth: () => Promise<void>;
|
||||
}
|
||||
const ininitialValue = stringToBoolean(localStorage.getItem("loggedIn"));
|
||||
|
||||
const AppContext = createContext<AppContextValue>({
|
||||
isLoggedIn: signal(ininitialValue),
|
||||
});
|
||||
const initialLoggedIn = localStorage.getItem("loggedIn") === "true";
|
||||
|
||||
const AppContext = createContext<AppContextValue | null>(null);
|
||||
|
||||
const AppProvider = ({ children }: { children: JSX.Element }) => {
|
||||
const isLoggedIn = signal(initialLoggedIn);
|
||||
const isCheckingAuth = signal(true);
|
||||
const currentUser = signal<UserData | null>(null);
|
||||
|
||||
const checkAuth = async () => {
|
||||
console.log("Checking auth status...");
|
||||
isCheckingAuth.value = true;
|
||||
try {
|
||||
const response = await apiClient<AuthStatusResponse>("/api/auth/status/", {
|
||||
method: "GET",
|
||||
needsCsrf: false,
|
||||
});
|
||||
|
||||
if (response.isAuthenticated && response.user) {
|
||||
console.log("User is authenticated:", response.user.username);
|
||||
isLoggedIn.value = true;
|
||||
currentUser.value = response.user;
|
||||
localStorage.setItem("loggedIn", "true");
|
||||
} else {
|
||||
console.log("User is not authenticated.");
|
||||
isLoggedIn.value = false;
|
||||
currentUser.value = null;
|
||||
localStorage.removeItem("loggedIn");
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error("Auth check failed:", error.message);
|
||||
isLoggedIn.value = false;
|
||||
currentUser.value = null;
|
||||
localStorage.removeItem("loggedIn");
|
||||
} finally {
|
||||
isCheckingAuth.value = false;
|
||||
console.log("Auth check finished. isLoggedIn:", isLoggedIn.value);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
checkAuth();
|
||||
}, []);
|
||||
|
||||
const value: AppContextValue = {
|
||||
isLoggedIn: signal(ininitialValue),
|
||||
isLoggedIn,
|
||||
isCheckingAuth,
|
||||
currentUser,
|
||||
checkAuth,
|
||||
};
|
||||
|
||||
return <AppContext.Provider value={value}>{children}</AppContext.Provider>;
|
||||
@@ -29,3 +84,4 @@ const useAppContext = () => {
|
||||
};
|
||||
|
||||
export { AppProvider, useAppContext };
|
||||
export type { UserData };
|
||||
|
||||
99
src/services/api.ts
Normal file
99
src/services/api.ts
Normal file
@@ -0,0 +1,99 @@
|
||||
import { Signal } from "@preact/signals";
|
||||
|
||||
function getCookie(name: string): string | null {
|
||||
let cookieValue = null;
|
||||
if (document.cookie && document.cookie !== "") {
|
||||
const cookies = document.cookie.split(";");
|
||||
for (let i = 0; i < cookies.length; i++) {
|
||||
const cookie = cookies[i].trim();
|
||||
if (cookie.substring(0, name.length + 1) === name + "=") {
|
||||
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return cookieValue;
|
||||
}
|
||||
|
||||
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || "http://localhost:8000";
|
||||
|
||||
interface RequestOptions extends RequestInit {
|
||||
needsCsrf?: boolean;
|
||||
isFormData?: boolean;
|
||||
}
|
||||
|
||||
async function apiClient<T>(
|
||||
endpoint: string,
|
||||
options: RequestOptions = {},
|
||||
isLoggedInSignal?: Signal<boolean>
|
||||
): Promise<T> {
|
||||
const url = `${API_BASE_URL}${endpoint}`;
|
||||
const { needsCsrf = true, isFormData = false, ...fetchOptions } = options;
|
||||
|
||||
const headers: HeadersInit = {
|
||||
...(isFormData ? {} : { "Content-Type": "application/json" }),
|
||||
Accept: "application/json",
|
||||
...fetchOptions.headers,
|
||||
};
|
||||
|
||||
const method = options.method?.toUpperCase() || "GET";
|
||||
if (needsCsrf && ["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
|
||||
const csrfToken = getCookie("csrftoken");
|
||||
if (csrfToken) {
|
||||
(headers as Record<string, string>)["X-CSRFToken"] = csrfToken;
|
||||
} else {
|
||||
console.warn("CSRF token not found in cookies.");
|
||||
await fetchCsrfToken(); // Implement this function if needed
|
||||
const newCsrfToken = getCookie("csrftoken");
|
||||
if (newCsrfToken) {
|
||||
(headers as Record<string, string>)["X-CSRFToken"] = newCsrfToken;
|
||||
} else {
|
||||
throw new Error("CSRF token is missing");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const config: RequestInit = {
|
||||
...fetchOptions,
|
||||
headers,
|
||||
credentials: "include",
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await fetch(url, config);
|
||||
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
console.error("Authentication error:", response.status);
|
||||
if (isLoggedInSignal) {
|
||||
isLoggedInSignal.value = false;
|
||||
localStorage.setItem("loggedIn", "false");
|
||||
}
|
||||
throw new Error(`Authentication failed: ${response.status}`);
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
console.error("API Error:", response.status, errorData);
|
||||
throw new Error(`HTTP error ${response.status}: ${JSON.stringify(errorData) || response.statusText}`);
|
||||
}
|
||||
|
||||
if (response.status === 204) {
|
||||
return {} as T;
|
||||
}
|
||||
|
||||
return (await response.json()) as T;
|
||||
} catch (error) {
|
||||
console.error("API Client Fetch Error:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchCsrfToken() {
|
||||
try {
|
||||
await apiClient("/api/get-csrf/", { method: "GET", needsCsrf: false });
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch CSRF token:", error);
|
||||
}
|
||||
}
|
||||
|
||||
export default apiClient;
|
||||
Reference in New Issue
Block a user