auth update
This commit is contained in:
parent
fdda0bef3f
commit
5c5cd5a0b6
778
package-lock.json
generated
778
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -11,6 +11,7 @@
|
|||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"axios": "^1.5.0",
|
"axios": "^1.5.0",
|
||||||
|
"bcrypt": "^5.1.1",
|
||||||
"body-parser": "^1.20.2",
|
"body-parser": "^1.20.2",
|
||||||
"dotenv": "^16.3.1",
|
"dotenv": "^16.3.1",
|
||||||
"express": "^4.18.2",
|
"express": "^4.18.2",
|
||||||
|
88
server.js
88
server.js
@ -13,6 +13,8 @@ const bodyParser = require('body-parser');
|
|||||||
const _ = require('lodash');
|
const _ = require('lodash');
|
||||||
const puppeteer = require('puppeteer');
|
const puppeteer = require('puppeteer');
|
||||||
const session = require('express-session');
|
const session = require('express-session');
|
||||||
|
const bcrypt = require('bcrypt');
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const storage = multer.diskStorage({
|
const storage = multer.diskStorage({
|
||||||
@ -399,8 +401,10 @@ app.post('/setup', async (req, res) => {
|
|||||||
res.redirect('/signin');
|
res.redirect('/signin');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const hashedPassword = await bcrypt.hash(password, saltRounds);
|
||||||
|
|
||||||
const insertQuery = 'INSERT INTO main (organisation, login, password) VALUES ($1, $2, $3)';
|
const insertQuery = 'INSERT INTO main (organisation, login, password) VALUES ($1, $2, $3)';
|
||||||
await pool.query(insertQuery, [name, login, password]);
|
await pool.query(insertQuery, [name, login, hashedPassword]);
|
||||||
|
|
||||||
res.status(200).json({ message: 'Данные успешно добавлены' });
|
res.status(200).json({ message: 'Данные успешно добавлены' });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@ -425,22 +429,26 @@ app.post('/login', async (req, res) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const mainQuery = await pool.query(
|
const mainQuery = await pool.query(
|
||||||
'SELECT * FROM main WHERE login = $1 AND password = $2',
|
'SELECT login, password FROM main WHERE login = $1',
|
||||||
[email, password]
|
[email]
|
||||||
);
|
);
|
||||||
|
|
||||||
const mainUser = mainQuery.rows[0];
|
const mainUser = mainQuery.rows[0];
|
||||||
|
|
||||||
if (mainUser) {
|
if (mainUser) {
|
||||||
|
const mainPasswordMatch = await bcrypt.compare(password, mainUser.password);
|
||||||
|
|
||||||
|
if (mainPasswordMatch) {
|
||||||
req.session.userId = "admin";
|
req.session.userId = "admin";
|
||||||
|
|
||||||
console.log("Авторизация успешна (из таблицы main)");
|
console.log("Авторизация успешна (админ)");
|
||||||
return res.status(200).json({ message: 'Авторизация успешна' });
|
return res.status(200).json({ message: 'Авторизация успешна (админ)' });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const userQuery = await pool.query(
|
const userQuery = await pool.query(
|
||||||
'SELECT id, name, surname FROM users WHERE email = $1 AND password = $2',
|
'SELECT id, password FROM users WHERE email = $1',
|
||||||
[email, password]
|
[email]
|
||||||
);
|
);
|
||||||
|
|
||||||
const user = userQuery.rows[0];
|
const user = userQuery.rows[0];
|
||||||
@ -449,16 +457,23 @@ app.post('/login', async (req, res) => {
|
|||||||
return res.status(401).json({ message: 'Неправильное имя пользователя или пароль' });
|
return res.status(401).json({ message: 'Неправильное имя пользователя или пароль' });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const passwordMatch = await bcrypt.compare(password, user.password);
|
||||||
|
|
||||||
|
if (passwordMatch) {
|
||||||
req.session.userId = user.id;
|
req.session.userId = user.id;
|
||||||
|
|
||||||
console.log("Авторизация успешна (из таблицы users)");
|
console.log("Авторизация успешна");
|
||||||
res.status(200).json({ message: 'Авторизация успешна' });
|
return res.status(200).json({ message: 'Авторизация успешна' });
|
||||||
|
} else {
|
||||||
|
return res.status(401).json({ message: 'Неправильное имя пользователя или пароль' });
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Ошибка при выполнении запроса к базе данных:', error);
|
console.error('Ошибка при выполнении запроса к базе данных:', error);
|
||||||
res.status(500).json({ message: 'Ошибка сервера' });
|
res.status(500).json({ message: 'Ошибка сервера' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
app.get('/logout', (req, res) => {
|
app.get('/logout', (req, res) => {
|
||||||
req.session.destroy((err) => {
|
req.session.destroy((err) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
@ -3439,6 +3454,8 @@ async function adminPanel(req, res) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Обработка POST-запроса для добавления пользователя
|
// Обработка POST-запроса для добавления пользователя
|
||||||
|
const saltRounds = 10;
|
||||||
|
|
||||||
app.post("/add-user", async (req, res) => {
|
app.post("/add-user", async (req, res) => {
|
||||||
if (req.session.userId === undefined) {
|
if (req.session.userId === undefined) {
|
||||||
return res.redirect("/signin");
|
return res.redirect("/signin");
|
||||||
@ -3448,9 +3465,8 @@ app.post("/add-user", async (req, res) => {
|
|||||||
}
|
}
|
||||||
const { name, surname, email, phone, password } = req.body;
|
const { name, surname, email, phone, password } = req.body;
|
||||||
|
|
||||||
// console.log(name, surname, email, phone, password)
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
const hashedPassword = await bcrypt.hash(password, saltRounds);
|
||||||
|
|
||||||
const pool = new Pool({
|
const pool = new Pool({
|
||||||
user: DB_User,
|
user: DB_User,
|
||||||
@ -3463,12 +3479,12 @@ app.post("/add-user", async (req, res) => {
|
|||||||
const client = await pool.connect();
|
const client = await pool.connect();
|
||||||
|
|
||||||
const query = `
|
const query = `
|
||||||
INSERT INTO users (name, surname, email, phone, password, added)
|
INSERT INTO users (name, surname, email, phone, password, added, devices)
|
||||||
VALUES ($1, $2, $3, $4, $5, NOW())
|
VALUES ($1, $2, $3, $4, $5, NOW(), $6)
|
||||||
RETURNING id
|
RETURNING id
|
||||||
`;
|
`;
|
||||||
|
|
||||||
const result = await client.query(query, [name, surname, email, phone, password]);
|
const result = await client.query(query, [name, surname, email, phone, hashedPassword, "{}"]);
|
||||||
|
|
||||||
// Освобождение клиента
|
// Освобождение клиента
|
||||||
client.release();
|
client.release();
|
||||||
@ -3481,6 +3497,7 @@ app.post("/add-user", async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
app.get('/admin/user/:id', async (req, res) => {
|
app.get('/admin/user/:id', async (req, res) => {
|
||||||
if (req.session.userId === undefined) {
|
if (req.session.userId === undefined) {
|
||||||
return res.redirect("/signin");
|
return res.redirect("/signin");
|
||||||
@ -3503,7 +3520,6 @@ app.get('/admin/user/:id', async (req, res) => {
|
|||||||
Surname: "",
|
Surname: "",
|
||||||
Email: "",
|
Email: "",
|
||||||
Phone: "",
|
Phone: "",
|
||||||
Password: "",
|
|
||||||
Devices: [],
|
Devices: [],
|
||||||
EditTransport: false,
|
EditTransport: false,
|
||||||
DeleteTransport: false,
|
DeleteTransport: false,
|
||||||
@ -3571,7 +3587,6 @@ templateData.Name = response.name;
|
|||||||
templateData.Surname = response.surname;
|
templateData.Surname = response.surname;
|
||||||
templateData.Email = response.email;
|
templateData.Email = response.email;
|
||||||
templateData.Phone = response.phone;
|
templateData.Phone = response.phone;
|
||||||
templateData.Password = response.password;
|
|
||||||
templateData.Devices = response.devices;
|
templateData.Devices = response.devices;
|
||||||
templateData.DeleteTransport = response.deletetransport;
|
templateData.DeleteTransport = response.deletetransport;
|
||||||
templateData.EditTransport = response.edittransport;
|
templateData.EditTransport = response.edittransport;
|
||||||
@ -3636,6 +3651,41 @@ app.post("/updateuser/:id", async (req, res) => {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
|
|
||||||
|
if (password === "" || password === undefined) {
|
||||||
|
|
||||||
|
const query = `
|
||||||
|
UPDATE users
|
||||||
|
SET
|
||||||
|
name = $2,
|
||||||
|
surname = $3,
|
||||||
|
email = $4,
|
||||||
|
phone = $5,
|
||||||
|
editTransport = $6,
|
||||||
|
deleteTransport = $7,
|
||||||
|
update = $8,
|
||||||
|
devices = $9
|
||||||
|
WHERE id = $1
|
||||||
|
RETURNING *;
|
||||||
|
`;
|
||||||
|
|
||||||
|
const values = [
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
surname,
|
||||||
|
email,
|
||||||
|
phone,
|
||||||
|
EditTransport,
|
||||||
|
DeleteTransport,
|
||||||
|
Update,
|
||||||
|
devices,
|
||||||
|
];
|
||||||
|
|
||||||
|
const result = await client.query(query, values);
|
||||||
|
|
||||||
|
} else {
|
||||||
|
|
||||||
|
const hashedPassword = await bcrypt.hash(password, saltRounds);
|
||||||
|
|
||||||
const query = `
|
const query = `
|
||||||
UPDATE users
|
UPDATE users
|
||||||
SET
|
SET
|
||||||
@ -3658,7 +3708,7 @@ app.post("/updateuser/:id", async (req, res) => {
|
|||||||
surname,
|
surname,
|
||||||
email,
|
email,
|
||||||
phone,
|
phone,
|
||||||
password,
|
hashedPassword,
|
||||||
EditTransport,
|
EditTransport,
|
||||||
DeleteTransport,
|
DeleteTransport,
|
||||||
Update,
|
Update,
|
||||||
@ -3667,8 +3717,8 @@ app.post("/updateuser/:id", async (req, res) => {
|
|||||||
|
|
||||||
const result = await client.query(query, values);
|
const result = await client.query(query, values);
|
||||||
|
|
||||||
const updatedRow = result.rows[0];
|
}
|
||||||
// console.log("Updated row:", updatedRow);
|
|
||||||
|
|
||||||
res.send("Data updated successfully");
|
res.send("Data updated successfully");
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
@ -179,8 +179,8 @@
|
|||||||
<input name="phone" type="text" id="user-phone" placeholder="Номер телефона пользователя" value="{{Phone}}" required>
|
<input name="phone" type="text" id="user-phone" placeholder="Номер телефона пользователя" value="{{Phone}}" required>
|
||||||
</div>
|
</div>
|
||||||
<div class="parameters-input">
|
<div class="parameters-input">
|
||||||
<label for="user-password">Пароль<span style="color: rgba(255, 69, 58, 1);">*</span></label>
|
<label for="user-password">Новый пароль (необязательно)</label>
|
||||||
<input name="password" type="text" id="user-password" placeholder="Пароль пользователя" value="{{Password}}" required>
|
<input name="password" type="text" id="user-password" placeholder="Новый пароль пользователя" required>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</form>
|
</form>
|
||||||
|
Loading…
Reference in New Issue
Block a user