summaryrefslogtreecommitdiff
path: root/app/models/token.rb
diff options
context:
space:
mode:
authorAzul <azul@leap.se>2014-05-16 08:42:36 +0200
committerAzul <azul@leap.se>2014-05-16 08:42:36 +0200
commit8fbbb8717f0578536b97c2dc0883c632f120e976 (patch)
tree17aeb2b48ada703ac916a9a65fbf3c75a5dadb86 /app/models/token.rb
parent81555ec6244ed76f92e3629880f68104b8705817 (diff)
parenta4f7a410c536d88c91c834cab6ee950c71005ddd (diff)
Merge remote-tracking branch 'origin/develop'
Conflicts: app/assets/javascripts/srp test/nagios/soledad_sync.py test/nagios/webapp_login.py
Diffstat (limited to 'app/models/token.rb')
-rw-r--r--app/models/token.rb73
1 files changed, 73 insertions, 0 deletions
diff --git a/app/models/token.rb b/app/models/token.rb
new file mode 100644
index 0000000..e759ee3
--- /dev/null
+++ b/app/models/token.rb
@@ -0,0 +1,73 @@
+class Token < CouchRest::Model::Base
+
+ use_database :tokens
+
+ belongs_to :user
+
+ # timestamps! does not create setters and only sets updated_at
+ # if the object has changed and been saved. Instead of triggering
+ # that we rather use our own property we have control over:
+ property :last_seen_at, Time, accessible: false
+
+ 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
+ return [] unless expires_after
+ 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 to_s
+ id
+ end
+
+ def authenticate
+ if expired?
+ destroy
+ return nil
+ else
+ touch
+ return user
+ end
+ end
+
+ # Tokens can be cleaned up in different ways.
+ # So let's make sure we don't crash if they disappeared
+ def destroy_with_rescue
+ destroy_without_rescue
+ rescue RestClient::ResourceNotFound
+ end
+ alias_method_chain :destroy, :rescue
+
+ def touch
+ self.last_seen_at = Time.now
+ save
+ end
+
+ def expired?
+ Token.expires_after and
+ last_seen_at < Token.expires_after.minutes.ago
+ end
+
+ def initialize(*args)
+ super
+ if new_record?
+ self.id = SecureRandom.urlsafe_base64(32).gsub(/^_*/, '')
+ self.last_seen_at = Time.now
+ end
+ end
+end
+