Сделано подтверждение регистрации пользователей #22
This commit is contained in:
@@ -42,7 +42,7 @@ create(Email, Password) ->
|
||||
email = Email,
|
||||
password_hash = PasswordHash,
|
||||
role = user,
|
||||
status = active,
|
||||
status = pending,
|
||||
reason = ?DEFAULT_REASON,
|
||||
nickname = extract_nickname(Email),
|
||||
avatar_url = ?DEFAULT_AVATAR_URL,
|
||||
@@ -302,9 +302,9 @@ apply_updates(User, Updates) ->
|
||||
-spec set_field(atom(), term(), #user{}) -> #user{}.
|
||||
set_field(email, Value, U) -> U#user{email = Value};
|
||||
set_field(password_hash, Value, U) -> U#user{password_hash = Value};
|
||||
set_field(role, Value, U) when Value =:= user; Value =:= admin; Value =:= bot ->
|
||||
set_field(role, Value, U) when Value =:= user; Value =:= bot ->
|
||||
U#user{role = Value};
|
||||
set_field(status, Value, U) when Value =:= active; Value =:= frozen; Value =:= deleted ->
|
||||
set_field(status, Value, U) when Value =:= active; Value =:= frozen; Value =:= deleted; Value =:= pending ->
|
||||
U#user{status = Value};
|
||||
set_field(reason, Value, U) -> U#user{reason = Value};
|
||||
set_field(nickname, Value, U) -> U#user{nickname = Value};
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
-module(core_verification).
|
||||
-include("records.hrl").
|
||||
-export([create_token/1, verify_token/1, get_or_create_token/1, delete_token/1]).
|
||||
|
||||
-define(TOKEN_LIFETIME_HOURS, 1).
|
||||
|
||||
%%%-------------------------------------------------------------------
|
||||
%%% @doc Создаёт верификационный токен для пользователя.
|
||||
%%% @end
|
||||
%%%-------------------------------------------------------------------
|
||||
-spec create_token(UserId :: binary()) -> {ok, Token :: binary(), ExpiresAt :: calendar:datetime()}.
|
||||
create_token(UserId) ->
|
||||
Token = infra_utils:generate_id(32),
|
||||
Expires = calendar:gregorian_seconds_to_datetime(
|
||||
calendar:datetime_to_gregorian_seconds(calendar:universal_time()) + ?TOKEN_LIFETIME_HOURS * 3600),
|
||||
mnesia:dirty_write(#verification{token = Token, user_id = UserId, expires_at = Expires}),
|
||||
{ok, Token, Expires}.
|
||||
|
||||
%%%-------------------------------------------------------------------
|
||||
%%% @doc Проверяет токен. Возвращает `{ok, UserId}` или ошибку.
|
||||
%%% @end
|
||||
%%%-------------------------------------------------------------------
|
||||
-spec verify_token(Token :: binary()) ->
|
||||
{ok, UserId :: binary()} | {error, expired | not_found}.
|
||||
verify_token(Token) ->
|
||||
case mnesia:dirty_read(verification, Token) of
|
||||
[#verification{user_id = UserId, expires_at = Expires}] ->
|
||||
case Expires > calendar:universal_time() of
|
||||
true -> {ok, UserId};
|
||||
false -> {error, expired}
|
||||
end;
|
||||
[] -> {error, not_found}
|
||||
end.
|
||||
|
||||
%%%-------------------------------------------------------------------
|
||||
%%% @doc Возвращает существующий токен пользователя или создаёт новый.
|
||||
%%% @end
|
||||
%%%-------------------------------------------------------------------
|
||||
-spec get_or_create_token(UserId :: binary()) ->
|
||||
{ok, Token :: binary(), ExpiresAt :: calendar:datetime()} | {error, not_found}.
|
||||
get_or_create_token(UserId) ->
|
||||
case mnesia:dirty_match_object(#verification{user_id = UserId, _ = '_'}) of
|
||||
[V] -> {ok, V#verification.token, V#verification.expires_at};
|
||||
[] ->
|
||||
case core_user:get_by_id(UserId) of
|
||||
{ok, _} -> create_token(UserId);
|
||||
Error -> Error
|
||||
end
|
||||
end.
|
||||
|
||||
%%%-------------------------------------------------------------------
|
||||
%%% @doc Удаляет токен.
|
||||
%%% @end
|
||||
%%%-------------------------------------------------------------------
|
||||
-spec delete_token(Token :: binary()) -> ok.
|
||||
delete_token(Token) ->
|
||||
mnesia:dirty_delete(verification, Token),
|
||||
ok.
|
||||
@@ -66,6 +66,7 @@ start_http() ->
|
||||
{"/metrics/[:registry]", prometheus_cowboy2_handler, []},
|
||||
{"/health", handler_health, []},
|
||||
{"/v1/register", handler_register, []},
|
||||
{"/v1/verify", handler_verify, []},
|
||||
{"/v1/login", handler_login, []},
|
||||
{"/v1/refresh", handler_refresh, []},
|
||||
{"/v1/user/me", handler_user_me, []},
|
||||
@@ -113,6 +114,7 @@ start_admin_http() ->
|
||||
% ================== ПОЛЬЗОВАТЕЛИ ==================
|
||||
{"/v1/admin/users", admin_handler_users, []},
|
||||
{"/v1/admin/users/:id", admin_handler_user_by_id, []},
|
||||
{"/v1/admin/users/:id/verification-token", admin_handler_user_verification_token, []},
|
||||
% ================== КАЛЕНДАРИ ==================
|
||||
{"/v1/admin/calendars", admin_handler_calendars, []},
|
||||
{"/v1/admin/calendars/:id", admin_handler_calendar_by_id, []},
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
-module(admin_handler_user_verification_token).
|
||||
-behaviour(cowboy_handler).
|
||||
-export([init/2]).
|
||||
-export([trails/0]).
|
||||
|
||||
init(Req, _Opts) ->
|
||||
case cowboy_req:method(Req) of
|
||||
<<"GET">> -> get_token(Req);
|
||||
_ -> handler_utils:send_error(Req, 405, <<"Method not allowed">>)
|
||||
end.
|
||||
|
||||
get_token(Req) ->
|
||||
case handler_utils:auth_admin(Req) of
|
||||
{ok, _AdminId, Req1} ->
|
||||
UserId = cowboy_req:binding(id, Req1),
|
||||
case core_verification:get_or_create_token(UserId) of
|
||||
{ok, Token, ExpiresAt} ->
|
||||
handler_utils:send_json(Req1, 200, #{
|
||||
<<"token">> => Token,
|
||||
<<"expires_at">> => handler_utils:datetime_to_iso8601(ExpiresAt)
|
||||
});
|
||||
{error, not_found} ->
|
||||
handler_utils:send_error(Req1, 404, <<"User not found">>)
|
||||
end;
|
||||
{error, Code, Msg, Req1} ->
|
||||
handler_utils:send_error(Req1, Code, Msg)
|
||||
end.
|
||||
|
||||
trails() ->
|
||||
[#{path => <<"/v1/admin/users/:id/verification-token">>,
|
||||
method => <<"GET">>,
|
||||
description => <<"Get or create verification token for user (admin)">>,
|
||||
tags => [<<"Users">>],
|
||||
parameters => [#{name => <<"id">>, in => <<"path">>, required => true, schema => #{type => string}}],
|
||||
responses => #{200 => #{description => <<"Token">>}}}].
|
||||
@@ -86,6 +86,8 @@ login(Req) ->
|
||||
<<"refresh_token">> => RefreshToken
|
||||
},
|
||||
handler_utils:send_json(Req1, 200, Response);
|
||||
{error, not_verified} ->
|
||||
handler_utils:send_error(Req1, 403, <<"Account not verified">>);
|
||||
{error, frozen} ->
|
||||
handler_utils:send_error(Req1, 403, <<"Account frozen">>);
|
||||
{error, deleted} ->
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
%%%-------------------------------------------------------------------
|
||||
%%% @doc Обработчик регистрации пользователя (клиентский API).
|
||||
%%% POST – создаёт нового пользователя, возвращает JWT токен.
|
||||
%%% POST – создаёт нового пользователя (статус pending), возвращает
|
||||
%%% информацию о пользователе без JWT токена.
|
||||
%%% @end
|
||||
%%%-------------------------------------------------------------------
|
||||
-module(handler_register).
|
||||
@@ -23,7 +24,7 @@ trails() ->
|
||||
#{
|
||||
path => <<"/v1/register">>,
|
||||
method => <<"POST">>,
|
||||
description => <<"Register a new user">>,
|
||||
description => <<"Register a new user (account will be pending until email verified)">>,
|
||||
tags => [<<"Auth">>],
|
||||
requestBody => #{
|
||||
required => true,
|
||||
@@ -37,7 +38,7 @@ trails() ->
|
||||
}}}
|
||||
},
|
||||
responses => #{
|
||||
201 => #{description => <<"User registered, returns token and user info">>},
|
||||
201 => #{description => <<"User registered successfully (pending verification)">>},
|
||||
400 => #{description => <<"Missing email or password, or invalid JSON">>},
|
||||
409 => #{description => <<"Email already exists">>}
|
||||
}
|
||||
@@ -74,17 +75,16 @@ register(Req) ->
|
||||
false ->
|
||||
case core_user:create(Email, Password) of
|
||||
{ok, User} ->
|
||||
Token = logic_auth:generate_jwt(
|
||||
User#user.id,
|
||||
atom_to_binary(User#user.role, utf8)
|
||||
),
|
||||
% Создаём верификационный токен и отправляем письмо
|
||||
{ok, VerificationToken, _Expires} = core_verification:create_token(User#user.id),
|
||||
logic_email:send_verification_email(Email, VerificationToken),
|
||||
Response = #{
|
||||
user => #{
|
||||
id => User#user.id,
|
||||
email => User#user.email,
|
||||
role => User#user.role
|
||||
},
|
||||
token => Token
|
||||
id => User#user.id,
|
||||
email => User#user.email,
|
||||
role => atom_to_binary(User#user.role, utf8),
|
||||
status => atom_to_binary(User#user.status, utf8) % <<"pending">>
|
||||
}
|
||||
},
|
||||
handler_utils:send_json(Req1, 201, Response);
|
||||
{error, email_exists} ->
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
%%%-------------------------------------------------------------------
|
||||
%%% @doc Обработчик подтверждения email.
|
||||
%%% POST /v1/verify – активирует аккаунт по верификационному токену.
|
||||
%%% @end
|
||||
%%%-------------------------------------------------------------------
|
||||
-module(handler_verify).
|
||||
-behaviour(cowboy_handler).
|
||||
-export([init/2]).
|
||||
-export([trails/0]).
|
||||
|
||||
%%% cowboy_handler callback
|
||||
init(Req, _Opts) ->
|
||||
case cowboy_req:method(Req) of
|
||||
<<"POST">> ->
|
||||
{ok, Body, Req1} = cowboy_req:read_body(Req),
|
||||
try jsx:decode(Body, [return_maps]) of
|
||||
#{<<"token">> := Token} ->
|
||||
case core_verification:verify_token(Token) of
|
||||
{ok, UserId} ->
|
||||
core_user:update(UserId, [{status, active}]),
|
||||
core_verification:delete_token(Token),
|
||||
handler_utils:send_json(Req1, 200, #{<<"message">> => <<"Account verified">>});
|
||||
{error, expired} ->
|
||||
handler_utils:send_error(Req1, 410, <<"Token expired">>);
|
||||
{error, not_found} ->
|
||||
handler_utils:send_error(Req1, 404, <<"Token not found">>)
|
||||
end;
|
||||
_ ->
|
||||
handler_utils:send_error(Req1, 400, <<"Missing token">>)
|
||||
catch
|
||||
_:_ -> handler_utils:send_error(Req1, 400, <<"Invalid JSON">>)
|
||||
end;
|
||||
_ ->
|
||||
handler_utils:send_error(Req, 405, <<"Method not allowed">>)
|
||||
end.
|
||||
|
||||
%%% Swagger metadata
|
||||
-spec trails() -> [map()].
|
||||
trails() ->
|
||||
[
|
||||
#{
|
||||
path => <<"/v1/verify">>,
|
||||
method => <<"POST">>,
|
||||
description => <<"Verify user account using email verification token">>,
|
||||
tags => [<<"Auth">>],
|
||||
requestBody => #{
|
||||
required => true,
|
||||
content => #{
|
||||
<<"application/json">> => #{
|
||||
schema => #{
|
||||
type => object,
|
||||
required => [<<"token">>],
|
||||
properties => #{
|
||||
token => #{type => string, description => <<"Verification token received by email">>}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
responses => #{
|
||||
200 => #{description => <<"Account verified successfully">>},
|
||||
400 => #{description => <<"Missing token field or invalid JSON">>},
|
||||
404 => #{description => <<"Token not found">>},
|
||||
410 => #{description => <<"Token expired">>}
|
||||
}
|
||||
}
|
||||
].
|
||||
@@ -12,7 +12,7 @@
|
||||
terminate/2, code_change/3]).
|
||||
|
||||
-define(TABLES, [
|
||||
user, session, admin, admin_session,
|
||||
user, session, verification, admin, admin_session,
|
||||
calendar, calendar_share, calendar_specialist,
|
||||
event, recurrence_exception,
|
||||
booking,
|
||||
@@ -22,7 +22,7 @@
|
||||
stats, schema_migration
|
||||
]).
|
||||
|
||||
-define(DISC_TABLES, ?TABLES -- [session, admin_session]).
|
||||
-define(DISC_TABLES, ?TABLES -- [session, verification, admin_session]).
|
||||
-define(TABLE_WAIT_TIMEOUT, 5000).
|
||||
-define(CLEANUP_INTERVAL, 30000). % 30 секунд
|
||||
|
||||
@@ -219,6 +219,7 @@ table_opts(notification) -> [{disc_copies, [node()]}, {attributes, record_info(f
|
||||
table_opts(stats) -> [{disc_copies, [node()]}, {attributes, record_info(fields, stats)}];
|
||||
table_opts(schema_migration) -> [{disc_copies, [node()]}, {attributes, record_info(fields, schema_migration)}];
|
||||
table_opts(session) -> [{ram_copies, [node()]}, {attributes, record_info(fields, session)}];
|
||||
table_opts(verification) -> [{ram_copies, [node()]}, {attributes, record_info(fields, verification)}];
|
||||
table_opts(admin_session) -> [{ram_copies, [node()]}, {attributes, record_info(fields, admin_session)}].
|
||||
|
||||
%% ===================================================================
|
||||
|
||||
@@ -35,11 +35,15 @@ authenticate_user(Email, Password) ->
|
||||
{ok, User} ->
|
||||
case verify_password(Password, User#user.password_hash) of
|
||||
{ok, true} ->
|
||||
{ok, #{
|
||||
id => User#user.id,
|
||||
email => User#user.email,
|
||||
role => atom_to_binary(User#user.role, utf8)
|
||||
}};
|
||||
case User#user.status of
|
||||
pending -> {error, not_verified};
|
||||
active -> {ok, #{
|
||||
id => User#user.id,
|
||||
email => User#user.email,
|
||||
role => atom_to_binary(User#user.role, utf8)
|
||||
}};
|
||||
_ -> {error, invalid_credentials}
|
||||
end;
|
||||
_ -> {error, invalid_credentials}
|
||||
end;
|
||||
{error, not_found} -> {error, invalid_credentials}
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
-module(logic_email).
|
||||
-export([send_verification_email/2]).
|
||||
send_verification_email(Email, Token) ->
|
||||
io:format("Sending verification email to ~s with token ~s~n", [Email, Token]).
|
||||
@@ -1,15 +1,25 @@
|
||||
-module(eventhub_trails).
|
||||
-export([admin/0, user/0, all/0]).
|
||||
|
||||
%%%-------------------------------------------------------------------
|
||||
%%% @doc Возвращает список Swagger-трасс для административных эндпоинтов.
|
||||
%%% @end
|
||||
%%%-------------------------------------------------------------------
|
||||
-spec admin() -> [map()].
|
||||
admin() ->
|
||||
Modules = [
|
||||
% ================== БАЗОВЫЕ ==================
|
||||
admin_handler_health,
|
||||
admin_handler_stats,
|
||||
admin_handler_login,
|
||||
admin_handler_refresh, % ← добавлен
|
||||
% ================== ПОЛЬЗОВАТЕЛИ ==================
|
||||
admin_handler_users,
|
||||
admin_handler_user_by_id,
|
||||
admin_handler_user_verification_token, % ← добавлен
|
||||
% ================== КАЛЕНДАРИ ==================
|
||||
admin_handler_calendars, % ← добавлен
|
||||
admin_handler_calendar_by_id, % ← добавлен
|
||||
% ================== СОБЫТИЯ ==================
|
||||
admin_handler_events,
|
||||
admin_handler_event_by_id,
|
||||
@@ -33,16 +43,23 @@ admin() ->
|
||||
% ================== Управление ролями (только для superadmin) ==================
|
||||
admin_handler_me,
|
||||
admin_handler_admins,
|
||||
admin_handler_admins_by_id, % ← добавлен
|
||||
admin_handler_audit
|
||||
],
|
||||
lists:flatmap(fun trails_from_module/1, Modules).
|
||||
|
||||
%%%-------------------------------------------------------------------
|
||||
%%% @doc Возвращает список Swagger-трасс для пользовательских эндпоинтов.
|
||||
%%% @end
|
||||
%%%-------------------------------------------------------------------
|
||||
-spec user() -> [map()].
|
||||
user() ->
|
||||
Modules = [
|
||||
handler_health,
|
||||
handler_register,
|
||||
handler_login,
|
||||
handler_refresh,
|
||||
handler_verify, % ← добавлен
|
||||
handler_booking_by_id,
|
||||
handler_bookings,
|
||||
handler_calendar_by_id,
|
||||
@@ -64,9 +81,20 @@ user() ->
|
||||
],
|
||||
lists:flatmap(fun trails_from_module/1, Modules).
|
||||
|
||||
%%%-------------------------------------------------------------------
|
||||
%%% @doc Возвращает полный список Swagger-трасс (административные + пользовательские).
|
||||
%%% @end
|
||||
%%%-------------------------------------------------------------------
|
||||
-spec all() -> [map()].
|
||||
all() ->
|
||||
admin() ++ user().
|
||||
|
||||
%%%-------------------------------------------------------------------
|
||||
%%% @doc Безопасно извлекает `trails/0` из модуля.
|
||||
%%% Если функция отсутствует, возвращает пустой список.
|
||||
%%% @end
|
||||
%%%-------------------------------------------------------------------
|
||||
-spec trails_from_module(atom()) -> [map()].
|
||||
trails_from_module(Module) ->
|
||||
try Module:trails() of
|
||||
Trails when is_list(Trails) -> Trails
|
||||
|
||||
Reference in New Issue
Block a user