salix/services/print/application/auth.js

80 lines
2.0 KiB
JavaScript

var database = require('./database.js');
let config = require('./config.js');
module.exports = {
/**
* Initialize auth
* @param {Object} request - Request object
* @param {Object} response - Response object
* @param {Object} next - Next object
*/
init: function(request, response, next) {
this.request = request;
this.response = response;
this.next = next;
this.validateToken();
},
/**
* Validate auth token
*/
validateToken: async function() {
let query = 'SELECT userId, ttl, created FROM salix.AccessToken WHERE id = ?';
try {
let [result] = await database.pool.query(query, [this.getToken()]);
let token = result[0];
if (result.length == 0)
throw new Error('Invalid token');
if (this.isTokenExpired(token.created, token.ttl))
throw new Error('Token expired');
// Set proxy host
let proxy = config.proxy;
if (!proxy)
proxy = {
host: 'localhost',
port: 80
};
this.request.proxyHost = `http://${proxy.host}:${proxy.port}`;
this.request.user = {
id: token.userId,
token: this.getToken()
};
this.next();
} catch (e) {
this.response.status(401).send({message: e.message});
this.next(e);
}
},
/**
* Get request token
* @return {String} Token
*/
getToken: function() {
return this.request.headers.authorization || this.request.query.token;
},
/**
* Checks if the token has expired
* @param {String} created - Creation date
* @param {Integer} ttl - Ttl seconds
* @return {Boolean} True if the token has expired
*/
isTokenExpired: function(created, ttl) {
let date = new Date(created);
let currentDate = new Date();
date.setSeconds(date.getSeconds() + ttl);
if (currentDate > date)
return true;
}
};