Рефакторинг обработчиков. Часть 1 #21
This commit is contained in:
@@ -1,117 +1,103 @@
|
||||
-module(admin_handler_admins).
|
||||
-behaviour(cowboy_handler).
|
||||
|
||||
-include("records.hrl").
|
||||
|
||||
-export([init/2]).
|
||||
-export([trails/0]).
|
||||
|
||||
-include("records.hrl").
|
||||
|
||||
init(Req, _Opts) ->
|
||||
case cowboy_req:method(Req) of
|
||||
<<"GET">> -> list_admins(Req);
|
||||
<<"POST">> -> create_admin(Req);
|
||||
<<"PUT">> -> update_admin_role(Req);
|
||||
_ -> send_error(Req, 405, <<"Method not allowed">>)
|
||||
_ -> handler_utils:send_error(Req, 405, <<"Method not allowed">>)
|
||||
end.
|
||||
|
||||
list_admins(Req) ->
|
||||
case handler_auth:authenticate(Req) of
|
||||
{ok, AdminId, Req1} ->
|
||||
case admin_utils:check_role(AdminId, superadmin) of
|
||||
true ->
|
||||
Admins = core_admin:list_all(),
|
||||
Json = [admin_to_json(A) || A <- Admins],
|
||||
send_json(Req1, 200, Json);
|
||||
false ->
|
||||
send_error(Req1, 403, <<"Superadmin access required">>)
|
||||
end;
|
||||
{error, Code, Message, Req1} ->
|
||||
send_error(Req1, Code, Message)
|
||||
end.
|
||||
trails() ->
|
||||
[
|
||||
#{
|
||||
path => <<"/v1/admin/admins">>,
|
||||
method => <<"GET">>,
|
||||
description => <<"List all admins (superadmin only)">>,
|
||||
tags => [<<"Admins">>],
|
||||
parameters => [
|
||||
#{name => <<"role">>, in => <<"query">>, schema => #{type => string}},
|
||||
#{name => <<"status">>, in => <<"query">>, schema => #{type => string}},
|
||||
#{name => <<"limit">>, in => <<"query">>, schema => #{type => integer}},
|
||||
#{name => <<"offset">>, in => <<"query">>, schema => #{type => integer}}
|
||||
],
|
||||
responses => #{
|
||||
200 => #{
|
||||
description => <<"Array of admins">>,
|
||||
content => #{<<"application/json">> => #{schema => #{
|
||||
type => array,
|
||||
items => admin_schema()
|
||||
}}}
|
||||
}
|
||||
}
|
||||
}
|
||||
].
|
||||
|
||||
create_admin(Req) ->
|
||||
case handler_auth:authenticate(Req) of
|
||||
{ok, AdminId, Req1} ->
|
||||
case admin_utils:check_role(AdminId, superadmin) of
|
||||
true ->
|
||||
{ok, Body, Req2} = cowboy_req:read_body(Req1),
|
||||
try jsx:decode(Body, [return_maps]) of
|
||||
#{<<"email">> := Email, <<"password">> := Password, <<"role">> := RoleBin} ->
|
||||
Role = binary_to_atom(RoleBin, utf8),
|
||||
case core_admin:create(Email, Password, Role) of
|
||||
{ok, Admin} ->
|
||||
send_json(Req2, 201, admin_to_json(Admin));
|
||||
{error, email_exists} ->
|
||||
send_error(Req2, 409, <<"Email already exists">>);
|
||||
{error, Reason} ->
|
||||
send_error(Req2, 500, Reason)
|
||||
end;
|
||||
_ ->
|
||||
send_error(Req2, 400, <<"Missing required fields (email, password, role)">>)
|
||||
catch
|
||||
_:_ -> send_error(Req2, 400, <<"Invalid JSON">>)
|
||||
end;
|
||||
false ->
|
||||
send_error(Req1, 403, <<"Superadmin access required">>)
|
||||
end;
|
||||
{error, Code, Message, Req1} ->
|
||||
send_error(Req1, Code, Message)
|
||||
end.
|
||||
|
||||
update_admin_role(Req) ->
|
||||
case handler_auth:authenticate(Req) of
|
||||
{ok, AdminId, Req1} ->
|
||||
case admin_utils:check_role(AdminId, superadmin) of
|
||||
true ->
|
||||
AdminIdToUpdate = cowboy_req:binding(id, Req1),
|
||||
{ok, Body, Req2} = cowboy_req:read_body(Req1),
|
||||
try jsx:decode(Body, [return_maps]) of
|
||||
#{<<"role">> := RoleBin} ->
|
||||
NewRole = binary_to_atom(RoleBin, utf8),
|
||||
case core_admin:update_role(AdminIdToUpdate, NewRole) of
|
||||
{ok, Admin} ->
|
||||
send_json(Req2, 200, admin_to_json(Admin));
|
||||
{error, not_found} ->
|
||||
send_error(Req2, 404, <<"Admin not found">>);
|
||||
{error, Reason} ->
|
||||
send_error(Req2, 500, Reason)
|
||||
end;
|
||||
_ ->
|
||||
send_error(Req2, 400, <<"Missing 'role' field">>)
|
||||
catch
|
||||
_:_ -> send_error(Req2, 400, <<"Invalid JSON">>)
|
||||
end;
|
||||
false ->
|
||||
send_error(Req1, 403, <<"Superadmin access required">>)
|
||||
end;
|
||||
{error, Code, Message, Req1} ->
|
||||
send_error(Req1, Code, Message)
|
||||
end.
|
||||
|
||||
admin_to_json(A) ->
|
||||
admin_schema() ->
|
||||
#{
|
||||
id => A#admin.id,
|
||||
email => A#admin.email,
|
||||
role => A#admin.role,
|
||||
status => A#admin.status,
|
||||
created_at => datetime_to_iso8601(A#admin.created_at),
|
||||
updated_at => datetime_to_iso8601(A#admin.updated_at)
|
||||
type => object,
|
||||
properties => #{
|
||||
id => #{type => string},
|
||||
email => #{type => string, format => <<"email">>},
|
||||
role => #{type => string, enum => [<<"superadmin">>, <<"admin">>, <<"moderator">>, <<"support">>]},
|
||||
status => #{type => string, enum => [<<"active">>, <<"blocked">>]},
|
||||
nickname => #{type => string, nullable => true},
|
||||
avatar_url => #{type => string, nullable => true},
|
||||
timezone => #{type => string, nullable => true},
|
||||
language => #{type => string, nullable => true},
|
||||
phone => #{type => string, nullable => true},
|
||||
preferences => #{type => object, nullable => true},
|
||||
last_login => #{type => string, format => <<"date-time">>},
|
||||
created_at => #{type => string, format => <<"date-time">>},
|
||||
updated_at => #{type => string, format => <<"date-time">>}
|
||||
}
|
||||
}.
|
||||
|
||||
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.
|
||||
list_admins(Req) ->
|
||||
case handler_utils:auth_admin(Req) of
|
||||
{ok, _AdminId, Req1} ->
|
||||
Filters = parse_admin_filters(Req1),
|
||||
Pagination = handler_utils:parse_pagination_params(Req1),
|
||||
{ok, Total, Admins} = logic_admin:list_admins(Filters, Pagination),
|
||||
Json = [admin_to_json(A) || A <- Admins],
|
||||
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.
|
||||
|
||||
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, []}.
|
||||
parse_admin_filters(Req) ->
|
||||
Qs = cowboy_req:parse_qs(Req),
|
||||
#{
|
||||
role => proplists:get_value(<<"role">>, Qs),
|
||||
status => proplists:get_value(<<"status">>, Qs)
|
||||
}.
|
||||
|
||||
send_error(Req, Code, Message) ->
|
||||
Body = jsx:encode(#{error => Message}),
|
||||
Req2 = cowboy_req:reply(Code, #{<<"content-type">> => <<"application/json">>}, Body, Req),
|
||||
{ok, Req2, []}.
|
||||
admin_to_json(Admin) ->
|
||||
#{
|
||||
id => Admin#admin.id,
|
||||
email => Admin#admin.email,
|
||||
role => Admin#admin.role,
|
||||
status => Admin#admin.status,
|
||||
nickname => Admin#admin.nickname,
|
||||
avatar_url => Admin#admin.avatar_url,
|
||||
timezone => Admin#admin.timezone,
|
||||
language => Admin#admin.language,
|
||||
phone => Admin#admin.phone,
|
||||
preferences => Admin#admin.preferences,
|
||||
last_login => handler_utils:parse_datetime(Admin#admin.last_login), % требует доработки – лучше общую функцию
|
||||
created_at => handler_utils:parse_datetime(Admin#admin.created_at),
|
||||
updated_at => handler_utils:parse_datetime(Admin#admin.updated_at)
|
||||
}.
|
||||
|
||||
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">>
|
||||
}.
|
||||
Reference in New Issue
Block a user