1
+ import cheerio from 'cheerio'
1
2
import * as fs from 'fs-extra'
2
3
import nodeFetch from 'node-fetch'
3
4
import tough = require( 'tough-cookie' )
@@ -8,7 +9,8 @@ import config from './config'
8
9
9
10
interface APIOptions {
10
11
serverUrl : string
11
- cookiePath : string
12
+ cookiePath : string ,
13
+ enterprise : boolean
12
14
}
13
15
14
16
type nodeFetchType = ( url : RequestInfo , init ?: RequestInit | undefined ) => Promise < Response >
@@ -36,10 +38,11 @@ export type HistoryItem = {
36
38
*/
37
39
class API {
38
40
public readonly serverUrl : string
41
+ private readonly enterprise : boolean
39
42
private readonly _fetch : nodeFetchType
40
43
41
44
constructor ( ) {
42
- const { serverUrl, cookiePath} : APIOptions = config
45
+ const { serverUrl, cookiePath, enterprise } : APIOptions = config
43
46
44
47
fs . ensureFileSync ( cookiePath )
45
48
@@ -48,16 +51,18 @@ class API {
48
51
49
52
this . _fetch = fetch
50
53
this . serverUrl = serverUrl
54
+ this . enterprise = enterprise
51
55
}
52
56
53
57
async login ( email : string , password : string ) {
54
58
const response = await this . fetch ( `${ this . serverUrl } /login` , {
55
59
method : 'post' ,
56
60
body : encodeFormComponent ( { email, password} ) ,
57
- headers : {
61
+ headers : await this . wrapHeaders ( {
58
62
'Content-Type' : 'application/x-www-form-urlencoded;charset=UTF-8'
59
- }
63
+ } )
60
64
} )
65
+
61
66
return response . status === 200
62
67
}
63
68
@@ -73,7 +78,12 @@ class API {
73
78
}
74
79
75
80
async logout ( ) {
76
- const response = await this . fetch ( `${ this . serverUrl } /logout` )
81
+ const response = await this . fetch ( `${ this . serverUrl } /logout` , {
82
+ method : this . enterprise ? 'POST' : 'GET' ,
83
+ headers : await this . wrapHeaders ( {
84
+ 'Content-Type' : 'application/x-www-form-urlencoded;charset=UTF-8' ,
85
+ } )
86
+ } )
77
87
return response . status === 200
78
88
}
79
89
@@ -149,6 +159,25 @@ class API {
149
159
get domain ( ) {
150
160
return url . parse ( this . serverUrl ) . host
151
161
}
162
+
163
+ private async wrapHeaders ( headers : any ) {
164
+ if ( this . enterprise ) {
165
+ const csrf = await this . loadCSRFToken ( )
166
+ return {
167
+ ...headers ,
168
+ 'X-XSRF-Token' : csrf
169
+ }
170
+ } else {
171
+ return headers
172
+ }
173
+ }
174
+
175
+ private async loadCSRFToken ( ) {
176
+ const html = await this . fetch ( `${ this . serverUrl } ` ) . then ( r => r . text ( ) )
177
+ const $ = cheerio . load ( html )
178
+
179
+ return $ ( 'meta[name="csrf-token"]' ) . attr ( 'content' ) || ''
180
+ }
152
181
}
153
182
154
183
export default API
0 commit comments