OSDN Git Service

Delete previous tokens when creating a new one.
authorJean-Philippe Lang <jp_lang@yahoo.fr>
Tue, 2 Jun 2009 17:24:50 +0000 (17:24 +0000)
committerJean-Philippe Lang <jp_lang@yahoo.fr>
Tue, 2 Jun 2009 17:24:50 +0000 (17:24 +0000)
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/trunk@2778 e93f8b46-1217-0410-a6f0-8f06a7374b81

app/models/token.rb
test/unit/token_test.rb

index a5199c7..b59d4f2 100644 (file)
@@ -1,5 +1,5 @@
-# redMine - project management software
-# Copyright (C) 2006  Jean-Philippe Lang
+# Redmine - project management software
+# Copyright (C) 2006-2009  Jean-Philippe Lang
 #
 # This program is free software; you can redistribute it and/or
 # modify it under the terms of the GNU General Public License
@@ -19,6 +19,8 @@ class Token < ActiveRecord::Base
   belongs_to :user
   validates_uniqueness_of :value
   
+  before_create :delete_previous_tokens
+  
   @@validity_time = 1.day
   
   def before_create
@@ -39,4 +41,11 @@ private
   def self.generate_token_value
     ActiveSupport::SecureRandom.hex(20)
   end
+  
+  # Removes obsolete tokens (same user and action)
+  def delete_previous_tokens
+    if user
+      Token.delete_all(['user_id = ? AND action = ?', user.id, action])
+    end
+  end
 end
index 5a34e0a..64ac85a 100644 (file)
@@ -1,5 +1,5 @@
-# redMine - project management software
-# Copyright (C) 2006-2007  Jean-Philippe Lang
+# Redmine - project management software
+# Copyright (C) 2006-2009  Jean-Philippe Lang
 #
 # This program is free software; you can redistribute it and/or
 # modify it under the terms of the GNU General Public License
@@ -26,4 +26,13 @@ class TokenTest < Test::Unit::TestCase
     assert_equal 40, token.value.length
     assert !token.expired?
   end
+  
+  def test_create_should_remove_existing_tokens
+    user = User.find(1)
+    t1 = Token.create(:user => user, :action => 'autologin')
+    t2 = Token.create(:user => user, :action => 'autologin')
+    assert_not_equal t1.value, t2.value
+    assert !Token.exists?(t1.id)
+    assert  Token.exists?(t2.id)
+  end
 end