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) { app.all(alias, (req, res, next) => { res.redirect(aliases[alias]) }) } } async function auther(req, res, next) { let body = { ...req.cookies, ...req.body }; let { token } = body; let match = await db.all('SELECT * FROM token WHERE token = ?', [ token || 'blah' ]); let username = match[0] ? match[0].username : '!nobody'; let valid = await db.all('SELECT * FROM auth WHERE username = ?', [ username ]); res.auth = { username, valid: valid[0], rootUrl: process.env.URL, }; 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()); app.use(auther) app.use(initr) app.use('/api/form', upload.none()); app.use('/api/file', upload.single('file')); doAliases(app); 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 };