diff --git a/apps/iot/src/endpoint/endpoint_http.erl b/apps/iot/src/endpoint/endpoint_http.erl index bf9615c..752b274 100644 --- a/apps/iot/src/endpoint/endpoint_http.erl +++ b/apps/iot/src/endpoint/endpoint_http.erl @@ -69,8 +69,15 @@ handle_call(get_stat, _From, State = #state{buffer = Buffer}) -> {noreply, NewState :: #state{}} | {noreply, NewState :: #state{}, timeout() | hibernate} | {stop, Reason :: term(), NewState :: #state{}}). -handle_cast({forward, Metric}, State = #state{buffer = Buffer}) -> - NBuffer = endpoint_buffer:append(Metric, Buffer), +handle_cast({forward, Metric}, State = #state{buffer = Buffer, endpoint = #endpoint{config = #http_endpoint{token = Token}}}) -> + Tuple = case is_binary(Token) andalso Token /= <<>> of + true -> + Sign = iot_util:sha256(erlang:iolist_to_binary([Token, Metric, Token])), + {Metric, Sign}; + false -> + {Metric, <<>>} + end, + NBuffer = endpoint_buffer:append(Tuple, Buffer), {noreply, State#state{buffer = NBuffer}}; handle_cast(cleanup, State = #state{buffer = Buffer}) -> @@ -83,10 +90,14 @@ handle_cast(cleanup, State = #state{buffer = Buffer}) -> {noreply, NewState :: #state{}} | {noreply, NewState :: #state{}, timeout() | hibernate} | {stop, Reason :: term(), NewState :: #state{}}). -handle_info({next_data, Id, Metric}, State = #state{buffer = Buffer, endpoint = #endpoint{config = #http_endpoint{url = Url}}}) -> - Headers = [ - {<<"Content-Type">>, <<"application/json">>} - ], +handle_info({next_data, Id, {Metric, Sign}}, State = #state{buffer = Buffer, endpoint = #endpoint{config = #http_endpoint{url = Url}}}) -> + BaseHeaders = [{<<"Content-Type">>, <<"application/json">>}], + ExtraHeaders = if + Sign =:= <<>> -> []; + true -> [{<<"X-Signature">>, Sign}] + end, + Headers = BaseHeaders ++ ExtraHeaders, + case hackney:request(post, Url, Headers, Metric) of {ok, 200, _, ClientRef} -> {ok, RespBody} = hackney:body(ClientRef), diff --git a/apps/iot/src/iot_util.erl b/apps/iot/src/iot_util.erl index 9dbde0f..2c97506 100644 --- a/apps/iot/src/iot_util.erl +++ b/apps/iot/src/iot_util.erl @@ -113,13 +113,13 @@ assert_call(true, Fun) -> assert_call(false, _) -> ok. --spec sha256(Str :: string() | binary()) -> string(). +-spec sha256(Str :: string() | binary()) -> binary(). sha256(Str) when is_list(Str) -> sha256(unicode:characters_to_binary(Str)); sha256(Bin) when is_binary(Bin) -> HashBin = crypto:hash(sha256, Bin), HexStr = lists:flatten([io_lib:format("~2.16.0B", [B]) || B <- binary:bin_to_list(HashBin)]), - string:lowercase(HexStr). + list_to_binary(string:lowercase(HexStr)). -spec md5(Str :: binary()) -> binary(). md5(Str) when is_binary(Str) ->