【问题标题】:Rails: Using OmniAuth (FB authorization), Reading Data From Facebook HashRails:使用 OmniAuth(FB 授权),从 Facebook Hash 读取数据
【发布时间】:2012-11-01 11:31:47
【问题描述】:

使用 OmniAuth,我成功从 Facebook 获取哈希数据:存储在“auth”中

# extra=#] last_name="Jordan" link="http://www.facebook.com/michael" locale="en_US" middle_name="Ball" name="Michael Jordan" quotes="\"lalala\"\n\n\"lala\"" timezone=9 updated_time="2011-09-01T20:25:58+0000" username="mjordan82" verified=true>> info=# verified=true> provider="facebook" uid="123456879">

在用户模型中,我执行以下操作:

def self.create_with_omniauth(auth)
  create! do |user|
    user.provider = auth["provider"]
    user.uid = auth["uid"]
    user.name = auth["name"]
  end
end

当我检查数据库时,我只有提供者和 uid。 User.name 行为空。通过测试,我发现除了提供者和 uid 之外,我无法存储其他数据。例如,user.name = auth["provider"] 或 user.name = auth["uid"] 存储没有问题,但是当我尝试类似 user.name = auth["timezone"] 或 user.name = auth["last_name"],变量中没有存储任何内容。有人知道怎么修这个东西吗?我也试过 user.name = auth["user_info"]["name"],但它返回了一个错误。

我不确定为什么 user.name = auth["name"] 不存储任何内容。换句话说,为什么在这种情况下 auth["name"] 不是 "Michael Jordan"?

【问题讨论】:

    标签: ruby-on-rails hash authorization omniauth


    【解决方案1】:

    关键是:我以错误的方式访问身份验证哈希。答案是你这样做

    user.name = auth["info"]["name"]
    

    这里是关于 Auth Hash 的详细信息:

    :provider => 'facebook',
    :uid => '1234567',
    
    :info => {
     :nickname => 'jbloggs',
     :email => 'joe@bloggs.com',
     :name => 'Joe Bloggs',
     :first_name => 'Joe',
     :last_name => 'Bloggs',
     :image => 'http://graph.facebook.com/1234567/picture?type=square',
     :urls => { :Facebook => 'http://www.facebook.com/jbloggs' },
     :location => 'Palo Alto, California',
     :verified => true
    },
    :credentials => {
     :token => 'ABCDEF...', # OAuth 2.0 access_token, which you may wish to store
     :expires_at => 1321747205, # when the access token expires (it always will)
     :expires => true # this will always be true
    },
    :extra => {
      :raw_info => {
      :id => '1234567',
      :name => 'Joe Bloggs',
      :first_name => 'Joe',
      :last_name => 'Bloggs',
      :link => 'http://www.facebook.com/jbloggs',
      :username => 'jbloggs',
      :location => { :id => '123456789', :name => 'Palo Alto, California' },
      :gender => 'male',
      :email => 'joe@bloggs.com',
      :timezone => -8,
      :locale => 'en_US',
      :verified => true,
      :updated_time => '2011-11-11T06:21:03+0000'
    }
    

    来源:https://github.com/mkdynamic/omniauth-facebook

    这就是为什么我可以通过简单的 auth["provider"] 访问“provider”和“uid”,而我需要这样做

    auth["info"]["name"] 
    

    访问名称信息。

    同样,要获取用户的时区,您可以这样做

    auth["extra"]["timezone"]
    

    【讨论】:

    • 如果您想查看返回的哈希值,请将其添加到您的操作顶部:raise request.env['omniauth.auth'].to_yaml
    • 'render :text => request.env['omniauth.auth'].inspect' 也不错!
    猜你喜欢
    • 2011-05-15
    • 1970-01-01
    • 2014-11-10
    • 2011-06-21
    • 2012-12-09
    • 1970-01-01
    • 2013-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多