Added authentication

This commit is contained in:
Joan Sanchez 2020-03-05 09:28:20 +01:00
parent df3fbf291b
commit 675fa807e6
2 changed files with 53 additions and 6 deletions

View File

@ -52,5 +52,3 @@ module.exports = app => {
}); });
}); });
}; };

View File

@ -1,6 +1,55 @@
const path = require('path');
const fs = require('fs');
const db = require('./database');
module.exports = app => { module.exports = app => {
// Import methods const methodsPath = path.resolve(__dirname, '../methods');
require('../methods/closure')(app); const methodsDir = fs.readdirSync(methodsPath);
require('../methods/report')(app); const methods = [];
require('../methods/email')(app);
// 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 = ?`;
console.log('auth');
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) {
return request.headers.authorization || request.query.authorization;
}
function isTokenExpired(created, ttl) {
let date = new Date(created);
let currentDate = new Date();
date.setSeconds(date.getSeconds() + ttl);
if (currentDate > date)
return true;
}
// Mount methods
for (let method of methods)
require(`../methods/${method}`)(app);
}; };