我有以下方法设置来帮助刷新Oauth令牌:
module WhiplashOmniAuthentication
extend ActiveSupport::Concern
module ClassMethods
def from_omniauth(auth)
Rails.logger.debug auth.inspect
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.provider = auth.provider
user.uid = auth.uid
user.email = auth.info.email
user.store_token(auth.credentials)
end
end
end
def refresh_token!
settings = Devise.omniauth_configs[:whiplash].strategy
strategy = OmniAuth::Strategies::Whiplash.new(nil, settings.client_id, settings.client_secret, client_options: settings.client_options)
client = strategy.client
access_token = OAuth2::AccessToken.new client, token, refresh_token: refresh_token
if access_token
begin
result = access_token.refresh!
store_token(result)
save
rescue OAuth2::Error => e
errors[:token] << e.inspect
return false
end
else
errors[:token] << e.inspect
return false
end
end
def store_token(auth_token)
self.token = auth_token.token
self.refresh_token = auth_token.refresh_token
self.token_expires_at = Time.at(auth_token.expires_at).to_datetime
end
def token_expired?
Time.now > token_expires_at
end
end
我尝试将其分解为单独的方法,但它不断爆炸,所以我将在这里推迟读者。我正在寻找通过警察和学习的建议。
答案 0 :(得分:1)
refresh_token!
实施中肯定会发生太多事情。你总是想让方法做一件事,只做一件事。它使测试更容易(例如:特定方法的存根),调试和可读性。
查看以下内容是否有帮助:
module WhiplashOmniAuthentication
extend ActiveSupport::Concern
module ClassMethods
def from_omniauth(auth)
Rails.logger.debug auth.inspect
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.provider = auth.provider
user.uid = auth.uid
user.email = auth.info.email
user.store_token(auth.credentials)
end
end
end
def refresh_token!
access_token ? refresh_access_token! : false
end
def refresh_access_token!
result = access_token.refresh!
store_token(result)
save
rescue OAuth2::Error
false
end
def settings
@settings ||= Devise.omniauth_configs[:whiplash].strategy
end
def strategy
@strategy ||= OmniAuth::Strategies::Whiplash.new(nil, settings.client_id, settings.client_secret, client_options: settings.client_options)
end
def client
@client ||= strategy.client
end
def access_token
OAuth2::AccessToken.new(client, token, refresh_token: refresh_token)
end
def store_token(auth_token)
self.token = auth_token.token
self.refresh_token = auth_token.refresh_token
self.token_expires_at = Time.at(auth_token.expires_at).to_datetime
end
def token_expired?
Time.now > token_expires_at
end
end