Intro
Runs fast using OpenSSL::HMAC.
Supports
- ORMs and DOMs that use ActiveModel hmac_validator.rb (30 sloc)
- If support for something is missing, add an issue and the support will be added
Usage
class ApiUser < ActiveRecord::Base
has_many :posts
validates :secret_key, presence: true
validates :secret_algorithm, presence: true
end
class Post < ActiveRecord::Base
API_FIELDS = [:title, :body].sort # keep them in alphabetic order!
attr_accessible :api_user_id, :hmac
attr_accessible *MESSAGE_FIELDS
belongs_to :api_user
# these have same meaning (supports Lambdas and Symbols evaluating):
validate :hmac, precence: true, hmac: {
key: lambda { api_user.secret_key },
data: lambda { API_FIELDS.collect{|m| send(m) }.join },
algorithm: lambda { api_user.secret_algorithm }
}
validates :hmac, presence: true, hmac: {
key: :'api_user.secret_key',
data: API_FIELDS,
algorithm: :'api_user.secret_algorithm'
}
# these are not evaluated (presumed that static value is written)
validates :hmac, presence: true, hmac: {
key: 'all_the_time_same',
data: 'why you would like to have a static value here?',
algorithm: 'md5' # by default its sha1
}
end
Valid options
- key (required) - secret preshared key
- data (required) - data to be controlled with HMAC
- algorithm (optional) - by default 'sha1', 'md5', 'sha256', 'sha384', 'sha512' also supported
- message (optional) - errormessage to be shown if HMAC validation fails