3

Is it possible to only allow certain google accounts to log on? for example myname@mycompany.com is host through google (they are actually google account). I want only user with the @mycompany to be able log on is this possible? do you do this with devise or google api?

Thank you :)

Naomi K
  • 1,437
  • 4
  • 13
  • 20

1 Answers1

4

If you are using omniauth-google-oauth2, you can accomplish domain restrictions using by providing a value for hd option during initialization.

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :google_oauth2, ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET'], {
    scope: 'email, profile',
    hd: 'mycompany.com'
  }
end

It's also possible to handle this in your controller which is handling the callback. You can deny users depending on values provided in request.env["omniauth.auth"].

class OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def google_oauth2
    auth_details = request.env["omniauth.auth"]
    if auth_details.info['email'].split("@")[1] == "yourdomain.com"
      # do all the bits that come naturally in the callback controller
      user = User.from_omniauth(request.env["omniauth.auth"])
      if user.persisted?
        flash.notice = "Signed in Through Google!"
        sign_in_and_redirect user
      else
        session["devise.user_attributes"] = user.attributes
        flash.notice = "You are almost Done! Please provide a password to finish setting up your account"
        redirect_to new_user_registration_url
      end
    else
      # This is where you turn away the poor souls who do not match your domain
      render :text => "We're sorry, at this time we do not allow access to our app."
    end
  end
end
trh
  • 7,186
  • 2
  • 29
  • 41
  • Hi, Thank you very much for explanation! one question, why do you write [1] in .split("@")[1] ? – Naomi K Sep 18 '13 at 13:23
  • split returns an array of items. In this case you're splitting on the @ sign so the two items left in the array are the portion before the @ sign and the domain after. So the [1] is denoting the second item in the array. – trh Sep 18 '13 at 17:13
  • Hello, I am coming back to this question, sorry. but where did you get auth_details.info from? is this something omniauth already has? I ask because it doesnt seem to work – Naomi K Sep 23 '13 at 15:49
  • updated the answer - auth_details could have been named anything, it's just a map to the auth hash – trh Sep 23 '13 at 21:15
  • I see! thank you, what do you recommend i look up to read more about the request.env ? – Naomi K Sep 24 '13 at 14:13
  • You can see check the omniauth strategy for google oauth 2, they keep the docs updated with the hash, but you can always print the request it to the screen or a log if you're looking for the actual information: https://github.com/zquestz/omniauth-google-oauth2#auth-hash – trh Sep 24 '13 at 15:11