2014-06-23 66 views
0

由於某些原因,在我通過Omniauth創建用戶後,我無法再次登錄該用戶,因爲Google會返回不同的UID。Google UID在使用Rails和Devise登錄時發生變化

本質上,我首先登錄谷歌。如果用戶不存在,我創建一個用戶並保存UID。在下次登錄時,我通過provider和uid查找用戶,如果用戶已經「註冊」,那麼這兩個屬性應該能夠找到用戶。出於某種原因,Google會返回與首次登錄時不同的UID。

user.rb:

class User < ActiveRecord::Base 
    # Include default devise modules. Others available are: 
    # :confirmable, :lockable, :timeoutable and :omniauthable 
    devise :registerable, :rememberable, :trackable, :omniauthable, :omniauth_providers => [:google_oauth2] 

    def self.from_omniauth auth 
    user = User.find_by_provider_and_uid(auth.provider, auth.uid) || User.create_with_omniauth(auth) 
    end 

    def self.create_with_omniauth auth 
    create! do |user| 
     user.provider = auth.provider 
     user.uid = auth.uid 
     user.name = auth.info.name 
     user.email = auth.info.email 
     user.avatar = auth.info.image 
    end 
    end 
end 

OmniAuth回調控制器:

class OmniauthCallbacksController < Devise::OmniauthCallbacksController 
    def google_oauth2 
    user = User.from_omniauth(request.env["omniauth.auth"]) 
    if user.persisted? 
     flash.notice = "Signed in Through Google!" 
     sign_in_and_redirect user 
    else 
     flash.alert = "Something went wrong" 
     redirect_to root_url 
    end 
    end 
end 

誰知道爲什麼這種情況正在發生或如何解決呢?

回答

1

我還沒有面對谷歌這樣的問題,但你仍然可以處理它,因爲谷歌的電子郵件是唯一的。

def self.from_omniauth auth 
    user = User.find_by_provider_and_uid(auth.provider, auth.uid) || User.find_by_provider_and_email(auth.provider, auth.info[:email]) || User.create_with_omniauth(auth) 
end 
相關問題