Метод POST /api/v1/auth/register

Документация API: Регистрация пользователей с инициализацией контуров HOME и OFFICE

Author

Application & Simulation Services Framework Documentation

Published

July 2, 2026

WarningОграничение публичной документации

В открытом доступе представлена демонстрационная версия метода. В настоящей публичной документации отображены не все шаги, технические сценарии и приватные эндпоинты для системы цифровых симуляторов бизнес-процессов.

  • Полная спецификация метода: Будет доступна только во внутреннем контуре разработки (Confluence / Swagger Enterprise).

Функциональное назначение

This method is designed for initial user registration in the system.

Beyond standard account creation (password hashing), this method addresses the initialization of the resource storage infrastructure:

  1. Dynamic Space Branching: Based on the space_creation_mode parameter, the method either generates a brand-new isolated “refrigerator” with its unique home_group_id (for a family or an office) or links the new user to an already existing group based on the provided invite code (invite_token).
  2. Initial Business Logic Configuration: It locks in the account_type flag (HOME or OFFICE) for the created group. This flag subsequently determines whether hidden virtual negative balances are allowed during cooking and disposal, or if the system must operate in a strict warehouse control mode.

Interaction Protocol (HTTP Contract)

  • Method: POST
  • Route: /api/v1/auth/register
  • Data Format: application/json

Header Specification (HTTP Headers)

Header Required Description Example Value
Content-Type Yes Specifies the transmission of a strictly typed JSON payload application/json
X-Request-ID Yes End-to-end request ID for new account creation session tracing req-auth-reg-001a

Request Body Specification (Request Body)

Field Type Required Description Example Value
email String Yes Unique email address (validated by a regular expression) user@somedomain.kz
password String Yes User password (strictly at least 8 characters long) SecretSecurePassword123
space_creation_mode String (Enum) Yes Inventory space initialization mode "CREATE_NEW_OFFICE"
invite_token String No UUID of the invite code to join an already created family/office null (or UUID)

Allowed space_creation_mode Constants (Enum):

  • CREATE_NEW_HOME — create a new family space (virtual negative balances are allowed).
  • CREATE_NEW_OFFICE — create a new office space (strict inventory tracking, blocking deficit actions).
  • JOIN_EXISTING — join an existing group using the invite code provided in the invite_token field.

Request JSON Example (Payload — Scenario: company registration with new office space creation):

{
  "email": "user@somedomain.kz",
  "password": "SecretSecurePassword123",
  "space_creation_mode": "CREATE_NEW_OFFICE",
  "invite_token": null
}

Метод предназначен для первичной регистрации пользователя в cистеме.

Помимо стандартного создания учетной записи (хэширования паролей), данный метод решает задачу инициализации инфраструктуры хранения ресурсов:

  1. Динамическое ветвление пространств: На основе параметра space_creation_mode метод либо генерирует абсолютно новый изолированный “холодильник” со своим уникальным home_group_id (для семьи или офиса), либо привязывает нового пользователя к уже существующей группе на основе переданного инвайт-кода (invite_token).
  2. Первичная разметка бизнес-логики: Фиксирует для создаваемой группы флаг account_type (HOME или OFFICE), который в дальнейшем определяет, разрешены ли скрытые виртуальные минусы при готовке и утилизации, или система должна работать в режиме строгого складского контроля.

Протокол взаимодействия (HTTP Контракт)

  • Метод: POST
  • Маршрут: /api/v1/auth/register
  • Формат данных: application/json

Спецификация заголовков (HTTP Headers)

Заголовок Обязательный Описание Пример значения
Content-Type Да Указывает на передачу строго типизированного JSON-пакета application/json
X-Request-ID Да Сквозной ID запроса для трассировки создания новой учетной записи req-auth-reg-001a

Спецификация тела запроса (Request Body)

Поле Тип Обязательный Описание Пример значения
email String Да Уникальный адрес электронной почты (валидируется регулярным выражением) user@somedomain.kz
password String Да Пароль пользователя (строго не менее 8 символов) SecretSecurePassword123
space_creation_mode String (Enum) Да Режим инициализации складского пространства "CREATE_NEW_OFFICE"
invite_token String Нет UUID инвайт-кода для вступления в уже созданную семью/офис null (или UUID)

Допустимые константы space_creation_mode (Enum):

  • CREATE_NEW_HOME — создать новую семью (разрешены виртуальные минусы).
  • CREATE_NEW_OFFICE — создать новый офис (строгий контроль остатков, блокировка дефицита).
  • JOIN_EXISTING — вступить в готовую группу по инвайт-коду из поля invite_token.

Пример JSON-запроса (Payload — Сценарий: регистрация компании с созданием нового офисного пространства):

{
  "email": "user@somedomain.kz",
  "password": "SecretSecurePassword123",
  "space_creation_mode": "CREATE_NEW_OFFICE",
  "invite_token": null
}

Диаграмма последовательности (Mermaid)

The diagram illustrates the registration logic. The Auth service opens an atomic transaction, creates a record in the users table, generates a unique home_group_id for the new space (or links the user to an existing one via an invite code), and securely hashes the password.

sequenceDiagram
    autonumber
    
    actor App as APP (Mobile App)
    participant Nginx as Nginx Proxy
    participant GW as GATEWAY (backend-api)
    participant Auth as AUTH (auth-service)
    participant DB as DB_AUTH (PostgreSQL)

    App->>Nginx: Step 1: POST /api/v1/auth/register (email, password)
    activate Nginx
    Nginx->>GW: Step 2: POST /backend-api/v1/auth/register
    activate GW
    GW->>Auth: Step 3: gRPC: RegisterUser(RegisterRequest)
    activate Auth
    
    Auth->>DB: Step 4: SQL INSERT INTO users...
    activate DB
    DB-->>Auth: Step 5: Result: user_id
    deactivate DB
    
    note over Auth: Step 6: Internal method<br/>GenerateTokenPair(user_id)
    
    Auth->>DB: Step 7: SQL INSERT INTO user_sessions...
    activate DB
    DB-->>Auth: Session record confirmed
    deactivate DB
    
    Auth-->>GW: Step 8: gRPC: RegisterResponse
    deactivate Auth
    GW-->>App: Step 9: HTTP 201 Created (access, refresh)
    deactivate GW
    deactivate Nginx
    
    note over App: Step 10: Internal method<br/>SecureStorage.write(...)

New Account Registration Process (Register)

На диаграмме представлена логика регистрации. Сервис Auth открывает атомарную транзакцию, создаёт запись в таблице пользователей, генерирует уникальный home_group_id для нового пространства (или связывает пользователя с существующим по инвайт-коду) и надёжно хэширует пароль.

sequenceDiagram
    autonumber
    
    actor App as APP (Мобильное приложение)
    participant Nginx as Nginx Proxy
    participant GW as GATEWAY (backend-api)
    participant Auth as AUTH (auth-service)
    participant DB as DB_AUTH (PostgreSQL)

    App->>Nginx: Шаг 1: POST /api/v1/auth/register (email, password)
    activate Nginx
    Nginx->>GW: Шаг 2: POST /backend-api/v1/auth/register
    activate GW
    GW->>Auth: Шаг 3: gRPC: RegisterUser(RegisterRequest)
    activate Auth
    
    Auth->>DB: Шаг 4: SQL INSERT INTO users...
    activate DB
    DB-->>Auth: Шаг 5: Result: user_id
    deactivate DB
    
    note over Auth: Шаг 6: Внутренний метод<br/>GenerateTokenPair(user_id)
    
    Auth->>DB: Шаг 7: SQL INSERT INTO user_sessions...
    activate DB
    DB-->>Auth: Подтверждение записи сессии
    deactivate DB
    
    Auth-->>GW: Шаг 8: gRPC: RegisterResponse
    deactivate Auth
    GW-->>App: Шаг 9: HTTP 201 Created (access, refresh)
    deactivate GW
    deactivate Nginx
    
    note over App: Шаг 10: Внутренний метод<br/>SecureStorage.write(...)

Процесс регистрации нового аккаунта (Register)

Расшифровка шагов

Step Action Parameters / Requests / DTO Errors (Exceptions / Statuses)
Step 1 (App -> Nginx) The client sends registration details and the space initialization mode to the profile creation endpoint. HTTP POST /api/v1/auth/register
Payload (UserRegisterRequestDTO):
{ "email": "user@somedomain.kz", "password": "SecretSecurePassword123", "space_creation_mode": "CREATE_NEW_OFFICE", "invite_token": null }
HTTP 400 Bad Request (invalid email format or too short password)
HTTP 429 Too Many Requests (registration endpoint Rate Limit exceeded)
Step 2 (Nginx -> Gateway) The proxy server performs basic routing of the request to the gateway while injecting an end-to-end trace ID. HTTP POST /backend-api/v1/auth/register
Headers:
X-Request-ID: "req-auth-reg-001a"
No business errors
Step 3 (Gateway -> Auth) The API gateway validates the parameter contract and forwards the call to the authorization service. Protocol: gRPC
Method: RegisterUser(RegisterRequest)
Parameters: email, password, space_creation_mode, invite_token
gRPC Status: INVALID_ARGUMENT (parameter validation failure or unsupported space_creation_mode passed)
Step 4 (Auth -> DB_Auth) The service executes an SQL query to create the user account in the system boundary. SQL Query:
INSERT INTO users (email, password_hash, space_creation_mode) VALUES ('user@somedomain.kz', 'hash_bcrypt...', 'CREATE_NEW_OFFICE') RETURNING id;
gRPC Status: ALREADY_EXISTS / PostgreSQL Exception: UniqueViolation (the specified email is already registered in the system)
Step 5 (DB_Auth -> Auth) The database writes the record and returns the generated UUID of the new user. DBMS Dataset (RecordSet): returns id value (e.g., usr-8822-fa41). No business errors
Step 6 (Auth -> Auth) The service initializes the space (home_group_id), determines the account type, and generates a JWT pair, embedding business context into Claims. Internal method: GenerateTokenPair(user_id).
JWT Access Claims Payload:
{ "sub": "usr-8822-fa41", "home_group_id": "8a71d11e-9500-4b11-9a2c-d2b0d7b3dcba", "account_type": "OFFICE" }
No business errors
Step 7 (Auth -> DB_Auth) The service persists the hash of the long-lived Refresh token to manage the client’s active session. SQL Query:
INSERT INTO user_sessions (user_id, refresh_token_hash, expires_at) VALUES ('usr-8822-fa41', 'hash...', '2026-08-27');
No business errors
Confirmation (DB_Auth -> Auth) The database confirms the successful commit of the session row. DBMS Response: Status INSERT 0 1 (1 row successfully recorded). No business errors
Step 8 (Auth -> Gateway) The service returns the generated token structure and profile metadata back to the API gateway. Protocol: gRPC
Response: RegisterResponse
Payload: access_token, refresh_token, user_id, home_group_id, account_type
No business errors
Step 9 (Gateway -> App) The gateway relays the response through Nginx, returning a successful creation status and auth tokens to the app. HTTP Status: 201 Created
Response Body:
{ "status": "success", "data": { "user_id": "usr-8822-fa41", "home_group_id": "8a71d11e-9500-4b11-9a2c-d2b0d7b3dcba", "account_type": "OFFICE", "timestamp": "2026-07-02T02:15:00Z", "access": "eyJhbGci...", "refresh": "def456..." } }
No business errors
Step 10 (App -> App) The mobile app securely and persistently saves the tokens on the device hardware layer. Internal app method: SecureStorage.write(...)
Saves tokens to iOS Keychain or Android Keystore.
No business errors
Шаг Действие Параметры / Запросы / DTO Ошибки (Исключения / Статусы)
Шаг 1 (App -> Nginx) Клиент отправляет регистрационные данные и режим инициализации пространства на эндпоинт создания профиля. HTTP POST /api/v1/auth/register
Payload (UserRegisterRequestDTO):
{ "email": "user@somedomain.kz", "password": "SecretSecurePassword123", "space_creation_mode": "CREATE_NEW_OFFICE", "invite_token": null }
HTTP 400 Bad Request (некорректный формат email или слишком короткий пароль)
HTTP 429 Too Many Requests (превышен лимит Rate Limit запросов на регистрацию)
Шаг 2 (Nginx -> Gateway) Прокси-сервер выполняет базовую маршрутизацию запроса на шлюз с добавлением сквозного ID трассировки. HTTP POST /backend-api/v1/auth/register
Headers:
X-Request-ID: "req-auth-reg-001a"
Бизнес-ошибки отсутствуют
Шаг 3 (Gateway -> Auth) API-шлюз валидирует контракт параметров и транслирует вызов в сервис авторизации. Протокол: gRPC
Метод: RegisterUser(RegisterRequest)
Параметры: email, password, space_creation_mode, invite_token
gRPC Status: INVALID_ARGUMENT (ошибка валидации структуры параметров или передан неподдерживаемый режим space_creation_mode)
Шаг 4 (Auth -> DB_Auth) Сервис выполняет SQL-запрос на создание учетной записи пользователя в контуре. SQL-запрос:
INSERT INTO users (email, password_hash, space_creation_mode) VALUES ('user@somedomain.kz', 'hash_bcrypt...', 'CREATE_NEW_OFFICE') RETURNING id;
gRPC Status: ALREADY_EXISTS / PostgreSQL Exception: UniqueViolation (указанный email уже зарегистрирован в системе)
Шаг 5 (DB_Auth -> Auth) База данных выполняет запись и возвращает сгенерированный UUID нового пользователя. Набор данных СУБД (RecordSet): возвращается значение id (например, usr-8822-fa41). Бизнес-ошибки отсутствуют
Шаг 6 (Auth -> Auth) Сервис инициализирует пространство (home_group_id), определяет тип аккаунта и генерирует пару JWT, внедряя бизнес-контекст в Claims. Внутренний метод: GenerateTokenPair(user_id).
JWT Access Claims Payload:
{ "sub": "usr-8822-fa41", "home_group_id": "8a71d11e-9500-4b11-9a2c-d2b0d7b3dcba", "account_type": "OFFICE" }
Бизнес-ошибки отсутствуют
Шаг 7 (Auth -> DB_Auth) Сервис сохраняет хэш долгоживущего Refresh-токена для управления активной сессией клиента. SQL-запрос:
INSERT INTO user_sessions (user_id, refresh_token_hash, expires_at) VALUES ('usr-8822-fa41', 'hash...', '2026-08-27');
Бизнес-ошибки отсутствуют
Подтверждение (DB_Auth -> Auth) База данных подтверждает успешную запись сессии. Ответ СУБД: Статус INSERT 0 1 (успешная фиксация 1 строки). Бизнес-ошибки отсутствуют
Шаг 8 (Auth -> Gateway) Сервис возвращает сформированную структуру токенов и метаданные профиля на API-шлюз. Протокол: gRPC
Ответ: RegisterResponse
Payload: access_token, refresh_token, user_id, home_group_id, account_type
Бизнес-ошибки отсутствуют
Шаг 9 (Gateway -> App) Шлюз транслирует ответ через Nginx, возвращая приложению статус успешного создания сущностей и авторизационные токены. HTTP Статус: 201 Created
Response Body:
{ "status": "success", "data": { "user_id": "usr-8822-fa41", "home_group_id": "8a71d11e-9500-4b11-9a2c-d2b0d7b3dcba", "account_type": "OFFICE", "timestamp": "2026-07-02T02:15:00Z", "access": "eyJhbGci...", "refresh": "def456..." } }
Бизнес-ошибки отсутствуют
Шаг 10 (App -> App) Мобильное приложение изолированно сохраняет полученные токены на аппаратном уровне устройства. Внутренний метод: SecureStorage.write(...)
Запись в iOS Keychain или Android Keystore.
Бизнес-ошибки отсутствуют

Спецификация ответов сервера (Response Body)

Success Response

HTTP 201 Created

Returned to the mobile application after the successful commit of the registration transaction. The response body contains the newly generated user identifier and the warehouse environment parameters.

  • Response Headers:
    • Content-Type: application/json
  • Response Body:
{
  "status": "success",
  "data": {
    "user_id": "usr-8822-fa41",
    "home_group_id": "8a71d11e-9500-4b11-9a2c-d2b0d7b3dcba",
    "account_type": "OFFICE",
    "timestamp": "2026-07-02T02:15:00Z"
  }
}

Успешный ответ (Success Response)

HTTP 201 Created

Возвращается мобильному приложению после успешного коммита транзакции. В теле ответа фиксируется сгенерированный идентификатор пользователя и параметры контура.

  • Заголовки ответа (Response Headers):
    • Content-Type: application/json
  • Тело ответа (Response Body):
{
  "status": "success",
  "data": {
    "user_id": "usr-8822-fa41",
    "home_group_id": "8a71d11e-9500-4b11-9a2c-d2b0d7b3dcba",
    "account_type": "OFFICE",
    "timestamp": "2026-07-02T02:15:00Z"
  }
}