我有以下方法设置来帮助刷新 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
我试着把它分解成单独的方法,但它一直在爆炸,所以我要在这里听从读者的意见。我正在寻找通过警察和学习的建议。