2019-05-03 06:17:27 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2016-12-19 15:00:22 +08:00
|
|
|
# session that is not stored in cookie, expires after 1.hour unconditionally
|
|
|
|
class SecureSession
|
|
|
|
def initialize(prefix)
|
|
|
|
@prefix = prefix
|
|
|
|
end
|
|
|
|
|
2019-10-16 13:53:31 +08:00
|
|
|
def self.expiry
|
|
|
|
@expiry ||= 1.hour.to_i
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.expiry=(val)
|
|
|
|
@expiry = val
|
|
|
|
end
|
|
|
|
|
|
|
|
def set(key, val, expires: nil)
|
|
|
|
expires ||= SecureSession.expiry
|
2019-11-11 08:18:12 +08:00
|
|
|
$redis.setex(prefixed_key(key), expires.to_i, val.to_s)
|
2019-10-16 13:53:31 +08:00
|
|
|
true
|
|
|
|
end
|
|
|
|
|
2019-11-11 08:18:12 +08:00
|
|
|
def ttl(key)
|
|
|
|
$redis.ttl(prefixed_key(key))
|
|
|
|
end
|
|
|
|
|
2016-12-19 15:00:22 +08:00
|
|
|
def [](key)
|
2019-10-16 13:53:31 +08:00
|
|
|
$redis.get(prefixed_key(key))
|
2016-12-19 15:00:22 +08:00
|
|
|
end
|
|
|
|
|
2017-07-28 09:20:09 +08:00
|
|
|
def []=(key, val)
|
2016-12-19 15:00:22 +08:00
|
|
|
if val == nil
|
2019-10-16 13:53:31 +08:00
|
|
|
$redis.del(prefixed_key(key))
|
2016-12-19 15:00:22 +08:00
|
|
|
else
|
2019-10-16 13:53:31 +08:00
|
|
|
$redis.setex(prefixed_key(key), SecureSession.expiry.to_i, val.to_s)
|
2016-12-19 15:00:22 +08:00
|
|
|
end
|
2019-10-16 13:53:31 +08:00
|
|
|
val
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def prefixed_key(key)
|
|
|
|
"#{@prefix}#{key}"
|
2016-12-19 15:00:22 +08:00
|
|
|
end
|
|
|
|
end
|