Улучшение безопасности и обработки ошибок. Финал. #8

This commit is contained in:
2026-04-29 12:19:43 +03:00
parent 1ca27e93a9
commit 1787b0f8a3
4 changed files with 279 additions and 141 deletions
@@ -6,12 +6,11 @@
init(Req, _Opts) ->
case cowboy_req:binding(id, Req) of
undefined ->
handle_collection(Req);
_SubscriptionId ->
handle_item(Req)
undefined -> handle_collection(Req);
_SubId -> handle_item(Req)
end.
%% ================== Коллекция ==================
handle_collection(Req) ->
case cowboy_req:method(Req) of
<<"GET">> -> list_subscriptions(Req);
@@ -19,55 +18,33 @@ handle_collection(Req) ->
_ -> send_error(Req, 405, <<"Method not allowed">>)
end.
%% ================== Элемент ==================
handle_item(Req) ->
SubscriptionId = cowboy_req:binding(id, Req),
SubId = cowboy_req:binding(id, Req),
case cowboy_req:method(Req) of
<<"GET">> -> get_subscription(SubscriptionId, Req);
<<"PUT">> -> update_subscription(SubscriptionId, Req);
<<"DELETE">> -> delete_subscription(SubscriptionId, Req);
<<"GET">> -> get_subscription(SubId, Req);
<<"PUT">> -> update_subscription(SubId, Req);
<<"DELETE">> -> delete_subscription(SubId, Req);
_ -> send_error(Req, 405, <<"Method not allowed">>)
end.
%% ================== GET /subscriptions ==================
list_subscriptions(Req) ->
case auth_admin(Req) of
{ok, _AdminId, Req1} ->
Subscriptions = core_subscription:list_subscriptions(),
send_json(Req1, 200, [subscription_to_json(S) || S <- Subscriptions]);
Subs = core_subscription:list_subscriptions(),
send_json(Req1, 200, [subscription_to_json(S) || S <- Subs]);
{error, Code, Message, Req1} ->
send_error(Req1, Code, Message)
end.
create_subscription(Req) ->
%% ================== GET /subscriptions/:id ==================
get_subscription(Id, Req) ->
case auth_admin(Req) of
{ok, _AdminId, Req1} ->
{ok, Body, Req2} = cowboy_req:read_body(Req1),
try jsx:decode(Body, [return_maps]) of
#{<<"user_id">> := _UserId} = Data ->
SubscriptionData = maps:merge(#{
<<"status">> => <<"active">>,
<<"trial_used">> => false
}, Data),
case core_subscription:create_subscription(SubscriptionData) of
{ok, Subscription} ->
send_json(Req2, 201, subscription_to_json(Subscription));
{error, Reason} ->
send_error(Req2, 500, Reason)
end;
_ ->
send_error(Req2, 400, <<"Missing 'user_id' field">>)
catch
_:_ -> send_error(Req2, 400, <<"Invalid JSON">>)
end;
{error, Code, Message, Req1} ->
send_error(Req1, Code, Message)
end.
get_subscription(SubscriptionId, Req) ->
case auth_admin(Req) of
{ok, _AdminId, Req1} ->
case core_subscription:get_by_id(SubscriptionId) of
{ok, Subscription} ->
send_json(Req1, 200, subscription_to_json(Subscription));
case core_subscription:get_by_id(Id) of
{ok, Sub} ->
send_json(Req1, 200, subscription_to_json(Sub));
{error, not_found} ->
send_error(Req1, 404, <<"Subscription not found">>)
end;
@@ -75,22 +52,34 @@ get_subscription(SubscriptionId, Req) ->
send_error(Req1, Code, Message)
end.
update_subscription(SubscriptionId, Req) ->
%% ================== POST /subscriptions ==================
create_subscription(Req) ->
case auth_admin(Req) of
{ok, _AdminId, Req1} ->
{ok, AdminId, Req1} ->
{ok, Body, Req2} = cowboy_req:read_body(Req1),
try jsx:decode(Body, [return_maps]) of
UpdatesMap when is_map(UpdatesMap) ->
case core_subscription:update_subscription(SubscriptionId, UpdatesMap) of
{ok, Subscription} ->
send_json(Req2, 200, subscription_to_json(Subscription));
{error, not_found} ->
send_error(Req2, 404, <<"Subscription not found">>);
{error, Reason} ->
send_error(Req2, 500, Reason)
end;
_ ->
send_error(Req2, 400, <<"Invalid JSON">>)
try
Decoded = jsx:decode(Body, [return_maps]),
case Decoded of
#{<<"user_id">> := UserId, <<"plan">> := Plan} ->
case validate_plan(Plan) of
true ->
SubData = maps:merge(#{
<<"status">> => <<"active">>,
<<"trial_used">> => false
}, maps:without([<<"id">>], Decoded)), % ← исправлено: Decoded, а не Body
case core_subscription:create_subscription(SubData) of
{ok, Sub} ->
log_audit(AdminId, <<"create_subscription">>, <<"subscription">>, Sub#subscription.id, UserId),
send_json(Req2, 201, subscription_to_json(Sub));
{error, Reason} ->
send_error(Req2, 500, Reason)
end;
false ->
send_error(Req2, 400, <<"Invalid plan value">>)
end;
_ ->
send_error(Req2, 400, <<"Missing 'user_id' or 'plan' field">>)
end
catch
_:_ -> send_error(Req2, 400, <<"Invalid JSON">>)
end;
@@ -98,11 +87,41 @@ update_subscription(SubscriptionId, Req) ->
send_error(Req1, Code, Message)
end.
delete_subscription(SubscriptionId, Req) ->
%% ================== PUT /subscriptions/:id ==================
update_subscription(Id, Req) ->
case auth_admin(Req) of
{ok, _AdminId, Req1} ->
case core_subscription:delete_subscription(SubscriptionId) of
{ok, AdminId, Req1} ->
{ok, Body, Req2} = cowboy_req:read_body(Req1),
try
Updates = jsx:decode(Body, [return_maps]),
case map_size(Updates) > 0 of
true ->
case core_subscription:update_subscription(Id, Updates) of
{ok, Sub} ->
log_audit(AdminId, <<"update_subscription">>, <<"subscription">>, Id, <<"">>),
send_json(Req2, 200, subscription_to_json(Sub));
{error, not_found} ->
send_error(Req2, 404, <<"Subscription not found">>);
{error, Reason} ->
send_error(Req2, 500, Reason)
end;
false ->
send_error(Req2, 400, <<"Request body is empty">>)
end
catch
_:_ -> send_error(Req2, 400, <<"Invalid JSON">>)
end;
{error, Code, Message, Req1} ->
send_error(Req1, Code, Message)
end.
%% ================== DELETE /subscriptions/:id ==================
delete_subscription(Id, Req) ->
case auth_admin(Req) of
{ok, AdminId, Req1} ->
case core_subscription:delete_subscription(Id) of
{ok, deleted} ->
log_audit(AdminId, <<"delete_subscription">>, <<"subscription">>, Id, <<"">>),
send_json(Req1, 200, #{status => <<"deleted">>});
{error, not_found} ->
send_error(Req1, 404, <<"Subscription not found">>)
@@ -111,6 +130,7 @@ delete_subscription(SubscriptionId, Req) ->
send_error(Req1, Code, Message)
end.
%% ================== Аутентификация и роли ==================
auth_admin(Req) ->
case handler_auth:authenticate(Req) of
{ok, AdminId, Req1} ->
@@ -122,6 +142,16 @@ auth_admin(Req) ->
{error, Code, Message, Req1}
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.
%% ================== Сериализация ==================
subscription_to_json(S) ->
#{
id => S#subscription.id,
@@ -140,6 +170,12 @@ datetime_to_iso8601({{Year, Month, Day}, {Hour, Minute, Second}}) ->
[Year, Month, Day, Hour, Minute, Second]));
datetime_to_iso8601(undefined) -> undefined.
%% ================== Валидация ==================
validate_plan(Plan) when is_binary(Plan) ->
lists:member(Plan, [<<"monthly">>, <<"yearly">>, <<"quarterly">>, <<"biannual">>, <<"annual">>]);
validate_plan(_) -> false.
%% ================== HTTP-ответы ==================
send_json(Req, Status, Data) ->
Headers = #{
<<"content-type">> => <<"application/json">>,
@@ -150,7 +186,12 @@ send_json(Req, Status, Data) ->
cowboy_req:reply(Status, Headers, Body, Req),
{ok, Body, []}.
send_error(Req, Status, Message) ->
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(Status, #{<<"content-type">> => <<"application/json">>}, Body, Req),
cowboy_req:reply(Code, Headers, Body, Req),
{ok, Body, []}.