Refactor diaspora ID regex to be used in diaspora:// URL regex

This commit is contained in:
Benjamin Neff 2017-09-12 21:52:45 +02:00
parent 92dc8b0277
commit 5e3f510a88
No known key found for this signature in database
GPG key ID: 971464C3F1A90194
2 changed files with 11 additions and 9 deletions

View file

@ -5,23 +5,25 @@ module Validation
# A simple rule to validate the base structure of diaspora* IDs.
class DiasporaId
# The Regex for a valid diaspora* ID
DIASPORA_ID = begin
DIASPORA_ID_REGEX = begin
letter = "a-zA-Z"
digit = "0-9"
hexadecimal = "[a-fA-F#{digit}]"
username = "[#{letter}#{digit}\\-\\_\\.]+"
hostname_part = "[#{letter}#{digit}\\-]"
hostname = "#{hostname_part}+([.]#{hostname_part}*)*"
hostname = "#{hostname_part}+(?:[.]#{hostname_part}*)*"
ipv4 = "(?:[#{digit}]{1,3}\\.){3}[#{digit}]{1,3}"
ipv6 = "\\[(?:#{hexadecimal}{0,4}:){0,7}#{hexadecimal}{1,4}\\]"
ip_addr = "(?:#{ipv4}|#{ipv6})"
domain = "(?:#{hostname}|#{ip_addr})"
port = "(:[#{digit}]+)?"
addr_spec = "(#{username}\\@#{domain}#{port})?"
port = "(?::[#{digit}]+)?"
/\A#{addr_spec}\z/u
"#{username}\\@#{domain}#{port}"
end
# The Regex for validating a full diaspora* ID
DIASPORA_ID = /\A#{DIASPORA_ID_REGEX}\z/u
# The error key for this rule
# @return [Symbol] error key
def error_key
@ -30,7 +32,7 @@ module Validation
# Determines if value is a valid diaspora* ID
def valid_value?(value)
value.nil? || !DIASPORA_ID.match(value).nil?
value.is_a?(String) && value =~ DIASPORA_ID
end
# This rule has no params.

View file

@ -83,13 +83,13 @@ describe Validation::Rule::DiasporaId do
expect(validator.errors).to include(:diaspora_id)
end
it "allows nil and empty" do
it "fails for nil and empty" do
[nil, ""].each do |val|
validator = Validation::Validator.new(OpenStruct.new(diaspora_id: val))
validator.rule(:diaspora_id, :diaspora_id)
expect(validator).to be_valid
expect(validator.errors).to be_empty
expect(validator).not_to be_valid
expect(validator.errors).to include(:diaspora_id)
end
end
end