Class: TeamSnap::AuthMiddleware

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/teamsnap.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, options) ⇒ AuthMiddleware

Returns a new instance of AuthMiddleware.



41
42
43
44
# File 'lib/teamsnap.rb', line 41

def initialize(app, options)
  @options = options
  super(app)
end

Instance Method Details

#call(env) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/teamsnap.rb', line 46

def call(env)
  if token
    env[:request_headers].merge!({"Authorization" => "Bearer #{token}"})
  elsif client_id && client_secret
    query_params = Hash[URI.decode_www_form(env.url.query || "")]
      .merge({
        hmac_client_id: client_id,
        hmac_nonce: SecureRandom.uuid,
        hmac_timestamp: Time.now.to_i
      })
    env.url.query = URI.encode_www_form(query_params)

    env.request_headers["X-Teamsnap-Hmac"] = OpenSSL::HMAC.hexdigest(
      digest, client_secret, message_hash(env)
    )
  end

  @app.call(env)
end

#client_idObject



70
71
72
# File 'lib/teamsnap.rb', line 70

def client_id
  @client_id ||= @options[:client_id]
end

#client_secretObject



74
75
76
# File 'lib/teamsnap.rb', line 74

def client_secret
  @client_secret ||= @options[:client_secret]
end

#digestObject



78
79
80
# File 'lib/teamsnap.rb', line 78

def digest
  OpenSSL::Digest.new("sha256")
end

#message(env) ⇒ Object



92
93
94
# File 'lib/teamsnap.rb', line 92

def message(env)
  env.body || ""
end

#message_hash(env) ⇒ Object



82
83
84
85
86
# File 'lib/teamsnap.rb', line 82

def message_hash(env)
  digest.hexdigest(
    query_string(env) + message(env)
  )
end

#query_string(env) ⇒ Object



88
89
90
# File 'lib/teamsnap.rb', line 88

def query_string(env)
  "/?" + env.url.query.to_s
end

#tokenObject



66
67
68
# File 'lib/teamsnap.rb', line 66

def token
  @token ||= @options[:token]
end