Class: Hull::Paywall::Request

Inherits:
Object
  • Object
show all
Defined in:
lib/hull/paywall.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(env, secret) ⇒ Request

Returns a new instance of Request.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/hull/paywall.rb', line 12

def initialize env, secret
  @env      = env
  @secret   = secret
  @request  = Rack::Request.new(env)
  @user_id  = Hull.authenticate_user(env)
  @cookie_name = "_hull_p#{Hull.app_id}"
  raw_cookie = @request.cookies[@cookie_name]
  if raw_cookie
    decoded_cookie = Base64.decode64(raw_cookie) rescue nil
    sig, val = JSON.parse(decoded_cookie) rescue []
    @authorized_contents = check_signature(sig, val) ? val : []
  end
  @authorized_contents ||= []
end

Instance Attribute Details

#authorized_contentsObject (readonly)

Returns the value of attribute authorized_contents.



10
11
12
# File 'lib/hull/paywall.rb', line 10

def authorized_contents
  @authorized_contents
end

#user_idObject (readonly)

Returns the value of attribute user_id.



10
11
12
# File 'lib/hull/paywall.rb', line 10

def user_id
  @user_id
end

Instance Method Details

#check_authorization_for(key) ⇒ Object



50
51
52
53
# File 'lib/hull/paywall.rb', line 50

def check_authorization_for key
  return false unless @user_id
  @authorized_contents.include?(key) or fetch_authorized_contents.include?(key)
end

#check_signature(sig, val) ⇒ Object



31
32
33
34
35
# File 'lib/hull/paywall.rb', line 31

def check_signature sig, val
  return false unless @user_id
  return false if sig.nil? || val.nil?
  sig == sign(val.to_json)
end

#fetch_authorized_contentsObject



37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/hull/paywall.rb', line 37

def fetch_authorized_contents
  return [] if @user_id.nil?
  badges = Hull.get("#{user_id}/badges") || []
  @authorized_contents = badges.map do |badge|
    if badge['data'] && badge['data']['transactions']
      badge['data']['transactions'].map do |k,t|
        t['permalink']
      end
    end
  end.compact.flatten.uniq.sort
  @authorized_contents
end


55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/hull/paywall.rb', line 55

def set_cookie headers
  if !@user_id.nil? && @authorized_contents.length > 0
    signed_cookie = Base64.encode64([sign(@authorized_contents.to_json), @authorized_contents].to_json)
    Rack::Utils.set_cookie_header!(headers, @cookie_name, {
      :value => signed_cookie,
      :path => "/"
    })
  else
    Rack::Utils.delete_cookie_header!(headers, @cookie_name, {
      :path => "/"
    })
  end
end

#sign(val) ⇒ Object



27
28
29
# File 'lib/hull/paywall.rb', line 27

def sign val
  OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new('sha1'), @secret, val)
end