Commit 24657885 by ivan Lan

Add TTL to Ohm::Model & Add Ohm::McCree

parent 86cc5c41
module Ohm
class McCree
def initialize
@mutex = Mutex.new
@redis = Redic.new
@db = get_db(Ohm.redis.url) || '0'
enable_expired_event_notifications
end
def get_db redis_url
/^redis:\/\/.*:\d+\/(?<db>\d+)$/.match(redis_url)&.[](:db)
end
def overwatching
@thread = Thread.new { overwatch }
rescue
self.class.new.overwatching
end
def overwatch
@mutex.synchronize do
subscribe { |message, event, key| Ohm::Model.it_is_high_noon(key) if key }
end
end
def subscribe
@redis.call("SUBSCRIBE", "__keyevent@#{@db}__:expired")
loop { yield @redis.client.read }
end
def enable_expired_event_notifications
config_key = 'notify-keyspace-events'
@nke_was = @redis.call(
'config', 'get', config_key
)&.last
nke = ( @nke_was.chars | ['E', 'x'] ).join
@redis.call(
'config', 'set', config_key, nke
)
end
def disable_expired_event_notifications
@redis.call('config', 'set', 'notify-keyspace-events', @nke_was)
end
end
end
module Ohm
module TTL
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def it_is_high_noon ttl_key
class_name, id = ttl_key.split('@')
ohm_model = class_name.constantize rescue return
if Ohm::Model === ohm_model.allocate
ohm_model[id]&.delete
end
end
end
def ttl= sec
Ohm.redis.call('setex', ttl_key, sec, true)
end
def ttl
Ohm.redis.call('ttl', ttl_key)
end
def ttl_key
raise RuntimeError.new('Id is nil, please save it first.') unless id
"#{self.class.name}@#{id}"
end
end
end
......@@ -10,10 +10,14 @@ require "rails_api_authentication/auth_token"
require "rails_api_authentication/authable"
require "rails_api_authentication/acts_as_authenticationable"
require "rails_api_authentication/acts_as_authentication_handler"
require "ohm/mc_cree"
require "ohm/model"
module RailsApiAuthentication
extend Configuration
Ohm::Model.include Ohm::TTL
private
def self.ensure_models_can_act_as_token_authenticatables model_adapters
......
......@@ -24,7 +24,13 @@ module RailsApiAuthentication
def self.create(klass, params = {})
params[:klass] = klass
params[:token] = SecureRandom.uuid62
super params
obj = super params
obj.update_ttl
obj
end
def update_ttl sec=604800 # a week
self.ttl = sec
end
end
end
......@@ -146,9 +146,8 @@ module RailsApiAuthentication
def auth(token)
auth = AuthToken.find(token: token)&.first
if auth.nil?
nil
else
unless auth.nil?
auth.update_ttl
user = self.find_by(id: auth.oid)
user.token = auth.token
user.auth = auth
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment