-
Notifications
You must be signed in to change notification settings - Fork 1
/
auth.ts
82 lines (73 loc) · 2.51 KB
/
auth.ts
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
import {AuthOptions} from "./auth-options";
import * as request from "request";
import {CoreOptions, post} from "request";
import * as fs from 'fs';
import {parse} from 'yaml';
export class Auth {
private authHeader: string;
public async prepare(optionsFile: string) {
if (!optionsFile) {
return;
}
let options: AuthOptions;
try {
options = JSON.parse(optionsFile);
} catch {
const optionsContent = fs.readFileSync(optionsFile).toString();
options = parse(optionsContent);
}
switch (options.type) {
case 'bearerToken':
if (options.token) {
this.authHeader = `Bearer ${options.token}`;
}
return;
case 'basic':
if (options.basic) {
const token = btoa(options.basic.username + ':' + options.basic.password);
this.authHeader = `Basic ${token}`;
}
return;
case 'oauth':
if (options.oauth) {
switch (options.oauth.grantType) {
case 'client_credential':
const token = await this.getClientCredential(options.oauth.tokenUrl, options.oauth.clientId, options.oauth.secret, options.oauth.resource);
this.authHeader = `Bearer ${token}`;
return;
}
}
return;
}
}
public authenticateRequest(reqOptions: CoreOptions) {
if (this.authHeader) {
if (!reqOptions.headers) {
reqOptions.headers = {};
}
reqOptions.headers['Authorization'] = this.authHeader;
}
}
private async getClientCredential(tokenUrl: string, clientId: string, secret: string, resource?: string): Promise<string> {
const options = {
json: true,
form: <any> {
grant_type: 'client_credentials',
client_id: clientId,
client_secret: secret
}
};
if (resource) {
options.form.resource = resource;
}
return new Promise((resolve, reject) => {
request(tokenUrl, options, (err, res, body) => {
if (err) {
reject(err);
} else {
resolve(body.access_token);
}
});
});
}
}