ruby on rails -全功能重定向



所以我得到了具有Twitter验证功能的Omniauth,大约95%,换句话说,它几乎是全功能的。当点击我的应用程序上的| login with Twitter |按钮时,它会将我重定向到Twitter,然后提示我输入我的Twitter凭据,然后重定向回应用程序。

然而,在Twitter认证过程之后,我没有登录,而是在登录页面上得到以下错误:

1 error prohibited this user from being saved:
    Email can't be blank

我如何让Omniauth重定向到登录页面在我的情况下/posts页面?当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

我刚想起来,原因其实很简单,twitter在omniauth请求中不返回电子邮件,所以它会将您重定向到新用户注册页面,您必须填写您的电子邮件。

https://github.com/intridea/omniauth/wiki/Auth-Hash-Schema

此外,这可能有帮助

为omniauth-twitter跳过邮件验证

最新更新