login and register logic
This commit is contained in:
parent
a2f8452eec
commit
8d0c02e27e
15 changed files with 496 additions and 106 deletions
98
routes/init.js
Normal file
98
routes/init.js
Normal file
|
@ -0,0 +1,98 @@
|
|||
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 };
|
Loading…
Add table
Add a link
Reference in a new issue