-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
73 lines (65 loc) · 2.17 KB
/
index.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
const request = require('request');
class SNBearer {
constructor(config) {
this.config = config;
if (this.config) {
//config contains the url, client id and client secret
if (!this.config.url) throw new Error('The url was not defined!');
if (!this.config.client_id) throw new Error('The service now client id was not defined!')
if (!this.config.client_secret) throw new Error('The service now client secret was not defined!')
} else {
throw new Error('The config object was not defined!');
}
}
refresh(refresh_token) {
return new Promise((resolve, reject) => {
const options = {
method: 'POST',
url: `${this.config.url}/oauth_token.do`,
form: {
grant_type: 'refresh_token',
refresh_token: refresh_token,
client_id: this.config.client_id,
client_secret: this.config.client_secret
}
};
request(options, function (error, response, body) {
if (error) reject(new Error({Error: error}));
let access_token = JSON.parse(body);
if (access_token.error) {
reject(new Error('The refresh token was not refreshed!'));
}
access_token.date_requested = new Date();
resolve(access_token);
});
})
}
login(username, password) {
return new Promise((resolve, reject) => {
const options = {
method: 'POST',
url: `${this.config.url}/oauth_token.do`,
form: {
username: username,
password: password,
grant_type: 'password',
client_id: this.config.client_id,
client_secret: this.config.client_secret
}
};
request(options, (error, response, body) => {
if (error) reject(new Error(error));
let access_token = JSON.parse(body);
if(access_token.error_description){
reject(new Error('Username or Password was incorrect!'));
}
if (!access_token.access_token) {
reject(new Error('Service now did not return an Auth Token'));
}
access_token.date_requested = new Date();
resolve(access_token);
});
})
}
}
module.exports = SNBearer;