salix/print/core/router.js

75 lines
2.1 KiB
JavaScript
Raw Normal View History

2020-03-05 08:28:20 +00:00
const path = require('path');
const fs = require('fs');
const db = require('./database');
2019-01-22 08:55:35 +00:00
module.exports = app => {
2020-03-05 08:28:20 +00:00
const methodsPath = path.resolve(__dirname, '../methods');
const methodsDir = fs.readdirSync(methodsPath);
const methods = [];
// Get all methods
methodsDir.forEach(method => {
methods.push(method.replace('.js', ''));
});
// Auth middleware
const paths = [];
for (let method of methods)
paths.push(`/api/${method}/*`);
2020-05-20 14:23:53 +00:00
app.use(paths, async function(req, res, next) {
const token = getToken(req);
const query = `SELECT at.id, at.userId, eu.email, u.lang, at.ttl, at.created
FROM salix.AccessToken at
JOIN account.user u ON u.id = at.userid
JOIN account.emailUser eu ON eu.userFk = u.id
WHERE at.id = ?`;
2020-03-05 08:28:20 +00:00
try {
2020-05-20 14:23:53 +00:00
const auth = await db.findOne(query, [token]);
2020-03-05 08:28:20 +00:00
2020-05-20 14:23:53 +00:00
if (!auth || isTokenExpired(auth.created, auth.ttl))
2020-03-05 08:28:20 +00:00
throw new Error('Invalid authorization token');
2020-05-20 14:23:53 +00:00
const args = Object.assign({}, req.query);
const props = Object.assign(args, req.body);
props.authorization = auth.id;
req.args = props;
req.args.auth = {
userId: auth.userId,
token: auth.id,
email: auth.email,
2020-05-22 13:20:55 +00:00
locale: auth.lang
2020-03-31 06:18:10 +00:00
};
2020-03-05 08:28:20 +00:00
next();
} catch (error) {
next(error);
}
});
function getToken(request) {
const headers = request.headers;
2020-05-20 14:23:53 +00:00
const queryParams = request.query;
2020-05-20 14:23:53 +00:00
return headers.authorization || queryParams.authorization;
2020-03-05 08:28:20 +00:00
}
function isTokenExpired(created, ttl) {
const date = new Date(created);
const currentDate = new Date();
2020-03-05 08:28:20 +00:00
date.setSeconds(date.getSeconds() + ttl);
if (currentDate > date)
return true;
return false;
2020-03-05 08:28:20 +00:00
}
// Mount methods
for (let method of methods)
require(`../methods/${method}`)(app);
2019-01-22 08:55:35 +00:00
};