Skip to content
This repository was archived by the owner on Jan 23, 2025. It is now read-only.

check v3 token expiration #510

Merged
merged 2 commits into from
Jul 25, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 64 additions & 1 deletion initializers/v3client.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
var request = require('request');
var _ = require('underscore');
var async = require('async');
var atob = require('atob');

/**
* The URL of the V3 API
Expand Down Expand Up @@ -63,7 +64,7 @@ function getToken(connection, callback) {
return;
}
// Cached token
if (!_.isUndefined(tokens[connection.authToken])) {
if (!_.isUndefined(tokens[connection.authToken]) && !isTokenExpired(tokens[connection.authToken])) {
callback(null, tokens[connection.authToken]);
return;
}
Expand All @@ -86,6 +87,68 @@ function getToken(connection, callback) {
});
}

function urlBase64Decode(str) {
var output = str.replace(/-/g, '+').replace(/_/g, '/');

switch (output.length % 4) {
case 0:
break;

case 2:
output += '==';
break;

case 3:
output += '=';
break;

default:
throw 'Illegal base64url string!'
}
return decodeURIComponent(escape(atob(output)));//polyfill https://github.com/davidchambers/Base64.js
}

function decodeToken(token) {
var parts = token.split('.');

if (parts.length !== 3) {
throw new Error('The token is invalid')
}

var decoded = urlBase64Decode(parts[1]);

if (!decoded) {
throw new Error('Cannot decode the token')
}

return JSON.parse(decoded)
}

function getTokenExpirationDate(token) {
var decoded = decodeToken(token);

if(typeof decoded.exp === 'undefined') {
return null
}

var d = new Date(0);// The 0 here is the key, which sets the date to the epoch
d.setUTCSeconds(decoded.exp);

return d
}

function isTokenExpired(token) {
var d = getTokenExpirationDate(token);

if (d === null) {
return false
}

// Token expired?
return !(d.valueOf() > (new Date().valueOf()))
}


/**
* Get IDs of users in the specified group
*
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@
"validator": "~3.5.0",
"wkhtmltoimage": ">= 0.1.3",
"xml2js": "0.2.x",
"xtend": "2.1.x"
"xtend": "2.1.x",
"atob": "2.0.3"
},
"devDependencies": {
"supertest": "0.8.x",
Expand Down