在我的用户注册之前,我需要先通过 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