因此,我的 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