fix(backend): IP в аудите, closed_at тикетов и admin_activity в статистике. Refs EventHub/EventHubBack#27 #28 #29
This commit is contained in:
@@ -50,15 +50,26 @@ get_permissions(_) -> [].
|
||||
%% -- работа с IP -----------------------------------------------------------
|
||||
|
||||
%% @doc Возвращает IP-адрес клиента в виде бинарной строки (напр. <<"127.0.0.1">>).
|
||||
%% Сохранена для обратной совместимости; внутренне вызывает ip_to_binary/1.
|
||||
%% Сначала читает заголовки прокси, затем fallback на cowboy_req:peer/1.
|
||||
-spec client_ip(cowboy_req:req()) -> binary().
|
||||
client_ip(Req) ->
|
||||
ip_to_binary(cowboy_req:peer(Req)).
|
||||
case forwarded_client_ip(Req) of
|
||||
undefined -> ip_to_binary(cowboy_req:peer(Req));
|
||||
Ip -> Ip
|
||||
end.
|
||||
|
||||
%% @doc Преобразует IP-адрес из кортежа {A,B,C,D} в бинарную строку.
|
||||
-spec ip_to_binary({byte(), byte(), byte(), byte()}) -> binary().
|
||||
ip_to_binary({A, B, C, D}) ->
|
||||
list_to_binary(io_lib:format("~B.~B.~B.~B", [A, B, C, D]));
|
||||
%% @doc Преобразует IP-адрес в бинарную строку.
|
||||
-spec ip_to_binary(term()) -> binary().
|
||||
ip_to_binary(IP) when is_tuple(IP) ->
|
||||
case tuple_size(IP) of
|
||||
4 -> list_to_binary(inet:ntoa(IP));
|
||||
8 -> list_to_binary(inet:ntoa(IP));
|
||||
_ -> <<"unknown">>
|
||||
end;
|
||||
ip_to_binary(IP) when is_binary(IP) ->
|
||||
trim_ip_binary(IP);
|
||||
ip_to_binary(IP) when is_list(IP) ->
|
||||
list_to_binary(string:trim(IP));
|
||||
ip_to_binary(_) ->
|
||||
<<"unknown">>.
|
||||
|
||||
@@ -97,8 +108,31 @@ log_admin_action(AdminId, Action, EntityType, EntityId, Reason, Req) ->
|
||||
{ok, Admin} ->
|
||||
Email = Admin#admin.email,
|
||||
Role = atom_to_binary(Admin#admin.role, utf8),
|
||||
Ip = ip_to_binary(cowboy_req:peer(Req)),
|
||||
Ip = client_ip(Req),
|
||||
core_admin_audit:log(AdminId, Email, Role, Action, EntityType, EntityId, Ip, Reason),
|
||||
ok;
|
||||
_ -> ok
|
||||
end.
|
||||
end.
|
||||
|
||||
forwarded_client_ip(Req) ->
|
||||
pick_forwarded_ip(Req, [<<"x-forwarded-for">>, <<"x-real-ip">>]).
|
||||
|
||||
|
||||
pick_forwarded_ip(_Req, []) ->
|
||||
undefined;
|
||||
pick_forwarded_ip(Req, [Header | Rest]) ->
|
||||
case cowboy_req:header(Header, Req) of
|
||||
undefined -> pick_forwarded_ip(Req, Rest);
|
||||
Value -> first_forwarded_ip(Value)
|
||||
end.
|
||||
|
||||
|
||||
first_forwarded_ip(Value) ->
|
||||
case binary:split(Value, <<",">>) of
|
||||
[Head | _] -> trim_ip_binary(Head);
|
||||
[] -> undefined
|
||||
end.
|
||||
|
||||
|
||||
trim_ip_binary(Ip) ->
|
||||
list_to_binary(string:trim(binary_to_list(Ip))).
|
||||
Reference in New Issue
Block a user