Replace custom code generator with Base32
This commit is contained in:
@@ -1,18 +1,17 @@
|
||||
module MagicLink::Code
|
||||
CODE_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ".chars.freeze
|
||||
CODE_SUBSTITUTIONS = { "O" => "0", "I" => "1", "L" => "1" }.freeze
|
||||
|
||||
class << self
|
||||
def generate(length)
|
||||
Array.new(length) { CODE_ALPHABET[SecureRandom.random_number(CODE_ALPHABET.length)] }.join
|
||||
SecureRandom.base32(length)
|
||||
end
|
||||
|
||||
def sanitize(code)
|
||||
return nil if code.blank?
|
||||
|
||||
normalize_code(code)
|
||||
.then { apply_substitutions(_1) }
|
||||
.then { remove_invalid_characters(_1) }
|
||||
if code.present?
|
||||
normalize_code(code)
|
||||
.then { apply_substitutions(it) }
|
||||
.then { remove_invalid_characters(it) }
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
@@ -25,7 +24,7 @@ module MagicLink::Code
|
||||
end
|
||||
|
||||
def remove_invalid_characters(code)
|
||||
code.gsub(/[^#{CODE_ALPHABET.join}]/, "")
|
||||
code.gsub(/[^#{SecureRandom::BASE32_ALPHABET.join}]/, "")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -5,7 +5,7 @@ class MagicLink::CodeTest < ActiveSupport::TestCase
|
||||
code = MagicLink::Code.generate(6)
|
||||
|
||||
assert_equal 6, code.length
|
||||
assert_match(/\A[#{MagicLink::Code::CODE_ALPHABET.join}]+\z/, code)
|
||||
assert_match(/\A[#{SecureRandom::BASE32_ALPHABET.join}]+\z/, code)
|
||||
end
|
||||
|
||||
test "sanitize" do
|
||||
|
||||
Reference in New Issue
Block a user