meta/lib/recycledcloud/captcha.ex

34 lines
863 B
Elixir
Raw Normal View History

2021-02-03 09:37:00 +01:00
defmodule RecycledCloud.Captcha do
# We can't use a graphical-only captcha library such as
# https://hex.pm/packages/captcha since it would break accessibility for
# blind people. Let's make it simple maths instead!
# Captcha expression tuning:
@terms 1..6
@operands ["+", "-", "*"]
2021-02-03 09:37:00 +01:00
def validate(changeset, expected_result) do
result = Ecto.Changeset.get_field(changeset, :captcha)
if result == expected_result do
2021-02-03 09:37:00 +01:00
changeset
else
Ecto.Changeset.add_error(changeset, :captcha, "does not match")
end
end
def generate do
left = @terms |> Enum.random
right = @terms |> Enum.random
operation = @operands |> Enum.random
2021-02-03 09:37:00 +01:00
text = "#{left} #{operation} #{right}"
value = case operation do
"+" -> left + right
"-" -> left - right
"*" -> left * right
end
{text, value}
end
end