Devise + Twitter OmniAuth Get user Email

2019-06-13 19:57发布

问题:

I've been using Devise + OmniAuth Twitter to authenticate the user to my portal. I am currently facing two issues.

  1. When the user is accessing /users/sign_up, the form is publicly visible. Instead, I want to redirect him to the Twitter authentication page.

  2. When the user is accessing /users/sign_up, the email form is visible. I'm using this form to get the email address of the users after he signs up successfully from Twitter.

Can someone please help me solve this issue from people accessing the forms directly?

Adding Code Snippets:

 #config/routes.rb
  devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }

  devise_scope :user do
    get "skcript1625" => "devise/sessions#new", as: :login
    get "logout", to: "devise/sessions#destroy", as: :logout
  end



# app/models/user.rb
 devise :database_authenticatable, :registerable, :rememberable, :trackable, :validatable
 def self.from_omniauth(auth)
        where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
          user.email = auth.info.email
          user.password = Devise.friendly_token[0,20]
          user.name = auth.info.name   # assuming the user model has a name
          user.profileimg = auth.info.profileimg # assuming the user model has an image
        end
      end

回答1:

You have to redirect the user with the following link

<%= link_to "Sign in with Twitter", user_omniauth_authorize_path(:twitter) %>

Make sure you told your model (usually 'user') that it is 'omniauthable'

devise :omniauthable, :omniauth_providers => [:twitter]

When the user authorized twitter to share your info with the app, all the user's information is available in a hash request.env["omniauth.auth"].

See the documentation for more detail about this hash.

Edit: Everything is well explained here