2013-05-07 20 views
13

我使用omniauth-twitter gem在我的rails應用程序中啓用Twitter登錄。這裏是我的代碼...「omniauth-twitter」電子郵件ID不是從軌道上的ruby中的twitter獲取的

的Gemfile -

gem 'omniauth', '~> 1.1.1' 
gem 'omniauth-twitter' 

的routes.rb -

match '/auth/twitter/callback', to: 'users#twitter_login' 
match 'auth/failure', to: 'static_pages#home' 

User_controller.rb -

 def twitter_login 
     auth = request.env['omniauth.auth'] 
     authentication = Authentication.find_by_provider_and_uid(auth['provider'],auth['uid']) 
     if authentication 
      sign_in authentication.user 
      redirect_to root_url 
     else 
     if(User.where(:email => auth['extra']['raw_info']['email']).exists?) 
      flash[:notice] = "You already have account in ibetter" 
      redirect_to root_url   
     else 
      user = User.new 
      user.apply_omniauth(auth)   
      if user.save(:validate => false)  
       sign_in user   
       flash[:notice] = "Welcome to Ginfy"   
       redirect_to root_url 
      else 
       flash[:error] = "Error while creating a user account. Please try again." 
       redirect_to root_url 
      end 
      end 
     end 
    end 

session_helper.rb -

def sign_in(user) 
    cookies.permanent[:remember_token] = user.remember_token 
    self.current_user = user 
    end 

User.rb模型 -

before_save { |user| user.email = email.downcase } 
    def apply_omniauth(auth) 
    self.email = auth['extra']['raw_info']['email'] 
    self.name = auth['extra']['raw_info']['name'] 
    authentications.build(:provider => auth['provider'], :uid => auth['uid'], :token => auth['credentials']['token']) 
    end 

ERB碼 -

<%= link_to image_tag("login-twitter.png", alt: "twitter"), "/auth/twitter",:class => "popup", :"data-width" => "600", :"data-height" => "400" %> 

電子郵件ID是不是從Twitter獲取。請幫助

+0

我用pry來調試類似的問題。包括'撬'寶石,然後添加'binding.pry'就在你期望從twitter獲取電子郵件ID的地方。然後,您可以檢查twitter的反應並找出發生的事情。 http://yorickpeterse.com/articles/debugging-with-pry/應該可以幫助你開始撬。 – 2013-05-07 09:30:17

+0

感謝您的評論,'撬'真棒創業板調試。現在它顯示像這樣'[1] pry(#)> self.email = auth ['extra'] ['raw_info'] ['email'] => nil'' [2] pry(#)> self .name = auth ['extra'] ['raw_info'] ['name'] =>「Ginfy」' – SoftwareGeek 2013-05-07 09:49:19

+0

[檢查此](http://stackoverflow.com/questions/3599621/is-there-a-way -to-get-an-users-email-id-after-verifying-her-twitter-identity-us) – SoftwareGeek 2013-05-07 09:57:46

回答

14

Twitter不會通過API向您發送電子郵件。

如果您使用omniauth-facebook gem作爲例子,但是twitter不會爲您提供電子郵件,您就必須創建解決方法。

例如,請求用戶在第二步填寫他/她的電子郵件地址。

+5

我通過將自動填充的電子郵件定位爲「#{twitter_nickname}@example.org」並讓用戶在閒暇時更改它。 – 2013-05-07 10:44:07

+0

嘿,湯姆,我目前有同樣的問題。你能分享你的代碼如何自動填充電子郵件嗎? – 2013-08-31 15:37:40

+0

我會添加一個before_create鉤子並將其設置爲電子郵件。 – Mattherick 2013-08-31 18:45:01

0

GEM工作正常,問題是Twitter因爲某些原因不需要return email。不像facebook ..

+0

如果您更新了您的Twitter權限,但您仍未收到OmniAuth哈希中的電子郵件字段,則必須更新您的Twitter憑證標記以獲取額外的參數。 – ZombieBsAs 2016-10-12 17:13:33

相關問題