Skip to content

Instantly share code, notes, and snippets.

@rbazinet
Forked from ariejan/api_key.rb
Created August 7, 2009 13:00
Show Gist options
  • Save rbazinet/163883 to your computer and use it in GitHub Desktop.
Save rbazinet/163883 to your computer and use it in GitHub Desktop.
# Use ApiKey.generate to generate a new API key
class ApiKey < ActiveRecord::Base
validates_presence_of :key
validates_uniqueness_of :key
def self.generate(description = "No description")
key = Digest::SHA1.hexdigest("--#{Time.now}--#{description}--")
ApiKey.create(:description => description, :key => key)
end
# Set some stats and stamps
def touch
update_attributes(
:last_used_at => Time.now,
:times_used => read_attribute(:times_used) + 1
)
end
end
protected
# Check that params[:key] is a valid API key.
# When this is called, and a valid key is found, it's stats are
# automatically updated.
def verify_api_key
@api_key = ApiKey.find_by_key(params[:key])
render :text => "Invalid API Key. Access this server requires a valid API key." and return if @api_key.nil?
@api_key.touch
end
class CreateApiKeys < ActiveRecord::Migration
def self.up
create_table :api_keys do |t|
t.string :key, :limit => 40, :unique => true
t.string :description
t.datetime :last_used_at, :default => nil
t.integer :times_used, :default => 0, :limit => 8
t.timestamps
end
end
def self.down
drop_table :api_keys
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment