fix(jwt): make binary_to_number function support list type

This commit is contained in:
firest 2022-09-01 17:05:39 +08:00
parent a6cf74ea6f
commit 884ec15567
2 changed files with 23 additions and 17 deletions

View File

@ -26,7 +26,7 @@
, description/0
]).
-export([binary_to_number/1]).
-export([string_to_number/1]).
%%--------------------------------------------------------------------
%% Authentication callbacks
@ -73,7 +73,7 @@ check_acl(ClientInfo = #{jwt_claims := Claims},
end.
is_expired(Exp) when is_binary(Exp) ->
case binary_to_number(Exp) of
case string_to_number(Exp) of
{ok, Val} ->
is_expired(Val);
_ ->
@ -89,17 +89,12 @@ is_expired(Exp) ->
description() -> "Authentication with JWT".
binary_to_number(Bin) ->
try
{ok, erlang:binary_to_integer(Bin)}
catch _:_ ->
try
Val = erlang:binary_to_float(Bin),
{ok, erlang:round(Val)}
catch _:_ ->
false
end
end.
string_to_number(Bin) when is_binary(Bin) ->
string_to_number(Bin, fun erlang:binary_to_integer/1, fun erlang:binary_to_float/1);
string_to_number(Str) when is_list(Str) ->
string_to_number(Str, fun erlang:list_to_integer/1, fun erlang:list_to_float/1);
string_to_number(_) ->
false.
%%------------------------------------------------------------------------------
%% Verify Claims
@ -145,3 +140,14 @@ match_topic(ClientInfo, AclTopic, Topic) ->
TopicWords = emqx_topic:words(Topic),
AclTopicRendered = emqx_access_rule:feed_var(ClientInfo, AclTopicWords),
emqx_topic:match(TopicWords, AclTopicRendered).
string_to_number(Str, IntFun, FloatFun) ->
try
{ok, IntFun(Str)}
catch _:_ ->
try
{ok, FloatFun(Str)}
catch _:_ ->
false
end
end.

View File

@ -215,13 +215,13 @@ with_int_value(Fun) ->
case Value of
Int when is_integer(Int) -> Fun(Int);
Bin when is_binary(Bin) ->
case emqx_auth_jwt:binary_to_number(Bin) of
{ok, Int} -> Fun(Int);
case emqx_auth_jwt:string_to_number(Bin) of
{ok, Num} -> Fun(Num);
_ -> false
end;
Str when is_list(Str) ->
case emqx_auth_jwt:binary_to_number(Str) of
{ok, Int} -> Fun(Int);
case emqx_auth_jwt:string_to_number(Str) of
{ok, Num} -> Fun(Num);
_ -> false
end
end