0

I'm using omniauth and devise and google to have users login to the website. I need to only allow users to sign in if they have a specific company email. For example, they click on sign-in with google and then unless they have a "@somecompany.com" email address they can successfully login. Otherwise they cannot login with a normal "@gmail.com" email. I cant seem to find where to do that in the documentation.

user model

def self.from_omniauth(access_token)
  data = access_token.info
  user = User.where(email: data['email']).first_or_initialize
  user.given_name = data['first_name']
  user.family_name = data['last_name']
  user.password = SecureRandom.uuid
  user.save!
  user
end 

omniauth controller

def google_oauth2

  @user = User.from_omniauth(request.env["omniauth.auth"])

  if @user.persisted?
    flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Google"
    sign_in_and_redirect @user, :event => :authentication
  else
    session["devise.google_data"] = request.env["omniauth.auth"]
    redirect_to new_user_registration_url
  end
 end

routes

 devise_for :users, :controllers => { :omniauth_callbacks => "omniauth_callbacks" }
Kiloreux
  • 2,220
  • 1
  • 17
  • 24
wildrails
  • 97
  • 2
  • 11

2 Answers2

1

You can try:

providers:
      - { name: 'google_oauth2', app_id: 'APP-ID',
         app_secret: 'APP-SECRET',
         args: { access_type: 'offline', approval_prompt: 'auto', hd: 'example.com' } }

where example.com is changed to your company domain.

Otherwise you can try these answers on StackOverflow:

  1. In Rails, is it possible to limit who can log in with google using the api?
  2. Restrict Login Email with Google OAuth2.0 to Specific Domain Name
Community
  • 1
  • 1
Anu_5512
  • 46
  • 6
0

Update your method in model as

def self.from_omniauth(access_token)
 data = access_token.info
 user = User.where(email: data['email']).first_or_initialize
 user.given_name = data['first_name']
 user.family_name = data['last_name']
 user.password = SecureRandom.uuid
 user.save! unless data['email'].split("@").include?('gmail.com')
 user
end

update google_oauth2 method as well for already registered user

if @user.persisted? && !@user.email.split("@").include?('gmail.com')
Prakash Laxkar
  • 824
  • 1
  • 8
  • 17