How to use the tough-cookie.CookieJar function in tough-cookie

To help you get started, we’ve selected a few tough-cookie examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github 3846masa / axios-cookiejar-support / example / send-cookies.js View on Github external
'use strict';

const axios = require('axios').default;
const tough = require('tough-cookie');
const axiosCookieJarSupport = require('axios-cookiejar-support').default;

axiosCookieJarSupport(axios);

const cookieJar = new tough.CookieJar();
cookieJar.setCookieSync('key=value; domain=mockbin.org', 'https://mockbin.org');

axios
  .get('https://mockbin.org/request', {
    jar: cookieJar,
    withCredentials: true, // IMPORTANT!
  })
  .then((response) => {
    const data = response.data;
    console.log(data.headers.cookie);
  })
  .catch((err) => {
    console.error(err.stack || err);
  });
github coderafei / wechat-bot / weixinbot.js View on Github external
const axiosCookieJarSupport = require('node-axios-cookiejar');

const {
  getUrls, CODES, SP_ACCOUNTS, PUSH_HOST_LIST,
} = require('./conf');

Promise.promisifyAll(Datastore.prototype);
const debug = Debug('weixinbot');

let URLS = getUrls({});
const logo = fs.readFileSync(path.join(__dirname, 'logo.txt'), 'utf8');

// try persistent cookie
const cookiePath = path.join(process.cwd(), '.cookie.json');
touch.sync(cookiePath);
const jar = new tough.CookieJar(new FileCookieStore(cookiePath));

const req = axios.create({
  timeout: 35e3,
  headers: {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) ' +
      'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2652.0 Safari/537.36',
    'Referer': 'https://wx2.qq.com/',
  },
  jar,
  withCredentials: true,
  xsrfCookieName: null,
  xsrfHeaderName: null,
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),
});
github Azure / azure-sdk-for-js / sdk / core / core-http / lib / nodeFetchHttpClient.ts View on Github external
httpAgent?: http.Agent;
  httpsAgent?: https.Agent;
}

function getCachedAgent(
  isHttps: boolean,
  agentCache: AgentCache
): http.Agent | https.Agent | undefined {
  return isHttps ? agentCache.httpsAgent : agentCache.httpAgent;
}

export class NodeFetchHttpClient extends FetchHttpClient {
  private proxyAgents: AgentCache = {};
  private keepAliveAgents: AgentCache = {};

  private readonly cookieJar = new tough.CookieJar(undefined, { looseMode: true });

  private getOrCreateAgent(httpRequest: WebResource): http.Agent | https.Agent {
    const isHttps = isUrlHttps(httpRequest.url);

    // At the moment, proxy settings and keepAlive are mutually
    // exclusive because the 'tunnel' library currently lacks the
    // ability to create a proxy with keepAlive turned on.
    if (httpRequest.proxySettings) {
      let agent = getCachedAgent(isHttps, this.proxyAgents);
      if (agent) {
        return agent;
      }

      const tunnel: ProxyAgent = createProxyAgent(
        httpRequest.url,
        httpRequest.proxySettings,
github joyent / smartos-live / src / img / node_modules / docker-registry-client / lib / registry-client-v1.js View on Github external
if (opts.scheme) {
        this.repo.index.scheme = opts.scheme;
    } else if (common.isLocalhost(this.repo.index.name)) {
        // Per docker.git:registry/config.go#NewServiceConfig we special
        // case localhost to allow HTTP. Note that this lib doesn't do
        // the "try HTTPS, then fallback to HTTP if allowed" thing that
        // docker-docker does, we'll just prefer HTTP for localhost.
        this.repo.index.scheme = 'http';
    }

    if (opts.username && opts.password) {
        var buffer = new Buffer(opts.username + ':' + opts.password, 'utf8');
        this._authorization = 'Basic ' + buffer.toString('base64');
    }
    this._ensuredSession = false;
    this._cookieJar = new tough.CookieJar();

    this._indexUrl = common.urlFromIndex(this.repo.index);

    this._commonHttpClientOpts = {
        log: this.log,
        agent: opts.agent,
        proxy: opts.proxy,
        rejectUnauthorized: !this.insecure,
        userAgent: opts.userAgent || common.DEFAULT_USERAGENT
    };
    this._clientsToClose = [];

    Object.defineProperty(this, '_indexApi', {
        get: function () {
            if (self.__indexApi === undefined) {
                self.__indexApi = self._createClient('json', self._indexUrl);
github pmarkert / hyperpotamus / test / actions / cookies.js View on Github external
return result.then(() => {
					var jar = new tough.CookieJar(context.cookieStore());
					return Promise.promisify(jar.getCookieString, { context: jar })(url)
						.then(result => {
							assert.equal(result, expected);
						});
				});
			}
github serviejs / popsicle / src / jar.ts View on Github external
export default function cookieJar (store?: any) {
  return new CookieJar(store)
}
github dkarter / NetflixScraperAPI / index.js View on Github external
fs.readFile(cookieFile, function(error, data){
		if (error) throw error;
		var jar = new tough.CookieJar();

		var cookies = JSON.parse(data);
		
		for (var i = 0; i < cookies.length; i++) {
			cookies[i].key = cookies[i].name;
			cookies[i].domain = apiDomain;
			var cookie = tough.Cookie.fromJSON(JSON.stringify(cookies[i]));
			jar.store.putCookie(cookie, noop);
		}
		
		serveAPI(jar);
	});	
}
github autonomoussoftware / metronome-wallet-desktop / public / main / plugins / bloq-eth-explorer / index.js View on Github external
const { CookieJar } = require('tough-cookie')
const axios = require('axios')
const axiosCookieJarSupport = require('axios-cookiejar-support').default
const io = require('socket.io-client')
const logger = require('electron-log')

const createBasePlugin = require('../../base-plugin')

const { getIndexerApiUrl } = require('./settings')
const api = require('./api')

axiosCookieJarSupport(axios)

const baseURL = getIndexerApiUrl()

const jar = new CookieJar()

const setTimeoutAsync = timeout => new Promise(function (resolve) {
  setTimeout(resolve, timeout)
})

const getSocket = () =>
  axios.get(baseURL, { jar, withCredentials: true })
    .then(function () {
      return io(`${baseURL}/v1`, {
        autoConnect: false,
        extraHeaders: {
          Cookie: jar.getCookiesSync(baseURL).join(';')
        }
      })
    })
    .catch(function (err) {
github pmarkert / hyperpotamus / lib / actions / request.js View on Github external
function mergeRequestWithDefaults(request, request_defaults) {
	var result = {};
	var args = [result, hyperpotamus_defaults];
	var request_defaults_jar = new tough.CookieJar(request_defaults);
	var getCookies = Promise.promisify(request_defaults_jar.getCookies, { context: request_defaults_jar });
	return getCookies(request.url)
		.then(request_defaults => {
			args = args.concat(_.map(request_defaults, "value"));
			args.push(request);
			_.merge.apply(null, args);
			return result;
		});
}
github grantila / fetch-h2 / dist / lib / cookie-jar.js View on Github external
    constructor(jar = new tough_cookie_1.CookieJar()) {
        this.reset(jar);
    }
    reset(jar = new tough_cookie_1.CookieJar()) {