Validate language codes in MapOfString

This commit is contained in:
tusooa 2022-12-28 15:23:58 -05:00 committed by marcin mikołajczak
parent 8822dc1191
commit dbebd7fbf4
3 changed files with 33 additions and 2 deletions

View file

@ -12,7 +12,11 @@ def cast(object) when is_map(object) do
object
|> Enum.reduce(%{}, fn
{lang, value}, acc when is_binary(lang) and is_binary(value) ->
Map.put(acc, lang, value)
if is_good_locale_code?(lang) do
Map.put(acc, lang, value)
else
acc
end
_, acc ->
acc
@ -21,6 +25,20 @@ def cast(object) when is_map(object) do
{:ok, data}
end
defp is_good_locale_code?(code) do
code
|> String.codepoints()
|> Enum.all?(&valid_char?/1)
end
# [a-zA-Z0-9-]
defp valid_char?(char) do
("a" <= char and char <= "z") or
("A" <= char and char <= "Z") or
("0" <= char and char <= "9") or
char == "-"
end
def cast(_), do: :error
def dump(data), do: {:ok, data}

View file

@ -35,6 +35,18 @@ test "it ignores non-strings within the map" do
assert validated_data == %{"en-US" => "mew mew"}
end
test "it ignores bad locale codes" do
data = %{
"en-US" => "mew mew",
"en_GB" => "meow meow",
"en<<#@!$#!@%!GB" => "meow meow"
}
assert {:ok, validated_data} = MapOfString.cast(data)
assert validated_data == %{"en-US" => "mew mew"}
end
test "it complains with non-map data" do
assert :error = MapOfString.cast("mew")
assert :error = MapOfString.cast(["mew"])

View file

@ -38,7 +38,8 @@ test "resistent to tampering" do
"en-GB" => "meow {code} {content}"
}
assert MultiLanguage.map_to_str(data) == "[en-GB] meow {code} {content} | [en-US] mew {code} {content}"
assert MultiLanguage.map_to_str(data) ==
"[en-GB] meow {code} {content} | [en-US] mew {code} {content}"
end
end