簡體   English   中英

如何更新 Twitter omniauth 訪問令牌和訪問令牌秘密

[英]How to update twitter omniauth access token and access token secret

在我的 rails 6 應用程序中,用戶必須使用 twitter omniauth 登錄並設計。 我已經能夠通過遵循本教程來實現它。

我遇到的問題是,當用戶從他們的 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
  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

我通過使用 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM