Created
August 7, 2009 12:49
-
-
Save ariejan/163880 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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