Skip to content

Instantly share code, notes, and snippets.

@postmodern
Created March 26, 2010 06:07
Show Gist options
  • Save postmodern/344568 to your computer and use it in GitHub Desktop.
Save postmodern/344568 to your computer and use it in GitHub Desktop.
A basic DataMapper Type to represent unique API keys.
require 'digest/sha2'
module DataMapper
module Types
class APIKey < DataMapper::Type
primitive String
length 64
#
# Loads the API key from the database.
#
# @param [String, nil] value
# The value loaded from the database.
#
# @return [String]
# The unique API key.
#
def self.load(value, property)
if value.blank?
generate_api_key
else
value
end
end
#
# Dumps the API key out into a storable format.
#
# @param [String, nil] value
# The value to dump.
#
# @return [String]
# A storable API key.
#
def self.dump(value, property)
if value.blank?
nil
else
value.to_s
end
end
#
# Typecasts a value into an API key.
#
# @param [Object, String, nil] value
# The value to typecast.
#
# @return [String]
# The API key which represents the given value. If `nil` was given
# as the value, a new API key will be generated.
#
def self.typecast(value, property)
if value.kind_of?(Digest::Base)
value.hexdigest
elsif value.nil?
generate_api_key
else
Digest::SHA256.hexdigest(value.to_s)
end
end
#
# Generates a new unique API key, by calculating the SHA256 digest
# of the current time and random characters.
#
# @return [String]
# A unique API key.
#
def self.generate_api_key
unique = Time.now.to_i
salt = lambda { Array.new(10) { rand(256) }.join }
digest = Digest::SHA256.new()
digest << salt.call()
digest << unique.to_s
digest << salt.call()
return digest.hexdigest
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment