我一直在与Facebook Omniauth and Devise合作,但遇到了一个问题,即返回的哈希不包含我在我的信息字段中请求的任何信息。我只是试图让Facebook通过电子邮件返回名字和姓氏,如果它可以单独提供,那么我可以用这些信息创建新用户。我不认为我需要设置Facebook的特定权限才能返回这些字段(就像你需要验证的一些info_fields一样)。
我使用的是Rails 4.2.6。 这是返回的哈希:
#<OmniAuth::AuthHash credentials=#<OmniAuth::AuthHash
expires=true expires_at=1486542909
token="EAAXYor9I0XgBADbIaZC99Lu0xGAdVVSXSyZC1TsZCHcZCi0kiWPdZCHA0DsLait7zn1cSpEsbc1mViWvFxZAPraz2Hdyfyn2pfonpeDlhP6Nqv7RiGNpDQ1Bxxm81LHwoPHMIbag95pksGZChcQ7YMrk8eUuQNkgScZD">
extra=#<OmniAuth::AuthHash
raw_info=#<OmniAuth::AuthHash id="xxxxxxxxxx" name="xxxxxxxx">>
info=#<OmniAuth::AuthHash::InfoHash
image="http://graph.facebook.com/xxxxxxxxxx/picture?type=square"
name="xxxxxxxxxx">
provider="facebook"
uid="xxxxxxxxxx">
类似问题的大部分解决方案都涉及到devise.rb中的一些内容,对我来说这似乎是这样的:
config.omniauth :facebook, "xxxIDxxx", "xxxSECRETxxx", scope: 'email,public_profile', info_fields: 'email, first_name, last_name'
我的CallBacksController:
class CallbacksController < Devise::OmniauthCallbacksController
def all
@user = User.from_omniauth(request.env["omniauth.auth"])
@request = request.env["omniauth.auth"]
if @user.persisted?
flash.notice = "You have successfully signed in!"
sign_in_and_redirect @user
else
session["devise.user_attributes"] = @user.attributes
redirect_to new_user_registration_path
end
end
alias_method :facebook, :all
end
我的User.rb:
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :omniauthable, :omniauth_providers => [:facebook]
has_many :posts
def self.from_omniauth(auth)
puts auth
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.provider = auth.provider
user.uid = auth.uid
user.email = auth.info.email || ""
user.password = Devise.friendly_token[0,20]
end
end
这些是我使用的相关宝石:
gem 'geocoder'
gem 'devise'
gem 'omniauth'
gem 'omniauth-facebook'
过去几天这让我发疯,我被困住了。任何建议将不胜感激。如果有些事情可能与我意外遗漏有关,请告诉我,我很乐意发布它们。谢谢!
答案 0 :(得分:0)
我使用omniauth gem和omniauth-facebook gem。我得到的哈希值很长。这就是我创建新用户的方式:
#Facebook login
def self.from_omniauth(auth)
where(email: auth.info.email).first_or_initialize.tap do |user|
user.name = auth.info.name
user.email = auth.info.email
user.password = auth.uid
user.password_confirmation = auth.uid
user.remote_avatar_url = auth.info.image
user.uid = auth.uid
user.provider = auth.provider
user.oauth_token = auth.credentials.token
user.oauth_expires_at = Time.at(auth.credentials.expires_at) if auth.provider == "facebook"
user.save!
end
end
要在那段时间调试这个,我在控制器中得到哈希值时出错:
raise request.env["omniauth.auth"].to_yaml
这使您在终端中获得了从Facebook获得的哈希的格式良好的输出。