2019-11-24 19:36:21 +01:00
|
|
|
defmodule PhilomenaWeb.CaptchaPlug do
|
|
|
|
alias Philomena.Captcha
|
2020-04-11 20:23:55 +02:00
|
|
|
import Plug.Conn
|
|
|
|
import Phoenix.Controller
|
2019-11-24 19:36:21 +01:00
|
|
|
|
|
|
|
def init([]), do: false
|
|
|
|
|
|
|
|
def call(conn, _opts) do
|
2020-07-28 22:56:26 +02:00
|
|
|
case captcha_enabled?() do
|
|
|
|
true -> maybe_check_captcha(conn, conn.assigns.current_user)
|
|
|
|
false -> conn
|
|
|
|
end
|
2019-11-24 19:36:21 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
defp maybe_check_captcha(conn, nil) do
|
|
|
|
case Captcha.valid_solution?(conn.params) do
|
2020-01-11 05:20:19 +01:00
|
|
|
true ->
|
|
|
|
conn
|
|
|
|
|
2019-11-24 19:36:21 +01:00
|
|
|
false ->
|
|
|
|
conn
|
2020-04-11 20:23:55 +02:00
|
|
|
|> put_flash(
|
2020-01-11 05:20:19 +01:00
|
|
|
:error,
|
|
|
|
"There was an error verifying you're not a robot. Please try again."
|
|
|
|
)
|
2020-04-11 20:23:55 +02:00
|
|
|
|> do_failure_response(ajax?(conn))
|
|
|
|
|> halt()
|
2019-11-24 19:36:21 +01:00
|
|
|
end
|
|
|
|
end
|
2020-01-11 05:20:19 +01:00
|
|
|
|
2019-11-24 19:36:21 +01:00
|
|
|
defp maybe_check_captcha(conn, _user), do: conn
|
2020-04-11 20:23:55 +02:00
|
|
|
|
|
|
|
defp do_failure_response(conn, true) do
|
|
|
|
conn
|
|
|
|
|> put_status(:multiple_choices)
|
|
|
|
|> text("")
|
|
|
|
end
|
|
|
|
|
|
|
|
defp do_failure_response(conn, _false) do
|
|
|
|
redirect(conn, external: conn.assigns.referrer)
|
|
|
|
end
|
|
|
|
|
|
|
|
def ajax?(conn) do
|
|
|
|
case get_req_header(conn, "x-requested-with") do
|
|
|
|
[value] -> String.downcase(value) == "xmlhttprequest"
|
|
|
|
_ -> false
|
|
|
|
end
|
|
|
|
end
|
2020-07-28 22:56:26 +02:00
|
|
|
|
|
|
|
def captcha_enabled? do
|
|
|
|
Application.get_env(:philomena, :captcha) != false
|
|
|
|
end
|
2019-11-24 19:36:21 +01:00
|
|
|
end
|