Загрузить файлы в «sk1/src»
This commit is contained in:
parent
cebe24bc42
commit
2758088ce5
99
sk1/src/server.js
Normal file
99
sk1/src/server.js
Normal file
@ -0,0 +1,99 @@
|
|||||||
|
// server.js - Express сервер для Brabus сайта
|
||||||
|
const express = require('express');
|
||||||
|
const mongoose = require('mongoose');
|
||||||
|
const jwt = require('jsonwebtoken');
|
||||||
|
const cors = require('cors');
|
||||||
|
const bodyParser = require('body-parser');
|
||||||
|
const path = require('path');
|
||||||
|
require('dotenv').config();
|
||||||
|
|
||||||
|
// Импорт модели пользователя
|
||||||
|
const User = require('./models/User');
|
||||||
|
|
||||||
|
// Инициализация Express приложения
|
||||||
|
const app = express();
|
||||||
|
const PORT = process.env.PORT || 3000;
|
||||||
|
|
||||||
|
// Middleware
|
||||||
|
app.use(cors());
|
||||||
|
app.use(bodyParser.json());
|
||||||
|
app.use(express.static(path.join(__dirname, 'public')));
|
||||||
|
|
||||||
|
// Подключение к MongoDB
|
||||||
|
mongoose.connect(process.env.MONGODB_URI, {
|
||||||
|
useNewUrlParser: true,
|
||||||
|
useUnifiedTopology: true
|
||||||
|
})
|
||||||
|
.then(() => console.log('Connected to MongoDB'))
|
||||||
|
.catch(err => console.error('MongoDB connection error:', err));
|
||||||
|
|
||||||
|
// Middleware для проверки токена
|
||||||
|
const authenticateToken = (req, res, next) => {
|
||||||
|
const authHeader = req.headers['authorization'];
|
||||||
|
const token = authHeader && authHeader.split(' ')[1];
|
||||||
|
|
||||||
|
if (!token) return res.status(401).json({ message: 'Access denied. No token provided.' });
|
||||||
|
|
||||||
|
jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
|
||||||
|
if (err) return res.status(403).json({ message: 'Invalid token' });
|
||||||
|
req.user = user;
|
||||||
|
next();
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// Маршруты API
|
||||||
|
// Регистрация
|
||||||
|
app.post('/api/register', async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { firstName, lastName, email, password } = req.body;
|
||||||
|
|
||||||
|
// Проверка на существование пользователя
|
||||||
|
const existingUser = await User.findOne({ email });
|
||||||
|
if (existingUser) {
|
||||||
|
return res.status(400).json({ message: 'User with this email already exists' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Создание нового пользователя
|
||||||
|
const user = new User({
|
||||||
|
firstName,
|
||||||
|
lastName,
|
||||||
|
email,
|
||||||
|
password
|
||||||
|
});
|
||||||
|
|
||||||
|
await user.save();
|
||||||
|
|
||||||
|
// Генерация JWT токена
|
||||||
|
const token = jwt.sign(
|
||||||
|
{ id: user._id, email: user.email },
|
||||||
|
process.env.JWT_SECRET,
|
||||||
|
{ expiresIn: '24h' }
|
||||||
|
);
|
||||||
|
|
||||||
|
res.status(201).json({
|
||||||
|
message: 'User registered successfully',
|
||||||
|
token,
|
||||||
|
user: {
|
||||||
|
id: user._id,
|
||||||
|
firstName: user.firstName,
|
||||||
|
lastName: user.lastName,
|
||||||
|
email: user.email
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Registration error:', error);
|
||||||
|
res.status(500).json({ message: 'Server error during registration' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Вход
|
||||||
|
app.post('/api/login', async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { email, password } = req.body;
|
||||||
|
|
||||||
|
// Поиск пользователя
|
||||||
|
const user = await User.findOne({ email });
|
||||||
|
if (!user) {
|
||||||
|
return res.status(400).json({ message: 'Invalid email or password' });
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in New Issue
Block a user