Всё переделано, разделено на 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
|
||||
.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",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"main": "dist/index.js",
|
||||
"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": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"type": "commonjs",
|
||||
"dependencies": {
|
||||
"-": "^0.0.1",
|
||||
"@prisma/client": "^6.16.1",
|
||||
"@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",
|
||||
"@prisma/client": "^5.14.0",
|
||||
"bcryptjs": "^2.4.3",
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^17.2.2",
|
||||
"express": "^5.1.0",
|
||||
"dotenv": "^16.4.5",
|
||||
"express": "^4.19.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",
|
||||
"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": {
|
||||
// File Layout
|
||||
// "rootDir": "./src",
|
||||
// "outDir": "./dist",
|
||||
|
||||
// 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",
|
||||
"target": "ES2020",
|
||||
"module": "Node16",
|
||||
"lib": ["ES2020"],
|
||||
"skipLibCheck": true,
|
||||
}
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"strict": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"moduleResolution": "node16",
|
||||
"resolveJsonModule": true,
|
||||
"noEmit": true,
|
||||
"verbatimModuleSyntax": false
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user