From 675fa807e6d4e5f92cb44356c017c3dc2f0f88c8 Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Thu, 5 Mar 2020 09:28:20 +0100 Subject: [PATCH] Added authentication --- print/boot.js | 2 -- print/core/router.js | 57 ++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 53 insertions(+), 6 deletions(-) diff --git a/print/boot.js b/print/boot.js index ae604db2c..02bb27817 100644 --- a/print/boot.js +++ b/print/boot.js @@ -52,5 +52,3 @@ module.exports = app => { }); }); }; - - diff --git a/print/core/router.js b/print/core/router.js index f015ac03b..a96f770cf 100644 --- a/print/core/router.js +++ b/print/core/router.js @@ -1,6 +1,55 @@ +const path = require('path'); +const fs = require('fs'); +const db = require('./database'); + module.exports = app => { - // Import methods - require('../methods/closure')(app); - require('../methods/report')(app); - require('../methods/email')(app); + 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 = ?`; + 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); };