renamed: spa/vue/servers/authserver.js -> node_servers/authserver.js
renamed: spa/vue/servers/feedbackserver.js -> node_servers/feedbackserver.js renamed: spa/vue/servers/techsupportserver.js -> node_servers/techsupportserver.js add and set to one more Docker coneiner for node servers
This commit is contained in:
@@ -0,0 +1,106 @@
|
||||
const express = require('express');
|
||||
const { Pool } = require('pg');
|
||||
const bcrypt = require('bcryptjs');
|
||||
const jwt = require('jsonwebtoken');
|
||||
const bodyParser = require('body-parser');
|
||||
const cors = require('cors');
|
||||
|
||||
const app = express();
|
||||
const PORT = 6000;
|
||||
const SECRET_KEY = '89044513447896254393432085332044367'; // Замените на свой секретный ключ
|
||||
|
||||
// Middleware
|
||||
app.use(bodyParser.json());
|
||||
app.use(cors());
|
||||
|
||||
// Подключение к PostgreSQL
|
||||
const pool = new Pool({
|
||||
user: 'postgres',
|
||||
host: 'db',
|
||||
database: 'postgres',
|
||||
password: 'postgres',
|
||||
port: 5432,
|
||||
});
|
||||
|
||||
|
||||
// Регистрация
|
||||
app.post('/register', async (req, res) => {
|
||||
try {
|
||||
const { username, email, password } = req.body;
|
||||
|
||||
// Проверка, существует ли пользователь с таким email
|
||||
const userExists = await pool.query('SELECT * FROM users WHERE email = $1', [email]);
|
||||
if (userExists.rows.length > 0) {
|
||||
return res.status(400).json({ message: 'User with this email already exists' });
|
||||
}
|
||||
|
||||
// Хеширование пароля
|
||||
const hashedPassword = await bcrypt.hash(password, 10);
|
||||
|
||||
// Создание нового пользователя
|
||||
const newUser = await pool.query(
|
||||
'INSERT INTO users (username, email, password) VALUES ($1, $2, $3) RETURNING *',
|
||||
[username, email, hashedPassword]
|
||||
);
|
||||
|
||||
res.status(201).json({ message: 'User registered successfully', email: newUser.rows[0].email });
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
res.status(500).json({ message: 'Something went wrong' });
|
||||
}
|
||||
});
|
||||
|
||||
// Авторизация
|
||||
app.post('/login', async (req, res) => {
|
||||
try {
|
||||
const { email, password } = req.body;
|
||||
|
||||
// Поиск пользователя по email
|
||||
const user = await pool.query('SELECT * FROM users WHERE email = $1', [email]);
|
||||
if (user.rows.length === 0) {
|
||||
return res.status(400).json({ message: 'User not found' });
|
||||
}
|
||||
|
||||
// Проверка пароля
|
||||
const isPasswordValid = await bcrypt.compare(password, user.rows[0].password);
|
||||
if (!isPasswordValid) {
|
||||
return res.status(400).json({ message: 'Invalid credentials' });
|
||||
}
|
||||
|
||||
// Создание JWT токена
|
||||
const token = jwt.sign({ userId: user.rows[0].id }, SECRET_KEY, { expiresIn: '1h' });
|
||||
|
||||
res.status(200).json({ token });
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
res.status(500).json({ message: 'Something went wrong' });
|
||||
}
|
||||
});
|
||||
|
||||
// Эндпоинт для проверки токенов
|
||||
app.get('/check', async (req, res) => {
|
||||
try {
|
||||
// Извлекаем токен из заголовка Authorization
|
||||
const authorizationHeader = req.headers.authorization;
|
||||
if (!authorizationHeader) {
|
||||
return res.status(401).send({ message: 'No token provided' });
|
||||
}
|
||||
|
||||
// Разделяем строку на части: Bearer и сам токен
|
||||
const token = authorizationHeader.split(' ')[1];
|
||||
|
||||
// Проверяем токен
|
||||
const decodedToken = jwt.verify(token, SECRET_KEY);
|
||||
|
||||
// Если всё хорошо, отправляем положительный ответ
|
||||
res.send({ message: 'Token is valid', userId: decodedToken.userId });
|
||||
} catch (err) {
|
||||
// Если произошла ошибка, возвращаем сообщение об ошибке
|
||||
res.status(401).send({ message: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Запуск сервера
|
||||
app.listen(PORT, () => {
|
||||
console.log(`Server is running on http://localhost:${PORT}`);
|
||||
})
|
||||
@@ -0,0 +1,45 @@
|
||||
const express = require('express');
|
||||
const bodyParser = require('body-parser');
|
||||
const { Pool } = require('pg');
|
||||
const cors = require('cors');
|
||||
|
||||
const app = express();
|
||||
const port = 3000;
|
||||
|
||||
app.use(cors());
|
||||
|
||||
app.use(bodyParser.json());
|
||||
|
||||
const pool = new Pool({
|
||||
user: 'postgres',
|
||||
host: 'db',
|
||||
database: 'postgres',
|
||||
password: 'postgres',
|
||||
port: 5432,
|
||||
});
|
||||
|
||||
app.get('/reviews', async(req, res) => {
|
||||
try {
|
||||
const result = await pool.query('SELECT * FROM reviews;');
|
||||
res.json(result.rows);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.status(500).send("Server error");
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/reviews', async(req, res) => {
|
||||
const { text } = req.body;
|
||||
try {
|
||||
const result = await pool.query('INSERT INTO reviews (text) VALUES ($1) RETURNING *', [text]);
|
||||
res.status(201).json(result.rows[0]);
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
res.status(500).send("Server error");
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
app.listen(port, '0.0.0.0', () => {
|
||||
console.log("Server is running on port ${port}");
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
const express = require('express');
|
||||
const bodyParser = require('body-parser');
|
||||
const { Pool } = require('pg');
|
||||
const cors = require('cors');
|
||||
|
||||
const app = express();
|
||||
const port = 4000;
|
||||
|
||||
app.use(cors());
|
||||
|
||||
app.use(bodyParser.json());
|
||||
|
||||
const pool = new Pool({
|
||||
user: 'postgres',
|
||||
host: 'db',
|
||||
database: 'postgres',
|
||||
password: 'postgres',
|
||||
port: 5432,
|
||||
});
|
||||
|
||||
app.post('/support', async (req, res) => {
|
||||
const { email, text } = req.body;
|
||||
try {
|
||||
const result = await pool.query('INSERT INTO posts (email, text) VALUES ($1, $2) RETURNING *', [email, text]);
|
||||
res.status(201).json(result.rows[0]);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.status(500).send("Server error");
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/support', async (req, res) => {
|
||||
try {
|
||||
const result = await pool.query('SELECT * FROM posts;');
|
||||
res.json(result.rows);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.status(500).send("Server error");
|
||||
}
|
||||
});
|
||||
|
||||
app.listen(port, '0.0.0.0', () => {
|
||||
console.log("Server is running on port ${port}");
|
||||
});
|
||||
Reference in New Issue
Block a user