-module(admin_handler_users). -include("records.hrl"). -export([init/2]). init(Req, Opts) -> handle(Req, Opts). handle(Req, _Opts) -> case cowboy_req:method(Req) of <<"GET">> -> list_users(Req); _ -> send_error(Req, 405, <<"Method not allowed">>) end. list_users(Req) -> case handler_auth:authenticate(Req) of {ok, AdminId, Req1} -> case is_admin(AdminId) of true -> Users = mnesia:dirty_match_object(#user{_ = '_'}), ActiveUsers = [U || U <- Users, U#user.status =/= deleted], Response = [user_to_json(U) || U <- ActiveUsers], send_json(Req1, 200, Response); 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} -> User#user.role =:= admin; _ -> false end. user_to_json(User) -> #{ id => User#user.id, email => User#user.email, role => User#user.role, status => User#user.status, created_at => datetime_to_iso8601(User#user.created_at), updated_at => datetime_to_iso8601(User#user.updated_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])). 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, []}.