fnando / has_tokens
- Source
- Commits
- Network (1)
- Issues (0)
- Downloads (0)
- Wiki (1)
- Graphs
-
Tree:
a73bc53
Lucas Fais (author)
Tue Feb 10 09:43:40 -0800 2009
commit a73bc537cb8477c49bd42e57d467c1f8eec364de
tree b4d68a22e3dccae314d836bf1a8a738965e559ee
parent d623568e0079dc1e790d4a6435f5761427f6d337
tree b4d68a22e3dccae314d836bf1a8a738965e559ee
parent d623568e0079dc1e790d4a6435f5761427f6d337
| name | age | message | |
|---|---|---|---|
| |
MIT-LICENSE | Sat Jul 19 08:31:33 -0700 2008 | |
| |
README | Fri Aug 08 15:45:34 -0700 2008 | |
| |
init.rb | Sat Jul 19 08:31:33 -0700 2008 | |
| |
lib/ | ||
| |
test/ | Fri Aug 08 15:45:34 -0700 2008 |
README
has_tokens
==========
Instalation
-----------
1) Install the plugin with `script/plugin install git://github.com/fnando/has_tokens.git`
2) Generate a migration with `script/generate migration create_tokens` and add the following code:
class CreateTokens < ActiveRecord::Migration
def self.up
create_table :tokens do |t|
t.integer :tokenizable_id, :null => false
t.string :tokenizable_type, :name, :null => false
t.string :token, :limit => 40, :null => false
t.text :data, :null => true
t.datetime :expires_at, :null => true
t.datetime :created_at
end
add_index :tokens, :tokenizable_type
add_index :tokens, :tokenizable_id
add_index :tokens, :token
add_index :tokens, :expires_at
end
def self.down
drop_table :tokens
end
end
3) Run the migrations with `rake db:migrate`
Usage
-----
1) Add the method call `has_tokens` to your model
class User < ActiveRecord::Base
has_tokens
end
# create a new token; remember that the object need to be saved before creating
# the token because it depends on the id
user = User.create(:login => "fnando")
# uses the default expires_at (2 days from now)
user.add_token(:activate)
# uses custom expires_at
user.add_token(:activate, :expires_at => 10.days.from_now)
# uses the default size (12 characters)
user.add_token(:activate)
# uses custom size (up to 32)
user.add_token(:activate, :size => 20)
# create token with arbitrary data
data = {:action => 'do something'}
user.add_token(:activate, :data => data.to_json)
# find token by name
user.find_token_by_name(:reset_account)
# find token by hash
user.find_token("ea2f14aeac40")
# check if a token has expired
user.tokens.first.expired?
# find user by token
User.find_by_token(:activate, "ea2f14aeac40")
# remove all expired tokens except those with NULL values
Token.delete_expired
# generate a token as string, without saving it
User.generate_token
# remove a token by its name
user.remove_token(:activate)
# find user by token
User.find_by_token(:activate, 'ea2f14aeac40')
# find user by valid token (same name, same hash, not expired)
User.find_by_valid_token(:activate, 'ea2f14aeac40')
# find a token using class scope
User.find_token(:activate, 'ea2f14aeac40')
# Token hash
token.to_s #=> ea2f14aeac40
Copyright (c) 2008 Nando Vieira, released under the MIT license

