2016-10-02 20:57:00 +00:00
|
|
|
import {CookieJar} from 'tough-cookie';
|
2016-08-15 17:04:36 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Get a list of cookie objects from a request.jar()
|
|
|
|
*
|
2016-09-03 04:32:45 +00:00
|
|
|
* @param jar
|
2016-08-15 17:04:36 +00:00
|
|
|
*/
|
2016-10-02 20:57:00 +00:00
|
|
|
export function cookiesFromJar (jar) {
|
2016-08-15 17:04:36 +00:00
|
|
|
return new Promise(resolve => {
|
2016-10-05 04:43:48 +00:00
|
|
|
jar.store.getAllCookies((err, cookies) => {
|
2016-08-15 17:04:36 +00:00
|
|
|
if (err) {
|
|
|
|
console.warn('Failed to get cookies form jar', err);
|
|
|
|
resolve([]);
|
|
|
|
} else {
|
|
|
|
resolve(cookies);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
});
|
2016-10-02 20:57:00 +00:00
|
|
|
}
|
2016-08-15 17:04:36 +00:00
|
|
|
|
2016-10-05 04:43:48 +00:00
|
|
|
/**
|
|
|
|
* Get cookies header
|
|
|
|
* @param jar
|
|
|
|
* @param uri
|
|
|
|
* @returns {Promise}
|
|
|
|
*/
|
|
|
|
export function cookieHeaderValueForUri (jar, uri) {
|
2016-11-10 09:00:29 +00:00
|
|
|
return new Promise(resolve => {
|
2016-10-05 04:43:48 +00:00
|
|
|
jar.getCookies(uri, (err, cookies) => {
|
2016-11-10 09:00:29 +00:00
|
|
|
cookies = err ? [] : cookies;
|
|
|
|
resolve(cookies.map(c => c.cookieString()).join('; '));
|
2017-03-03 20:09:08 +00:00
|
|
|
});
|
|
|
|
});
|
2016-10-05 04:43:48 +00:00
|
|
|
}
|
|
|
|
|
2016-08-15 17:04:36 +00:00
|
|
|
/**
|
|
|
|
* Get a request.jar() from a list of cookie objects
|
|
|
|
*
|
|
|
|
* @param cookies
|
|
|
|
*/
|
2016-10-02 20:57:00 +00:00
|
|
|
export function jarFromCookies (cookies) {
|
2016-10-06 16:52:26 +00:00
|
|
|
let jar;
|
|
|
|
|
2016-08-15 17:04:36 +00:00
|
|
|
try {
|
2016-10-05 05:10:48 +00:00
|
|
|
// For some reason, fromJSON modifies `cookies`. Create a copy first
|
|
|
|
// just to be sure
|
|
|
|
const copy = JSON.stringify({cookies});
|
2016-10-06 16:52:26 +00:00
|
|
|
jar = CookieJar.fromJSON(copy);
|
2016-08-15 17:04:36 +00:00
|
|
|
} catch (e) {
|
|
|
|
console.log('Failed to initialize cookie jar', e);
|
2016-10-06 16:52:26 +00:00
|
|
|
jar = new CookieJar();
|
2016-08-15 17:04:36 +00:00
|
|
|
}
|
2016-10-06 16:52:26 +00:00
|
|
|
|
|
|
|
jar.rejectPublicSuffixes = false;
|
|
|
|
jar.looseMode = true;
|
|
|
|
|
2017-03-03 20:09:08 +00:00
|
|
|
return jar;
|
2016-10-02 20:57:00 +00:00
|
|
|
}
|
2016-08-15 17:04:36 +00:00
|
|
|
|
2016-10-02 20:57:00 +00:00
|
|
|
export function cookieToString (cookie) {
|
2016-12-08 18:19:18 +00:00
|
|
|
let str = cookie.toString();
|
2016-08-15 17:04:36 +00:00
|
|
|
|
|
|
|
// tough-cookie toString() doesn't put domain on all the time.
|
|
|
|
// This hack adds when tough-cookie won't
|
|
|
|
if (cookie.domain && cookie.hostOnly) {
|
|
|
|
str += '; Domain=' + cookie.domain;
|
|
|
|
}
|
|
|
|
|
|
|
|
return str;
|
2016-10-02 20:57:00 +00:00
|
|
|
}
|