This commit is contained in:
2026-04-20 10:28:53 +03:00
parent 7e776ea6e3
commit 4224da1a22
11 changed files with 520 additions and 6 deletions
+36
View File
@@ -0,0 +1,36 @@
-module(middleware_auth).
-behaviour(cowboy_middleware).
-export([execute/2]).
execute(Req, Env) ->
case authenticate(Req) of
{ok, UserId, Role} ->
% Добавляем user_id и role в env
NewReq = cowboy_req:set_resp_header(<<"X-User-Id">>, UserId, Req),
{ok, NewReq, [{user_id, UserId}, {role, Role} | Env]};
{error, {Code, Message}} ->
send_error(Req, Code, Message)
end.
authenticate(Req) ->
case cowboy_req:parse_header(<<"authorization">>, Req) of
{ok, <<"Bearer ", Token/binary>>, _} ->
case logic_auth:verify_jwt(Token) of
{ok, Claims} ->
UserId = maps:get(<<"user_id">>, Claims),
Role = maps:get(<<"role">>, Claims),
{ok, UserId, Role};
{error, expired} ->
{error, {401, <<"Token expired">>}};
{error, _} ->
{error, {401, <<"Invalid token">>}}
end;
_ ->
{error, {401, <<"Missing or invalid Authorization header">>}}
end.
send_error(Req, Code, Message) ->
Body = jsx:encode(#{error => Message}),
NewReq = cowboy_req:reply(Code, #{<<"content-type">> => <<"application/json">>}, Body, Req),
{stop, NewReq}.