-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtpn.js
84 lines (78 loc) · 2.16 KB
/
tpn.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
var request = require('request');
var jwt = require('jsonwebtoken');
// request.debug = true;
// require('request-debug')(request);
const TPN_BASE = 'https://penapi.pacnetconnect.com';
function generatetoken(username, password, domain, callback) {
request.post(
{
url:`${TPN_BASE}/1.0.0/auth/generatetoken`,
form: {
username: `${domain}/${username}`,
password: password,
grant_type: 'password',
}
},
function(err, httpResponse, body) {
var token = JSON.parse(body);
callback(err, token);
}
);
}
function generatejwt(token, secret, callback) {
const payload = {
access_token: token.access_token,
iss: 'issuer',
sub: 'subject',
aud: 'audience',
};
jwt.sign(payload, secret, { expiresIn: token.expires_in }, callback);
}
// Validate jwt signature and return the access token
function extractAccessToken(token, secret, callback) {
jwt.verify(token, secret, function(err, payload) {
if (err) {
callback(err, null);
} else {
console.log(`access_token: ${payload.access_token}`);
callback(err, payload.access_token);
}
});
}
// currently expects body as a string object and returns body as a string. This
// is a bit inconsistent
function proxyRequest(method, path, token, body, callback) {
console.log('Request to TPN:');
console.log(` host: ${TPN_BASE}`);
console.log(` method: ${method}`);
console.log(` path: ${path}`);
console.log(` token: ${token}`);
console.log(` body: ${body}`);
request({
method: method,
uri: `${TPN_BASE}${path}`,
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: body,
},
function (err, httpResponse, body) {
const response = {
statusCode: httpResponse.statusCode,
headers: {
"Cache-Control" : "no-cache",
},
body: body,
};
console.log('Response from TPN:');
console.log(` response: ${JSON.stringify(response)}`);
callback(err, response);
});
}
module.exports = {
generatetoken: generatetoken,
generatejwt: generatejwt,
proxyRequest: proxyRequest,
extractAccessToken: extractAccessToken,
};