Всё переделано, разделено на backend и frontend
This commit is contained in:
24
ospabhost/backend/.gitignore
vendored
24
ospabhost/backend/.gitignore
vendored
@@ -1,5 +1,25 @@
|
|||||||
node_modules
|
node_modules/
|
||||||
# Keep environment variables out of version control
|
# Keep environment variables out of version control
|
||||||
.env
|
.env
|
||||||
|
.env.*
|
||||||
|
|
||||||
/src/generated/prisma
|
dist/
|
||||||
|
build/
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
|
||||||
|
# TypeScript
|
||||||
|
*.tsbuildinfo
|
||||||
|
|
||||||
|
# Prisma
|
||||||
|
prisma/.env
|
||||||
|
prisma/migrations/*/README.md
|
||||||
|
|
||||||
|
# VSCode
|
||||||
|
.vscode/
|
||||||
|
|
||||||
|
# OS
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
|||||||
1034
ospabhost/backend/package-lock.json
generated
1034
ospabhost/backend/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -2,29 +2,31 @@
|
|||||||
"name": "backend",
|
"name": "backend",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"description": "",
|
"description": "",
|
||||||
"main": "index.js",
|
"main": "dist/index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "echo \"Error: no test specified\" && exit 1"
|
"dev": "ts-node-dev --respawn --transpile-only src/index.ts",
|
||||||
|
"start": "node dist/index.js",
|
||||||
|
"build": "tsc"
|
||||||
},
|
},
|
||||||
"keywords": [],
|
"keywords": [],
|
||||||
"author": "",
|
"author": "",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"type": "commonjs",
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"-": "^0.0.1",
|
"@prisma/client": "^5.14.0",
|
||||||
"@prisma/client": "^6.16.1",
|
"bcryptjs": "^2.4.3",
|
||||||
"@types/bcrypt": "^6.0.0",
|
|
||||||
"@types/cors": "^2.8.19",
|
|
||||||
"@types/express": "^5.0.3",
|
|
||||||
"@types/jsonwebtoken": "^9.0.10",
|
|
||||||
"@types/node": "^24.4.0",
|
|
||||||
"bcrypt": "^6.0.0",
|
|
||||||
"cors": "^2.8.5",
|
"cors": "^2.8.5",
|
||||||
"dotenv": "^17.2.2",
|
"dotenv": "^16.4.5",
|
||||||
"express": "^5.1.0",
|
"express": "^4.19.2",
|
||||||
"jsonwebtoken": "^9.0.2",
|
"jsonwebtoken": "^9.0.2",
|
||||||
"prisma": "^6.16.1",
|
"prisma": "^5.14.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/bcryptjs": "^2.4.6",
|
||||||
|
"@types/cors": "^2.8.17",
|
||||||
|
"@types/express": "^4.17.21",
|
||||||
|
"@types/jsonwebtoken": "^9.0.6",
|
||||||
|
"@types/node": "^20.12.12",
|
||||||
"ts-node-dev": "^2.0.0",
|
"ts-node-dev": "^2.0.0",
|
||||||
"typescript": "^5.9.2"
|
"typescript": "^5.4.5"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
27
ospabhost/backend/prisma/schema.prisma
Normal file
27
ospabhost/backend/prisma/schema.prisma
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
// This is your Prisma schema file,
|
||||||
|
// learn more about it in the docs: https://pris.ly/d/prisma-schema
|
||||||
|
|
||||||
|
generator client {
|
||||||
|
provider = "prisma-client-js"
|
||||||
|
}
|
||||||
|
|
||||||
|
datasource db {
|
||||||
|
provider = "mysql"
|
||||||
|
url = env("DATABASE_URL")
|
||||||
|
}
|
||||||
|
|
||||||
|
model User {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
username String
|
||||||
|
email String @unique
|
||||||
|
password String
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Пока что у тебя нет других моделей, но ты можешь
|
||||||
|
// добавить их сюда позже, например:
|
||||||
|
// model Plan {
|
||||||
|
// id Int @id @default(autoincrement())
|
||||||
|
// name String @unique
|
||||||
|
// price Float
|
||||||
|
// }
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import express from 'express';
|
||||||
|
import cors from 'cors';
|
||||||
|
import dotenv from 'dotenv';
|
||||||
|
import authRoutes from './modules/auth/auth.routes';
|
||||||
|
|
||||||
|
// Загружаем переменные окружения из .env файла
|
||||||
|
dotenv.config();
|
||||||
|
|
||||||
|
// Инициализируем приложение Express
|
||||||
|
const app = express();
|
||||||
|
|
||||||
|
// Middleware для CORS
|
||||||
|
// Это позволяет фронтенду (на другом порту) отправлять запросы на бэкенд
|
||||||
|
app.use(cors());
|
||||||
|
|
||||||
|
// Middleware для парсинга JSON
|
||||||
|
// Это позволяет Express читать данные, которые приходят в теле запроса в формате JSON
|
||||||
|
app.use(express.json());
|
||||||
|
|
||||||
|
// Основной маршрут для проверки работы сервера
|
||||||
|
app.get('/', (req, res) => {
|
||||||
|
res.send('Сервер ospab.host запущен!');
|
||||||
|
});
|
||||||
|
|
||||||
|
// Подключаем наши маршруты для аутентификации
|
||||||
|
// Все маршруты в authRoutes будут доступны по адресу /api/auth/...
|
||||||
|
app.use('/api/auth', authRoutes);
|
||||||
|
|
||||||
|
// Получаем порт из переменных окружения или используем 5000 по умолчанию
|
||||||
|
const PORT = process.env.PORT || 5000;
|
||||||
|
|
||||||
|
// Запускаем сервер
|
||||||
|
app.listen(PORT, () => {
|
||||||
|
console.log(`Сервер работает на порту ${PORT}`);
|
||||||
|
});
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
import type { Request, Response } from 'express';
|
||||||
|
import bcrypt from 'bcryptjs';
|
||||||
|
import jwt from 'jsonwebtoken';
|
||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
|
||||||
|
const prisma = new PrismaClient();
|
||||||
|
|
||||||
|
// Замените 'любая_секретная_строка' на вашу переменную окружения JWT_SECRET
|
||||||
|
const JWT_SECRET = process.env.JWT_SECRET || 'любая_секретная_строка';
|
||||||
|
|
||||||
|
export const register = async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const { name, email, password } = req.body;
|
||||||
|
|
||||||
|
// Проверка, есть ли уже пользователь с таким email
|
||||||
|
const existingUser = await prisma.user.findUnique({ where: { email } });
|
||||||
|
if (existingUser) {
|
||||||
|
return res.status(409).json({ message: 'Пользователь с таким email уже существует.' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Хеширование пароля
|
||||||
|
const salt = await bcrypt.genSalt(10);
|
||||||
|
const hashedPassword = await bcrypt.hash(password, salt);
|
||||||
|
|
||||||
|
// Создание нового пользователя в базе данных
|
||||||
|
const newUser = await prisma.user.create({
|
||||||
|
data: {
|
||||||
|
name,
|
||||||
|
email,
|
||||||
|
password: hashedPassword,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Генерация JWT токена
|
||||||
|
const token = jwt.sign({ id: newUser.id }, JWT_SECRET, { expiresIn: '1h' });
|
||||||
|
|
||||||
|
res.status(201).json({
|
||||||
|
message: 'Регистрация прошла успешно!',
|
||||||
|
token,
|
||||||
|
user: {
|
||||||
|
id: newUser.id,
|
||||||
|
name: newUser.name,
|
||||||
|
email: newUser.email,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Ошибка при регистрации:', error);
|
||||||
|
res.status(500).json({ message: 'Внутренняя ошибка сервера' });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const login = async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const { email, password } = req.body;
|
||||||
|
|
||||||
|
// Поиск пользователя по email
|
||||||
|
const user = await prisma.user.findUnique({ where: { email } });
|
||||||
|
if (!user) {
|
||||||
|
return res.status(401).json({ message: 'Неверный email или пароль' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Проверка пароля
|
||||||
|
const isMatch = await bcrypt.compare(password, user.password);
|
||||||
|
if (!isMatch) {
|
||||||
|
return res.status(401).json({ message: 'Неверный email или пароль' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Генерация JWT токена
|
||||||
|
const token = jwt.sign({ id: user.id }, JWT_SECRET, { expiresIn: '1h' });
|
||||||
|
|
||||||
|
res.status(200).json({
|
||||||
|
message: 'Вход выполнен успешно!',
|
||||||
|
token,
|
||||||
|
user: {
|
||||||
|
id: user.id,
|
||||||
|
name: user.name,
|
||||||
|
email: user.email,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Ошибка при входе:', error);
|
||||||
|
res.status(500).json({ message: 'Внутренняя ошибка сервера' });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getMe = async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
// ID пользователя будет добавлен в req.user.id мидлваром
|
||||||
|
const userId = (req as any).userId;
|
||||||
|
|
||||||
|
// Получение пользователя из базы данных, исключая пароль
|
||||||
|
const user = await prisma.user.findUnique({
|
||||||
|
where: { id: userId },
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
email: true,
|
||||||
|
createdAt: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return res.status(404).json({ message: 'Пользователь не найден' });
|
||||||
|
}
|
||||||
|
|
||||||
|
res.status(200).json({ user });
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Ошибка при получении данных пользователя:', error);
|
||||||
|
res.status(500).json({ message: 'Внутренняя ошибка сервера' });
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import { Request, Response, NextFunction } from 'express';
|
||||||
|
import jwt from 'jsonwebtoken';
|
||||||
|
|
||||||
|
// Расширяем интерфейс Request, чтобы добавить поле userId
|
||||||
|
interface CustomRequest extends Request {
|
||||||
|
userId?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Замените 'любая_секретная_строка' на вашу переменную окружения JWT_SECRET
|
||||||
|
const JWT_SECRET = process.env.JWT_SECRET || 'любая_секретная_строка';
|
||||||
|
|
||||||
|
export const authMiddleware = (req: CustomRequest, res: Response, next: NextFunction) => {
|
||||||
|
try {
|
||||||
|
// Получаем токен из заголовка Authorization
|
||||||
|
const authHeader = req.headers.authorization;
|
||||||
|
if (!authHeader) {
|
||||||
|
return res.status(401).json({ message: 'Нет токена авторизации' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Токен имеет формат 'Bearer <токен>', поэтому мы его разделяем
|
||||||
|
const token = authHeader.split(' ')[1];
|
||||||
|
if (!token) {
|
||||||
|
return res.status(401).json({ message: 'Неправильный формат токена' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Проверяем валидность токена
|
||||||
|
const decoded = jwt.verify(token, JWT_SECRET) as { id: number };
|
||||||
|
|
||||||
|
// Сохраняем ID пользователя в объекте запроса
|
||||||
|
req.userId = decoded.id;
|
||||||
|
|
||||||
|
// Передаем управление следующему мидлвару или контроллеру
|
||||||
|
next();
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Ошибка в мидлваре аутентификации:', error);
|
||||||
|
if (error instanceof jwt.JsonWebTokenError) {
|
||||||
|
return res.status(401).json({ message: 'Неверный или просроченный токен' });
|
||||||
|
}
|
||||||
|
res.status(500).json({ message: 'Внутренняя ошибка сервера' });
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { Router } from 'express';
|
||||||
|
import { register, login, getMe } from './auth.controller';
|
||||||
|
import { authMiddleware } from './auth.middleware';
|
||||||
|
|
||||||
|
const router = Router();
|
||||||
|
|
||||||
|
// Маршрут для регистрации нового пользователя
|
||||||
|
router.post('/register', register);
|
||||||
|
|
||||||
|
// Маршрут для входа
|
||||||
|
router.post('/login', login);
|
||||||
|
|
||||||
|
// Маршрут для получения данных о текущем пользователе
|
||||||
|
// Он защищен мидлваром authMiddleware
|
||||||
|
router.get('/me', authMiddleware, getMe);
|
||||||
|
|
||||||
|
export default router;
|
||||||
@@ -1,44 +1,20 @@
|
|||||||
{
|
{
|
||||||
// Visit https://aka.ms/tsconfig to read more about this file
|
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
// File Layout
|
"target": "ES2020",
|
||||||
// "rootDir": "./src",
|
"module": "Node16",
|
||||||
// "outDir": "./dist",
|
"lib": ["ES2020"],
|
||||||
|
|
||||||
// Environment Settings
|
|
||||||
// See also https://aka.ms/tsconfig/module
|
|
||||||
"module": "nodenext",
|
|
||||||
"target": "esnext",
|
|
||||||
"types": [],
|
|
||||||
// For nodejs:
|
|
||||||
// "lib": ["esnext"],
|
|
||||||
// "types": ["node"],
|
|
||||||
// and npm install -D @types/node
|
|
||||||
|
|
||||||
// Other Outputs
|
|
||||||
"sourceMap": true,
|
|
||||||
"declaration": true,
|
|
||||||
"declarationMap": true,
|
|
||||||
|
|
||||||
// Stricter Typechecking Options
|
|
||||||
"noUncheckedIndexedAccess": true,
|
|
||||||
"exactOptionalPropertyTypes": true,
|
|
||||||
|
|
||||||
// Style Options
|
|
||||||
// "noImplicitReturns": true,
|
|
||||||
// "noImplicitOverride": true,
|
|
||||||
// "noUnusedLocals": true,
|
|
||||||
// "noUnusedParameters": true,
|
|
||||||
// "noFallthroughCasesInSwitch": true,
|
|
||||||
// "noPropertyAccessFromIndexSignature": true,
|
|
||||||
|
|
||||||
// Recommended Options
|
|
||||||
"strict": true,
|
|
||||||
"jsx": "react-jsx",
|
|
||||||
"verbatimModuleSyntax": true,
|
|
||||||
"isolatedModules": true,
|
|
||||||
"noUncheckedSideEffectImports": true,
|
|
||||||
"moduleDetection": "force",
|
|
||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"allowSyntheticDefaultImports": true,
|
||||||
|
"strict": true,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"moduleResolution": "node16",
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"noEmit": true,
|
||||||
|
"verbatimModuleSyntax": false
|
||||||
|
},
|
||||||
|
"include": ["src/**/*.ts"],
|
||||||
|
"exclude": ["node_modules"]
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
|
|||||||
3444
ospabhost/frontend/package-lock.json
generated
Normal file
3444
ospabhost/frontend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
@@ -11,7 +11,8 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"react": "^19.1.1",
|
"react": "^19.1.1",
|
||||||
"react-dom": "^19.1.1"
|
"react-dom": "^19.1.1",
|
||||||
|
"react-router-dom": "^7.9.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^9.33.0",
|
"@eslint/js": "^9.33.0",
|
||||||
|
|||||||
@@ -1,35 +1,32 @@
|
|||||||
import { useState } from 'react'
|
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
|
||||||
import reactLogo from './assets/react.svg'
|
import HomePage from './pages/index';
|
||||||
import viteLogo from '/vite.svg'
|
import LoginPage from './pages/login';
|
||||||
import './App.css'
|
import RegisterPage from './pages/register';
|
||||||
|
import DashboardPage from './pages/dashboard/index';
|
||||||
function App() {
|
|
||||||
const [count, setCount] = useState(0)
|
|
||||||
|
|
||||||
|
const App = () => {
|
||||||
return (
|
return (
|
||||||
<>
|
<Router>
|
||||||
|
<header className="bg-gray-800 text-white p-4">
|
||||||
|
<nav className="container mx-auto flex justify-between items-center">
|
||||||
|
<Link to="/" className="text-2xl font-bold">ospab.host</Link>
|
||||||
<div>
|
<div>
|
||||||
<a href="https://vite.dev" target="_blank">
|
<Link to="/login" className="px-4 py-2 hover:bg-gray-700 rounded-md">Вход</Link>
|
||||||
<img src={viteLogo} className="logo" alt="Vite logo" />
|
<Link to="/register" className="px-4 py-2 ml-2 hover:bg-gray-700 rounded-md">Регистрация</Link>
|
||||||
</a>
|
<Link to="/dashboard" className="px-4 py-2 ml-2 hover:bg-gray-700 rounded-md">Дашборд</Link>
|
||||||
<a href="https://react.dev" target="_blank">
|
|
||||||
<img src={reactLogo} className="logo react" alt="React logo" />
|
|
||||||
</a>
|
|
||||||
</div>
|
</div>
|
||||||
<h1>Vite + React</h1>
|
</nav>
|
||||||
<div className="card">
|
</header>
|
||||||
<button onClick={() => setCount((count) => count + 1)}>
|
<main className="p-4">
|
||||||
count is {count}
|
<Routes>
|
||||||
</button>
|
<Route path="/" element={<HomePage />} />
|
||||||
<p>
|
<Route path="/login" element={<LoginPage />} />
|
||||||
Edit <code>src/App.tsx</code> and save to test HMR
|
<Route path="/register" element={<RegisterPage />} />
|
||||||
</p>
|
<Route path="/dashboard" element={<DashboardPage />} />
|
||||||
</div>
|
</Routes>
|
||||||
<p className="read-the-docs">
|
</main>
|
||||||
Click on the Vite and React logos to learn more
|
</Router>
|
||||||
</p>
|
);
|
||||||
</>
|
};
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
export default App
|
export default App;
|
||||||
3
ospabhost/frontend/src/pages/dashboard/index.tsx
Normal file
3
ospabhost/frontend/src/pages/dashboard/index.tsx
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
const DashboardPage = () => <div>Дашборд (заглушка)</div>;
|
||||||
|
|
||||||
|
export default DashboardPage;
|
||||||
10
ospabhost/frontend/src/pages/index.tsx
Normal file
10
ospabhost/frontend/src/pages/index.tsx
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
const HomePage = () => {
|
||||||
|
return (
|
||||||
|
<div className="text-center mt-20">
|
||||||
|
<h1 className="text-4xl font-bold">Добро пожаловать на ospab.host!</h1>
|
||||||
|
<p className="text-lg mt-4">Мы работаем над нашим сайтом.</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default HomePage;
|
||||||
77
ospabhost/frontend/src/pages/login.tsx
Normal file
77
ospabhost/frontend/src/pages/login.tsx
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { useNavigate } from 'react-router-dom';
|
||||||
|
|
||||||
|
const LoginPage = () => {
|
||||||
|
const [email, setEmail] = useState('');
|
||||||
|
const [password, setPassword] = useState('');
|
||||||
|
const [message, setMessage] = useState('');
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
const handleLogin = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setMessage('');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch('http://localhost:5000/api/auth/login', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ email, password }),
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
setMessage(data.message);
|
||||||
|
localStorage.setItem('token', data.token);
|
||||||
|
navigate('/dashboard'); // Перенаправляем на дашборд после успешного входа
|
||||||
|
} else {
|
||||||
|
setMessage(data.message || 'Ошибка входа. Проверьте email и пароль.');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Ошибка:', error);
|
||||||
|
setMessage('Не удалось подключиться к серверу.');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col items-center justify-center min-h-screen bg-gray-100">
|
||||||
|
<h1 className="text-3xl font-bold mb-4">Вход</h1>
|
||||||
|
<form onSubmit={handleLogin} className="bg-white p-8 rounded-lg shadow-md w-96">
|
||||||
|
<div className="mb-4">
|
||||||
|
<label className="block text-gray-700">Email</label>
|
||||||
|
<input
|
||||||
|
type="email"
|
||||||
|
className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||||
|
value={email}
|
||||||
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="mb-6">
|
||||||
|
<label className="block text-gray-700">Пароль</label>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
className="w-full bg-blue-500 text-white py-2 rounded-md hover:bg-blue-600 transition-colors"
|
||||||
|
>
|
||||||
|
Войти
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
{message && <p className="mt-4 text-center text-red-500">{message}</p>}
|
||||||
|
<p className="mt-4">
|
||||||
|
Нет аккаунта? <a href="/register" className="text-blue-500 hover:underline">Зарегистрироваться</a>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default LoginPage;
|
||||||
88
ospabhost/frontend/src/pages/register.tsx
Normal file
88
ospabhost/frontend/src/pages/register.tsx
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { useNavigate } from 'react-router-dom';
|
||||||
|
|
||||||
|
const RegisterPage = () => {
|
||||||
|
const [username, setUsername] = useState('');
|
||||||
|
const [email, setEmail] = useState('');
|
||||||
|
const [password, setPassword] = useState('');
|
||||||
|
const [message, setMessage] = useState('');
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
const handleRegister = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setMessage('');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch('http://localhost:5000/api/auth/register', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ username, email, password }),
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
setMessage(data.message);
|
||||||
|
localStorage.setItem('token', data.token);
|
||||||
|
navigate('/dashboard'); // Перенаправляем на дашборд после успешной регистрации
|
||||||
|
} else {
|
||||||
|
setMessage(data.message || 'Ошибка регистрации.');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Ошибка:', error);
|
||||||
|
setMessage('Не удалось подключиться к серверу.');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col items-center justify-center min-h-screen bg-gray-100">
|
||||||
|
<h1 className="text-3xl font-bold mb-4">Регистрация</h1>
|
||||||
|
<form onSubmit={handleRegister} className="bg-white p-8 rounded-lg shadow-md w-96">
|
||||||
|
<div className="mb-4">
|
||||||
|
<label className="block text-gray-700">Имя пользователя</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||||
|
value={username}
|
||||||
|
onChange={(e) => setUsername(e.target.value)}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="mb-4">
|
||||||
|
<label className="block text-gray-700">Email</label>
|
||||||
|
<input
|
||||||
|
type="email"
|
||||||
|
className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||||
|
value={email}
|
||||||
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="mb-6">
|
||||||
|
<label className="block text-gray-700">Пароль</label>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
className="w-full bg-blue-500 text-white py-2 rounded-md hover:bg-blue-600 transition-colors"
|
||||||
|
>
|
||||||
|
Зарегистрироваться
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
{message && <p className="mt-4 text-center text-red-500">{message}</p>}
|
||||||
|
<p className="mt-4">
|
||||||
|
Уже есть аккаунт? <a href="/login" className="text-blue-500 hover:underline">Войти</a>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default RegisterPage;
|
||||||
Reference in New Issue
Block a user