Generates an OAuth signature and updates the args with the required fields
 @param [String] method HTTP method that the request is sent as
 @param [String] uri Full URL of the request
 @param [Hash] form_args Args to be passed to the server
19765
def sign_request(method, uri, form_args)
      # Convert non-string keys to strings so the sort works
      args = {}
      if form_args
        form_args.each do |key, value|
          next unless value and value != ""

          key = key.to_s unless key.is_a?(String)
          args[key] = value
        end
      end

      # Add the necessary OAuth args
      args["oauth_version"] = "1.0"
      args["oauth_consumer_key"] = @config[:api_key]
      args["oauth_nonce"] = Digest::MD5.hexdigest("#{Time.now.to_f}#{rand(10 ** 30)}")
      args["oauth_signature_method"] = "HMAC-SHA1"
      args["oauth_timestamp"] = Time.now.utc.to_i
      args["oauth_token"] = @config[:user][:token]

      # RFC 1738 (http://www.ietf.org/rfc/rfc1738.txt) says:
      #
      #     Thus, only alphanumerics, the special characters "$-_.+!*'(),", and
      #     reserved characters used for their reserved purposes may be used
      #     unencoded within a URL.
      #
      # However, if we don't escape apostrophes and parentheses the SmugMug API fails
      # with an invalid signature error:
      #
      #     Error #35, invalid signature (SmugMug::OAuthError)
      #
      # To overcome this, define a new unreserved character list and use this in URI::escape
      unreserved = "\\-_.!~*a-zA-Z\\d"
      unsafe = Regexp.new("[^#{unreserved}]", false, 'N')

      # Sort the params
      sorted_args = []
      args.sort.each do |key, value|
        sorted_args.push("#{key.to_s}=#{URI::escape(value.to_s, unsafe)}")
      end

      postdata = sorted_args.join("&")

      # Final string to hash
      sig_base = "#{method}&#{URI::escape("#{uri.scheme}://#{uri.host}#{uri.path}", unsafe)}&#{URI::escape(postdata, unsafe)}"

      signature = OpenSSL::HMAC.digest(@digest, "#{@config[:oauth_secret]}&#{@config[:user][:secret]}", sig_base)
      signature = URI::escape(Base64.encode64(signature).chomp, unsafe)

      if uri == API_URI
        "#{postdata}&oauth_signature=#{signature}"
      else
        args["oauth_signature"] = signature
        args
      end
    end
192865
def plaintext(method, options = {})
      bootstrap = form_bootstrap.scoped(options.delete(:bootstrap))
      draw_form_group(bootstrap, method, options) do
        remove_css_class!(options, "form-control")
        add_css_class!(options, "form-control-plaintext")
        options[:readonly] = true
        ActionView::Helpers::FormBuilder.instance_method(:text_field).bind(self).call(method, options)
      end
    end
98855
def request(method, path, opts = {})
      raise ClientError, 'Access token missing' unless @access_token

      opts[:headers] = {} if opts[:headers].nil?
      opts[:headers]['Accept'] = 'application/json'
      opts[:headers]['Content-Type'] = 'application/json' unless method == :get
      opts[:headers]['User-Agent'] = user_agent
      opts[:body] = MultiJson.encode(opts[:data]) if !opts[:data].nil?
      path = URI.encode(path)

      # Reset the URL in case the environment / base URL has been changed.
      @oauth_client.site = base_url

      header_keys = opts[:headers].keys.map(&:to_s)
      if header_keys.map(&:downcase).include?('authorization')
        @oauth_client.request(method, path, opts)
      else
        @access_token.send(method, path, opts)
      end
    rescue OAuth2::Error => err
      raise GoCardless::ApiError.new(err.response)
    end
263461
def create_http_request(http_method, path, *arguments)
        http_method = http_method.to_sym

        if [:post, :put].include?(http_method)
          data = arguments.shift
        end

        headers = arguments.first.is_a?(Hash) ? arguments.shift : {}

        case http_method
        when :post
          request = Net::HTTP::Post.new(path,headers)
          request["Content-Length"] = 0 # Default to 0
        when :put
          request = Net::HTTP::Put.new(path,headers)
          request["Content-Length"] = 0 # Default to 0
        when :get
          request = Net::HTTP::Get.new(path,headers)
        when :delete
          request =  Net::HTTP::Delete.new(path,headers)
        else
          raise ArgumentError, "Don't know how to handle http_method: :#{http_method.to_s}"
        end
      
        # handling basic http auth
        request.basic_auth @config[:username], @config[:password]

        if data.is_a?(Hash)
          request.set_form_data(data)
        elsif data
          request.body = data.to_s
          request["Content-Length"] = request.body.length
        end

        request
      end
1327785
public static function from_request($http_method = null, $http_url = null, $parameters = null) {
        $scheme = (!is_https()) ? 'http' : 'https';
        $port = "";
        if ($_SERVER['SERVER_PORT'] != "80" && $_SERVER['SERVER_PORT'] != "443" && strpos(':', $_SERVER['HTTP_HOST']) < 0) {
            $port = ':' . $_SERVER['SERVER_PORT'];
        }
        @$http_url or $http_url = $scheme .
        '://' . $_SERVER['HTTP_HOST'] .
        $port .
        $_SERVER['REQUEST_URI'];
        @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];

        // We weren't handed any parameters, so let's find the ones relevant to
        // this request.
        // If you run XML-RPC or similar you should use this to provide your own
        // parsed parameter-list
        if (!$parameters) {
            // Find request headers
            $request_headers = OAuthUtil::get_headers();

            // Parse the query-string to find GET parameters
            $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);

            $ourpost = $_POST;
            // Add POST Parameters if they exist
            $parameters = array_merge($parameters, $ourpost);

            // We have a Authorization-header with OAuth data. Parse the header
            // and add those overriding any duplicates from GET or POST
            if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
                $header_parameters = OAuthUtil::split_header($request_headers['Authorization']);
                $parameters = array_merge($parameters, $header_parameters);
            }

        }

        return new OAuthRequest($http_method, $http_url, $parameters);
    }
215365
public function form($method='request',array $args=null) {
        $method = $method === 'auto'?strtolower($this->method()):$method;
        $input = [];
        switch ($method) {
            case 'request':
                $input = $this->request;
                break;
            case 'post':
                $input = $this->post;
                break;
            case 'get':
                $input = $this->get;
                break;
            case 'request':
                $input = $this->request;
                break;
            case 'input':
                $input = $this->input;
                break;
            case 'put':
                parse_str($this->input, $input);
                break;
            case 'files':
                $input = $this->files;
                break;
            case 'server':
                $input = $this->server;
                break;
        }
        if($args) {
            $_input = [];
            foreach ($args as $arg) {
                $_input[$arg] = isset($input[$arg])?$input[$arg]:null;
            }
            $input = $_input;
        }
        return $input;
    }
336415
def method_missing(method, *args)
      unless args.size == 1 && [Hash, Array].include?(args[0].class)
        raise 'Expected 1 Hash or Array argument'
      end

      call_remote method, args[0]
    end
259657
function(uri, method, form) {
  this.method = method = method || 'GET';
  this.headers = {};
  this.url = uri;
  this.pathname = uri;
  this.cookies = {};
  this.params = [];

  if (document.cookie) {
    this.headers['Cookie'] = document.cookie;
    this.cookies = DOM.getCookies();
  }

  if (form) {
    var serial = DOM.serialize(form) || {};
    this.headers['Content-Type'] =
      form.enctype || 'application/x-www-form-urlencoded';
    if (method === 'GET') {
      this.query = serial.data;
      this.rawQuery = serial.encoded;
    } else {
      this.body = serial.data;
      this.rawBody = serial.encoded;
    }
    // method override
    if (serial.data & serial.data._method) {
      this.method = method = serial.data._method.toUpperCase();
    }
  }

  if (~uri.indexOf('?')) {
    uri = uri.split('?');
    this.query = parsePairs(uri[1], '&');
    this.rawQuery = uri[1];
    this.pathname = uri = uri[0];
  }
}
107271
def sign_request(self, signature_method, consumer, token):
        """"""

        if not self.is_form_encoded:
            # according to
            # http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html
            # section 4.1.1 "OAuth Consumers MUST NOT include an
            # oauth_body_hash parameter on requests with form-encoded
            # request bodies."
            if not self.body:
               self.body = ''
            self['oauth_body_hash'] = base64.b64encode(sha1(to_utf8(self.body)).digest())

        if 'oauth_consumer_key' not in self:
            self['oauth_consumer_key'] = consumer.key

        if token and 'oauth_token' not in self:
            self['oauth_token'] = token.key

        self['oauth_signature_method'] = signature_method.name
        self['oauth_signature'] = signature_method.sign(self, consumer, token)
413994
protected function registerApi(&$url, $method, $arguments = [])
    {
        $this->currentMethod = ['method' => $method, 'arguments' => $arguments];
        if (empty($this->access_token)) {
            $this->access_token = $this->getAccessToken();
        }
        return $url = str_replace('ACCESS_TOKEN', $this->access_token, $url);
    }
755232
def request(http_method, uri, options={})
      response = self.class.__send__(http_method, uri, options.merge(basic_auth))
      # Add some logger.debug here ...
      response
    end
799450
public String buildAuthorizationHeaderValue(HttpMethod method, URI targetUrl, Map<String, String> oauthParameters, MultiValueMap<String, String> additionalParameters, String consumerSecret, String tokenSecret) {
		StringBuilder header = new StringBuilder();
		header.append("OAuth ");
		for (Entry<String, String> entry : oauthParameters.entrySet()) {
			header.append(oauthEncode(entry.getKey())).append("=\"").append(oauthEncode(entry.getValue())).append("\", ");
		}
		MultiValueMap<String, String> collectedParameters = new LinkedMultiValueMap<String, String>((int) ((oauthParameters.size() + additionalParameters.size()) / .75 + 1));
		collectedParameters.setAll(oauthParameters);
		collectedParameters.putAll(additionalParameters);		
		String baseString = buildBaseString(method, getBaseStringUri(targetUrl), collectedParameters);
		String signature = calculateSignature(baseString, consumerSecret, tokenSecret);
		header.append(oauthEncode("oauth_signature")).append("=\"").append(oauthEncode(signature)).append("\"");
		return header.toString();
	}
919001
function signatureBaseString (method, url, parameters) {
  return method.toUpperCase() + '&' +
  encodeOAuthData(signatureBaseStringURI(url)) + '&' +
  encodeOAuthData(parameters)
}
672402
public static function fromRequest($http_method = null, $http_url = null, $parameters = null)
    {
        $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")
            ? 'http'
            : 'https';
        $http_url = ($http_url) ? $http_url : $scheme .
            '://' . $_SERVER['SERVER_NAME'] .
            ':' .
            $_SERVER['SERVER_PORT'] .
            $_SERVER['REQUEST_URI'];
        $http_method = ($http_method) ? $http_method : $_SERVER['REQUEST_METHOD'];

        // We weren't handed any parameters, so let's find the ones relevant to
        // this request.
        // If you run XML-RPC or similar you should use this to provide your own
        // parsed parameter-list
        if (!$parameters) {
            // Find request headers
            $request_headers = Util::getHeaders();

            // Parse the query-string to find GET parameters
            $parameters = Util::parseParameters($_SERVER['QUERY_STRING']);

            // It's a POST request of the proper content-type, so parse POST
            // parameters and add those overriding any duplicates from GET
            if ($http_method == "POST"
                &&  isset($request_headers['Content-Type'])
                && strstr(
                    $request_headers['Content-Type'],
                    'application/x-www-form-urlencoded'
                )
            ) {
                $post_data = Util::parseParameters(
                    file_get_contents(self::$POST_INPUT)
                );
                $parameters = array_merge($parameters, $post_data);
            }

            // We have a Authorization-header with OAuth data. Parse the header
            // and add those overriding any duplicates from GET or POST
            if (isset($request_headers['Authorization']) && substr($request_headers['Authorization'], 0, 6) == 'OAuth ') {
                $header_parameters = Util::splitHeader(
                    $request_headers['Authorization']
                );
                $parameters = array_merge($parameters, $header_parameters);
            }
        }

        return new Request($http_method, $http_url, $parameters);
    }
988741
def _auth_required(method, validator):
    
    @gen.coroutine
    @functools.wraps(method)
    def wrapper(self, *args, **kwargs):
        token = _get_token(self.request)
        valid_token = yield validator(token)
        if not valid_token:
            message = 'Invalid token: {}'.format(token)
            logging.warning(message)
            raise HTTPError(401, message)
        result = method(self, *args, **kwargs)

        if isinstance(result, Future):
            result = yield result

        raise gen.Return(result)

    return wrapper
1361527
def construct_request(uri, params, credentials=[])
      Weary::Request.new uri, @method do |r|
        pass_values_onto_requestable(r)
        if !expected_params.empty?
          r.params params.reject {|k,v| !expects? k }
        end
        r.send @authenticates, *credentials if authenticates?
      end
    end
1115651
def post(api_method, parameters = {})
      parameters.merge!({"token" => @token})

      body = {}
      body.merge!({:method => api_method})
      body.merge!({:params => parameters})

      self.class.post(@write_api_url, {:body => {:json => JSON.generate(body)}})
    end