ariejan (owner)

Forks

Revisions

gist: 163880 Download_button fork
public
Public Clone URL: git://gist.github.com/163880.git
Embed All Files: show embed
api_key.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 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
 
application_controller.rb #
1
2
3
4
5
6
7
8
9
10
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
create_api_keys.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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