【发布时间】:2015-07-20 19:02:53
【问题描述】:
我有这个方法,我将通过该方法检查提供者和 uid 属性,以在创建新寄存器或获取现有寄存器之间进行选择。
这是将 facebook 登录集成到我的应用程序中。
如果我想检查已经在我的应用程序中注册的用户,而不是通过 facebook,使用他们的电子邮件地址作为搜索键,然后将来自 facebook 的 proivider 和 uid 属性添加到该帐户,那么一个好的逻辑是什么?
def self.from_omniauth(hash)
where(provider: hash.provider, uid: hash.uid).first_or_create do |user|
user.email = hash.info.email
user.password = Devise.friendly_token[0,20]
user.username = hash.info.name
end
更新
类用户::OmniauthCallbacksController
def facebook
@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 => "Facebook") if is_navigational_format?
else
session["devise.facebook_data"] = request.env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
end
我按照你建议的方法更新了代码
def self.from_omniauth(hash)
find_by_provider_and_uid(hash.provider, hash.uid) || find_by_omni_email(hash.info.email) || create_with_omniauth(hash)
end
def self.create_with_omniauth(hash)
u = User.new
u.provider = hash.provider
u.uid = hash.uid
u.email = hash.info.email
u.password = Devise.friendly_token[0,20]
u.username = hash.info.name
puts "tried to create_with+omniauth"
end
def self.find_by_omni_email(email)
User.where(email: email).first
puts "ran find_by_omni_email"
end
def self.find_by_provider_and_uid(provider, uid)
User.where(provider: provider, uid: uid).first
puts "ran find_by_provider_and_uid"
end
【问题讨论】:
-
这一行:
where(provider: hash.provider, uid: hash.uid).first_or_create如果用户已经存在,则不会创建任何新记录。
标签: ruby-on-rails oauth