Merge pull request #2102 from basecamp/replace-custom-code-generator-with-base32

Replace custom code generator with Base32
This commit is contained in:
Stanko Krtalić
2025-12-12 07:57:10 +01:00
committed by GitHub
2 changed files with 8 additions and 9 deletions
+7 -8
View File
@@ -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
+1 -1
View File
@@ -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