【发布时间】:2013-03-01 04:45:28
【问题描述】:
所以我的 Omniauth 和 Twitter 验证功能大约 95%,换句话说,它几乎可以完全正常工作。当单击 |使用 Twitter 登录 |按钮,它将我重定向到 Twitter,然后提示我输入我的 Twitter 凭据,然后重定向回应用程序。
但是,我没有在 Twitter 身份验证过程之后登录,而是在登录页面上收到以下错误:
1 error prohibited this user from being saved:
Email can't be blank
在 /posts 页面的情况下,如何让 Omniauth 将我重定向到登录页面?当 Omniauth 应该通过 Twitter 验证授权我时,为什么会产生这样的错误?
用户模型:
class User < ActiveRecord::Base
has_many :authentications
# Include default devise modules. Others available are:
# :token_authenticatable, :lockable, :timeoutable and :activatable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation
# attr_accessible :title, :body
def apply_omniauth(omniauth)
self.email = omniauth['info']['email'] if email.blank?
authentications.build(:provider => omniauth['provider'], :uid => omniauth['uid'])
end
def password_required?
(authentications.empty? || !password.blank?) && super
end
end
身份验证控制器:
class AuthenticationsController < ApplicationController
def create
omniauth = request.env["omniauth.auth"]
authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
if authentication
flash[:notice] = "Signed in successfully."
sign_in_and_redirect(:user, authentication.user)
elsif current_user
current_user.authentications.create!(:provider => omniauth['provider'], :uid => omniauth['uid'])
flash[:notice] = "Authentication successful."
redirect_to authentications_url
else
user = User.new
user.apply_omniauth(omniauth)
if user.save
flash[:notice] = "Signed in successfully."
sign_in_and_redirect(:user, user)
else
session[:omniauth] = omniauth.except('extra')
redirect_to new_user_registration_url
end
end
end
end
注册控制器:
class RegistrationsController < Devise::RegistrationsController
def create
super
session[:omniauth] = nil unless @user.new_record?
end
private
def build_resource(*args)
super
if session[:omniauth]
@user.apply_omniauth(session[:omniauth])
@user.valid?
end
end
end
【问题讨论】:
-
omniauth 首先尝试在回调时创建一个用户,在您的用户模型中您有
validate_presence_of :email,所以您可能没有在初始omniauth 过程之后分配电子邮件? -
@Guy 感谢您的回复,您愿意详细说明吗?我已经将我的 user.rb 文件添加到了操作中,如果有任何其他文件我应该添加来帮助解决这个问题,请告诉我!
-
你能把控制器也展示一下吗?
-
当然,我已经用他们更新了操作。
标签: ruby-on-rails ruby-on-rails-3 rubygems omniauth