diff --git a/lib/httparrot.ex b/lib/httparrot.ex index c71237e..ec7176c 100644 --- a/lib/httparrot.ex +++ b/lib/httparrot.ex @@ -12,6 +12,7 @@ defmodule HTTParrot do {'/redirect-to', HTTParrot.RedirectToHandler, []}, {'/cookies', HTTParrot.CookiesHandler, []}, {'/cookies/set', HTTParrot.SetCookiesHandler, []}, + {'/cookies/delete', HTTParrot.DeleteCookiesHandler, []}, {'/basic-auth/:user/:passwd', HTTParrot.BasicAuthHandler, []}, {'/html', :cowboy_static, {:priv_file, :httparrot, "html.html"}} ] } ]) diff --git a/lib/httparrot/delete_cookies_handler.ex b/lib/httparrot/delete_cookies_handler.ex new file mode 100644 index 0000000..805bb64 --- /dev/null +++ b/lib/httparrot/delete_cookies_handler.ex @@ -0,0 +1,33 @@ +defmodule HTTParrot.DeleteCookiesHandler do + def init(_transport, _req, _opts) do + {:upgrade, :protocol, :cowboy_rest} + end + + def allowed_methods(req, state) do + {["GET"], req, state} + end + + def malformed_request(req, state) do + {qs_vals, req} = :cowboy_req.qs_vals(req) + if Enum.empty?(qs_vals), do: {true, req, state}, else: {false, req, qs_vals} + end + + def content_types_provided(req, state) do + {[{{"application", "json", []}, :get_json}], req, state} + end + + def get_json(req, qs_vals) do + req = Enum.reduce qs_vals, req, fn({name, value}, req) -> + delete_cookie(name, value, req) + end + {:ok, req} = :cowboy_req.reply(302, [{"location", "/cookies"}], "Redirecting...", req) + {:halt, req, qs_vals} + end + + defp delete_cookie(name, true, req), do: delete_cookie(name, "", req) + defp delete_cookie(name, value, req) do + :cowboy_req.set_resp_cookie(name, value, [path: "/", max_age: 0], req) + end + + def terminate(_, _, _), do: :ok +end diff --git a/test/delete_cookies_handler_test.exs b/test/delete_cookies_handler_test.exs new file mode 100644 index 0000000..764f616 --- /dev/null +++ b/test/delete_cookies_handler_test.exs @@ -0,0 +1,23 @@ +defmodule HTTParrot.DeleteCookiesHandlerTest do + use ExUnit.Case + import :meck + import HTTParrot.DeleteCookiesHandler + + setup do + new :cowboy_req + end + + teardown do + unload :cowboy_req + end + + test "delete cookies and redirect to /cookies " do + expect(:cowboy_req, :set_resp_cookie, [{[:k1, :v1, [path: "/", max_age: 0], :req1], :req2}, + {[:k2, :v2, [path: "/", max_age: 0], :req2], :req3}]) + expect(:cowboy_req, :reply, [{[302, [{"location", "/cookies"}], "Redirecting...", :req3], {:ok, :req4}}]) + + assert get_json(:req1, [k1: :v1, k2: :v2]) == {:halt, :req4, [k1: :v1, k2: :v2]} + + assert validate :cowboy_req + end +end