89 lines
2.2 KiB
JavaScript
89 lines
2.2 KiB
JavaScript
const pool = global.db_pool;
|
|
if (!pool) {
|
|
throw new Error('Database pool is not defined');
|
|
}
|
|
|
|
const express = require('express');
|
|
const app = new express.Router();
|
|
|
|
app.get('/logout', (req, res) => {
|
|
req.session.destroy();
|
|
res.redirect('/admin/login');
|
|
});
|
|
|
|
app.get('/login', (req, res) => {
|
|
res.render('admin/login');
|
|
});
|
|
|
|
app.get('/', (req, res) => {
|
|
if (!req.session.adminAuthenticated) {
|
|
res.redirect('/admin/login');
|
|
return;
|
|
}
|
|
res.render('admin/index', { user: req.session.user });
|
|
});
|
|
|
|
app.get('/create', (req, res) => {
|
|
if (!req.session.adminAuthenticated) {
|
|
res.redirect('/admin/login');
|
|
return;
|
|
}
|
|
res.render('admin/create', { user: req.session.user });
|
|
});
|
|
|
|
app.get('/route/:id', (req, res) => {
|
|
if (!req.session.adminAuthenticated) {
|
|
res.redirect('/admin/login');
|
|
return;
|
|
}
|
|
pool.getConnection().then(conn => {
|
|
conn.query('SELECT * FROM routes WHERE id = ?', [req.params.id]).then((rows) => {
|
|
const row = rows[0];
|
|
if (!row) {
|
|
res.status(404).send('Not Found');
|
|
return;
|
|
}
|
|
res.render('admin/edit', { user: req.session.user, data: row });
|
|
}).catch(err => {
|
|
console.error('Error getting route:', err);
|
|
res.status(500).send('Internal server error');
|
|
}).finally(() => {
|
|
conn.release();
|
|
});
|
|
});
|
|
});
|
|
|
|
app.post('/login', (req, res) => {
|
|
const username = req.body.username;
|
|
const password = req.body.password;
|
|
pool.getConnection().then(conn => {
|
|
conn.query("SELECT * FROM users WHERE username = ?", [String(username)]).then((rows) => {
|
|
const row = rows[0];
|
|
if (!row) {
|
|
res.status(401).send('Unauthorized (Not Found)');
|
|
return;
|
|
}
|
|
bcrypt.compare(password, row.passwordHash, (err, result) => {
|
|
if (err) {
|
|
console.error('Error comparing password:', err);
|
|
res.status(500).send('Internal server error');
|
|
return;
|
|
}
|
|
if (result) {
|
|
req.session.adminAuthenticated = true;
|
|
req.session.user = row.username;
|
|
res.redirect('/admin');
|
|
} else {
|
|
res.status(401).send('Unauthorized');
|
|
}
|
|
});
|
|
}).catch(err => {
|
|
console.error('Error getting user:', err);
|
|
res.status(500).send('Internal server error');
|
|
}).finally(() => {
|
|
conn.release();
|
|
});
|
|
});
|
|
});
|
|
|
|
module.exports = app; |