-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCookieRestClient.ts
78 lines (67 loc) · 2.03 KB
/
CookieRestClient.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
/* eslint-disable no-param-reassign, no-underscore-dangle, class-methods-use-this */
import { promisify } from 'util';
import request from 'request';
import { NoAuthRestClient } from './NoAuthRestClient';
const requestCall = promisify(request);
export class CookieRestClient extends NoAuthRestClient {
loggedIn: boolean;
jar: any;
constructor(emitter, cfg) {
super(emitter, cfg);
this.jar = request.jar();
this.loggedIn = false;
}
private basicResponseCheck(response) {
if (response.statusCode >= 400) {
throw new Error(`Error in authentication. Status code: ${response.statusCode}, Body: ${JSON.stringify(response.body)}`);
}
}
protected handleLoginResponse(response) {
this.basicResponseCheck(response);
}
protected handleLogoutResponse(response) {
this.basicResponseCheck(response);
}
async login() {
this.emitter.logger.info('Performing Login ...');
const loginResponse = await requestCall({
method: 'POST',
url: this.cfg.loginUrl,
form: {
username: this.cfg.username,
password: this.cfg.password,
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
jar: this.jar,
});
this.handleLoginResponse(loginResponse);
this.loggedIn = true;
this.emitter.logger.info('Login Complete.');
}
async logout() {
if (this.cfg.logoutUrl && this.loggedIn) {
this.emitter.logger.info('Performing Logout...');
const logoutResponse = await requestCall({
method: this.cfg.logoutMethod,
url: this.cfg.logoutUrl,
jar: this.jar,
});
this.handleLogoutResponse(logoutResponse);
this.loggedIn = false;
this.emitter.logger.info('Logout complete.');
} else {
this.emitter.logger.info('Nothing to logout');
}
}
protected addAuthenticationToRequestOptions(requestOptions) {
requestOptions.jar = this.jar;
}
async makeRequest(options) {
if (!this.loggedIn) {
await this.login();
}
return super.makeRequest(options);
}
}