我試圖做一個認證的路線/me
使用omniauth-google-oauth2。到目前爲止,我已經建立了登錄和註銷庫,並且工作正常。不過,我希望只有當用戶登錄時才能訪問某些路線。我發現this snippet並做了一些小修改以適應我的設置。Omniauth認證的路線谷歌
application_controller.rb
before_filter :authenticate
def authenticate
redirect_to :login unless User.from_omniauth(env["omniauth.auth"])
end
user.rb
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_initialize.tap do |user|
user.provider = auth.provider
user.uid = auth.uid
user.name = auth.info.name
user.first_name = auth.info.first_name
user.last_name = auth.info.last_name
user.email = auth.info.email
user.picture = auth.info.image
user.oauth_token = auth.credentials.token
user.oauth_expires_at = Time.at(auth.credentials.expires_at)
user.save!
end
我以前env["omniauth"]
,因爲這是我在SessionsController
使用的身份驗證哈希。
不過,現在每當我去localhost:3000
,我得到以下錯誤:
undefined method `provider' for nil:NilClass
我假設這是因爲env["omniauth.auth"]
是不是從application_controller.rb
訪問?如果是這樣的話,那麼我該如何正確訪問認證哈希?
你的'from_omniauth'類方法在'user.rb'文件中看起來像什麼? –
@JustinLicata剛剛更新了原來的文章 – Carpetfizz
'env [「omniauth.auth」]'當您訪問「localhost:3000」時返回'nil'。我相信的原因是這個env變量只能在社交登錄後的回調請求中設置。對於所有其他請求,這將是'nil'。 –