【发布时间】:2020-06-21 20:47:35
【问题描述】:
我在 Rails 5.2 演示应用程序中使用 Devise (4.7.1) 和 omniauth-google-oauth2 (0.8.0) 来处理第 3 方注册。我可以使用种子数据正确登录并创建新用户没问题。但是,当我尝试使用“使用 Google OAuth2.0 登录”按钮时,它不起作用。它将我的返回路由到根,这是回调控制器操作的一部分。
我一直在网上查看有关 CSRF 失败和使用无效凭据的各种指南。我已经解决了这些问题,但现在只剩下这个让我感到困惑的问题。我得到的错误是:
User Load (0.6ms) SELECT "users".* FROM "users" WHERE "users"."provider" = ? AND "users"."uid" = ? ORDER BY "users"."id" ASC LIMIT ? [["provider", "google_oauth2"], ["uid", "106922203178875367517"], ["LIMIT", 1]]
↳ app/models/user.rb:21
(0.1ms) begin transaction
↳ app/models/user.rb:21
User Exists (0.7ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = ? LIMIT ? [["email", ""], ["LIMIT", 1]]
↳ app/models/user.rb:21
(0.1ms) rollback transaction
似乎创建新用户的操作开始了,但由于回调 uri 生成的 params 哈希中没有电子邮件而停止。
params 哈希如下所示:
Parameters: {"state"=>"XXXXXXXXXXX", "code"=>"XXXXXXXXXXX", "scope"=>"email profile https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile openid", "authuser"=>"0", "prompt"=>"consent"}
我的用户模型如下所示:
class User < ApplicationRecord
has_many :comments
has_many :books, through: :comments
validates :email, uniqueness: true
# validates :first_name, presence: {message: "Please enter your first name"}
# validates :last_name, presence: {message: "Please enter your surname"}
validates :encrypted_password, presence: true
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable, :omniauthable, :omniauth_providers => [:google_oauth2]
def self.from_omniauth(auth)
# Either create a User record or update it based on the provider (Google) and the UID
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.token = auth.credentials.token
user.expires = auth.credentials.expires
user.expires_at = auth.credentials.expires_at
user.refresh_token = auth.credentials.refresh_token
end
end
end
回调控制器如下所示:
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
skip_before_action :verify_authenticity_token
def google_oauth2
@user = User.from_omniauth(request.env["omniauth.auth"])
if @user.persisted?
sign_in @user, :event => :authentication #this will throw if @user is not activated
set_flash_message(:notice, :success, :kind => "Google") if is_navigational_format?
else
session["devise.google_data"] = request.env["omniauth.auth"]
end
redirect_to '/'
end
end
任何关于这方面的帮助/指导将不胜感激,因为我现在有点难过。
谢谢:)
【问题讨论】:
标签: ruby devise ruby-on-rails-5