init
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
import { Navigate } from "react-router";
|
||||
import { useMe } from "../hooks/useAuth";
|
||||
|
||||
interface ProtectedRouteProps {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Компонент для защиты роутов - перенаправляет неавторизованных пользователей на страницу логина
|
||||
*/
|
||||
function ProtectedRoute({ children }: ProtectedRouteProps) {
|
||||
const { data: user, isLoading } = useMe();
|
||||
|
||||
// Показываем загрузку пока проверяем авторизацию
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center">
|
||||
<div className="text-xl">Проверка авторизации...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Если пользователь не авторизован - перенаправляем на логин
|
||||
if (!user) {
|
||||
return <Navigate to="/login" replace />;
|
||||
}
|
||||
|
||||
// Если авторизован - показываем защищённый контент
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
export default ProtectedRoute;
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { Navigate } from "react-router";
|
||||
import { useMe } from "../hooks/useAuth";
|
||||
|
||||
interface PublicRouteProps {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Компонент для публичных роутов (логин/регистрация)
|
||||
* Если пользователь уже авторизован - перенаправляет на главную
|
||||
*/
|
||||
function PublicRoute({ children }: PublicRouteProps) {
|
||||
const { data: user, isLoading } = useMe();
|
||||
|
||||
// Показываем загрузку пока проверяем авторизацию
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center">
|
||||
<div className="text-xl">Загрузка...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Если пользователь уже авторизован - перенаправляем на главную
|
||||
if (user) {
|
||||
return <Navigate to="/" replace />;
|
||||
}
|
||||
|
||||
// Если не авторизован - показываем публичный контент (логин/регистрация)
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
export default PublicRoute;
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { api } from "../lib/api";
|
||||
import type {
|
||||
LoginData,
|
||||
RegisterData,
|
||||
LoginResponse,
|
||||
RegisterResponse,
|
||||
MeResponse,
|
||||
} from "../types/auth";
|
||||
|
||||
// Query keys
|
||||
export const authKeys = {
|
||||
me: ["auth", "me"] as const,
|
||||
};
|
||||
|
||||
/**
|
||||
* Хук для получения текущего пользователя
|
||||
*/
|
||||
export function useMe() {
|
||||
return useQuery({
|
||||
queryKey: authKeys.me,
|
||||
queryFn: async () => {
|
||||
const data = await api.get("auth/me").json<MeResponse>();
|
||||
return data.user;
|
||||
},
|
||||
enabled: !!localStorage.getItem("authToken"), // Запрос только если есть токен
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Хук для логина
|
||||
*/
|
||||
export function useLogin() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (data: LoginData) => {
|
||||
const response = await api
|
||||
.post("auth/login", { json: data })
|
||||
.json<LoginResponse>();
|
||||
return response;
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
// Сохраняем токен в localStorage
|
||||
localStorage.setItem("authToken", data.session.token);
|
||||
|
||||
// Обновляем кэш текущего пользователя
|
||||
queryClient.setQueryData(authKeys.me, data.user);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Хук для регистрации
|
||||
*/
|
||||
export function useRegister() {
|
||||
return useMutation({
|
||||
mutationFn: async (data: RegisterData) => {
|
||||
const response = await api
|
||||
.post("auth/register", { json: data })
|
||||
.json<RegisterResponse>();
|
||||
return response;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Хук для логаута
|
||||
*/
|
||||
export function useLogout() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async () => {
|
||||
await api.post("auth/logout").json();
|
||||
},
|
||||
onSuccess: () => {
|
||||
// Удаляем токен
|
||||
localStorage.removeItem("authToken");
|
||||
|
||||
// Очищаем кэш
|
||||
queryClient.clear();
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
@@ -0,0 +1,21 @@
|
||||
import ky from "ky";
|
||||
|
||||
// Базовый API клиент
|
||||
export const api = ky.create({
|
||||
prefixUrl: "http://localhost:3000",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
hooks: {
|
||||
beforeRequest: [
|
||||
(request) => {
|
||||
// Автоматически добавляем токен из localStorage если есть
|
||||
const token = localStorage.getItem("authToken");
|
||||
if (token) {
|
||||
request.headers.set("Authorization", `Bearer ${token}`);
|
||||
}
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
|
||||
export const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
retry: 1,
|
||||
staleTime: 5 * 60 * 1000, // 5 минут
|
||||
refetchOnWindowFocus: false,
|
||||
},
|
||||
mutations: {
|
||||
retry: 0,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { createRoot } from "react-dom/client";
|
||||
import "./index.css";
|
||||
import HomePage from "./pages/HomePage";
|
||||
import { createBrowserRouter, RouterProvider } from "react-router";
|
||||
import SessionPage from "./pages/SessionPage";
|
||||
import LoginPage from "./pages/LoginPage";
|
||||
import RegisterPage from "./pages/RegisterPage";
|
||||
import { QueryClientProvider } from "@tanstack/react-query";
|
||||
import { queryClient } from "./lib/queryClient";
|
||||
import ProtectedRoute from "./components/ProtectedRoute";
|
||||
import PublicRoute from "./components/PublicRoute";
|
||||
|
||||
const router = createBrowserRouter([
|
||||
{
|
||||
path: "/",
|
||||
element: (
|
||||
<ProtectedRoute>
|
||||
<HomePage />
|
||||
</ProtectedRoute>
|
||||
),
|
||||
},
|
||||
{
|
||||
path: "/login",
|
||||
element: (
|
||||
<PublicRoute>
|
||||
<LoginPage />
|
||||
</PublicRoute>
|
||||
),
|
||||
},
|
||||
{
|
||||
path: "/register",
|
||||
element: (
|
||||
<PublicRoute>
|
||||
<RegisterPage />
|
||||
</PublicRoute>
|
||||
),
|
||||
},
|
||||
{
|
||||
path: "/sessions/:id",
|
||||
element: (
|
||||
<ProtectedRoute>
|
||||
<SessionPage />
|
||||
</ProtectedRoute>
|
||||
),
|
||||
},
|
||||
]);
|
||||
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<RouterProvider router={router} />
|
||||
</QueryClientProvider>
|
||||
);
|
||||
@@ -0,0 +1,43 @@
|
||||
import { useMe, useLogout } from "../hooks/useAuth";
|
||||
import { useNavigate } from "react-router";
|
||||
|
||||
function HomePage() {
|
||||
const { data: user } = useMe();
|
||||
const logoutMutation = useLogout();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const handleLogout = async () => {
|
||||
await logoutMutation.mutateAsync();
|
||||
navigate("/login");
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 py-8">
|
||||
<div className="max-w-4xl mx-auto px-4">
|
||||
<div className="bg-white rounded-lg shadow-md p-8">
|
||||
<h1 className="text-3xl font-bold mb-6">Главная страница</h1>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
|
||||
<h2 className="text-xl font-semibold mb-2">
|
||||
Добро пожаловать, {user?.fullName}!
|
||||
</h2>
|
||||
<p className="text-gray-600">Email: {user?.email}</p>
|
||||
<p className="text-gray-600">Роль: {user?.role}</p>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
disabled={logoutMutation.isPending}
|
||||
className="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 disabled:opacity-50"
|
||||
>
|
||||
{logoutMutation.isPending ? "Выход..." : "Выйти"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default HomePage;
|
||||
@@ -0,0 +1,98 @@
|
||||
import { useState } from "react";
|
||||
import { useLogin } from "../hooks/useAuth";
|
||||
import { useNavigate, Link } from "react-router";
|
||||
|
||||
function LoginPage() {
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const navigate = useNavigate();
|
||||
|
||||
const loginMutation = useLogin();
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
try {
|
||||
await loginMutation.mutateAsync({ email, password });
|
||||
// Перенаправляем на главную после успешного логина
|
||||
navigate("/");
|
||||
} catch (error) {
|
||||
console.error("Login failed:", error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-50">
|
||||
<div className="max-w-md w-full space-y-8 p-8 bg-white rounded-lg shadow-md">
|
||||
<div>
|
||||
<h2 className="text-3xl font-bold text-center text-gray-900">
|
||||
Вход в аккаунт
|
||||
</h2>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="mt-8 space-y-6">
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label
|
||||
htmlFor="email"
|
||||
className="block text-sm font-medium text-gray-700"
|
||||
>
|
||||
Email
|
||||
</label>
|
||||
<input
|
||||
id="email"
|
||||
type="email"
|
||||
required
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
|
||||
placeholder="your@email.com"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label
|
||||
htmlFor="password"
|
||||
className="block text-sm font-medium text-gray-700"
|
||||
>
|
||||
Пароль
|
||||
</label>
|
||||
<input
|
||||
id="password"
|
||||
type="password"
|
||||
required
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
|
||||
placeholder="••••••••"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{loginMutation.isError && (
|
||||
<div className="text-red-600 text-sm text-center">
|
||||
Неверный email или пароль
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loginMutation.isPending}
|
||||
className="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{loginMutation.isPending ? "Вход..." : "Войти"}
|
||||
</button>
|
||||
|
||||
<div className="text-center text-sm text-gray-600">
|
||||
Нет аккаунта?{" "}
|
||||
<Link to="/register" className="text-blue-600 hover:text-blue-700 font-medium">
|
||||
Зарегистрироваться
|
||||
</Link>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default LoginPage;
|
||||
@@ -0,0 +1,112 @@
|
||||
import { useState } from "react";
|
||||
import { useRegister } from "../hooks/useAuth";
|
||||
import { useNavigate } from "react-router";
|
||||
|
||||
function RegisterPage() {
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [fullName, setFullName] = useState("");
|
||||
const navigate = useNavigate();
|
||||
|
||||
const registerMutation = useRegister();
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
try {
|
||||
await registerMutation.mutateAsync({ email, password, fullName });
|
||||
// Перенаправляем на страницу логина после успешной регистрации
|
||||
navigate("/login");
|
||||
} catch (error) {
|
||||
console.error("Registration failed:", error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-50">
|
||||
<div className="max-w-md w-full space-y-8 p-8 bg-white rounded-lg shadow-md">
|
||||
<div>
|
||||
<h2 className="text-3xl font-bold text-center text-gray-900">
|
||||
Регистрация
|
||||
</h2>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="mt-8 space-y-6">
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label
|
||||
htmlFor="fullName"
|
||||
className="block text-sm font-medium text-gray-700"
|
||||
>
|
||||
Полное имя
|
||||
</label>
|
||||
<input
|
||||
id="fullName"
|
||||
type="text"
|
||||
required
|
||||
value={fullName}
|
||||
onChange={(e) => setFullName(e.target.value)}
|
||||
className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
|
||||
placeholder="Иван Иванов"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label
|
||||
htmlFor="email"
|
||||
className="block text-sm font-medium text-gray-700"
|
||||
>
|
||||
Email
|
||||
</label>
|
||||
<input
|
||||
id="email"
|
||||
type="email"
|
||||
required
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
|
||||
placeholder="your@email.com"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label
|
||||
htmlFor="password"
|
||||
className="block text-sm font-medium text-gray-700"
|
||||
>
|
||||
Пароль
|
||||
</label>
|
||||
<input
|
||||
id="password"
|
||||
type="password"
|
||||
required
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
|
||||
placeholder="••••••••"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{registerMutation.isError && (
|
||||
<div className="text-red-600 text-sm text-center">
|
||||
Пользователь с таким email уже существует
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={registerMutation.isPending}
|
||||
className="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{registerMutation.isPending
|
||||
? "Регистрация..."
|
||||
: "Зарегистрироваться"}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default RegisterPage;
|
||||
@@ -0,0 +1,9 @@
|
||||
import { useParams } from "react-router";
|
||||
|
||||
function SessionPage() {
|
||||
const { id } = useParams();
|
||||
|
||||
return <div>SessionPage {id}</div>;
|
||||
}
|
||||
|
||||
export default SessionPage;
|
||||
@@ -0,0 +1,38 @@
|
||||
export type RoleName = "admin" | "director" | "manager";
|
||||
|
||||
export interface User {
|
||||
id: string;
|
||||
email: string;
|
||||
fullName: string;
|
||||
role: RoleName;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface LoginData {
|
||||
email: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface RegisterData {
|
||||
email: string;
|
||||
password: string;
|
||||
fullName: string;
|
||||
}
|
||||
|
||||
export interface LoginResponse {
|
||||
user: User;
|
||||
session: {
|
||||
id: string;
|
||||
token: string;
|
||||
expiresAt: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface RegisterResponse {
|
||||
user: User;
|
||||
}
|
||||
|
||||
export interface MeResponse {
|
||||
user: User;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user