homepage.js/routes/admin.js

95 lines
2.2 KiB
JavaScript
Raw Normal View History

2023-02-25 07:32:11 +01:00
const handler = require('express-async-handler')
const Helpers = require('../helpers');
const db = require('../models');
2023-02-27 13:13:36 +01:00
const express = require('express');
2023-02-25 07:32:11 +01:00
async function login(req, res) {
res.send(await Helpers.ViewLoader.load('admin/login.pug', {
current_route: req.originalUrl
}));
}
async function apiLogin(req, res) {
if (req.session.user) {
res.send('Already logged in');
return;
}
const user = (await db.User.authenticate(req.body));
if (!user) {
res.status(401).send('Bad auth');
}
const session = await user.createSession();
req.session.user = session;
2023-02-27 08:24:49 +01:00
res.redirect('/admin/panel');
return;
}
async function panel(req, res) {
2023-02-27 13:13:36 +01:00
const user = await db.User.bySession(req.session);
if (!user) {
res.status(401).send('Forbidden');
return;
}
const gb_records = await db.Guestbook.findAll({
order: [['id', 'DESC']]
});
2023-02-27 14:26:24 +01:00
const articles = await db.Article.findAll({where: {hidden: true}});
2023-03-11 16:54:53 +01:00
res.template('admin/panel.pug', {
current_route: req.originalUrl,
2023-02-27 13:13:36 +01:00
gb_records,
access_level: user.accessLevel
2023-03-11 16:54:53 +01:00
});
2023-02-25 07:32:11 +01:00
return;
}
async function gb_api(req, res) {
let action = false;
const id = req.body.id;
2023-02-27 13:13:36 +01:00
const user = await db.User.bySession(req.session);
if (!user) {
res.status(401).send('Forbidden');
return;
}
if (req.body.hide) action = 'hide';
if (!action) {
res.redirect('/admin/panel');
return;
}
switch (action) {
case 'hide':
const response = await db.Guestbook.update({hidden: db.Sequelize.literal('NOT hidden')}, {where: {id}})
res.redirect('/admin/panel');
return;
}
}
async function article_new(req, res) {
2023-03-11 16:54:53 +01:00
res.template('articles/new.pug')
}
2023-02-25 07:32:11 +01:00
module.exports = (router) => {
2023-02-27 08:24:49 +01:00
// login
2023-02-25 07:32:11 +01:00
router.get('/login', handler(login));
router.get('/admin/login', handler(login));
router.post('/admin/login', handler(apiLogin));
2023-02-27 08:24:49 +01:00
router.post('/gb_api', handler(gb_api));
2023-02-27 13:13:36 +01:00
2023-02-27 08:24:49 +01:00
// panel
router.get('/admin/panel', handler(panel));
// article
router.get('/admin/article/new', handler(article_new));
2023-02-25 07:32:11 +01:00
}