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
|
2021-10-01 10:41:31 +00:00
|
|
|
for (let method of methodsDir) {
|
|
|
|
if (method.includes('.js'))
|
|
|
|
methods.push(method.replace('.js', ''));
|
|
|
|
}
|
2020-03-05 08:28:20 +00:00
|
|
|
|
|
|
|
// 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) {
|
2020-03-05 12:56:45 +00:00
|
|
|
const headers = request.headers;
|
2020-05-20 14:23:53 +00:00
|
|
|
const queryParams = request.query;
|
2020-03-05 12:56:45 +00:00
|
|
|
|
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) {
|
2020-03-05 12:56:45 +00:00
|
|
|
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;
|
2020-03-05 12:56:45 +00:00
|
|
|
|
|
|
|
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
|
|
|
};
|