Module: SimpleOAuth::Header::ClassMethods

Included in:
SimpleOAuth::Header
Defined in:
lib/simple_oauth/header/class_methods.rb,
sig/simple_oauth/header/class_methods.rbs

Overview

Class methods for Header - parsing, defaults, and body hashing

Instance Method Summary collapse

Instance Method Details

#body_hash(body, algorithm = "SHA1") ⇒ String

Computes the oauth_body_hash for a request body

Parameters:

  • body (String, nil)
  • algorithm (String) (defaults to: "SHA1")

Returns:

  • (String)


38
39
40
# File 'lib/simple_oauth/header/class_methods.rb', line 38

def body_hash(body, algorithm = "SHA1")
  encode_base64(OpenSSL::Digest.digest(algorithm, body || ""))
end

#default_options(body = nil) ⇒ Header::oauth_options

Returns default OAuth options with generated nonce and timestamp

Parameters:

  • body (String, nil) (defaults to: nil)

Returns:

  • (Header::oauth_options)


20
21
22
23
24
25
26
27
# File 'lib/simple_oauth/header/class_methods.rb', line 20

def default_options(body = nil)
  {
    nonce: generate_nonce,
    signature_method: DEFAULT_SIGNATURE_METHOD,
    timestamp: Integer(Time.now).to_s,
    version: OAUTH_VERSION
  }.tap { |opts| opts[:body_hash] = body_hash(body) if body }
end

#encode_base64(data) ⇒ String

Encodes binary data as Base64 without newlines

Parameters:

  • data (String)

Returns:

  • (String)


94
95
96
# File 'lib/simple_oauth/header/class_methods.rb', line 94

def encode_base64(data)
  Base64.strict_encode64(data)
end

#generate_nonceString

Generates a random nonce for OAuth requests

Returns:

  • (String)


85
86
87
# File 'lib/simple_oauth/header/class_methods.rb', line 85

def generate_nonce
  SecureRandom.hex
end

#parse(header) ⇒ Header::oauth_options

Parses an OAuth Authorization header string into a hash

Parameters:

  • header (String, _ToS)

Returns:

  • (Header::oauth_options)


51
52
53
# File 'lib/simple_oauth/header/class_methods.rb', line 51

def parse(header)
  Parser.new(header).parse(PARSE_KEYS)
end

#parse_form_body(body) ⇒ Header::oauth_options

Parses OAuth parameters from a form-encoded POST body

Parameters:

  • body (String, _ToS)

Returns:

  • (Header::oauth_options)


66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/simple_oauth/header/class_methods.rb', line 66

def parse_form_body(body)
  valid_keys = PARSE_KEYS.map(&:to_s)

  result = {} #: Hash[Symbol, String]
  CGI.parse(body.to_s).each do |key, values|
    next unless key.start_with?(OAUTH_PREFIX)

    parsed_key = key.delete_prefix(OAUTH_PREFIX)
    result[parsed_key.to_sym] = values.first || "" if valid_keys.include?(parsed_key)
  end
  result
end