Internal: Faraday connection to use when sending an authentication request.
179210
def connection
      @connection ||= Faraday.new(faraday_options) do |builder|
        builder.use Faraday::Request::UrlEncoded
        builder.use Restforce::Middleware::Mashify, nil, @options
        builder.response :json

        if Restforce.log?
          builder.use Restforce::Middleware::Logger,
                      Restforce.configuration.logger,
                      @options
        end

        builder.adapter @options[:adapter]
      end
    end
852690
def connection
      @connection ||= Faraday.new(base_url, :builder_class => Saddle::RackBuilder) do |connection|
        # Include the requester level options
        connection.builder.saddle_options[:client_options] = @options

        # Config options
        connection.options[:timeout] = @timeout
        connection.builder.saddle_options[:request_style] = @request_style
        connection.builder.saddle_options[:num_retries] = @num_retries
        connection.builder.saddle_options[:client] = @parent_client

        # Support default return values upon exception
        connection.use(Saddle::Middleware::Response::DefaultResponse)

        # Hard timeout on the entire request
        connection.use(Saddle::Middleware::RubyTimeout)

        # Set up a user agent
        connection.use(Saddle::Middleware::Request::UserAgent)

        # Set up the path prefix if needed
        connection.use(Saddle::Middleware::Request::PathPrefix)

        # Apply additional implementation-specific middlewares
        @additional_middlewares.each do |m|
          m[:args] ? connection.use(m[:klass], *m[:args]) : connection.use(m[:klass])
        end

        # Request encoding
        connection.use(Saddle::Middleware::Request::JsonEncoded)
        connection.use(Saddle::Middleware::Request::UrlEncoded)

        # Automatic retries
        connection.use(Saddle::Middleware::Request::Retry)

        # Raise exceptions on 4xx and 5xx errors
        connection.use(Saddle::Middleware::Response::RaiseError)

        # Handle parsing out the response if it's JSON
        connection.use(Saddle::Middleware::Response::ParseJson)

        # Set up instrumentation around the adapter for extensibility
        connection.use(FaradayMiddleware::Instrumentation)

        # Add in extra env data if needed
        connection.use(Saddle::Middleware::ExtraEnv)

        # Set up our adapter
        if @stubs.nil?
          # Use the default adapter
          connection.adapter(@http_adapter[:key], *@http_adapter[:args])
        else
          # Use the test adapter
          connection.adapter(:test, @stubs)
        end
      end
    end
1324710
def connection
      options = { url: api_url, ssl: { verify: false } }

      connection = Faraday.new(options) do |conn|
        conn.response :readmill_errors
        conn.response :mashify
        conn.response :json

        conn.adapter  adapter
      end

      connection
    end
110111
def connection options = {}
      the_options = {
        :headers => {
          "Accept" => "application/json",
          "User-Agent" => Oembedr.user_agent
        },
        :url => parsed_url.host
      }.merge(options)

      Faraday.new(the_options) do |builder|
        builder.use Faraday::Request::UrlEncoded
        builder.use Faraday::Response::ParseJson
        builder.use Faraday::Response::RaiseError
        builder.use FaradayMiddleware::FollowRedirects
        builder.adapter Oembedr.adapter
      end
    end
596166
async def do_authentication(sender):
    
    # Step 1 sending: PQ Request, endianness doesn't matter since it's random
    nonce = int.from_bytes(os.urandom(16), 'big', signed=True)
    res_pq = await sender.send(ReqPqMultiRequest(nonce))
    assert isinstance(res_pq, ResPQ), 'Step 1 answer was %s' % res_pq

    if res_pq.nonce != nonce:
        raise SecurityError('Step 1 invalid nonce from server')

    pq = get_int(res_pq.pq)

    # Step 2 sending: DH Exchange
    p, q = Factorization.factorize(pq)
    p, q = rsa.get_byte_array(p), rsa.get_byte_array(q)
    new_nonce = int.from_bytes(os.urandom(32), 'little', signed=True)

    pq_inner_data = bytes(PQInnerData(
        pq=rsa.get_byte_array(pq), p=p, q=q,
        nonce=res_pq.nonce,
        server_nonce=res_pq.server_nonce,
        new_nonce=new_nonce
    ))

    # sha_digest + data + random_bytes
    cipher_text, target_fingerprint = None, None
    for fingerprint in res_pq.server_public_key_fingerprints:
        cipher_text = rsa.encrypt(fingerprint, pq_inner_data)
        if cipher_text is not None:
            target_fingerprint = fingerprint
            break

    if cipher_text is None:
        raise SecurityError(
            'Step 2 could not find a valid key for fingerprints: {}'
            .format(', '.join(
                [str(f) for f in res_pq.server_public_key_fingerprints])
            )
        )

    server_dh_params = await sender.send(ReqDHParamsRequest(
        nonce=res_pq.nonce,
        server_nonce=res_pq.server_nonce,
        p=p, q=q,
        public_key_fingerprint=target_fingerprint,
        encrypted_data=cipher_text
    ))

    assert isinstance(
        server_dh_params, (ServerDHParamsOk, ServerDHParamsFail)),\
        'Step 2.1 answer was %s' % server_dh_params

    if server_dh_params.nonce != res_pq.nonce:
        raise SecurityError('Step 2 invalid nonce from server')

    if server_dh_params.server_nonce != res_pq.server_nonce:
        raise SecurityError('Step 2 invalid server nonce from server')

    if isinstance(server_dh_params, ServerDHParamsFail):
        nnh = int.from_bytes(
            sha1(new_nonce.to_bytes(32, 'little', signed=True)).digest()[4:20],
            'little', signed=True
        )
        if server_dh_params.new_nonce_hash != nnh:
            raise SecurityError('Step 2 invalid DH fail nonce from server')

    assert isinstance(server_dh_params, ServerDHParamsOk),\
        'Step 2.2 answer was %s' % server_dh_params

    # Step 3 sending: Complete DH Exchange
    key, iv = helpers.generate_key_data_from_nonce(
        res_pq.server_nonce, new_nonce
    )
    if len(server_dh_params.encrypted_answer) % 16 != 0:
        # See PR#453
        raise SecurityError('Step 3 AES block size mismatch')

    plain_text_answer = AES.decrypt_ige(
        server_dh_params.encrypted_answer, key, iv
    )

    with BinaryReader(plain_text_answer) as reader:
        reader.read(20)  # hash sum
        server_dh_inner = reader.tgread_object()
        assert isinstance(server_dh_inner, ServerDHInnerData),\
            'Step 3 answer was %s' % server_dh_inner

    if server_dh_inner.nonce != res_pq.nonce:
        raise SecurityError('Step 3 Invalid nonce in encrypted answer')

    if server_dh_inner.server_nonce != res_pq.server_nonce:
        raise SecurityError('Step 3 Invalid server nonce in encrypted answer')

    dh_prime = get_int(server_dh_inner.dh_prime, signed=False)
    g_a = get_int(server_dh_inner.g_a, signed=False)
    time_offset = server_dh_inner.server_time - int(time.time())

    b = get_int(os.urandom(256), signed=False)
    gb = pow(server_dh_inner.g, b, dh_prime)
    gab = pow(g_a, b, dh_prime)

    # Prepare client DH Inner Data
    client_dh_inner = bytes(ClientDHInnerData(
        nonce=res_pq.nonce,
        server_nonce=res_pq.server_nonce,
        retry_id=0,  # TODO Actual retry ID
        g_b=rsa.get_byte_array(gb)
    ))

    client_dh_inner_hashed = sha1(client_dh_inner).digest() + client_dh_inner

    # Encryption
    client_dh_encrypted = AES.encrypt_ige(client_dh_inner_hashed, key, iv)

    # Prepare Set client DH params
    dh_gen = await sender.send(SetClientDHParamsRequest(
        nonce=res_pq.nonce,
        server_nonce=res_pq.server_nonce,
        encrypted_data=client_dh_encrypted,
    ))

    nonce_types = (DhGenOk, DhGenRetry, DhGenFail)
    assert isinstance(dh_gen, nonce_types), 'Step 3.1 answer was %s' % dh_gen
    name = dh_gen.__class__.__name__
    if dh_gen.nonce != res_pq.nonce:
        raise SecurityError('Step 3 invalid {} nonce from server'.format(name))

    if dh_gen.server_nonce != res_pq.server_nonce:
        raise SecurityError(
            'Step 3 invalid {} server nonce from server'.format(name))

    auth_key = AuthKey(rsa.get_byte_array(gab))
    nonce_number = 1 + nonce_types.index(type(dh_gen))
    new_nonce_hash = auth_key.calc_new_nonce_hash(new_nonce, nonce_number)

    dh_hash = getattr(dh_gen, 'new_nonce_hash{}'.format(nonce_number))
    if dh_hash != new_nonce_hash:
        raise SecurityError('Step 3 invalid new nonce hash')

    if not isinstance(dh_gen, DhGenOk):
        raise AssertionError('Step 3.2 answer was %s' % dh_gen)

    return auth_key, time_offset
1238261
def call(request_env)
      request_body = request_env[:body]

      begin
        request_env[:body] = request_body

        @app.call(request_env).on_complete do |response_env|
          status_code = response_env.status

          if @times > 0 && (status_code == 408 || (status_code >= 500 && status_code != 501 && status_code != 505))
            sleep @delay
            fail 'faraday_retry'
          end
        end
      rescue Exception => e
        raise e if e.message != 'faraday_retry'
        @times = @times - 1
        retry
      end
    end
363325
def client
      Faraday.new(url: address) do |conn|
        conn.request :json
        conn.response :json, content_type: /\bjson$/
        conn.adapter Faraday.default_adapter # make requests with Net::HTTP
      end
    end
1095661
def do_request(method, path, obj = nil, options = {})
      # hatt clients pass in path possibly including query params.
      # Faraday needs the query and path seperately.
      parsed_uri = URI.parse make_path(path)
      # faraday needs the request params as a hash.
      # this turns out to be non-trivial
      query_hash = if parsed_uri.query
                     cgi_hash = CGI.parse(parsed_uri.query)
                     # this next line accounts for one param having multiple values
                     cgi_hash.each_with_object({}) { |(k, v), h| h[k] = v[1] ? v : v.first; }
                   end

      req_headers = make_headers(options)

      body = if options[:form]
               URI.encode_www_form obj
             else
               jsonify(obj)
      end


      log_request(method, parsed_uri, query_hash, req_headers, body)

      # doing it this way avoids problem with OPTIONS method: https://github.com/lostisland/faraday/issues/305
      response = nil
      metrics_obj = { method: method, service: @name, path: parsed_uri.path }
      ActiveSupport::Notifications.instrument('request.hatt', metrics_obj) do
        response = @faraday_connection.run_request(method, nil, nil, nil) do |req|
          req.path = parsed_uri.path
          req.params = metrics_obj[:params] = query_hash if query_hash

          req.headers = req_headers
          req.body = body
          req.options[:timeout] = options.fetch(:timeout, @default_timeout)
        end
        metrics_obj[:response] = response
      end

      logger.info "Request status: (#{response.status}) #{@name}: #{method.to_s.upcase} #{path}"
      @last_request = {
        method: method,
        path: parsed_uri.path,
        query: parsed_uri.query,
        headers: req_headers,
        body: body
      }
      @last_response = response

      response_obj = objectify response.body

      log_response(response, response_obj)

      raise RequestException.new(nil, response) unless response.status >= 200 && response.status < 300

      response_obj
    end
834246
function authenticateClient (req, res, next) {
  Client.authenticate(req, function (err, client) {
    if (err) { return next(err) }
    req.client = client
    next()
  })
}
732155
def connection
      @connection ||= begin
        conn = Faraday.new(site, options[:connection_opts])
        conn.build do |b|
          options[:connection_build].call(b)
        end if options[:connection_build]
        conn
      end
    end
643066
def authentication(self):
        '''
        
        '''
        url = '%s/authentication' % (self.domain)
        res = self.session.get(url)
        self._check_response(res)
        return res.json()
1054092
public function connectAndAuthenticate() {
		// 1. connect
		if (!$this->isConnected()) {
			$this->connect();
		}
		$this->hello();
		
		// 2. open tls connection if needed
		$securityMode = $this->config->getSecurityMode();
		if ($securityMode == SmtpConfig::SECURITY_MODE_TLS) {
			$this->startTls();
			$this->hello();
		}
		
		// 3. authenticat if needed
		if ($this->config->doAuthenticate()) {
			$this->authenticate();
		}
	}
744653
def get_request(self, request):
        """"""
        request.headers['authenticate'] = {
            'complexType': 'PortalLoginToken',
            'userId': self.user_id,
            'authToken': self.auth_token,
        }
        return request
176841
def client
      Faraday.new(url: Wanikani::API_ENDPOINT) do |conn|
        conn.response :json, :content_type => /\bjson$/
        conn.adapter Faraday.default_adapter
      end
    end
1264838
def get_connection(service, module=None, region=None, key=None, keyid=None,
                   profile=None):
    '''
    
    '''

    # future lint: disable=blacklisted-function
    module = str(module or service)
    module, submodule = (str('boto.') + module).rsplit(str('.'), 1)
    # future lint: enable=blacklisted-function

    svc_mod = getattr(__import__(module, fromlist=[submodule]), submodule)

    cxkey, region, key, keyid = _get_profile(service, region, key,
                                             keyid, profile)
    cxkey = cxkey + ':conn'

    if cxkey in __context__:
        return __context__[cxkey]

    try:
        conn = svc_mod.connect_to_region(region, aws_access_key_id=keyid,
                                         aws_secret_access_key=key)
        if conn is None:
            raise SaltInvocationError('Region "{0}" is not '
                                      'valid.'.format(region))
    except boto.exception.NoAuthHandlerFound:
        raise SaltInvocationError('No authentication credentials found when '
                                  'attempting to make boto {0} connection to '
                                  'region "{1}".'.format(service, region))
    __context__[cxkey] = conn
    return conn
172043
def authenticate(self):
        """"""
        try:
            payload = self._api.domain.info(self._api_key, self._domain)
            self._zone_id = payload['zone_id']
            return payload['id']
        except xmlrpclib.Fault as err:
            raise Exception("Failed to authenticate: '{0}'".format(err))
398611
def request(self, verb, subpath, data=''):
        
        if not self.api_key or not self.api_secret:
            raise Exception("Vingd authentication credentials undefined.")
        
        endpoint = urlparse(self.api_endpoint)
        if endpoint.scheme != 'https':
            raise Exception("Invalid Vingd endpoint URL (non-https).")
        
        host = endpoint.netloc.split(':')[0]
        port = 443
        path = urljoin(endpoint.path+'/', subpath)
        
        creds = "%s:%s" % (self.api_key, self.api_secret)
        headers = {
            'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')),
            'User-Agent': self.USER_AGENT
        }
        try:
            conn = httplib.HTTPSConnection(host, port)
            conn.request(verb.upper(), quote(path), data, headers)
            r = conn.getresponse()
            content = r.read().decode('ascii')
            code = r.status
            conn.close()
        except httplib.HTTPException as e:
            raise InternalError('HTTP request failed! (Network error? Installation error?)')
        
        try:
            content = json.loads(content)
        except:
            raise GeneralException(content, 'Non-JSON server response', code)
        
        if 200 <= code <= 299:
            try:
                return content['data']
            except:
                raise InvalidData('Invalid server DATA response format!')
        
        try:
            message = content['message']
            context = content['context']
        except:
            raise InvalidData('Invalid server ERROR response format!')
        
        if code == Codes.BAD_REQUEST:
            raise InvalidData(message, context)
        elif code == Codes.FORBIDDEN:
            raise Forbidden(message, context)
        elif code == Codes.NOT_FOUND:
            raise NotFound(message, context)
        elif code == Codes.INTERNAL_SERVER_ERROR:
            raise InternalError(message, context)
        elif code == Codes.CONFLICT:
            raise GeneralException(message, context)
        
        raise GeneralException(message, context, code)