如何使用omniauth查看用户的个人数据?

时间:2015-09-23 15:59:20

标签: ruby-on-rails ruby omniauth

我希望使用Ruby on Rails的gem Omniauth查看用户的个人数据。现在,我只能查看公共数据。我收到错误电子邮件不能为空,因为我只能访问公共数据,而不是个人用户数据。所有答案都表示赞赏。这是我的应用程序的代码:

#identity.rb

class Identity < ActiveRecord::Base
 belongs_to :user
 validates_presence_of :uid, :provider
 validates_uniqueness_of :uid, :scope => :provider

 def self.find_for_oauth(auth)
   find_or_create_by(uid: auth.uid, provider: auth.provider)
 end

end

#user.rb


      def self.find_for_oauth(auth, signed_in_resource = nil)
identity = Identity.find_for_oauth(auth)
user = signed_in_resource ? signed_in_resource : identity.user
if user.nil?

  email = auth.info.email
  user = User.where(:email => email).first if email

  # Create the user if it's a new registration
  if user.nil?
    user = User.new(
      full_name: auth.info.name,
      username: 'User'+auth.uid,
      email: auth.info.email,
      password: auth.uid
    )
    user.skip_confirmation!
    user.save!
   end 
end


if identity.user != user
  identity.user = user
  identity.save!
end
user
 end

#omniauth_callbacks_controller.rb


     def self.provides_callback_for(provider)
class_eval %Q{
  def #{provider}
    @user = User.find_for_oauth(env["omniauth.auth"], current_user)

    if @user.persisted?
      sign_in_and_redirect @user, event: :authentication
      set_flash_message(:notice, :success, kind: "#{provider}".capitalize) if is_navigational_format?
    else
      session["devise.#{provider}_data"] = env["omniauth.auth"]
      redirect_to new_user_registration_url
    end
  end
}
 end

[:github, :google_oauth2].each do |provider|
provides_callback_for provider
 end

1 个答案:

答案 0 :(得分:1)

您需要在GitHub omniauth配置中请求特定范围。

<强>配置/初始化/ devise.rb

config.omniauth :github, 'YOUR_API_KEYS', scope: 'user'