|
1
|
|
|
const requestify = require('requestify'); |
|
2
|
|
|
|
|
3
|
|
|
let getBaseUrl = (url) => { |
|
4
|
|
|
if (!url) { |
|
5
|
|
|
throw new Error('url not specified - can\'t get base url'); |
|
6
|
|
|
} |
|
7
|
|
|
let index = url.indexOf('rest/'); |
|
8
|
|
|
if (index === -1) { |
|
9
|
|
|
throw new Error('Invalid url (can\'t find \'rest/\' string) - can\'t get base url'); |
|
10
|
|
|
} |
|
11
|
|
|
let baseUrl = url.substr(0, index + 5); |
|
12
|
|
|
|
|
13
|
|
|
return baseUrl; |
|
14
|
|
|
}; |
|
15
|
|
|
|
|
16
|
|
|
let extractSessionCookie = (cookies, cookieName) => { |
|
17
|
|
|
if (!cookieName) { |
|
18
|
|
|
throw new Error('cookie name not specified - can\'t extract session cookie'); |
|
19
|
|
|
} |
|
20
|
|
|
if (!cookies) { |
|
21
|
|
|
throw new Error('cookies not specified - can\'t extract session cookie'); |
|
22
|
|
|
} |
|
23
|
|
|
if (!Array.isArray(cookies)) { |
|
24
|
|
|
throw new Error('cookies is not an array - can\'t extract session cookie'); |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
try { |
|
28
|
|
|
var sessionCookie = cookies.find((cookie) => { // eslint-disable-line no-var |
|
29
|
|
|
let name = cookie.split('=')[0]; |
|
30
|
|
|
let value = cookie.split('=')[1].split(';')[0]; |
|
31
|
|
|
return ((name === cookieName) && (value != '""')); |
|
32
|
|
|
}).split(';')[0]; |
|
33
|
|
|
} catch (error) { |
|
34
|
|
|
throw new Error('cookie name not found in cookies - can\'t extract session cookie'); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
return sessionCookie; |
|
38
|
|
|
}; |
|
39
|
|
|
|
|
40
|
|
|
module.exports = { |
|
41
|
|
|
login: (userName, password, url) => new Promise((resolve, reject) => { |
|
42
|
|
|
try { |
|
43
|
|
|
let loginUrl = getBaseUrl(url) + 'auth/1/session'; |
|
44
|
|
|
let body = {'username': userName, 'password': password}; |
|
45
|
|
|
let options = { |
|
46
|
|
|
cache: { |
|
47
|
|
|
cache: false, |
|
48
|
|
|
}, |
|
49
|
|
|
}; |
|
50
|
|
|
|
|
51
|
|
|
requestify.post(loginUrl, body, options) |
|
52
|
|
|
.then((response) => { |
|
53
|
|
|
resolve(extractSessionCookie(response.headers['set-cookie'], JSON.parse(response.body).session.name)); |
|
54
|
|
|
}) |
|
55
|
|
|
.catch((error) => { |
|
56
|
|
|
reject(new Error('Can\'t get cookie [' + error.message + ']')); |
|
57
|
|
|
}); |
|
58
|
|
|
} catch (error) { |
|
59
|
|
|
reject(new Error('Can\'t get cookie [' + error.message + ']')); |
|
60
|
|
|
} |
|
61
|
|
|
}), |
|
62
|
|
|
getHeader: (sessionCookie) => { |
|
63
|
|
|
return {'cookie': sessionCookie, 'Cache-Control': 'public, max-age=60'}; |
|
64
|
|
|
}, |
|
65
|
|
|
}; |
|
66
|
|
|
|