我正在Rails 5.2演示应用程序中使用Devise(4.7.1)和omniauth-google-oauth2(0.8.0)来处理第三方注册。我可以使用种子数据正确登录并创建新用户没有问题。但是,当我尝试使用“使用Google OAuth2.0登录”按钮时,它不起作用。它将我路由回到根,这是回调控制器操作的一部分。
我一直在研究Web上有关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
关于此的任何帮助/指导,将不胜感激,因为我现在有点困惑。
谢谢:)
从我看到的代码中,您正在创建没有电子邮件的用户,但是您具有此验证validates :email, uniqueness: true
,如果您尝试创建2个帐户,则此验证将无效。
您能验证一下吗? User.where(email: "").count
,让我知道。我认为如果大于0,则无法注册。
删除电子邮件唯一性验证或尝试从身份验证参数中获取电子邮件。
您可以通过在回调控制器中打印错误日志进行调试
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
Rails.logger.info(@user.errors.full_messages)
session["devise.google_data"] = request.env["omniauth.auth"]
end