-module(handler_register). -include("records.hrl"). -export([init/2]). init(Req, Opts) -> handle(Req, Opts). handle(Req, _Opts) -> case cowboy_req:method(Req) of <<"POST">> -> case cowboy_req:has_body(Req) of true -> {ok, Body, Req1} = cowboy_req:read_body(Req), case Body of <<>> -> send_error(Req1, 400, <<"Empty request body">>); _ -> try jsx:decode(Body, [return_maps]) of #{<<"email">> := Email, <<"password">> := Password} -> case core_user:email_exists(Email) of true -> send_error(Req1, 409, <<"Email already exists">>); false -> case core_user:create(Email, Password) of {ok, User} -> Token = logic_auth:generate_jwt(User#user.id, User#user.role), Response = #{ user => #{ id => User#user.id, email => User#user.email, role => User#user.role }, token => Token }, send_json(Req1, 201, Response); {error, email_exists} -> send_error(Req1, 409, <<"Email already exists">>); {error, _} -> send_error(Req1, 500, <<"Internal server error">>) end end; _ -> send_error(Req1, 400, <<"Missing email or password">>) catch _:_ -> send_error(Req1, 400, <<"Invalid JSON">>) end end; false -> send_error(Req, 400, <<"Missing request body">>) end; _ -> send_error(Req, 405, <<"Method not allowed">>) end. send_json(Req, Status, Data) -> Body = jsx:encode(Data), cowboy_req:reply(Status, #{<<"content-type">> => <<"application/json">>}, Body, Req). send_error(Req, Status, Message) -> Body = jsx:encode(#{error => Message}), cowboy_req:reply(Status, #{<<"content-type">> => <<"application/json">>}, Body, Req).