diff --git a/lib/dingtalk/api/base.rb b/lib/dingtalk/api/base.rb index 99cc7bb..bd75e3f 100644 --- a/lib/dingtalk/api/base.rb +++ b/lib/dingtalk/api/base.rb @@ -4,12 +4,17 @@ module Dingtalk attr_accessor :corp_id ACCESS_TOKEN = "access_token" - def initialize(corp_id = nil) + def initialize(corp_id = nil, permanent_code = nil) @corp_id = corp_id + @permanent_code = permanent_code end def access_token - "#{corp_id}_#{ACCESS_TOKEN}" + redis.get("#{corp_id}_#{ACCESS_TOKEN}") || set_access_token + end + + def set_access_token + Suite.new.set_corp_access_token(@corp_id, @permanent_code) end private diff --git a/lib/dingtalk/api/suite.rb b/lib/dingtalk/api/suite.rb index 4521f95..c93c484 100644 --- a/lib/dingtalk/api/suite.rb +++ b/lib/dingtalk/api/suite.rb @@ -5,10 +5,9 @@ module Dingtalk SUITE_ACCESS_TOKEN = "suite_access_token" EXPIRATION = 7200 - def initialize(suite_key, suite_secret) - # put them into config file? - @suite_key = suite_key - @suite_secret = suite_secret + def initialize + @suite_key = Dingtalk.suite_key + @suite_secret = Dingtalk.suite_secret end def get_permanent_code(tmp_auth_code) @@ -29,13 +28,25 @@ module Dingtalk suite_secret: @suite_secret, suite_ticket: suite_ticket } - http_post('get_suite_token', params) - # TODO check response values + res = http_post('get_suite_token', params) + # TODO globally check response values redis.set(SUITE_ACCESS_TOKEN, res['suite_access_token']) redis.expire(SUITE_ACCESS_TOKEN, EXPIRATION) redis.get(SUITE_ACCESS_TOKEN) end + def set_corp_access_token(corp_id, permanent_code) + params = { + suite_access_token: suite_access_token, + permanent_code: permanent_code, + auth_corpid: corp_id + } + res = http_post('get_corp_token', params) + redis.set("#{corp_id}_#{ACCESS_TOKEN}", res['access_token']) + redis.expire("#{corp_id}_#{ACCESS_TOKEN}", EXPIRATION) + redis.get("#{corp_id}_#{ACCESS_TOKEN}") + end + def suite_ticket redis.get(SUITE_TICKET) end diff --git a/lib/dingtalk/config.rb b/lib/dingtalk/config.rb index ca4919b..5fb7ece 100644 --- a/lib/dingtalk/config.rb +++ b/lib/dingtalk/config.rb @@ -10,9 +10,17 @@ module Dingtalk return nil unless self.config @redis ||= config.redis end + + def suite_key + @suite_key ||= config.suite_key + end + + def suite_secret + @suite_secret ||= config.suite_secret + end end class Config - attr_accessor :redis + attr_accessor :redis, :redis_options, :suite_key, :suite_secret end end -- libgit2 0.21.0