salix/print/core/router.js

63 lines
1.6 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}/*`);
app.use(paths, async function(request, response, next) {
const authorization = getToken(request);
const query = `SELECT userId, ttl, created
FROM salix.AccessToken WHERE id = ?`;
try {
const authToken = await db.findOne(query, [authorization]);
if (!authToken || isTokenExpired(authToken.created, authToken.ttl))
throw new Error('Invalid authorization token');
next();
} catch (error) {
next(error);
}
});
function getToken(request) {
const headers = request.headers;
const params = request.query;
if (headers.authorization)
params.authorization = headers.authorization;
return headers.authorization || params.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
};