68 lines
2.4 KiB
Erlang
68 lines
2.4 KiB
Erlang
-module(handler_login).
|
|
-behaviour(cowboy_handler).
|
|
-export([init/2]).
|
|
|
|
-include("records.hrl").
|
|
|
|
init(Req0, State) ->
|
|
handle(Req0, State).
|
|
|
|
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 eventhub_auth:authenticate_user_request(Req1, Email, Password) of
|
|
{ok, Token, User} ->
|
|
{RefreshToken, _ExpiresAt} = eventhub_auth:generate_refresh_token(maps:get(id, User)),
|
|
core_session:create(maps:get(id, User), RefreshToken),
|
|
Response = #{
|
|
user => #{
|
|
id => maps:get(id, User),
|
|
email => maps:get(email, User),
|
|
role => maps:get(role, User)
|
|
},
|
|
token => Token,
|
|
refresh_token => RefreshToken
|
|
},
|
|
send_json(Req1, 200, Response);
|
|
{error, frozen} ->
|
|
send_error(Req1, 403, <<"Account frozen">>);
|
|
{error, deleted} ->
|
|
send_error(Req1, 403, <<"Account deleted">>);
|
|
{error, _Reason} ->
|
|
send_error(Req1, 401, <<"Invalid credentials">>)
|
|
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),
|
|
{ok, Body, []}.
|
|
|
|
send_error(Req, Status, Message) ->
|
|
Body = jsx:encode(#{error => Message}),
|
|
cowboy_req:reply(Status, #{
|
|
<<"content-type">> => <<"application/json">>
|
|
}, Body, Req),
|
|
{ok, Body, []}. |