Files
danbooru/app/models/ip_ban.rb
evazion b4ce2d83a6 models: remove belongs_to_creator macro.
The belongs_to_creator macro was used to initialize the creator_id field
to the CurrentUser. This made tests complicated because it meant you had
to create and set the current user every time you wanted to create an
object, when lead to the current user being set over and over again. It
also meant you had to constantly be aware of what the CurrentUser was in
many different contexts, which was often confusing. Setting creators
explicitly simplifies everything greatly.
2020-01-21 00:09:38 -06:00

46 lines
1.3 KiB
Ruby

class IpBan < ApplicationRecord
belongs_to :creator, class_name: "User"
validate :validate_ip_addr
validates_presence_of :reason
validates_uniqueness_of :ip_addr
after_create { ModAction.log("#{creator.name} created ip ban for #{ip_addr}", :ip_ban_create) }
after_destroy { ModAction.log("#{creator.name} deleted ip ban for #{ip_addr}", :ip_ban_delete) }
def self.is_banned?(ip_addr)
where("ip_addr >>= ?", ip_addr).exists?
end
def self.search(params)
q = super
q = q.search_attributes(params, :creator, :reason)
if params[:ip_addr].present?
q = q.where("ip_addr = ?", params[:ip_addr])
end
q.apply_default_order(params)
end
def validate_ip_addr
if ip_addr.blank?
errors[:ip_addr] << "is invalid"
elsif ip_addr.ipv4? && ip_addr.prefix < 24
errors[:ip_addr] << "may not have a subnet bigger than /24"
elsif ip_addr.ipv6? && ip_addr.prefix < 64
errors[:ip_addr] << "may not have a subnet bigger than /64"
elsif ip_addr.private? || ip_addr.loopback? || ip_addr.link_local?
errors[:ip_addr] << "must be a public address"
end
end
def has_subnet?
(ip_addr.ipv4? && ip_addr.prefix < 32) || (ip_addr.ipv6? && ip_addr.prefix < 128)
end
def subnetted_ip
str = ip_addr.to_s
str += "/" + ip_addr.prefix.to_s if has_subnet?
str
end
end