如何使用Google Oauth2登录用户并在rails应用中创建新用户帐户?

时间:2017-07-25 10:01:43

标签: ruby-on-rails authentication

我正在为rails应用程序进行Google身份验证。目前正在使用omniauth-google-oauth2 gem来实施Google身份验证。我设法让用户使用谷歌登录。但是,我也希望用户能够使用谷歌注册。我的问题是,我将google回调网址与特定的控制器操作(sessions #create)相匹配。 是否可以根据用户是登录还是注册来选择2个重定向URI?目前,我唯一的想法是创建用于注册的新谷歌客户端凭据,我希望有更好的方法。

1 个答案:

答案 0 :(得分:0)

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

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 = 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

尽管如此,您无法确定用户是否会授予您对电子邮件的范围访问权限,因此我个人认为第一个版本即使有点长也更强大。然后在较短的版本上还有问题,if @user是假的,为什么会这样?并且需要你添加更多的逻辑来弄清楚为什么会这样,而在第一个中,对每种情况应用正确的响应要容易得多。