Stage 3.4
This commit is contained in:
@@ -9,31 +9,46 @@ init(Req, Opts) ->
|
||||
handle(Req, _Opts) ->
|
||||
case cowboy_req:method(Req) of
|
||||
<<"POST">> ->
|
||||
{ok, Body, Req1} = cowboy_req:read_body(Req),
|
||||
case 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, _} ->
|
||||
send_error(Req1, 500, <<"Internal server error">>)
|
||||
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;
|
||||
_ ->
|
||||
send_error(Req1, 400, <<"Invalid request body">>)
|
||||
false ->
|
||||
send_error(Req, 400, <<"Missing request body">>)
|
||||
end;
|
||||
_ ->
|
||||
send_error(Req, 405, <<"Method not allowed">>)
|
||||
|
||||
Reference in New Issue
Block a user