Class: FaradayMiddleware::Reddit::Modhash

Inherits:
Faraday::Middleware
  • Object
show all
Includes:
ModhashHelpers
Defined in:
lib/faraday_middleware/reddit/use/modhash.rb

Overview

Middleware that keeps track of and sets modhash-related HTTP headers.

Reddit uses modhashes as a form of XSS protection and requires them for most POST and PUT requests. Modhashes are currently provided in response to listing GET requests.

Instance Method Summary collapse

Methods included from ModhashHelpers

#extract_modhash, included

Constructor Details

#initialize(app, options = nil) ⇒ Modhash



15
16
17
18
19
# File 'lib/faraday_middleware/reddit/use/modhash.rb', line 15

def initialize(app, options = nil)
  super(app)
  @options = options || {}
  @modhash = @options[:modhash]
end

Instance Method Details

#call(env) ⇒ Object



21
22
23
24
25
26
27
28
29
30
# File 'lib/faraday_middleware/reddit/use/modhash.rb', line 21

def call(env)
  # Modhash unnecessary when using OAuth.
  return @app.call(env) if env[:request_headers]['Authorization']

  @modhash = env[:modhash] if env[:modhash]
  env[:request_headers]['X-Modhash'] = @modhash if @modhash
  @app.call(env).on_complete do |response_env|
    update_modhash(response_env)
  end
end

#update_modhash(env) ⇒ Object



32
33
34
35
36
37
# File 'lib/faraday_middleware/reddit/use/modhash.rb', line 32

def update_modhash(env)
  modhash = extract_modhash(env)
  @modhash = modhash if modhash
rescue JSON::JSONError
  # Ignore -- modhash can be acquired lazily.
end