How to use the superagent.agent function in superagent

To help you get started, we’ve selected a few superagent 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 tmrowco / tmrowapp-contrib / integrations / transportation / rejsekort.js View on Github external
import { ACTIVITY_TYPE_TRANSPORTATION, TRANSPORTATION_MODE_PUBLIC_TRANSPORT } from '../../definitions';

/*
Potential improvements:
- only refetch items since last fetch.
*/

// Urls for requests
const LOGIN_URL = 'https://selvbetjening.rejsekort.dk/CWS/Home/UserNameLogin';
const LOGIN_FORM_URL = 'https://selvbetjening.rejsekort.dk/CWS/Home/Index';
const TRAVELS_URL = 'https://selvbetjening.rejsekort.dk/CWS/TransactionServices/TravelCardHistory';
const TRAVELS_FORM_URL = 'https://selvbetjening.rejsekort.dk/CWS/TransactionServices/TravelCardHistory';

// Create an agent that can hold cookies
const agent = request.agent();

function extractRequestToken(text) {
  const tokenString = text.match(/antiForgeryToken = '<input length="" name="__RequestVerificationToken.*/)[0];
  const value = tokenString.match(/value="> 92 which indicates a problem
github tmrowco / tmrowapp-contrib / integrations / transportation / ryanair.js View on Github external
import moment from 'moment';
import request from 'superagent';
import { ACTIVITY_TYPE_TRANSPORTATION, TRANSPORTATION_MODE_PLANE } from '../../definitions';
import { HTTPError, AuthenticationError } from '../utils/errors';

const agent = request.agent();
const BASE_URL = 'https://api.ryanair.com/userprofile/rest/api/v1/';
const LOGIN_URL = `${BASE_URL}login`;
const PROFILE_URL = `${BASE_URL}secure/users/`;
// user info available at `${PROFILE_URL}${customerId}/profile/full/`

async function logIn(username, password) {
  const res = await agent
    .post(LOGIN_URL)
    .type('application/x-www-form-urlencoded')
    .send({
      password,
      username,
    });

  if (!res.ok) {
    throw new HTTPError(res.text, res.status);
github mendersoftware / gui / src / js / api / general-api.js View on Github external
import Cookies from 'universal-cookie';
import { unauthorizedRedirect } from '../auth';
const cookies = new Cookies();
var request = require('superagent')
  .agent()
  .use(unauthorizedRedirect);

const Api = {
  get: url => {
    var token = cookies.get('JWT');
    return new Promise((resolve, reject) => {
      request
        .get(url)
        .auth(token, { type: 'bearer' })
        .timeout({
          response: 10000, // wait 10 seconds for server to start sending
          deadline: 60000 // allow one minute to finish loading
        })
        .end((err, res) => {
          if (err || !res.ok) {
github RebootJeff / phone-tag / test / integration / routeSpec.js View on Github external
describe('Any users', function(){
    var agent = superagent.agent();

    it('should NOT be able to visit / route', function(done){
      agent.get('http://localhost:3000')
      .end(function(err, res){
        expect(err).not.exist;
        res.status.should.eql(200);
        res.redirects.should.eql([ 'http://localhost:3000/login' ]);
        done();
      });
    });

    it('should be able to visit /login route', function(done){
      agent.get('http://localhost:3000/login')
      .end(function(err, res){
        expect(err).not.exist;
        res.status.should.eql(200);
github hellgrenj / hulken / hulken.js View on Github external
function prepareHulkenAgents() {
  for (var i = 0; i &lt; hulken.settings.numberOfHulkenAgents; i++) {
    var agent = superAgent.agent();
    agent.id = (i + 1);
    hulken.agents.push(agent);
  }
}
github Andro999b / torrent-player / server / service / extractVideo / streamguardExtractor.js View on Github external
module.exports = async ({ url, referer }, res) => {
    let targetUrl

    if(url.startsWith('https://edge')) {
        targetUrl = url
    } else {
        const agent = superagent.agent()
        const iframeRes = await agent
            .get(url)
            .set({
                'Referer': referer
            })

        const matches = iframeRes.text.match(/var video_balancer_options = ([^;]+);/)
        const options = JSON.parse(toJson(matches[1]))

        const USER_AGENT = 'Mozilla/5.0 Gecko/20100101 Firefox/59.0'
        const item = {
            a : options.partner_id,
            b : options.domain_id,
            c : false,
            d : options.player_skin,
            e : options.video_token,
github tmrowco / tmrowapp-contrib / integrations / purchase / nordic-api-gateway.js View on Github external
import { HTTPError, AuthenticationError } from '../utils/errors';

import env from '../loadEnv';
import { getCallbackUrl } from '../utils/oauth';

const baseUrl = 'https://api.nordicapigateway.com';
const initializeUrl = `${baseUrl}/v1/authentication/initialize`;
const tokenUrl = `${baseUrl}/v1/authentication/tokens`;
const unattendedUrl = `${baseUrl}/v1/authentication/unattended`;
const accountInfoUrl = `${baseUrl}/v2/accounts`;
const providerInfoUrl = `${baseUrl}/v1/providers/{providerId}`;
const transactionsUrl = `${baseUrl}/v2/accounts/{accountId}/transactions`;
const categoriesUrl = `${baseUrl}/v1/category-sets/DK/categories`;


const agent = request.agent();
agent.set('X-Client-Id', env.NAG_CLIENT_ID).set('X-Client-Secret', env.NAG_CLIENT_SECRET).set('Accept-Language', 'en');

const NAG_CATEGORY = {
  Supermarket: { purchaseType: PURCHASE_CATEGORY_FOOD_SUPERMARKET, activityType: ACTIVITY_TYPE_PURCHASE },
  'Remodeling & Repair': { purchaseType: PURCHASE_CATEGORY_STORE_DEPARTMENT, activityType: ACTIVITY_TYPE_PURCHASE },
  'Food & Drinks': { activityType: ACTIVITY_TYPE_MEAL },
  Transfer: null,
  'Shared Expense': null,
  Exclude: null,
  'Pension Payout': null,
  'Unemployment Benefits': null,
  'Student Grant': null,
  'Child Benefits': null,
  'Alimony & Child Support': null,
  'Holiday Pay': null,
  Income: null,
github BitMEX / api-connectors / clients / javascript / src / ApiClient.js View on Github external
*/
        this.cache = true;

        /**
         * If set to true, the client will save the cookies from each server
         * response, and return them in the next request.
         * @default false
         */
        this.enableCookies = false;

        /*
         * Used to save and return cookies in a node.js (non-browser) setting,
         * if this.enableCookies is set to true.
         */
        if (typeof window === 'undefined') {
          this.agent = new superagent.agent();
        }
    }
github rcos / observatory-server / server / auth / util.integration.js View on Github external
return new Promise((resolve, reject) => {
    let agent = superagent.agent();
    agent
      .post('http://127.0.0.1:9000/auth/local')
      .send(authInfo)
      .end((err, res) => {
          if (err) return reject(err);
          let creds = {
              token: res.body.token,
              cookie: res.headers['set-cookie']
          };
          resolve({
            get: function() {
              return wrapAuth(creds, request(app).get.apply(this, arguments));
            },
            post: function() {
              return wrapAuth(creds, request(app).post.apply(this, arguments));
            },
github Midburn / spark / libs / drupal_access.js View on Github external
return new Promise((resolve, reject) => {
            if (request_agent && !forceLogin) {
                resolve({ request_agent })
            } else {
                request_agent = request.agent();
                request_agent
                    .post(drupalConfig.url + '/api/user/login')
                    .accept('application/json')
                    .set('Content-Type', 'application/x-www-form-urlencoded')
                    .send({ 'username': drupalConfig.username, 'password': drupalConfig.password })
                    .then((res) => {
                        resolve({ request_agent });
                    }).catch((err) => {
                        request_agent = false;
                        reject(err)
                    });
            }
        });
    };