Replace custom code generator with Base32

This commit is contained in:
Stanko K.R.
2025-12-12 07:45:23 +01:00
parent 23425cb67b
commit a4d11e169f
2 changed files with 8 additions and 9 deletions
+6 -7
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?
if code.present?
normalize_code(code)
.then { apply_substitutions(_1) }
.then { remove_invalid_characters(_1) }
.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