Ruby on rails 如何在rails应用程序中使用GoogleOAuth2登录用户和创建新用户帐户?

Ruby on rails 如何在rails应用程序中使用GoogleOAuth2登录用户和创建新用户帐户?,ruby-on-rails,authentication,Ruby On Rails,Authentication,我正在为rails应用程序进行google身份验证。目前正在使用gem实现googleauth。我已经设法让用户使用谷歌登录。不过,我也希望用户能够使用谷歌注册。我的问题是,我已经将google回调URL与特定的控制器操作(会话#创建)匹配。 是否可以根据用户是登录还是注册在2个重定向URI之间进行选择?目前,我唯一的想法是创建新的用于注册的google客户端凭据,我希望有更好的方法。您不需要有2个重定向URI,只需要在接收回调时做更多的工作。例如: class SessionsControll

我正在为rails应用程序进行google身份验证。目前正在使用gem实现googleauth。我已经设法让用户使用谷歌登录。不过,我也希望用户能够使用谷歌注册。我的问题是,我已经将google回调URL与特定的控制器操作(会话#创建)匹配。
是否可以根据用户是登录还是注册在2个重定向URI之间进行选择?目前,我唯一的想法是创建新的用于注册的google客户端凭据,我希望有更好的方法。

您不需要有2个重定向URI,只需要在接收回调时做更多的工作。例如:

class SessionsController < ApplicationController

  ...

  def create
    email = auth_hash['info']['email'] # assuming your omniauth hash is auth_hash and you're requiring the email scope
    @user = User.find_by(email: email) if !email.blank? # assuming your user model is User

    if @user
      login_user(@user) # use your login method
    elsif !email.blank?
      @user = User.new(name: auth_hash['info']['name'], email: email) 
      unless @user.save!(validate: false) # validate false because I'm enforcing passwords on devise - hence I need to allow passwordless register here)
          # deal with error on saving
      end
    else
      # deal with no found user and no email
    end
  end

  protected

    def auth_hash
        request.env['omniauth.auth']
    end

end
尽管如此,你不能确定用户是否会给你电子邮件的访问权限,所以我个人认为第一个版本,即使稍微长一点,也更可靠。在较短的版本中,还有一个问题,
如果@user
为false,为什么会这样?这将需要你添加更多的逻辑来找出原因,而在第一个逻辑中,对每种情况应用正确的反应要容易得多

@user = User.create_with(name: auth_hash['info']['name']).find_or_initialize_by(email: email)
@user.save! if @user.new_record?
if @user 
  login_user(@user)
else 
  # deal with no user
end