2017-11-26 20:45:40 +00:00
|
|
|
const {CookieJar, Cookie} = require('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
|
|
|
*/
|
2017-11-26 20:45:40 +00:00
|
|
|
module.exports.cookiesFromJar = function (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 {
|
2017-11-03 18:32:22 +00:00
|
|
|
// NOTE: Perform toJSON so we have a plain JS object instead of Cookie instance
|
2017-10-16 21:09:42 +00:00
|
|
|
resolve(cookies.map(c => c.toJSON()));
|
2016-08-15 17:04:36 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
});
|
2017-11-26 20:45:40 +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
|
|
|
|
*/
|
2017-11-26 20:45:40 +00:00
|
|
|
module.exports.jarFromCookies = function (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) {
|
2017-11-18 22:47:54 +00:00
|
|
|
console.log('[cookies] 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;
|
2017-11-26 20:45:40 +00:00
|
|
|
};
|
2016-08-15 17:04:36 +00:00
|
|
|
|
2017-11-26 20:45:40 +00:00
|
|
|
module.exports.cookieToString = function (cookie) {
|
2017-10-16 22:19:16 +00:00
|
|
|
// Cookie can either be a plain JS object or Cookie instance
|
|
|
|
if (!(cookie instanceof Cookie)) {
|
|
|
|
cookie = Cookie.fromJSON(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;
|
2017-11-26 20:45:40 +00:00
|
|
|
};
|
|
|
|
|