In Rails, is it possible to limit who can log in w

2020-02-26 02:11发布

问题:

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 :)

回答1:

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