From 3cc12a7c88b97c039db239026ee9721b3e2f904c Mon Sep 17 00:00:00 2001 From: iTakeshi Date: Fri, 18 Jul 2014 11:44:31 +0900 Subject: [PATCH] AccessToken functions ref: https://github.com/NoamB/sorcery/pull/415 --- app/models/access_token.rb | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/app/models/access_token.rb b/app/models/access_token.rb index 5f52ad8..418c6ff 100644 --- a/app/models/access_token.rb +++ b/app/models/access_token.rb @@ -11,5 +11,35 @@ # class AccessToken < ActiveRecord::Base + TERM_OF_VALIDITY = 2.weeks + belongs_to :user + + validates(:user_id) { presence } + validates(:token) { presence; uniqueness } + + before_create :generate_token, :update_last_activity_time + + def self.delete_expired + self + .where + .not(last_activity_at: (Time.now - TERM_OF_VALIDITY)..Time.now) + .delete_all + end + + def expired? + Time.now - TERM_OF_VALIDITY > self.last_activity_at + end + + def update_last_activity_time + self.last_activity_at = Time.now + end + + private + + def generate_token + begin + self.token = SecureRandom.hex(32) + end while self.class.find_by(token: self.token) + end end