E-Mail Sign-Up and OAuth Log-In - how to set it up with Devise on Rails

74 Views Asked by At

I have set up Devise to allow a user to register with e-mail. Now I have included a Log In via LinkedIn with omniauth. Therefore I had to save provider as well as uid in the users table.

The problem I have now, is that the combination of provider and uid should be unique. But when a user decides to register with email I don't have any values for provider and uid. How can I deal with this problem in a good way?

I am new to Rails and did not find any other answers to it.

Thanks a lot!

2

There are 2 best solutions below

2
On

I would probably fill in manual in the provider and generate a uid with SecureRandom.uuid.

You could do this in your User model using a before_validation hook.

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

  before_validation(on: :create) do
    if self.provider.nil?
      self.provider = 'manual'
      self.uid = SecureRandom.uuid
    end
  end

...

end

You could also hook into the controller which creates the user.

If you need the uid to prevent a user from signing up twice with the same email, I'd use a sha256 hash of the email-address.

0
On

Get it from request.env['omniauth.auth']

More details here: https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview