diff --git a/src/API/hooks.ts b/src/API/hooks.ts index 482ee6a..426c91b 100644 --- a/src/API/hooks.ts +++ b/src/API/hooks.ts @@ -29,7 +29,7 @@ export function useDataPage(application:string, endpoint: string, params:{[ke }) } }, - [data, application, endpoint, needLoad] + [data, application, endpoint, needLoad, params] ) // function changePage(pageUrl: string|undefined) { @@ -92,7 +92,7 @@ export function useData(application:string, endpoint: string, id: string|numb } interface CachedData{ - get(id: string | number, needLoad: boolean): T|undefined|null + get(id: string | number, needLoad?: boolean): T|undefined|null } export function useCachedData(application: string, endpoint: string): CachedData { diff --git a/src/layouts/DashboardLayout.tsx b/src/layouts/DashboardLayout.tsx index fcf6037..fe3e288 100644 --- a/src/layouts/DashboardLayout.tsx +++ b/src/layouts/DashboardLayout.tsx @@ -1,29 +1,46 @@ -import {useUser} from "../utils/users/UseUser.ts"; -import {Outlet, useNavigate} from "react-router-dom"; -import React, {useEffect} from "react"; +import { useUser } from "../utils/users/UseUser.ts"; // Хук для получения информации о пользователе +import { Outlet, Link, useNavigate } from "react-router-dom"; // Композиция для маршрутизации +import React, { useEffect } from "react"; +import {UserContextType} from "../types/users.ts"; export function DashboardLayout() { - const { user } = useUser(); - const navigate = useNavigate(); + const { user, logout } = useUser() as UserContextType; // Получаем данные о пользователе + const navigate = useNavigate(); // Получаем функцию для навигации + // Проверяем, есть ли пользователь, если нет, редиректим на страницу логина useEffect(() => { if (!user) { - navigate("/login/") + navigate("/login/"); } }, [navigate, user]); - if (!user){ - return null; + if (!user) { + return null; // Если пользователь не найден, ничего не отображаем } + + // Определяем класс для активной ссылки + const isActive = (path: string) => window.location.pathname.includes(path)? 'selected' : 'unselected'; + return ( - <> -
+
+

Pro-Fi

+

{user.roleTitle || "Роль не опознана"}

{/* Отображаем текущую роль пользователя */} +
- +
); } \ No newline at end of file diff --git a/src/pages/LoginPage.tsx b/src/pages/LoginPage.tsx index 49b5228..19e7bcd 100644 --- a/src/pages/LoginPage.tsx +++ b/src/pages/LoginPage.tsx @@ -23,12 +23,18 @@ export function LoginPage() { const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (login && loginInput && password) { + let success = false; try { - await login({ login: loginInput, password }); + success = await login({ login: loginInput, password }); + setError(null); + if (!success){ + setError('Ошибка входа'); + } } catch { setError('Ошибка входа'); } + } }; diff --git a/src/types/users.ts b/src/types/users.ts index 4c8b327..e3d424b 100644 --- a/src/types/users.ts +++ b/src/types/users.ts @@ -2,7 +2,7 @@ import {UniqueItem} from "./common.ts"; export type UserContextType = { user: Account | undefined; - login: (credentials: TokenObtainPair) => Promise; + login: (credentials: TokenObtainPair) => Promise; logout: () => void; }; @@ -14,13 +14,11 @@ export interface ContactData{ email?:string; } -interface Role extends UniqueItem{ - title: string; -} export interface Account extends UniqueItem, ContactData{ login: string; - role?: Role; + role?: number; + roleTitle?: string; is_staff: boolean; is_active: boolean; diff --git a/src/utils/users/UserProvider.tsx b/src/utils/users/UserProvider.tsx index cf81d3f..df3cebe 100644 --- a/src/utils/users/UserProvider.tsx +++ b/src/utils/users/UserProvider.tsx @@ -31,7 +31,6 @@ export function UserProvider({ children }: { children: ReactNode }) { }, [tokens]); useEffect(() => { - console.log(user) if (user) { localStorage.setItem('user', JSON.stringify(user)); } else { @@ -48,21 +47,27 @@ export function UserProvider({ children }: { children: ReactNode }) { response = await getFetch(`/users/auth/users/${(response.body as Account).id}/`); - if (response.success){ - return response.body as Account + if (!response.success){ + return undefined; } - // if (response?.success && response.body) { - // return response.body as Account; // Возвращаем данные о пользователе - // } - return undefined; + const account = response.body as Account ; + + if (account.role){ + response = await getFetch(`/users/roles/${account.role}/`); + if (response.success){ + account.roleTitle = (response.body as {name:string}).name; + } + } + return account; }; const handleLogin = async (credentials: TokenObtainPair) => { const tokens = await apiLogin(credentials); if (tokens) { setTokens(tokens); - + return true; } + return false; }; const handleLogout = () => { @@ -70,25 +75,26 @@ export function UserProvider({ children }: { children: ReactNode }) { setTokens(undefined); }; - const validateToken = async () => { - if (tokens?.access) { - const isValid = await verifyToken({ token: tokens.access }); - if (!isValid && tokens.refresh) { - const newTokens = await refreshToken({ refresh: tokens.refresh }); - if (newTokens) { - setTokens(newTokens); - } else { - handleLogout(); - } - } else if (!isValid) { - handleLogout(); - } - } - }; + useEffect(() => { + async function validateToken() { + if (tokens?.access) { + const isValid = await verifyToken({ token: tokens.access }); + if (!isValid && tokens.refresh) { + const newTokens = await refreshToken({ refresh: tokens.refresh }); + if (newTokens) { + setTokens(newTokens); + } else { + handleLogout(); + } + } else if (!isValid) { + handleLogout(); + } + } + } validateToken().then(); - }, []); + }, [tokens]); return (