Commit 94e46abe by lanrion

refactor with adapter storage

parent 993cee97
# encoding: utf-8
module WeixinAuthorize
class ClientStorage < Storage
def valid?
super
end
def token_expired?
# 如果当前token过期时间小于现在的时间,则重新获取一次
client.expired_at <= Time.now.to_i
end
def authenticate
super
end
def access_token
super
client.access_token
end
end
end
# encoding: utf-8
module WeixinAuthorize
class RedisStorage < Storage
def valid?
weixin_redis.del(client.redis_key)
super
end
def token_expired?
weixin_redis.hvals(client.redis_key).empty?
end
def authenticate
super
weixin_redis.hmset(client.redis_key, :access_token, client.access_token,
:expired_at, client.expired_at)
weixin_redis.expireat(client.redis_key, client.expired_at.to_i-10) # 提前10秒超时
end
def access_token
super
client.access_token = weixin_redis.hget(client.redis_key, "access_token")
client.expired_at = weixin_redis.hget(client.redis_key, "expired_at")
client.access_token
end
def weixin_redis
WeixinAuthorize.config.redis
end
end
end
......@@ -3,22 +3,27 @@ module WeixinAuthorize
class Storage
attr_accessor :storage
attr_accessor :client
def initialize(storage)
@storage = storage
def initialize(client)
@client = client
end
def self.init_with(storage)
if storage.is_a? Client
ObjectStorage.new(storage)
def self.init_with(client)
if WeixinAuthorize.config.redis.nil?
ClientStorage.new(client)
else
RedisStorage.new(storage)
RedisStorage.new(client)
end
end
def valid?
raise NotImplementedError, "Subclasses must implement a valid? method"
valid_result = http_get_access_token
if valid_result.keys.include?("access_token")
set_access_token_for_client(valid_result)
return true
end
false
end
def token_expired?
......@@ -26,44 +31,28 @@ module WeixinAuthorize
end
def authenticate
raise NotImplementedError, "Subclasses must implement a authenticate method"
raise "APPID or APPSECRET is invalid" if !valid?
set_access_token_for_client
end
def get_access_token
def access_token
authenticate if token_expired?
end
end
class RedisStorage < Storage
def valid?
storage.del(storage.redis_key)
def set_access_token_for_client(access_token_infos=nil)
token_infos = access_token_infos || http_get_access_token
client.access_token = token_infos["access_token"]
client.expired_at = Time.now.to_i + token_infos["expires_in"].to_i
end
def token_expired?
storage.hvals(redis_key).empty?
def http_get_access_token
WeixinAuthorize.http_get_without_token("/token", authenticate_headers)
end
def authenticate
def authenticate_headers
{grant_type: "client_credential", appid: client.app_id, secret: client.app_secret}
end
end
class ObjectStorage < Storage
def valid?
end
def token_expired?
# 如果当前token过期时间小于现在的时间,则重新获取一次
stoage.expired_at <= Time.now.to_i
end
def authenticate
end
end
end
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