In Rails, is it possible to limit who can log in with google using the api?

前端 未结 1 1632
面向向阳花
面向向阳花 2020-12-30 19:04

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 wa

1条回答
  •  礼貌的吻别
    2020-12-30 19:25

    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
    

    0 讨论(0)
提交回复
热议问题