2018-07-12 18:29:03 +00:00
|
|
|
const { jarFromCookies } = require('insomnia-cookies');
|
|
|
|
|
|
|
|
module.exports.templateTags = [
|
|
|
|
{
|
2018-07-23 17:24:41 +00:00
|
|
|
name: 'cookie',
|
|
|
|
displayName: 'Cookie',
|
2018-07-12 18:29:03 +00:00
|
|
|
description: 'reference a cookie value from the cookie jar',
|
|
|
|
args: [
|
|
|
|
{
|
|
|
|
type: 'string',
|
2018-07-23 17:24:41 +00:00
|
|
|
displayName: 'Cookie Url',
|
2018-12-12 17:36:11 +00:00
|
|
|
description: 'fully qualified URL (e.g. https://domain.tld/path)',
|
2018-07-12 18:29:03 +00:00
|
|
|
},
|
|
|
|
{
|
|
|
|
type: 'string',
|
2018-12-12 17:36:11 +00:00
|
|
|
displayName: 'Cookie Name',
|
|
|
|
},
|
2018-07-12 18:29:03 +00:00
|
|
|
],
|
|
|
|
async run(context, url, name) {
|
|
|
|
const { meta } = context;
|
|
|
|
|
|
|
|
if (!meta.requestId || !meta.workspaceId) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2018-10-17 16:42:33 +00:00
|
|
|
const workspace = await context.util.models.workspace.getById(meta.workspaceId);
|
2018-07-12 18:29:03 +00:00
|
|
|
|
|
|
|
if (!workspace) {
|
|
|
|
throw new Error(`Workspace not found for ${meta.workspaceId}`);
|
|
|
|
}
|
|
|
|
|
2018-10-17 16:42:33 +00:00
|
|
|
const cookieJar = await context.util.models.cookieJar.getOrCreateForWorkspace(workspace);
|
2018-07-12 18:29:03 +00:00
|
|
|
|
2018-07-23 17:24:41 +00:00
|
|
|
return getCookieValue(cookieJar, url, name);
|
2018-12-12 17:36:11 +00:00
|
|
|
},
|
|
|
|
},
|
2018-07-12 18:29:03 +00:00
|
|
|
];
|
|
|
|
|
|
|
|
function getCookieValue(cookieJar, url, name) {
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
const jar = jarFromCookies(cookieJar.cookies);
|
|
|
|
|
|
|
|
jar.getCookies(url, {}, (err, cookies) => {
|
|
|
|
if (err) {
|
|
|
|
console.warn(`Failed to find cookie for ${url}`, err);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!cookies || cookies.length === 0) {
|
|
|
|
console.log(cookies);
|
|
|
|
reject(new Error(`No cookies in store for url "${url}"`));
|
|
|
|
}
|
|
|
|
|
|
|
|
const cookie = cookies.find(cookie => cookie.key === name);
|
|
|
|
if (!cookie) {
|
|
|
|
const names = cookies.map(c => `"${c.key}"`).join(',\n\t');
|
|
|
|
throw new Error(
|
2018-12-12 17:36:11 +00:00
|
|
|
`No cookie with name "${name}".\nChoices are [\n\t${names}\n] for url "${url}"`,
|
2018-07-12 18:29:03 +00:00
|
|
|
);
|
|
|
|
} else {
|
|
|
|
resolve(cookie ? cookie.value : null);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|