Рефакторинг обработчиков. Часть 1 #21

This commit is contained in:
2026-05-10 22:14:38 +03:00
parent a35d6f7acc
commit 6403f061df
46 changed files with 3082 additions and 2091 deletions
+160 -139
View File
@@ -1,156 +1,177 @@
%%%-------------------------------------------------------------------
%%% @doc Административный обработчик бан-слов.
%%% GET – список всех слов с пагинацией.
%%% POST – добавить новое слово.
%%% DELETE – удалить слово по :word.
%%% @end
%%%-------------------------------------------------------------------
-module(admin_handler_banned_words).
-behaviour(cowboy_handler).
-export([init/2]).
-export([trails/0]).
-include("records.hrl").
-spec init(cowboy_req:req(), any()) -> {ok, cowboy_req:req(), any()}.
init(Req, _Opts) ->
case cowboy_req:binding(word, Req) of
undefined -> handle_collection(Req);
Word -> handle_item(Word, Req)
end.
handle_collection(Req) ->
case cowboy_req:method(Req) of
<<"GET">> -> list_banned_words(Req);
<<"POST">> -> add_banned_word(Req);
_ -> send_error(Req, 405, <<"Method not allowed">>)
<<"GET">> -> list_words(Req);
<<"POST">> -> add_word(Req);
<<"DELETE">> -> delete_word(Req);
_ -> handler_utils:send_error(Req, 405, <<"Method not allowed">>)
end.
handle_item(Word, Req) ->
case cowboy_req:method(Req) of
<<"DELETE">> -> delete_banned_word(Word, Req);
<<"PUT">> -> update_banned_word(Word, Req);
_ -> send_error(Req, 405, <<"Method not allowed">>)
end.
-spec trails() -> [map()].
trails() ->
[
#{ % GET list
path => <<"/v1/admin/banned-words">>,
method => <<"GET">>,
description => <<"List all banned words (admin)">>,
tags => [<<"Banned Words">>],
parameters => [
#{name => <<"limit">>, in => <<"query">>, schema => #{type => integer}, description => <<"Page size">>},
#{name => <<"offset">>, in => <<"query">>, schema => #{type => integer}, description => <<"Offset">>}
],
responses => #{
200 => #{
description => <<"Array of banned words">>,
content => #{<<"application/json">> => #{schema => #{
type => array,
items => banned_word_schema()
}}}
}
}
},
#{ % POST add
path => <<"/v1/admin/banned-words">>,
method => <<"POST">>,
description => <<"Add a new banned word">>,
tags => [<<"Banned Words">>],
requestBody => #{
required => true,
content => #{<<"application/json">> => #{schema => #{
type => object,
required => [<<"word">>],
properties => #{
word => #{type => string}
}
}}}
},
responses => #{
201 => #{description => <<"Word added">>},
409 => #{description => <<"Word already exists">>}
}
},
#{ % DELETE by word
path => <<"/v1/admin/banned-words/:word">>,
method => <<"DELETE">>,
description => <<"Remove a banned word">>,
tags => [<<"Banned Words">>],
parameters => [
#{
name => <<"word">>,
in => <<"path">>,
description => <<"The word to remove">>,
required => true,
schema => #{type => string}
}
],
responses => #{
200 => #{description => <<"Word removed">>},
404 => #{description => <<"Word not found">>}
}
}
].
%% ================== GET /banned-words ==================
list_banned_words(Req) ->
case auth_admin(Req) of
{ok, _AdminId, Req1} ->
Words = core_banned_words:list_banned_words(),
send_json(Req1, 200, [banned_word_to_json(W) || W <- Words]);
{error, Code, Message, Req1} ->
send_error(Req1, Code, Message)
end.
%% ================== POST /banned-words ==================
add_banned_word(Req) ->
case auth_admin(Req) of
{ok, AdminId, Req1} ->
{ok, Body, Req2} = cowboy_req:read_body(Req1),
try jsx:decode(Body, [return_maps]) of
#{<<"word">> := Word} when byte_size(Word) > 0 ->
case core_banned_words:add_banned_word(Word, AdminId) of
{ok, BW} ->
log_audit(AdminId, <<"add_banned_word">>, <<"banned_word">>, BW#banned_word.id, <<"">>),
send_json(Req2, 201, banned_word_to_json(BW));
{error, already_exists} ->
send_error(Req2, 409, <<"Word already exists">>);
{error, _} ->
send_error(Req2, 500, <<"Internal server error">>)
end;
_ ->
send_error(Req2, 400, <<"Missing or empty 'word'">>)
catch
_:_ -> send_error(Req2, 400, <<"Invalid JSON">>)
end;
{error, Code, Message, Req1} ->
send_error(Req1, Code, Message)
end.
%% ================== DELETE /banned-words/:word ==================
delete_banned_word(Word, Req) ->
case auth_admin(Req) of
{ok, AdminId, Req1} ->
case core_banned_words:remove_banned_word(Word) of
{ok, deleted} ->
log_audit(AdminId, <<"delete_banned_word">>, <<"banned_word">>, Word, <<"">>),
send_json(Req1, 200, #{status => <<"deleted">>});
{error, not_found} ->
send_error(Req1, 404, <<"Word not found">>)
end;
{error, Code, Message, Req1} ->
send_error(Req1, Code, Message)
end.
%% ================== PUT /banned-words/:word ==================
update_banned_word(OldWord, Req) ->
case auth_admin(Req) of
{ok, AdminId, Req1} ->
{ok, Body, Req2} = cowboy_req:read_body(Req1),
try jsx:decode(Body, [return_maps]) of
#{<<"word">> := NewWord} when byte_size(NewWord) > 0 ->
case core_banned_words:update_banned_word(OldWord, NewWord) of
{ok, BW} ->
log_audit(AdminId, <<"update_banned_word">>, <<"banned_word">>, BW#banned_word.id, <<"">>),
send_json(Req2, 200, banned_word_to_json(BW));
{error, not_found} ->
send_error(Req2, 404, <<"Word not found">>);
{error, _} ->
send_error(Req2, 500, <<"Internal server error">>)
end;
_ ->
send_error(Req2, 400, <<"Missing or empty 'word'">>)
catch
_:_ -> send_error(Req2, 400, <<"Invalid JSON">>)
end;
{error, Code, Message, Req1} ->
send_error(Req1, Code, Message)
end.
%% ── Аудит ──────────────────────────────────────────────
log_audit(AdminId, Action, EntityType, EntityId, Reason) ->
case core_admin:get_by_id(AdminId) of
{ok, Admin} ->
core_admin_audit:log(AdminId, Admin#admin.email, Admin#admin.role,
Action, EntityType, EntityId, <<"127.0.0.1">>, Reason);
_ -> ok
end.
%% ================== Аутентификация ==================
auth_admin(Req) ->
case handler_auth:authenticate(Req) of
{ok, AdminId, Req1} ->
case admin_utils:is_admin(AdminId) of
true -> {ok, AdminId, Req1};
false -> {error, 403, <<"Admin access required">>, Req1}
end;
{error, Code, Message, Req1} ->
{error, Code, Message, Req1}
end.
%% ================== Сериализация ==================
banned_word_to_json(BW) ->
banned_word_schema() ->
#{
id => BW#banned_word.id,
word => BW#banned_word.word,
added_by => BW#banned_word.added_by,
added_at => datetime_to_iso8601(BW#banned_word.added_at)
type => object,
properties => #{
id => #{type => string},
word => #{type => string},
added_by => #{type => string, nullable => true},
added_at => #{type => string, format => <<"date-time">>, nullable => true}
}
}.
%%% Internal functions
list_words(Req) ->
case handler_utils:auth_admin(Req) of
{ok, _AdminId, Req1} ->
Pagination = handler_utils:parse_pagination_params(Req1),
%% core_banned_words:list_banned_words() возвращает список, а не {ok, List}
AllWords = core_banned_words:list_banned_words(),
BannedWords = lists:sort(AllWords),
Total = length(BannedWords),
Page = lists:sublist(BannedWords, maps:get(offset, Pagination) + 1, maps:get(limit, Pagination)),
Json = [word_to_map(W) || W <- Page],
ExtraHeaders = pagination_headers(Pagination, Total),
handler_utils:send_json(Req1, 200, Json, ExtraHeaders);
{error, Code, Msg, Req1} ->
handler_utils:send_error(Req1, Code, Msg)
end.
add_word(Req) ->
case handler_utils:auth_admin(Req) of
{ok, AdminId, Req1} ->
{ok, Body, Req2} = cowboy_req:read_body(Req1),
try jsx:decode(Body, [return_maps]) of
#{<<"word">> := Word} ->
case core_banned_words:add_banned_word(Word, AdminId) of
{ok, _} ->
handler_utils:send_json(Req2, 201, #{status => <<"added">>});
{error, already_exists} ->
handler_utils:send_error(Req2, 409, <<"Word already exists">>);
{error, _} ->
handler_utils:send_error(Req2, 500, <<"Internal server error">>)
end;
_ ->
handler_utils:send_error(Req2, 400, <<"Missing 'word' field">>)
catch
_:_ -> handler_utils:send_error(Req1, 400, <<"Invalid JSON">>)
end;
{error, Code, Msg, Req1} ->
handler_utils:send_error(Req1, Code, Msg)
end.
delete_word(Req) ->
case handler_utils:auth_admin(Req) of
{ok, _AdminId, Req1} ->
Word = cowboy_req:binding(word, Req1),
case core_banned_words:remove_banned_word(Word) of
{ok, _} ->
handler_utils:send_json(Req1, 200, #{status => <<"deleted">>});
{error, not_found} ->
handler_utils:send_error(Req1, 404, <<"Word not found">>);
{error, _} ->
handler_utils:send_error(Req1, 500, <<"Internal server error">>)
end;
{error, Code, Msg, Req1} ->
handler_utils:send_error(Req1, Code, Msg)
end.
%% @private Преобразование записи banned_word в JSON-совместимую карту.
word_to_map(W) ->
#{
id => W#banned_word.id,
word => W#banned_word.word,
added_by => W#banned_word.added_by,
added_at => datetime_to_iso8601(W#banned_word.added_at)
}.
%% @private Форматирование datetime в ISO8601 строку.
datetime_to_iso8601(undefined) -> undefined;
datetime_to_iso8601({{Year, Month, Day}, {Hour, Minute, Second}}) ->
iolist_to_binary(io_lib:format("~4..0B-~2..0B-~2..0BT~2..0B:~2..0B:~2..0BZ",
[Year, Month, Day, Hour, Minute, Second]));
datetime_to_iso8601(undefined) -> undefined.
[Year, Month, Day, Hour, Minute, Second])).
%% ================== HTTP-ответы ==================
send_json(Req, Status, Data) ->
Headers = #{
<<"content-type">> => <<"application/json">>,
<<"access-control-allow-origin">> => <<"*">>,
<<"access-control-expose-headers">> => <<"Content-Range">>
},
Body = jsx:encode(Data),
cowboy_req:reply(Status, Headers, Body, Req),
{ok, Body, []}.
send_error(Req, Code, Message) ->
Headers = #{
<<"content-type">> => <<"application/json">>,
<<"access-control-allow-origin">> => <<"*">>,
<<"access-control-expose-headers">> => <<"Content-Range">>
},
Body = jsx:encode(#{error => Message}),
cowboy_req:reply(Code, Headers, Body, Req),
{ok, Body, []}.
pagination_headers(#{limit := Limit, offset := Offset}, Total) ->
RangeEnd = min(Offset + Limit - 1, Total - 1),
#{
<<"content-range">> => iolist_to_binary(io_lib:format("items ~B-~B/~B", [Offset, RangeEnd, Total])),
<<"x-total-count">> => integer_to_binary(Total),
<<"access-control-expose-headers">> => <<"Content-Range, X-Total-Count">>
}.