Skip to content

Commit

Permalink
add domain block model and checks
Browse files Browse the repository at this point in the history
  • Loading branch information
Floppy committed Nov 28, 2024
1 parent e742637 commit fd43895
Show file tree
Hide file tree
Showing 5 changed files with 72 additions and 0 deletions.
9 changes: 9 additions & 0 deletions app/models/federails/moderation/domain_block.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
module Federails::Moderation
class DomainBlock < ApplicationRecord
validates :domain, presence: true, uniqueness: true, "federails/moderation/domain_name": true

def self.blocked?(query)
self.exists?(domain: [ query, PublicSuffix.parse(query).domain ])
end
end
end
9 changes: 9 additions & 0 deletions app/validators/federails/moderation/domain_name_validator.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
require "public_suffix"

module Federails::Moderation
class DomainNameValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors.add attribute, :invalid unless PublicSuffix.valid?(value, default_rule: nil)
end
end
end
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
class CreateFederailsModerationDomainBlocks < ActiveRecord::Migration[8.0]
def change
create_table :federails_moderation_domain_blocks do |t|
t.string "domain", null: false, index: { unique: true }
t.timestamps
end
end
end
1 change: 1 addition & 0 deletions federails-moderation.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,5 @@ Gem::Specification.new do |spec|
end
spec.add_dependency "rails", ">= 7.2.2"
spec.add_dependency "federails", "~> 0.3"
spec.add_dependency "public_suffix", "~> 6.0"
end
45 changes: 45 additions & 0 deletions spec/models/domain_block_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
RSpec.describe Federails::Moderation::DomainBlock do
[
"example.com",
"my.website.co.uk",
"Bücher.de",
"кц.рф",
"互联网中心.中国",
"☃.com"
].each do |test|
it "is valid if domain name is #{test.inspect}" do
block = described_class.new(domain: test)
expect(block).to be_valid
end
end

[
nil,
"",
"example.invalid",
".example.com"
].each do |test|
it "is invalid if domain name is #{test.inspect}" do
block = described_class.new(domain: test)
expect(block).not_to be_valid
end
end

context "with a blocked domain" do
before do
described_class.create(domain: "blocked.com")
end

it "blocks the domain" do
expect(described_class.blocked?("blocked.com")).to be true
end

it "blocks subdomains" do
expect(described_class.blocked?("www.blocked.com")).to be true
end

it "allows other domains" do
expect(described_class.blocked?("example.com")).to be false
end
end
end

0 comments on commit fd43895

Please sign in to comment.