如何改进这个Oauth Rubocop代码?

问题描述 投票:0回答:1

我有以下方法设置来帮助刷新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

我尝试将其分解为单独的方法,但它不断爆炸,所以我将在这里推迟读者。我正在寻找通过警察和学习的建议。

ruby-on-rails oauth ruby-style-guide
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.