about summary refs log tree commit diff
path: root/app/helpers/autoreject_helper.rb
blob: 2f869d405df67f2058798aa11d2c3f700f7b7469 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
module AutorejectHelper
  include ModerationHelper

	def should_reject?(uri = nil)
    if uri.nil?
      if @object
        uri = object_uri.start_with?('http') ? object_uri : @object['url']
      elsif @json
        uri = @json['id']
      end
    end

    return if uri.nil?
    return unless @json || @object

    domain = uri.scan(/[\w\-]+\.[\w\-]+(?:\.[\w\-]+)*/).first
    blocks = DomainBlock.suspend
    return [:domain, uri] if blocks.where(domain: domain).or(blocks.where('domain LIKE ?', "%.#{domain}")).exists?

    if @json
      oid = @json['id']
      if oid
        return [:id_starts_with, uri] if ENV.fetch('REJECT_IF_ID_STARTS_WITH', '').split.any? { |r| oid.start_with?(r) }
        return [:id_contains, uri] if ENV.fetch('REJECT_IF_ID_CONTAINS', '').split.any? { |r| r.in?(oid) }
      end

      username = @json['preferredUsername'] || @json['username']
      if username && username.is_a?(String)
        username = (@json['actor'] && @json['actor'].is_a?(String)) ? @json['actor'] : ''
        username = username.scan(/(?<=\/user\/|\/@|\/users\/)([^\s\/]+)/).first
      end

      unless username.blank?
        username.downcase!
        return [:username, uri] if ENV.fetch('REJECT_IF_USERNAME_EQUALS', '').split.any? { |r| r == username }
        return [:username_starts_with, uri] if ENV.fetch('REJECT_IF_USERNAME_STARTS_WITH', '').split.any? { |r| username.start_with?(r) }
        return [:username_contains, uri] if ENV.fetch('REJECT_IF_USERNAME_CONTAINS', '').split.any? { |r| r.in?(username) }
      end
    end

    nil
  end

  def reject_reason(reason)
    case reason
    when :domain
      "the origin domain is blocked"
    when :id_starts_with
      "the object's URI starts with a blocked phrase"
    when :id_contains
      "the object's URI contains a blocked phrase"
    when :username
      "the author's username is blocked"
    when :username_starts_with
      "the author's username starts with a blocked phrase"
    when :username_contains
      "the author's username contains a blocked phrase"
    else
      "of an undefined reason"
    end
  end

  def autoreject?(uri = nil)
    return false if @options && @options[:imported]
    reason, uri = should_reject?(uri)
    if reason
      reason = reject_reason(reason)
      if @json
        Rails.logger.info("Rejected an incoming '#{@json['type']}#{@object && " #{@object['type']}".rstrip}' from #{@json['id']} because #{reason}.")
      elsif uri
        Rails.logger.info("Rejected an outgoing request to #{uri} because #{reason}.")
      end
      return true
    end
    false
  end
end