2017-09-27 15:44:51 +00:00
|
|
|
var database = require('./database.js');
|
2017-11-27 14:08:18 +00:00
|
|
|
let config = require('./config.js');
|
2017-09-27 15:44:51 +00:00
|
|
|
|
|
|
|
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: function() {
|
|
|
|
let query = 'SELECT userId, ttl, created FROM salix.AccessToken WHERE id = ?';
|
|
|
|
|
|
|
|
database.pool.query(query, [this.getToken()], (error, result) => {
|
|
|
|
let token = result[0];
|
|
|
|
|
2017-10-17 06:22:59 +00:00
|
|
|
if (error || result.length == 0)
|
|
|
|
return this.response.status(401).send({message: 'Invalid token'});
|
2017-09-27 15:44:51 +00:00
|
|
|
|
|
|
|
if (this.isTokenExpired(token.created, token.ttl))
|
2017-10-17 06:22:59 +00:00
|
|
|
return this.response.status(401).send({message: 'Token expired'});
|
2017-09-27 15:44:51 +00:00
|
|
|
|
2017-11-27 14:08:18 +00:00
|
|
|
// Set proxy host
|
|
|
|
let host = this.request.headers.host.split(':')[0];
|
|
|
|
let proxy;
|
|
|
|
|
|
|
|
if (host == '127.0.0.1')
|
|
|
|
proxy = config.proxy.localhost;
|
|
|
|
else if(process.env.NODE_ENV == 'production')
|
|
|
|
proxy = config.proxy.salix;
|
|
|
|
else if(process.env.NODE_ENV == 'development')
|
|
|
|
proxy = config.proxy.testSalix;
|
|
|
|
|
|
|
|
this.request.proxyHost = `http://${proxy.host}:${proxy.port}`;
|
|
|
|
this.request.user = {
|
|
|
|
id: token.userId,
|
|
|
|
token: this.getToken()
|
|
|
|
}
|
|
|
|
|
2017-09-27 15:44:51 +00:00
|
|
|
this.next();
|
|
|
|
});
|
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get request token
|
|
|
|
* @return {String} Token
|
|
|
|
*/
|
|
|
|
getToken: function() {
|
2017-10-19 10:47:05 +00:00
|
|
|
return this.request.headers.authorization || this.request.query.token;
|
2017-09-27 15:44:51 +00:00
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* 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;
|
|
|
|
}
|
|
|
|
};
|