-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathget_client_expiredtoken.js
66 lines (59 loc) · 2.16 KB
/
get_client_expiredtoken.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
'use strict';
var Client = require('node-rest-client').Client,
clientOptions = {
connection: {
rejectUnauthorized: false,
requestCert: true,
}
},
client = new Client(clientOptions),
authData = {
'grant_type':'client_credentials',
'client_id':'foo',
'client_secret':'bar',
'scope':'*'
},
storedAuthToken = process.argv[2]; //simulation of local storage
var getAuthToken = function (data, callback){
var tokenArgs = {
'data': data,
headers: {
'Content-Type':'application/json'
}
};
client.post('https://api.fronter.com/oauth/token', tokenArgs, function (data, response) {
console.log('authorize: ', data);
storedAuthToken=data.token_type + ' ' + data.access_token;
callback(storedAuthToken);
}).on('error', function (err) {
console.log('err: ', err);
});
};
var getClient = function(client_id, authToken, authData, callback){
var clientArgs = {
headers: {
'Content-Type': 'application/json',
'Authorization': authToken
}
};
//if token missing, call getAuthToken with callback to myself, clear the authData parameter for preventing infinite loop
if(!authToken) {
getAuthToken(authData,function(newAuthToken){getClient(client_id,newAuthToken,{},callback);});
} else {
client.get('https://api.fronter.com/clients/' + client_id, clientArgs, function (data, response) {
console.log('clientInternal: ', data);
if(JSON.parse(data).error === 'token_expired') {
getAuthToken(authData,function(newAuthToken){getClient(client_id,newAuthToken,{},callback);});
}
else
callback(data);
}).on('error', function (err) {
//if token expired, call getAuthToken with callback to myself, clear the authData parameter for preventing infinite loop
console.log('err: ', err);
});
}
};
var getClientCallback = function(data){
console.log('getClientCallback: ' + data);
};
getClient(authData.client_id, storedAuthToken, authData, getClientCallback);