derv-net/routes/init.js
2025-02-25 22:53:22 -05:00

105 lines
No EOL
2.2 KiB
JavaScript

import { importRouters } from "../lib.js";
import multer from "multer";
import cookieParser from "cookie-parser";
import { initDb } from "../db.js";
let db = await initDb();
const upload = multer({ dest: 'uploads/' });
const aliases = {
'/': '/walls/get/home'
};
const routers = {
'/you': './routes/you.js',
'/api/form/you': './routes/youApi.js'
}
function doAliases(app) {
for (let alias in aliases) {
let aliasV = aliases[alias];
app.all(alias, (req, res, next) => {
res.redirect(aliasV)
})
}
}
async function auther(req, res, next) {
let { token } = req.cookies;
if (!token) {
res.auth = {};
return;
}
let match = await db.all('SELECT * FROM token WHERE token = ?', [
token || 'blah'
]);
let username = match[0] ? match[0].username : '!nobody';
let valid = false;
if (username != '!nobody') {
valid = await db.all('SELECT * FROM auth WHERE username = ?', [
username
]);
}
res.auth = {
username,
valid: valid[0]
};
next();
}
function initr(req, res, next) {
let headerCtx = [
{ link: '/walls/get/home', icon: '/icon.svg', name: 'DervNet' },
{ link: '/walls/list', icon: '/walls.svg', name: 'Explore' },
{ link: '/you/logout', icon: '/logout.svg', name: 'Leave' } // fix icon
];
if (!res.auth || !res.auth.valid) {
headerCtx = [
{ link: '/walls/get/home', icon: '/icon.svg', name: 'DervNet' },
{ link: '/you/login', icon: '/walls.svg', name: 'Log in' },
{ link: '/you/new', icon: '/walls.svg', name: 'Join' }
];
}
res.ctx = {
mainPage: '404.ejs',
mainCtx: {},
headerCtx
};
next();
}
async function doInit(app) {
app.use(cookieParser());
doAliases(app);
app.use(auther)
app.use(initr)
app.use('/api/form', upload.none());
app.use('/api/file', upload.single('file'));
await importRouters(app, routers);
app.use('/api', (req, res, next) => {
res.send(res.api);
})
app.use((req, res, next) => {
res.render('root.ejs', res.ctx)
})
}
export { doInit };