%%%------------------------------------------------------------------- %%% @author cheese %%% @copyright (C) 2015, %%% @doc %%% %%% @end %%% Created : 24. Nov 2015 8:22 %%%------------------------------------------------------------------- -module(http_utilites). -author("cheese"). %% API -export([is_valid_client/2, get_current_user_ip/1, is_websocket_request/1, get_header_value/2]). %% Internal -export([get_client_ip/2, check_client_ip/2]). get_current_user_ip(CowboyReq) -> {{Client, _Port}, Req1} = cowboy_req:peer(CowboyReq), {XRealIP, Req} = cowboy_req:header(<<"x-real-ip">>,Req1, <<"">>), {get_client_ip(XRealIP, Client), Req}. -spec(is_valid_client(any(), [binary()]) -> {ok, binary(), any()} | {error, binary(), any()}). is_valid_client(CowboyReq, ValidIpList) -> {RealClient, Req} = get_current_user_ip(CowboyReq), case check_client_ip(RealClient, ValidIpList) of {ok} -> {ok, RealClient, Req}; {error, Reason} -> {error, RealClient, Reason} end. %% Internal get_client_ip(<<>>, Client) -> Client; get_client_ip(XRealIP, _Client) -> socket_utilites:parse_ip_from_bytes(XRealIP). check_client_ip(_ClientIP, []) -> {error, access_denied}; check_client_ip(_ClientIP, [all | _OtherIP]) -> {ok}; check_client_ip(ClientIP, [ClientIP | _OtherIP]) -> {ok}; check_client_ip(ClientIP, [_IP | OtherIP]) -> check_client_ip(ClientIP, OtherIP). -spec(is_websocket_request(term()) -> {true | false, term()}). is_websocket_request(Req) -> {AllHeaders, Req2} = cowboy_req:headers(Req), Value = get_header_value(<<"UPGRADE">>, AllHeaders), case list_to_binary(string:to_upper(binary_to_list(Value))) of <<"WEBSOCKET">> -> {true, Req2}; _ -> {false, Req2} end. -spec(get_header_value(binary(), [{term(), term()}]) -> binary()). get_header_value(_Name, []) -> <<>>; get_header_value(Name, [{Key, Val} | Tail]) -> KeyUpper = list_to_binary(string:to_upper(binary_to_list(Key))), case bytes_extension:are_equal(KeyUpper, Name) of true -> Val; _ -> get_header_value(Name, Tail) end.