繁体   English   中英

设计+ Omniauth + Twitter。 如何获取用户信息?

[英]Devise + Omniauth + Twitter. How to get user information?

我正在尝试创建一个允许用户使用Twitter进行注册的系统。 我正在关注本教程:

http://www.orhancanceylan.com/rails-twitter-and-facebook-authentications-with-omniauth-and-devise/

现在,我陷入了Twitter的回调操作中。 我已经检查了是否已经有身份验证,是否已经登录了用户,并且此方法应该可以正常工作,现在我正在创建“新用户”操作,该操作应同时创建身份验证和用户。

我希望用户单击“使用Twitter登录”按钮,然后该脚本应从Twitter的回调中获取“名称”,“用户名”,“生物”和“位置”。 然后,应将用户重定向到“第二步页面”,在该页面中应提供电子邮件和密码以完成注册。

在我的身份验证控制器中,我这样写:

  user = User.new

  user.name = omni['info'].name
  user.username = omni['info'].nickname
  user.location = omni['info'].location
  user.bio = omni['info'].description

  user.apply_omniauth omni
  user.avatar_from_url omni['info'].image

  session[:omniauth] = omni.except('extra')

  #What should I do here?

我已经尝试过重定向到new_user_registration_path因为它说的是教程,但随后我得到了原始的注册表单。 我仅使用电子邮件和密码字段创建了一个不同的视图,但我的主要问题是:

如何获取Twitter用户信息并将此数据传递给Devise控制器的create方法?

@khanh的回答略有错误:我没有足够的声誉来发表评论,所以我将在这里发布,对不起

uid可以通过这种方式获取(@khanh),但是昵称应该采用这种方式

puts env['omniauth.auth']['info']['name']

['info']哈希包括以下内容:

  • description
  • email (在Twitter中nil ),
  • image (个人资料图片链接),
  • location
  • name (Twitter用户名),
  • nickname (@username),
  • urlsurls哈希)。

整个['omniauth.auth']看起来像这样:

#<OmniAuth::AuthHash 
   credentials=#<OmniAuth::AuthHash
                  secret="some-secret-xxxxxxxxxxxxxxxxxxxxxx"
                  token="some-token-xxxxxxxxxxxxxxxxxxxxxx"
   >
   extra=#<OmniAuth::AuthHash 
            access_token=#<OAuth::AccessToken:0x0055cab742d2b8 
                            @token="some-token-xxxxxxxxxxxxxxxxxxxxxx", 
                            @secret="some-secret-xxxxxxxxxxxxxxxxxxxxxx", 
                            @consumer=#<OAuth::Consumer:0x0055cab760ba58 
                                          @key="some-consumer-key-xxxxxxxxxxxxxx", 
                                          @secret="some-consumer-secret-xxxxxxxxxxxxxx", 
                                          @options={
                                            :signature_method=>"HMAC-SHA1", 
                                            :request_token_path=>"/oauth/request_token", 
                                            :authorize_path=>"/oauth/authenticate", 
                                            :access_token_path=>"/oauth/access_token", 
                                            :proxy=>nil, 
                                            :scheme=>:header, 
                                            :http_method=>:post, 
                                            :oauth_version=>"1.0", 
                                            :site=>"https://api.twitter.com"
                                          }, 
                                          @http=#<Net::HTTP api.twitter.com:443 open=false>, 
                                          @http_method=:post, 
                                          @uri=#<URI::HTTPS https://api.twitter.com>
                            >, 
                            @params={
                              :oauth_token=>"some-token-xxxxxxxxxxxxxxxxxxxxxx", 
                              "oauth_token"=>"some-token-xxxxxxxxxxxxxxxxxxxxxx", 
                              :oauth_token_secret=>"some-secret-xxxxxxxxxxxxxxxxxxxxxx", 
                              "oauth_token_secret"=>"some-secret-xxxxxxxxxxxxxxxxxxxxxx", 
                              :user_id=>"000000000", 
                              "user_id"=>"000000000", 
                              :screen_name=>"sample_user", 
                              "screen_name"=>"sample_user", 
                              :x_auth_expires=>"0", 
                              "x_auth_expires"=>"0"
                            }, 
                            @response=#<Net::HTTPOK 200 OK readbody=true>
            > 
            raw_info=#<OmniAuth::AuthHash 
                        contributors_enabled=false 
                        created_at="Fri Sep 02 23:56:11 +0000 2011" 
                        default_profile=false 
                        default_profile_image=false 
                        description="Hi my name is Sample and I'm a Twitter user." 
                        entities=#<OmniAuth::AuthHash 
                                    description=#<OmniAuth::AuthHash 
                                                    urls=[]
                                    > 
                                    url=#<OmniAuth::AuthHash 
                                            urls=[
                                              #<OmniAuth::AuthHash 
                                                 display_url="link.to/my/blog_or_someth…" 
                                                 expanded_url="http://link.to/my/blog_or_something.html" 
                                                 indices=[0, 23] 
                                                 url="https://t.co/SAMPLE007"
                                              >
                                            ]
                                    >
                        > 
                        favourites_count=690
                        follow_request_sent=false 
                        followers_count=42
                        following=false 
                        friends_count=34 
                        geo_enabled=false 
                        has_extended_profile=false 
                        id=000000000 
                        id_str="000000000" 
                        is_translation_enabled=false 
                        is_translator=false 
                        lang="ja" 
                        listed_count=24 
                        location="Tokyo, Japan" 
                        name="Sample user" 
                        notifications=false 
                        profile_background_color="DBE9ED" 
                        profile_background_image_url="http://abs.twimg.com/images/themes/theme17/bg.gif" 
                        profile_background_image_url_https="https://abs.twimg.com/images/themes/theme17/bg.gif" 
                        profile_background_tile=false 
                        profile_banner_url="https://pbs.twimg.com/profile_banners/0000000000/00000000000" 
                        profile_image_url="http://pbs.twimg.com/profile_images/010101010101010101/LeoGT5Xu_normal.png" 
                        profile_image_url_https="https://pbs.twimg.com/profile_images/010101010101010101/LeoGT5Xu_normal.png" 
                        profile_link_color="CC3366" 
                        profile_sidebar_border_color="DBE9ED" 
                        profile_sidebar_fill_color="E6F6F9" 
                        profile_text_color="333333" 
                        profile_use_background_image=true 
                        protected=false 
                        screen_name="sample_user" 
                        statuses_count=61468 
                        time_zone="Tokyo" 
                        url="https://t.co/SAMPLE007" 
                        utc_offset=32400 
                        verified=false
            >
  >
  info=#<OmniAuth::AuthHash::InfoHash
          description="Hi my name is Sample and I'm a Twitter user."
          email=nil
          image="http://pbs.twimg.com/profile_images/010101010101010101/LeoGT5Xu_normal.png"
          location="Tokyo, Japan"
          name="Sample User"
          nickname="sample_user"
          urls=#<OmniAuth::AuthHash
                  Twitter="https://twitter.com/sample_user"
                  Website="https://t.co/SAMPLE007">
  > 
  provider="twitter"
  uid="000000000"
>

这样您就可以从

env['omniauth.auth']['extra']['raw_info']['name']
env['omniauth.auth']['extra']['raw_info']['screen_name']

太。 我不确定哪个(来自['info']['raw_info'] )是更好的方法。 但是['raw_info']似乎['raw_info']提供了更多信息。


编辑:是的,所有的内容都写在Wiki中!

验证哈希模式-intridea / omniauth Wiki | Github上

但是Twitter没有具体的案例,所以也许我的回答毕竟有用! :)

您可以按照以下步骤操作:

devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }

users / omniauth_callbacks_controller.rb

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
   def twitter   
    # show twitter account information
    puts env['omniauth.auth']['uid']
    puts puts env['omniauth.auth']['nickname']
  end
end   

要将用户重定向到其他表单以输入他们的电子邮件,我们可以使用此方法进行注册。

重定向用户后(如果是新用户),我们将呈现一个TwitterForm表单,供用户输入电子邮件以完成注册。

接下来,表单将提交给我们指定的自定义操作,在我的案例中,我将其放在UsersController下,它将使用Twitter会话数据和用户输入的电子邮件完成注册过程。

完整答案在这里

设计CallbacksController

 def twitter
        auth = request.env["omniauth.auth"]
        @user = User.where(provider: auth.provider, uid: auth.uid).first_or_create
        if @user.persisted?
            flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Twitter"
            sign_in_and_redirect @user, :event => :authentication
        else
            @form = TwitterForm.new 
            session["devise.twitter_data"] = request.env["omniauth.auth"].except("extra")
            render :layout => 'none'
        end
    end

UsersController

def twitter_register
    @form = TwitterForm.new(params[:twitter_form])
    if @form.valid?
      email = params[:twitter_form][:email]      
      @user = User.from_twitter_omniauth(session["devise.twitter_data"],email)
      if @user.persisted?
        flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Twitter"
        sign_in_and_redirect @user, :event => :authentication
      else
        redirect_to register_path 
      end
    else 
      render 'callbacks/twitter',layout: 'none'
    end
  end

暂无
暂无

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

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