没有设计的 Omniauth 和 google oauth2 错误 - Rails 4

Omniauth and google oauth2 error without Devise - Rails 4

编辑:我已经按照下面的答案更新了 POST 因为我在其他地方被卡住了,下面给出的答案是正确的。

大家好,我正在尝试实施社交身份验证,但我被卡住了。

我已经在我的路由和 google 控制台中正确设置了回调 url,并且我已经通过在浏览器中显示 auth_hash 来验证它。

我的session_controller.rb

def google_oauth2
auth_hash = request.env['omniauth.auth']

@user = User.find_by_provider_and_uid(auth_hash["provider"], auth_hash["uid"])
if @user
  log_in @user
  flash[:success] = "Welcome, #{@user.name}!"
else
  @user = User.new(
    uid: auth_hash['uid'],
    provider: auth_hash['provider'],
    name: auth_hash['info']['name'],
    email: auth_hash['info']['email'],
    image_url: auth_hash['info']['image'],
    oauth_token: auth_hash['credentials']['token'],
    oauth_refresh_token: auth_hash['credentials']['refresh_token'],
    oauth_expires_at: auth_hash['credentials']['expires_at']
  )
  if @user.save
    log_in @user
    flash[:success] = "Hello, #{@user.name}! An account has been created for you!"
  else
    flash[:warning] = "There was an error while trying to authenticate you..."
  end
end
redirect_to root_path

结束

User.model

validates :name,
            presence: true,
            length: { maximum: 50 }



  validates :email,
            presence: true,
            length: { maximum: 255 },
            format: { with: VALID_EMAIL_REGEX },
            uniqueness: { case_sensitive:false }

  has_secure_password
  validates :password,
            presence:true,
            length: { minimum: 8 },
            allow_nil: true

这是控制台中的错误

    Started GET "/auth/google_oauth2/callback?state=00407988327c46ec93248da4dadba18c56efc88ef44c36b0&code=4/l666HRBZExC2XR93sI4VP7pWIYAkNySwD75sHtSOb_o" for ::1 at 2015-08-07 02:43:34 +0300
I, [2015-08-07T02:43:34.321568 #6869]  INFO -- omniauth: (google_oauth2) Callback phase initiated.
Processing by SessionsController#google_oauth2 as HTML
  Parameters: {"state"=>"00407988327c46ec93248da4dadba18c56efc88ef44c36b0", "code"=>"4/l666HRBZExC2XR93sI4VP7pWIYAkNySwD75sHtSOb_o", "provider"=>"google_oauth2"}
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."provider" = ? AND "users"."uid" = ? LIMIT 1  [["provider", "google_oauth2"], ["uid", "118084345864130537689"]]
   (0.0ms)  begin transaction
  User Exists (0.1ms)  SELECT  1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER('testemail@gmail.com') LIMIT 1
   (0.0ms)  rollback transaction
Redirected to http://localhost:3000/
Completed 302 Found in 20ms (ActiveRecord: 1.2ms)

问题是我的会话控制器中的错误每次都会触发,并且没有创建用户

"There was an error while trying to authenticate you..."

有谁可以合作吗?

救援很可能不是因为 @user.save!,而是 user.uid = auth_hash['uid'] 的错误,因为 user 未设置。

只需从所有名称中删除 user. 即可。

P.S.

1.You 不应该在没有指定要从中拯救的错误的情况下使用 rescue(现在它只是跳过可能出现的每一个错误)。

  1. 不需要将所有参数分配给变量。直接使用它们

  2. 您真的应该重构大部分代码。您的大部分控制器代码都应该进入模型。

我的代码版本是这样的:

session_controller.rb

def google_oauth2
    auth_hash = request.env['omniauth.auth']
    if User.from_omniauth(auth_hash)
      session[:user_id] = @user.id
      flash[:success] = "Welcome, #{@user.name}!"
      redirect_to root_path
    else
     User.new(uid: auth_hash['uid'],
      provider: auth_hash['provider'],
      name: auth_hash['info']['name'],
      email: auth_hash['info']['email'],
      image_url: auth_hash['info']['image'])

      if @user.save!
       flash[:success] = "Welcome, #{@user.name}!You've signed up!"
      else
       flash[:warning] = "There was an error while trying to authenticate you..."
      end
    end
    redirect_to root_path
end

user.rb

def self.from_omniauth(auth_hash)
      find_by(uid: auth_hash['uid'], provider: auth_hash['provider'])
end

但是,如果您将创建用户的所有代码也放入模型中,那就更好了。