summaryrefslogtreecommitdiff
path: root/test/elixir/lib/couch.ex
blob: 58581b2fd5e21387b198dd3215b84738edbce1c5 (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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
defmodule Couch.Session do
  @moduledoc """
  CouchDB session helpers.
  """

  @enforce_keys [:cookie]
  defstruct [:cookie]

  def new(cookie) do
    %Couch.Session{cookie: cookie}
  end

  def logout(sess) do
    headers = [
      "Content-Type": "application/x-www-form-urlencoded",
      "X-CouchDB-WWW-Authenticate": "Cookie",
      Cookie: sess.cookie
    ]

    Couch.delete!("/_session", headers: headers)
  end

  def get(sess, url, opts \\ []), do: go(sess, :get, url, opts)
  def get!(sess, url, opts \\ []), do: go!(sess, :get, url, opts)
  def put(sess, url, opts \\ []), do: go(sess, :put, url, opts)
  def put!(sess, url, opts \\ []), do: go!(sess, :put, url, opts)
  def post(sess, url, opts \\ []), do: go(sess, :post, url, opts)
  def post!(sess, url, opts \\ []), do: go!(sess, :post, url, opts)
  def delete(sess, url, opts \\ []), do: go(sess, :delete, url, opts)
  def delete!(sess, url, opts \\ []), do: go!(sess, :delete, url, opts)

  # Skipping head/patch/options for YAGNI. Feel free to add
  # if the need arises.

  def go(%Couch.Session{} = sess, method, url, opts) do
    opts = Keyword.merge(opts, cookie: sess.cookie)
    Couch.request(method, url, opts)
  end

  def go!(%Couch.Session{} = sess, method, url, opts) do
    opts = Keyword.merge(opts, cookie: sess.cookie)
    Couch.request!(method, url, opts)
  end
end

defmodule Couch do
  use HTTPotion.Base

  @moduledoc """
  CouchDB library to power test suite.
  """

  def process_url("http://" <> _ = url) do
    url
  end

  def process_url(url) do
    base_url = System.get_env("EX_COUCH_URL") || "http://127.0.0.1:15984"
    base_url <> url
  end

  def process_request_headers(headers, options) do
    headers = Keyword.put(headers, :"User-Agent", "couch-potion")

    headers =
      if headers[:"Content-Type"] do
        headers
      else
        Keyword.put(headers, :"Content-Type", "application/json")
      end

    case Keyword.get(options, :cookie) do
      nil ->
        headers

      cookie ->
        Keyword.put(headers, :Cookie, cookie)
    end
  end

  def process_options(options) do
    if Keyword.get(options, :cookie) == nil do
      headers = Keyword.get(options, :headers, [])

      if headers[:basic_auth] != nil or headers[:authorization] != nil do
        options
      else
        username = System.get_env("EX_USERNAME") || "adm"
        password = System.get_env("EX_PASSWORD") || "pass"
        Keyword.put(options, :basic_auth, {username, password})
      end
    else
      options
    end
  end

  def process_request_body(body) do
    if is_map(body) do
      :jiffy.encode(body)
    else
      body
    end
  end

  def process_response_body(headers, body) do
    content_type = headers[:"Content-Type"]

    if !!content_type and String.match?(content_type, ~r/application\/json/) do
      body |> IO.iodata_to_binary() |> :jiffy.decode([:return_maps])
    else
      process_response_body(body)
    end
  end

  def login(userinfo) do
    [user, pass] = String.split(userinfo, ":", parts: 2)
    login(user, pass)
  end

  def login(user, pass) do
    resp = Couch.post("/_session", body: %{:username => user, :password => pass})
    true = resp.body["ok"]
    cookie = resp.headers[:"set-cookie"]
    [token | _] = String.split(cookie, ";")
    %Couch.Session{cookie: token}
  end

  # HACK: this is here until this commit lands in a release
  # https://github.com/myfreeweb/httpotion/commit/f3fa2f0bc3b9b400573942b3ba4628b48bc3c614
  def handle_response(response) do
    case response do
      {:ok, status_code, headers, body, _} ->
        processed_headers = process_response_headers(headers)

        %HTTPotion.Response{
          status_code: process_status_code(status_code),
          headers: processed_headers,
          body: process_response_body(processed_headers, body)
        }

      {:ok, status_code, headers, body} ->
        processed_headers = process_response_headers(headers)

        %HTTPotion.Response{
          status_code: process_status_code(status_code),
          headers: processed_headers,
          body: process_response_body(processed_headers, body)
        }

      {:ibrowse_req_id, id} ->
        %HTTPotion.AsyncResponse{id: id}

      {:error, {:conn_failed, {:error, reason}}} ->
        %HTTPotion.ErrorResponse{message: error_to_string(reason)}

      {:error, :conn_failed} ->
        %HTTPotion.ErrorResponse{message: "conn_failed"}

      {:error, reason} ->
        %HTTPotion.ErrorResponse{message: error_to_string(reason)}
    end
  end

  # Anther HACK: Until we can get process_request_headers/2 merged
  # upstream.
  @spec process_arguments(atom, String.t(), [{atom(), any()}]) :: %{}
  defp process_arguments(method, url, options) do
    options = process_options(options)

    body = Keyword.get(options, :body, "")

    headers =
      Keyword.merge(
        Application.get_env(:httpotion, :default_headers, []),
        Keyword.get(options, :headers, [])
      )

    timeout =
      Keyword.get(
        options,
        :timeout,
        Application.get_env(:httpotion, :default_timeout, 5000)
      )

    ib_options =
      Keyword.merge(
        Application.get_env(:httpotion, :default_ibrowse, []),
        Keyword.get(options, :ibrowse, [])
      )

    follow_redirects =
      Keyword.get(
        options,
        :follow_redirects,
        Application.get_env(:httpotion, :default_follow_redirects, false)
      )

    ib_options =
      if stream_to = Keyword.get(options, :stream_to),
        do:
          Keyword.put(
            ib_options,
            :stream_to,
            spawn(__MODULE__, :transformer, [stream_to, method, url, options])
          ),
        else: ib_options

    ib_options =
      if user_password = Keyword.get(options, :basic_auth) do
        {user, password} = user_password
        Keyword.put(ib_options, :basic_auth, {to_charlist(user), to_charlist(password)})
      else
        ib_options
      end

    %{
      method: method,
      url: url |> to_string |> process_url(options) |> to_charlist,
      body: body |> process_request_body,
      headers:
        headers
        |> process_request_headers(options)
        |> Enum.map(fn {k, v} -> {to_charlist(k), to_charlist(v)} end),
      timeout: timeout,
      ib_options: ib_options,
      follow_redirects: follow_redirects
    }
  end
end