设计before_save过滤器不应用

时间:2013-03-15 15:35:19

标签: ruby-on-rails ruby-on-rails-3 devise

在我的用户可以注册之前,我需要先通过api对它们进行身份验证,看看他们的信息是否有效。无论如何我有我的validate_api方法工作,因为它需要我测试了这个,但我不确定为什么当我尝试注册一个错误的api它仍然保存用户。

我将我的方法放在一个控制器中并用一个有效的api调用它,它返回true然后是错误的api,它返回false。

因此,如果该方法正在运行,则要么被忽略,要么覆盖它。

我的用户模型

class User < ActiveRecord::Base
  attr_accessor :login

    before_save :validate_api

    # Include default devise modules. Others available are:
    # :token_authenticatable, :confirmable,
    # :lockable, :timeoutable and :omniauthable
    devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :authentication_keys => [:login]

    validates :username, :presence => true, :length => { :minimum => 6, :maximum => 255 }
    validates :apiid, :presence => true, :numericality => { :only_integer => true }
    validates :vcode, :presence => true, :length => { :minimum => 20, :maximum => 255 }

    # Setup accessible (or protected) attributes for your model
    attr_accessible :login, :username, :group, :apiid, :vcode, :email, :password, :password_confirmation, :remember_me

    # Check if user is banned before login
    def active_for_authentication?
      super && self.banned == 0
    end

    # Redefine authentication procedure to allow login with username or email
    def self.find_for_database_authentication(warden_conditions)
      conditions = warden_conditions.dup
      if login = conditions.delete(:login).downcase
        #where(conditions).where('$or' => [ {:username => /^#{Regexp.escape(login)}$/i}, {:email => /^#{Regexp.escape(login)}$/i} ]).first
        where(conditions).where("username = '#{login}' OR email = '#{login}'").first
      else
        where(conditions).first
      end
    end

    # Validate API information
    private
    def validate_api

        require 'nokogiri'
        require 'open-uri'

        uri = "https://*******?keyID=#{self.apiid}&vCode=#{self.vcode}"
        xml = Nokogiri::XML(open(uri))

        xml.xpath("//row").each do |row|
            if row['****'].downcase == '****'
                return true
            else
                return false                
            end
        end
    end

end

1 个答案:

答案 0 :(得分:1)

如果api检查失败,则应使用before_save :validate_api,然后添加错误消息(例如:validate :check_api),而不是使用errors[:apiid] << "must be a valid API id."