使用Rails和Devise登录时,Google UID会发生变化

时间:2014-06-23 05:45:04

标签: ruby-on-rails ruby devise omniauth

出于某种原因,在我通过Omniauth创建用户后,我无法再次登录该用户,因为Google会返回不同的UID。

基本上我首先使用Google登录。如果用户不存在,我创建一个用户,并保存UID。在下次登录时,我通过提供者和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 个答案:

答案 0 :(得分: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