Permalink
Browse files

generate a unique token for each user when creating

  • Loading branch information...
1 parent ca2ccd2 commit a51f468c272b04e978696b8275bd7ae33d841042 @ryanb committed Oct 28, 2010
Showing with 32 additions and 0 deletions.
  1. +10 −0 app/models/user.rb
  2. +9 −0 db/migrate/20101028222332_add_token_to_users.rb
  3. +8 −0 lib/tasks/application.rake
  4. +5 −0 spec/models/user_spec.rb
View
@@ -5,6 +5,7 @@ class User < ActiveRecord::Base
attr_accessor :password
before_save :prepare_password
+ before_create :generate_token
validates_presence_of :username, :unless => :guest?
validates_uniqueness_of :username, :email, :allow_blank => true
@@ -65,6 +66,15 @@ def move_games_to(user)
end
end
+ def generate_token
+ if token.blank?
+ characters = ('a'..'z').to_a + ('A'..'Z').to_a + ('1'..'9').to_a
+ begin
+ self.token = Array.new(16) { characters.sample }.join
@KieranP

KieranP Oct 29, 2010

I think this is one of the cleanest random character implementations I've seen :-) Is it Ruby 1.9.x specific? (never seen the Array#sample method before).

@JEG2

JEG2 Oct 29, 2010

Collaborator

sample() is a part of the methods added to Array in Ruby 1.9, yes.

+ end while self.class.exists?(:token => token)
+ end
+ end
+
private
def prepare_password
@@ -0,0 +1,9 @@
+class AddTokenToUsers < ActiveRecord::Migration
+ def self.up
+ add_column :users, :token, :string
+ end
+
+ def self.down
+ remove_column :users, :token
+ end
+end
@@ -33,3 +33,11 @@ task :fix_moves => :environment do
end
end
end
+
+desc "Generate tokens for users who don't have them"
+task :user_tokens => :environment do
+ User.where(:token => nil).find_each do |user|
+ user.generate_token
+ user.save(:validate => false)
+ end
+end
View
@@ -126,4 +126,9 @@
game.black_player.should == other_user
game.current_player.should == other_user
end
+
+ it "should generate a unique 16 digit token for each user" do
+ User.create!(:guest => true).token.should_not == User.create!(:guest => true).token
+ User.create!(:guest => true).token.length.should == 16
+ end
end

0 comments on commit a51f468

Please sign in to comment.