繁体   English   中英

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

[英]How can I view user's personal data with 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

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

配置/初始化程序/devise.rb

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM