%%%-------------------------------------------------------------------
%%% @author aresei
%%% @copyright (C) 2023, <COMPANY>
%%% @doc
%%% 授权校验模块
%%% @end
%%% Created : 27. 6月 2023 09:48
%%%-------------------------------------------------------------------
-module(iot_auth).
-author("aresei").

%% API
-export([check/5]).

%% 检测token是否是合法值
-spec check(Username :: binary(), Token :: binary(), UUID :: binary(), Salt :: binary(), Timestamp :: integer()) -> boolean().
check(Username, Token, UUID, Salt, Timestamp) when is_binary(Username), is_binary(Token), is_binary(UUID), is_binary(Salt), is_integer(Timestamp) ->
    BinTimestamp = integer_to_binary(Timestamp),
    %% 1分钟内有效
    case iot_util:current_time() - Timestamp =< 60 of
        true ->
            {ok, PreTokens} = application:get_env(iot, pre_tokens),
            case proplists:get_value(Username, PreTokens) of
                undefined ->
                    false;
                PreToken when is_binary(PreToken) ->
                    iot_util:md5(<<Salt/binary, "!", PreToken/binary, "!", UUID/binary, "!", BinTimestamp/binary>>) =:= Token
            end;
        false ->
            false
    end.
