Module: HmacAuthRails::HmacController

Defined in:
lib/hmac_auth_rails.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.encrypt(secret_key, string) ⇒ Object



62
63
64
65
66
67
68
69
# File 'lib/hmac_auth_rails.rb', line 62

def self.encrypt(secret_key,string)
  digest = OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha1'), secret_key, string)
  if Base64.respond_to?(:strict_encode64)
    Base64.strict_encode64(digest)
  else
    Base64.encode64(digest).gsub(/\n/, '')
  end
end

Instance Method Details

#hmac_auth(model = "User") ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/hmac_auth_rails.rb', line 36

def hmac_auth model="User"
  @my_user
  begin
    raise 'Missing X_HMAC_AUTHORIZATION header' unless header_exists? :HTTP_X_HMAC_AUTHORIZATION
    raise 'Missing header HTTP_X_HMAC_CONTENT_MD5 header' unless header_exists? :HTTP_X_HMAC_CONTENT_MD5
    raise 'Missing header HTTP_X_HMAC_CONTENT_TYPE header' unless header_exists? :HTTP_X_HMAC_CONTENT_TYPE
    raise 'Missing header HTTP_X_HMAC_DATE header' unless header_exists? :HTTP_X_HMAC_DATE
    raise 'Could not determine Devise model name' unless model = Object.const_get(model)
    credentials = load_header
    raise "Invalid #{model.auth_token_field}" unless user = model.where("#{model.auth_token_field}" => credentials[:auth_token] ).first
    raise "Invalid #{model.secret_key_field}" unless secret_key = user[model.secret_key_field]
    @my_user = user
    if credentials[:signature] == HmacAuthRails::HmacController.encrypt(secret_key, canonical_string)
      (user, store: false)
    else
      raise 'Authentication failed.'
    end
  rescue => e
    Rails.logger.error e.to_s
    head :unauthorized
  rescue => e
    Rails.logger.error e
    head :unauthorized
  end
end