【问题标题】:How to update twitter omniauth access token and access token secret如何更新 twitter omniauth 访问令牌和访问令牌秘密
【发布时间】:2021-02-01 11:05:42
【问题描述】:

在我的 rails 6 应用程序中,用户必须使用 twitter omniauth 登录并进行设计。我已经能够按照这个tutorial来实现它。

我遇到的问题是,当用户从他们的 Twitter 帐户中撤销我的应用程序权限时,我之前保存到我的数据库中的omniauth 访问令牌和访问秘密变得无效。如果同一用户决定重新进行身份验证,则该用户可以访问该应用,但该用户的令牌不会在数据库中更新,从而导致现有令牌无效。

我的问题是,如何持续更新数据库中的用户列,以便继续从 twitter 接收有效的访问令牌,尤其是当用户拥有访问令牌时。

这是来自我的用户模型的相关代码

  def self.from_omniauth(auth)
    where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
    user.email = auth.info.email
    user.password = Devise.friendly_token[0, 20]
    user.name = auth.info.name
    user.username = auth.info.nickname
    user.location = auth.info.location
    user.access_token = auth.credentials.token
    user.access_secret = auth.credentials.secret
    end
  end

我的用户控制器看起来像这样

  def twitter
    @user = User.from_omniauth(request.env["omniauth.auth"])

    if @user.persisted?
      sign_in_and_redirect @user, event: :authentication #this will throw if @user is not activated
      set_flash_message(:notice, :success, kind: "Twitter") if is_navigational_format?
    else
      session["devise.twitter_data"] = request.env["omniauth.auth"].except("extra")
      redirect_to new_user_registration_url
    end
  end

【问题讨论】:

    标签: ruby-on-rails ruby twitter devise omniauth


    【解决方案1】:
    1. 找到用户。
    2. 如果没有用户 - 创建用户。
    3. 使用新的omniauth 数据更新用户(现有和新用户)

    这样的事情应该可以完成:

    def self.from_omniauth(auth)
      #find from omniauth
      user = User.where(email: auth.email).first
    
      #find or create
      user ||= User.create(
        email: data["email"],
        password: Devise.friendly_token[0, 20]
      )
      #update with fresh data
      user.name = auth.info.name
      user.image = auth.info.image
      user.expires = auth.credentials.expires
      user.refresh_token = auth.credentials.refresh_token
    end
    

    【讨论】:

    • 从哪里得到这些行来自 user.expires = auth.credentials.expires 和 user.refresh_token = auth.credentials.refresh_token
    • 这是一个验证哈希github.com/zquestz/omniauth-google-oauth2#auth-hash的示例
    • 我写了一个示例方法。你可以检索你想要的数据,比如access_tokenwhatever
    • 我对此有错误,但现在它适用于 find_or_initialize_by 。感谢您的帮助
    【解决方案2】:

    我通过使用 find_or_initialize_by 来处理它

       def self.from_omniauth(auth)
        user = find_or_initialize_by(provider: auth.provider, uid: auth.uid)
        user.email = auth.info.email
        user.password = Devise.friendly_token[0, 20]
        user.name = auth.info.name
        user.username = auth.info.nickname
        user.location = auth.info.location
        user.access_token = auth.credentials.token
        user.access_secret = auth.credentials.secret
        user.save!
        return user
      end
    

    【讨论】:

      猜你喜欢
      • 2012-04-28
      • 2011-12-31
      • 2012-12-29
      • 1970-01-01
      • 2012-10-27
      • 2013-04-17
      • 2012-10-14
      • 2016-06-10
      • 2011-03-18
      相关资源
      最近更新 更多