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

Commit 4b9258b

Browse files
authored
Merge pull request #510 from appirio-tech/check_v3_token_expiration
check v3 token expiration
2 parents 3cdd766 + c50710c commit 4b9258b

File tree

2 files changed

+66
-2
lines changed

2 files changed

+66
-2
lines changed

initializers/v3client.js

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
var request = require('request');
1313
var _ = require('underscore');
1414
var async = require('async');
15+
var atob = require('atob');
1516

1617
/**
1718
* The URL of the V3 API
@@ -63,7 +64,7 @@ function getToken(connection, callback) {
6364
return;
6465
}
6566
// Cached token
66-
if (!_.isUndefined(tokens[connection.authToken])) {
67+
if (!_.isUndefined(tokens[connection.authToken]) && !isTokenExpired(tokens[connection.authToken])) {
6768
callback(null, tokens[connection.authToken]);
6869
return;
6970
}
@@ -86,6 +87,68 @@ function getToken(connection, callback) {
8687
});
8788
}
8889

90+
function urlBase64Decode(str) {
91+
var output = str.replace(/-/g, '+').replace(/_/g, '/');
92+
93+
switch (output.length % 4) {
94+
case 0:
95+
break;
96+
97+
case 2:
98+
output += '==';
99+
break;
100+
101+
case 3:
102+
output += '=';
103+
break;
104+
105+
default:
106+
throw 'Illegal base64url string!'
107+
}
108+
return decodeURIComponent(escape(atob(output)));//polyfill https://github.com/davidchambers/Base64.js
109+
}
110+
111+
function decodeToken(token) {
112+
var parts = token.split('.');
113+
114+
if (parts.length !== 3) {
115+
throw new Error('The token is invalid')
116+
}
117+
118+
var decoded = urlBase64Decode(parts[1]);
119+
120+
if (!decoded) {
121+
throw new Error('Cannot decode the token')
122+
}
123+
124+
return JSON.parse(decoded)
125+
}
126+
127+
function getTokenExpirationDate(token) {
128+
var decoded = decodeToken(token);
129+
130+
if(typeof decoded.exp === 'undefined') {
131+
return null
132+
}
133+
134+
var d = new Date(0);// The 0 here is the key, which sets the date to the epoch
135+
d.setUTCSeconds(decoded.exp);
136+
137+
return d
138+
}
139+
140+
function isTokenExpired(token) {
141+
var d = getTokenExpirationDate(token);
142+
143+
if (d === null) {
144+
return false
145+
}
146+
147+
// Token expired?
148+
return !(d.valueOf() > (new Date().valueOf()))
149+
}
150+
151+
89152
/**
90153
* Get IDs of users in the specified group
91154
*

package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,8 @@
4848
"validator": "~3.5.0",
4949
"wkhtmltoimage": ">= 0.1.3",
5050
"xml2js": "0.2.x",
51-
"xtend": "2.1.x"
51+
"xtend": "2.1.x",
52+
"atob": "2.0.3"
5253
},
5354
"devDependencies": {
5455
"supertest": "0.8.x",

0 commit comments

Comments
 (0)