aboutsummaryrefslogtreecommitdiff
path: root/lib/recaptcha/http.ex
blob: a9aaf0f62752d7e7fffdd441643d1e4577f0ecca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
defmodule Recaptcha.Http do
  @moduledoc """
   Responsible for managing HTTP requests to the reCAPTCHA API
  """

  alias Recaptcha.Config

  @headers [
    {"Content-type", "application/x-www-form-urlencoded"},
    {"Accept", "application/json"}
  ]

  @default_verify_url "https://www.google.com/recaptcha/api/siteverify"

  @doc """
  Sends an HTTP request to the reCAPTCHA version 2.0 API.

  See the [docs](https://developers.google.com/recaptcha/docs/verify#api-response)
  for more details on the API response.

  ## Options

    * `:timeout` - the timeout for the request (defaults to 5000ms)

  ## Example

    {:ok, %{
      "success" => success,
      "challenge_ts" => ts,
      "hostname" => host,
      "error-codes" => errors
    }} = Recaptcha.Http.request_verification(%{
      secret: "secret",
      response: "response",
      remote_ip: "remote_ip"
    })
  """
  @spec request_verification(map, [timeout: integer]) :: {:ok, map} | {:error, [atom]}
  def request_verification(body, options \\ []) do
    timeout = options[:timeout] || Config.get_env(:recaptcha, :timeout, 5000)
    url = Config.get_env(:recaptcha, :verify_url, @default_verify_url)

    result =
      with {:ok, response} <- HTTPoison.post(url, body, @headers, timeout: timeout),
           {:ok, data} <- Poison.decode(response.body) do
        {:ok, data}
      end

    case result do
      {:ok, data} -> {:ok, data}
      {:error, :invalid} -> {:error, [:invalid_api_response]}
      {:error, {:invalid, _reason}} -> {:error, [:invalid_api_response]}
      {:error, %{reason: reason}} -> {:error, [reason]}
    end
  end
end