Ролевая модель и аудит Часть 2. Финал. #6
This commit is contained in:
63
src/handlers/admin/admin_handler_audit.erl
Normal file
63
src/handlers/admin/admin_handler_audit.erl
Normal file
@@ -0,0 +1,63 @@
|
||||
-module(admin_handler_audit).
|
||||
-behaviour(cowboy_handler).
|
||||
|
||||
-include("records.hrl").
|
||||
|
||||
-export([init/2]).
|
||||
|
||||
init(Req, _Opts) ->
|
||||
case cowboy_req:method(Req) of
|
||||
<<"GET">> ->
|
||||
case handler_auth:authenticate(Req) of
|
||||
{ok, AdminId, Req1} ->
|
||||
case admin_utils:check_role(AdminId, superadmin) of
|
||||
true ->
|
||||
Filters = parse_filters(Req1),
|
||||
Entries = core_admin_audit:list(Filters),
|
||||
Json = [audit_to_json(E) || E <- Entries],
|
||||
send_json(Req1, 200, Json);
|
||||
false ->
|
||||
send_error(Req1, 403, <<"Superadmin access required">>)
|
||||
end;
|
||||
{error, Code, Message, Req1} ->
|
||||
send_error(Req1, Code, Message)
|
||||
end;
|
||||
_ ->
|
||||
send_error(Req, 405, <<"Method not allowed">>)
|
||||
end.
|
||||
|
||||
parse_filters(Req) ->
|
||||
Qs = cowboy_req:parse_qs(Req),
|
||||
lists:filtermap(fun
|
||||
({<<"admin_id">>, Val}) -> {true, {admin_id, Val}};
|
||||
({<<"action">>, Val}) -> {true, {action, Val}};
|
||||
(_) -> false
|
||||
end, Qs).
|
||||
|
||||
audit_to_json(E) ->
|
||||
#{
|
||||
id => E#admin_audit.id,
|
||||
admin_id => E#admin_audit.admin_id,
|
||||
email => E#admin_audit.email,
|
||||
role => E#admin_audit.role,
|
||||
action => E#admin_audit.action,
|
||||
entity_type => E#admin_audit.entity_type,
|
||||
entity_id => E#admin_audit.entity_id,
|
||||
timestamp => datetime_to_iso8601(E#admin_audit.timestamp),
|
||||
ip => E#admin_audit.ip,
|
||||
reason => E#admin_audit.reason
|
||||
}.
|
||||
|
||||
datetime_to_iso8601({{Y,M,D},{H,Min,S}}) ->
|
||||
iolist_to_binary(io_lib:format("~4..0B-~2..0B-~2..0BT~2..0B:~2..0B:~2..0BZ", [Y,M,D,H,Min,S]));
|
||||
datetime_to_iso8601(_) -> null.
|
||||
|
||||
send_json(Req, Status, Data) ->
|
||||
Body = jsx:encode(Data),
|
||||
Req2 = cowboy_req:reply(Status, #{<<"content-type">> => <<"application/json">>}, Body, Req),
|
||||
{ok, Req2, []}.
|
||||
|
||||
send_error(Req, Code, Message) ->
|
||||
Body = jsx:encode(#{error => Message}),
|
||||
Req2 = cowboy_req:reply(Code, #{<<"content-type">> => <<"application/json">>}, Body, Req),
|
||||
{ok, Req2, []}.
|
||||
Reference in New Issue
Block a user