首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Google Oauth2在rails应用程序中同时登录用户和创建新用户帐户?

如何使用Google Oauth2在rails应用程序中同时登录用户和创建新用户帐户?
EN

Stack Overflow用户
提问于 2017-07-25 18:01:43
回答 1查看 77关注 0票数 0

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-25 19:19:05

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

代码语言:javascript
复制
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

我已经编写了所有步骤,但创建过程可以缩短为:

代码语言:javascript
复制
@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是假的,为什么是这样呢?并且将需要您添加更多的逻辑来找出原因,而在第一个逻辑中,对每种情况应用正确的响应要容易得多。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45299977

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档