You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

token.rb 1.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # Redmine - project management software
  2. # Copyright (C) 2006-2011 Jean-Philippe Lang
  3. #
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU General Public License
  6. # as published by the Free Software Foundation; either version 2
  7. # of the License, or (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  17. class Token < ActiveRecord::Base
  18. belongs_to :user
  19. validates_uniqueness_of :value
  20. before_create :delete_previous_tokens, :generate_new_token
  21. @@validity_time = 1.day
  22. def generate_new_token
  23. self.value = Token.generate_token_value
  24. end
  25. # Return true if token has expired
  26. def expired?
  27. return Time.now > self.created_on + @@validity_time
  28. end
  29. # Delete all expired tokens
  30. def self.destroy_expired
  31. Token.delete_all ["action NOT IN (?) AND created_on < ?", ['feeds', 'api'], Time.now - @@validity_time]
  32. end
  33. private
  34. def self.generate_token_value
  35. Redmine::Utils.random_hex(20)
  36. end
  37. # Removes obsolete tokens (same user and action)
  38. def delete_previous_tokens
  39. if user
  40. Token.delete_all(['user_id = ? AND action = ?', user.id, action])
  41. end
  42. end
  43. end