summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAzul <azul@leap.se>2013-11-07 23:27:27 +0100
committerAzul <azul@leap.se>2013-11-08 09:45:09 +0100
commite2c0962077cf759b23639276cca42606ea2135ec (patch)
treea4a5faae5f26aefe0ae390c5ea01c94511631663
parentd4f835662fac2d9dca705b5cba2e207562dec833 (diff)
Token.destroy_all_expired to cleanup expired tokens (#4411)
-rw-r--r--users/app/models/token.rb35
-rw-r--r--users/test/unit/token_test.rb15
2 files changed, 39 insertions, 11 deletions
diff --git a/users/app/models/token.rb b/users/app/models/token.rb
index dd87344..bf9b0d0 100644
--- a/users/app/models/token.rb
+++ b/users/app/models/token.rb
@@ -11,6 +11,24 @@ class Token < CouchRest::Model::Base
validates :user_id, presence: true
+ design do
+ view :by_last_seen_at
+ end
+
+ def self.expires_after
+ APP_CONFIG[:auth] && APP_CONFIG[:auth][:token_expires_after]
+ end
+
+ def self.expired
+ self.by_last_seen_at.endkey(expires_after.minutes.ago)
+ end
+
+ def self.destroy_all_expired
+ self.expired.each do |token|
+ token.destroy
+ end
+ end
+
def authenticate
if expired?
destroy
@@ -27,21 +45,16 @@ class Token < CouchRest::Model::Base
end
def expired?
- expires_after and
- last_seen_at + expires_after.minutes < Time.now
- end
-
- def expires_after
- APP_CONFIG[:auth] && APP_CONFIG[:auth][:token_expires_after]
+ Token.expires_after and
+ last_seen_at < Token.expires_after.minutes.ago
end
def initialize(*args)
super
- self.id = SecureRandom.urlsafe_base64(32).gsub(/^_*/, '')
- self.last_seen_at = Time.now
- end
-
- design do
+ if new_record?
+ self.id = SecureRandom.urlsafe_base64(32).gsub(/^_*/, '')
+ self.last_seen_at = Time.now
+ end
end
end
diff --git a/users/test/unit/token_test.rb b/users/test/unit/token_test.rb
index f56c576..445a20c 100644
--- a/users/test/unit/token_test.rb
+++ b/users/test/unit/token_test.rb
@@ -61,6 +61,21 @@ class ClientCertificateTest < ActiveSupport::TestCase
end
end
+ test "Token.destroy_all_expired cleans up expired tokens only" do
+ expired = Token.new(user_id: @user.id)
+ expired.last_seen_at = 2.hours.ago
+ expired.save
+ fresh = Token.new(user_id: @user.id)
+ fresh.save
+ with_config auth: {token_expires_after: 60} do
+ Token.destroy_all_expired
+ end
+ assert_nil Token.find(expired.id)
+ assert_equal fresh, Token.find(fresh.id)
+ fresh.destroy
+ end
+
+
end