0
Fork 0
mirror of https://github.com/ninenines/cowboy.git synced 2025-07-14 12:20:24 +00:00

Add cowboy_req:filter_cookies/2

This commit is contained in:
Loïc Hoguin 2019-10-05 11:23:57 +02:00
parent 5ffb4f98e0
commit 03dac1486d
No known key found for this signature in database
GPG key ID: 8A9DF795F6FED764
5 changed files with 126 additions and 0 deletions

View file

@ -44,6 +44,7 @@
-export([headers/1]).
-export([parse_header/2]).
-export([parse_header/3]).
-export([filter_cookies/2]).
-export([parse_cookies/1]).
-export([match_cookies/2]).
@ -450,6 +451,35 @@ parse_header(Name, Req, Default, ParseFun) ->
Value -> ParseFun(Value)
end.
-spec filter_cookies([atom() | binary()], Req) -> Req when Req::req().
filter_cookies(Names0, Req=#{headers := Headers}) ->
Names = [if
is_atom(N) -> atom_to_binary(N, utf8);
true -> N
end || N <- Names0],
case header(<<"cookie">>, Req) of
undefined -> Req;
Value0 ->
Cookies0 = binary:split(Value0, <<$;>>),
Cookies = lists:filter(fun(Cookie) ->
lists:member(cookie_name(Cookie), Names)
end, Cookies0),
Value = iolist_to_binary(lists:join($;, Cookies)),
Req#{headers => Headers#{<<"cookie">> => Value}}
end.
%% This is a specialized function to extract a cookie name
%% regardless of whether the name is valid or not. We skip
%% whitespace at the beginning and take whatever's left to
%% be the cookie name, up to the = sign.
cookie_name(<<$\s, Rest/binary>>) -> cookie_name(Rest);
cookie_name(<<$\t, Rest/binary>>) -> cookie_name(Rest);
cookie_name(Name) -> cookie_name(Name, <<>>).
cookie_name(<<>>, Name) -> Name;
cookie_name(<<$=, _/bits>>, Name) -> Name;
cookie_name(<<C, Rest/bits>>, Acc) -> cookie_name(Rest, <<Acc/binary, C>>).
-spec parse_cookies(req()) -> [{binary(), binary()}].
parse_cookies(Req) ->
parse_header(<<"cookie">>, Req).