Перенести все админские эндпоинты на порт 8445 и добавить отдельную авторизацию для админов. Часть 1

This commit is contained in:
2026-04-27 15:54:48 +03:00
parent 62bc62f990
commit 4ed6a961ab
40 changed files with 3573 additions and 800 deletions
@@ -0,0 +1,96 @@
-module(admin_handler_report_by_id).
-behaviour(cowboy_handler).
-export([init/2]).
-include("records.hrl").
init(Req, _Opts) ->
case cowboy_req:method(Req) of
<<"GET">> -> get_report(Req);
<<"PUT">> -> update_report(Req);
_ -> send_error(Req, 405, <<"Method not allowed">>)
end.
get_report(Req) ->
case handler_auth:authenticate(Req) of
{ok, AdminId, Req1} ->
case is_admin(AdminId) of
true ->
ReportId = cowboy_req:binding(id, Req1),
case core_report:get_by_id(ReportId) of
{ok, Report} ->
send_json(Req1, 200, report_to_json(Report));
{error, not_found} ->
send_error(Req1, 404, <<"Report not found">>)
end;
false ->
send_error(Req1, 403, <<"Admin access required">>)
end;
{error, Code, Message, Req1} ->
send_error(Req1, Code, Message)
end.
update_report(Req) ->
case handler_auth:authenticate(Req) of
{ok, AdminId, Req1} ->
case is_admin(AdminId) of
true ->
ReportId = cowboy_req:binding(id, Req1),
{ok, Body, Req2} = cowboy_req:read_body(Req1),
try jsx:decode(Body, [return_maps]) of
#{<<"status">> := NewStatus} ->
case core_report:update_status(ReportId, NewStatus) of
{ok, Report} ->
send_json(Req2, 200, report_to_json(Report));
{error, not_found} ->
send_error(Req2, 404, <<"Report not found">>);
{error, _} ->
send_error(Req2, 500, <<"Internal server error">>)
end;
_ ->
send_error(Req2, 400, <<"Missing status field">>)
catch
_:_ -> send_error(Req2, 400, <<"Invalid JSON">>)
end;
false ->
send_error(Req1, 403, <<"Admin access required">>)
end;
{error, Code, Message, Req1} ->
send_error(Req1, Code, Message)
end.
is_admin(UserId) ->
case core_user:get_by_id(UserId) of
{ok, User} ->
Role = User#user.role,
Role =:= admin orelse Role =:= superadmin orelse
Role =:= moderator orelse Role =:= support;
_ -> false
end.
report_to_json(R) ->
#{
id => R#report.id,
reporter_id => R#report.reporter_id,
target_type => R#report.target_type,
target_id => R#report.target_id,
reason => R#report.reason,
status => R#report.status,
created_at => datetime_to_iso8601(R#report.created_at),
resolved_at => datetime_to_iso8601(R#report.resolved_at)
}.
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.
send_json(Req, Status, Data) ->
Body = jsx:encode(Data),
cowboy_req:reply(Status, #{<<"content-type">> => <<"application/json">>}, Body, Req),
{ok, Body, []}.
send_error(Req, Status, Message) ->
Body = jsx:encode(#{error => Message}),
cowboy_req:reply(Status, #{<<"content-type">> => <<"application/json">>}, Body, Req),
{ok, Body, []}.