我正在使用omniauth-facebook gem和devise。它一直工作到最近。我最近也从Rails 4升级到Rails 5.0.1,但我不确定是什么原因。
我目前有0个用户,我已登录Facebook。但是当我尝试在localhost上使用Facebook注册我的应用程序时,我收到此错误:
NoMethodError in RegistrationsController#facebook
undefined method `provider' for nil:NilClass
这是我的用户模型。我标记了错误突出显示的行。
User.rb
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable,
:omniauthable, :omniauth_providers => [:facebook]
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user| #ERROR
@data = auth.info
user.name = @data.name
# ...
end
end
RegistrationsController
def facebook
@user = User.from_omniauth(request.env["omniauth.auth"])
if @user.persisted?
sign_in_and_redirect @user, :event => :authentication
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
另外,这是我的链接:
<%= link_to "fb", user_facebook_omniauth_callback_path(:facebook, thing: @thing.id, degree: @degree, :format => :js) %>
HTML输出:
<a href=\"/auth/facebook/callback.js?thing=2\">fb<\/a>
路径:
localhost:3000/auth/facebook/callback.js?thing=2
所以问题是request.env["omniauth.auth"]
由于某种原因是零的。我在任何文档中都找不到任何类似错误的痕迹。
以前有人遇到这个或有任何想法吗?
答案 0 :(得分:1)
要通过Facebook进行身份验证,您只需要将您网站上的链接添加到Facebook:
www.yoursite.com/auth/facebook
然后设置一条路线,通过身份验证哈希接收来自Facebook的回调:
#routes.rb
get 'auth/facebook/callback' => 'sessions#create_facebook'
您可以指定此行的输出方式或传递其他信息的原因吗?:
<%= link_to "fb", user_facebook_omniauth_callback_path(:facebook, thing: @thing.id, degree: @degree, :format => :js) %>
修改强>
auth / facebook / callback是一个获取请求。 Facebook会在那里向您发送用户身份验证哈希。只有Facebook本身应该使用该路线。如果您想验证您的链接必须是:
localhost:3000/auth/facebook
他们有你的方式,omniauth期待facebook的身份验证哈希,但收到“?thing = 2”,导致身份验证失败。 Omniauth尝试从“?thing = 2”中提取信息,这不是哈希值,当您尝试访问auth [provider]时,auth为空,因此未定义提供程序导致:
undefined method `provider' for nil:NilClass
答案 1 :(得分:0)
我遇到了同样的问题,并通过从用户模型
中删除:omniauthable
来解决此问题