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

Commit 650f8b8

Browse files
committed
copy over token exipiration check logic
1 parent a2820ee commit 650f8b8

File tree

2 files changed

+64
-4
lines changed

2 files changed

+64
-4
lines changed

initializers/v3client.js

Lines changed: 63 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
var request = require('request');
1313
var _ = require('underscore');
1414
var async = require('async');
15-
var tcAccounts = require('tc-accounts');
1615

1716
/**
1817
* The URL of the V3 API
@@ -64,7 +63,7 @@ function getToken(connection, callback) {
6463
return;
6564
}
6665
// Cached token
67-
if (!_.isUndefined(tokens[connection.authToken]) && !tcAccounts.isTokenExpired(tokens[connection.authToken])) {
66+
if (!_.isUndefined(tokens[connection.authToken]) && !isTokenExpired(tokens[connection.authToken])) {
6867
callback(null, tokens[connection.authToken]);
6968
return;
7069
}
@@ -87,6 +86,68 @@ function getToken(connection, callback) {
8786
});
8887
}
8988

89+
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+
90151
/**
91152
* Get IDs of users in the specified group
92153
*

package.json

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,7 @@
4848
"validator": "~3.5.0",
4949
"wkhtmltoimage": ">= 0.1.3",
5050
"xml2js": "0.2.x",
51-
"xtend": "2.1.x",
52-
"tc-accounts": "https://github.com/appirio-tech/accounts-app#dev"
51+
"xtend": "2.1.x"
5352
},
5453
"devDependencies": {
5554
"supertest": "0.8.x",

0 commit comments

Comments
 (0)