I have a Rails app that uses Devise and Omniauth to handle authentications. As prescribed I am receiving callbacks from the providers in my omniauth\_callbacks\_controller, where I check if the authentication already exists, and whether a user with the email given by the provider already exists, creating a new user if necessary. 

I need a valid email for each user. My problem comes with callbacks from Twitter. Twitter doesn't provide an email for its users, so I can't create a valid user. To solve this I store the provider's data in a session and I send the user the new registrations page, asking them to submit their email address so I can create a valid user. When this form is submitted I hit a problem. The form has created a new user, but it is perfectly possible that a user with that email already exists (in which case I would need to add the authentication to that user).

At the moment I am checking to see if a user with the same email as the new user already exists. If so, I am ignoring the new user and applying the authentication to the user that already exists. However this feels really hacky.

How should I be doing this?

```
class Users::RegistrationsController < Devise::RegistrationsController

def build_resource(*args)
    super
    if session[:omniauth]
      #If a user with this email already exists then use them instead
      existing_user = User.find_by_email(@user.email)
      if(existing_user)
          existing_user.email = @user.email
          @user = existing_user
      end
      #If there is a session available, we know it contains data for adding an authentication
      @user.apply_omniauth_data_as_authentication(session[:omniauth])
      #Ensure validations are passed on to next page
      @user.valid?
    end
  end

```