Jasper
Jasper

Reputation: 168

Devise - Merge OAuth with existing account

I set up omniauth for Devise using the instructions on their website at https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview

I now want to allow users which already have an account to transparently login with their google account: if the google account uses the same email address as the user registered with earlier, the site should log in the user with that account.

I simply modified the proposed code at the link as follows:

def self.from_omniauth(auth)
  user = User.find_by(email: auth.info.email)
  if user
    user.skip_confirmation! 
    user.provider = auth.provider
    user.uid = auth.uid
    user.name = auth.info.name
    return user
  end

  where(auth.slice(:provider, :uid)).first_or_create do |user|
    user.skip_confirmation! 
    user.provider = auth.provider
    user.uid = auth.uid
    user.email = auth.info.email
    user.password = Devise.friendly_token[0,20]
    user.name = auth.info.name
  end
end

It seems to work fine, though I'm wondering if this code introduces any risks that I'm not aware of. Devise is kind of a black box to me.

Upvotes: 3

Views: 1517

Answers (2)

Jasper
Jasper

Reputation: 168

Here's the code I'm using now. Happy copy pasting.

def self.from_omniauth(auth)
  user = User.find_by(email: auth.info.email)
  if user and user.confirmed?
    user.provider = auth.provider
    user.uid = auth.uid
    return user
  end

  where(auth.slice(:provider, :uid)).first_or_create do |user|
    user.skip_confirmation! 
    user.provider = auth.provider
    user.uid = auth.uid
    user.email = auth.info.email
    user.password = Devise.friendly_token[0,20]
    user.name = auth.info.name
  end
end

Upvotes: 2

Ashitaka
Ashitaka

Reputation: 19203

You can only link accounts if they are both confirmed. Google is an email provider so the email is already confirmed on their end. However, you are not checking if your user account that already exists is confirmed.

So if I knew your email, I could register in your site with it and wait for you to login with Google later. I would then have access to your account.

You should only merge accounts if Devise's confirmed? method returns true.

Upvotes: 7

Related Questions