BigW Consortium Gitlab

url_sanitizer.rb 1.39 KB
Newer Older
1
module Gitlab
2 3 4 5 6
  class UrlSanitizer
    def self.sanitize(content)
      regexp = URI::Parser.new.make_regexp(['http', 'https', 'ssh', 'git'])

      content.gsub(regexp) { |url| new(url).masked_url }
7 8
    rescue Addressable::URI::InvalidURIError
      content.gsub(regexp, '')
9 10
    end

James Lopez committed
11 12 13 14 15 16 17 18
    def self.valid?(url)
      Addressable::URI.parse(url.strip)

      true
    rescue Addressable::URI::InvalidURIError
      false
    end

James Lopez committed
19
    def initialize(url, credentials: nil)
20
      @url = Addressable::URI.parse(url.strip)
James Lopez committed
21
      @credentials = credentials
22 23 24 25 26 27
    end

    def sanitized_url
      @sanitized_url ||= safe_url.to_s
    end

28 29 30 31 32 33 34
    def masked_url
      url = @url.dup
      url.password = "*****" unless url.password.nil?
      url.user = "*****" unless url.user.nil?
      url.to_s
    end

35 36 37 38
    def credentials
      @credentials ||= { user: @url.user, password: @url.password }
    end

James Lopez committed
39 40 41 42
    def full_url
      @full_url ||= generate_full_url.to_s
    end

43 44
    private

James Lopez committed
45
    def generate_full_url
James Lopez committed
46
      return @url unless valid_credentials?
James Lopez committed
47
      @full_url = @url.dup
48 49
      @full_url.user = credentials[:user]
      @full_url.password = credentials[:password]
James Lopez committed
50 51 52
      @full_url
    end

53 54 55 56 57 58
    def safe_url
      safe_url = @url.dup
      safe_url.password = nil
      safe_url.user = nil
      safe_url
    end
James Lopez committed
59 60 61 62

    def valid_credentials?
      credentials && credentials.is_a?(Hash) && credentials.any?
    end
63
  end
64
end