0

我在使用omniauth-facebook 时遇到问题。我尝试使用 facebook 登录我的 Rails 应用程序,但它给了我一个错误,并且 env['omniauth.auth'] 在这里抛出一个 nil 值是错误..

 NoMethodError at /auth/facebook/callback
 undefined method `slice' for nil:NilClass

这是我的模型

#fields
  field :provider
  field :uid
  field :name
  field :oauth_token 
  field :oauth_expires_at , type: DateTime

  #functions
  def self.from_omniauth(auth)
    where(auth.slice(:provider, :uid)).find_or_initialize_by.tap do |user|
      user.provider = auth.provider
      user.uid = auth.uid
      user.name = auth.info.name
      user.oauth_token = auth.credentials.token
      user.oauth_expires_at = Time.at(auth.credentials.expires_at)
      user.save!
    end
  end

这是我的控制器

  def create
    user = Usersfb.from_omniauth(ENV["omniauth.auth"])
    session[:user_id] = user.id
    redirect_to root_url
  end
  def destroy
    session[:user_id] = nil
    redirect_to root_url
  end

我的路线.rb

  root 'main#index'
  get 'session/destroy' , to: 'session#destroy'
  get 'auth/:provider/callback' => 'session#create'
4

2 回答 2

1

request.env 对我不起作用。我在omniauth初始化程序中添加了callback_path,它现在可以工作了。这是它的样子:

全域认证.rb

Rails.application.config.middleware.use OmniAuth::Builder do
provider :facebook, APP_ID, APP_SECRET, callback_path: '/auth/facebook/callback'
end
于 2018-07-27T03:21:27.463 回答
0

您在控制器操作中有错误:

def create
  #user = Usersfb.from_omniauth(ENV["omniauth.auth"])
  user = Usersfb.from_omniauth(request.env["omniauth.auth"])
  session[:user_id] = user.id
  redirect_to root_url
end

ENV不是环境变量request.env,这个ENV["omniauth.auth"]返回nil 和这个where(auth.slice(:provider, :uid))尝试切片nil引发 undefined method 'slice' for nil:NilClass

于 2014-07-14T07:59:44.890 回答