Skip to content

Create uniques random tokens for any model in ruby on rails. Backport of ActiveRecord::SecureToken 5 to AR 3.x and 4.x

License

Notifications You must be signed in to change notification settings

robertomiranda/has_secure_token

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

38 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Build Status Gem Version Dependency Status Code Climate

HasSecureToken

HasSecureToken provides an easy way to generate uniques random tokens for any model in ruby on rails. SecureRandom::base58 is used to generate the 24-character unique tokens, so collisions are highly unlikely.

Note If you're worried about possible collissions, there's a way to generate a race condition in the database in the same way that validates_uniqueness_of can. You're encouraged to add an unique index in the database to deal with this even more unlikely scenario.

Installation

Add this line to your application's Gemfile:

gem 'has_secure_token'

And then run:

$ bundle

Or install it yourself as:

$ gem install has_secure_token

Setting your Model

The first step is to generate a migration in order to add the token key field.

rails g migration AddTokenToUsers token:string
=>
   invoke  active_record
   create    db/migrate/20150424010931_add_token_to_users.rb

Then run rake db:migrate in order to update users table in the database. The next step is to add has_secure_token to the model:

# Schema: User(token:string, auth_token:string)
class User < ActiveRecord::Base
  has_secure_token
end

user = User.new
user.save
user.token # => "pX27zsMN2ViQKta1bGfLmVJE"
user.regenerate_token # => true

To use a custom column to store the token key field you can specify the column_name option. See example above (e.g: auth_token):

# Schema: User(token:string, auth_token:string)
class User < ActiveRecord::Base
  has_secure_token :auth_token
end

user = User.new
user.save
user.auth_token # => "pX27zsMN2ViQKta1bGfLmVJE"
user.regenerate_auth_token # => true

Running tests

Running

$ rake test

Should return

5 runs, 9 assertions, 0 failures, 0 errors, 0 skips

Contributing

  1. Fork it ( https://github.com/robertomiranda/has_secure_token/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

About

Create uniques random tokens for any model in ruby on rails. Backport of ActiveRecord::SecureToken 5 to AR 3.x and 4.x

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages