2020-03-05 08:28:20 +00:00
|
|
|
const db = require('./database');
|
|
|
|
|
2019-01-22 08:55:35 +00:00
|
|
|
module.exports = app => {
|
2022-01-19 07:40:13 +00:00
|
|
|
const routes = require('../methods/routes');
|
2022-01-05 13:48:21 +00:00
|
|
|
|
|
|
|
const paths = routes.map(route => route.url);
|
|
|
|
|
|
|
|
app.use(paths, async function(request, response, next) {
|
|
|
|
try {
|
|
|
|
const token = getToken(request);
|
|
|
|
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 = ?`;
|
|
|
|
|
|
|
|
const auth = await db.findOne(query, [token]);
|
|
|
|
|
|
|
|
if (!auth || isTokenExpired(auth.created, auth.ttl))
|
|
|
|
throw new Error('Invalid authorization token');
|
|
|
|
|
|
|
|
const args = Object.assign({}, request.query);
|
|
|
|
const props = Object.assign(args, request.body);
|
|
|
|
props.authorization = auth.id;
|
|
|
|
|
|
|
|
response.locals = props;
|
|
|
|
response.locals.auth = {
|
|
|
|
userId: auth.userId,
|
|
|
|
token: auth.id,
|
|
|
|
email: auth.email,
|
|
|
|
locale: auth.lang
|
|
|
|
};
|
|
|
|
|
|
|
|
next();
|
|
|
|
} catch (error) {
|
|
|
|
next(error);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
// Register routes
|
|
|
|
for (let route of routes)
|
|
|
|
app.use(route.url, route.cb);
|
|
|
|
|
|
|
|
function getToken(request) {
|
|
|
|
const headers = request.headers;
|
|
|
|
const queryParams = request.query;
|
|
|
|
|
|
|
|
return headers.authorization || queryParams.authorization;
|
|
|
|
}
|
|
|
|
|
|
|
|
function isTokenExpired(created, ttl) {
|
|
|
|
const date = new Date(created);
|
|
|
|
const currentDate = new Date();
|
|
|
|
|
|
|
|
date.setSeconds(date.getSeconds() + ttl);
|
|
|
|
|
|
|
|
if (currentDate > date)
|
|
|
|
return true;
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
2019-01-22 08:55:35 +00:00
|
|
|
};
|