1
0
Fork 0
mirror of https://github.com/edgurgel/httparrot synced 2025-04-05 08:12:31 -04:00

Add '/cookies/delete'

This commit is contained in:
Eduardo Gurgel 2014-01-02 00:32:53 -03:00
parent f5698b9708
commit 28d06eac1b
3 changed files with 57 additions and 0 deletions

View file

@ -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"}} ] }
])

View file

@ -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

View file

@ -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