12
12
var request = require ( 'request' ) ;
13
13
var _ = require ( 'underscore' ) ;
14
14
var async = require ( 'async' ) ;
15
- var tcAccounts = require ( 'tc-accounts ' ) ;
15
+ var atob = require ( 'atob ' ) ;
16
16
17
17
/**
18
18
* The URL of the V3 API
@@ -64,7 +64,7 @@ function getToken(connection, callback) {
64
64
return ;
65
65
}
66
66
// Cached token
67
- if ( ! _ . isUndefined ( tokens [ connection . authToken ] ) && ! tcAccounts . isTokenExpired ( tokens [ connection . authToken ] ) ) {
67
+ if ( ! _ . isUndefined ( tokens [ connection . authToken ] ) && ! isTokenExpired ( tokens [ connection . authToken ] ) ) {
68
68
callback ( null , tokens [ connection . authToken ] ) ;
69
69
return ;
70
70
}
@@ -87,6 +87,68 @@ function getToken(connection, callback) {
87
87
} ) ;
88
88
}
89
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
+
151
+
90
152
/**
91
153
* Get IDs of users in the specified group
92
154
*
0 commit comments