我正在使用 Rails 构建社交登录,并且已成功将其与 Google 和 Facebook 集成。所以,我对 Twitter 也是如此。但是登录 Twitter 后我无法重定向到我的应用程序。我收到如下错误:
ActiveRecord::RecordInvalid in Users::OmniauthCallbacksController#twitter 验证失败:电子邮件不能为空,电子邮件不能为空,电子邮件无效
这是我在控制器中的代码:
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def facebook
generic_callback("facebook")
end
def google_oauth2
generic_callback("google_oauth2")
end
def twitter
generic_callback("twitter")
end
def generic_callback provider
@user = User.from_omniauth(request.env["omniauth.auth"])
if @user.persisted?
log_in @user
flash[:success] = t("users.new.welcome")
redirect_to @user
else
flash[:error] = t("sessions.new.error")
redirect_to root_url
end
end
def failure
redirect_to root_path
end
end
模型中获取数据的部分代码
# Generate data from the social
def self.from_omniauth(auth)
user = User.where(email: auth.info.email).first
password = Devise.friendly_token[0,20]
user ||= User.create!(provider: auth.provider,
uid: auth.uid,
email: auth.info.email,
name: auth.info.name,
password: password,
password_confirmation: password)
end
并在文件中配置 devise.rb
config.omniauth :google_oauth2, ENV["CLIENT_ID"], ENV["CLIENT_SECRET"], scope: "email", info_fields: "email,name"
config.omniauth :facebook, ENV["FACEBOOK_ID"], ENV["FACEBOOK_SECRET"], scope: "email", info_fields: "email,name"
config.omniauth :twitter, ENV["TWITTER_ID"], ENV["TWITTER_SECRET"], scope: "email", info_fields: "email,name"