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

Документация API: Аутентификация пользователя (Login) с генерацией JWT, содержащего JWT Claims

Author

Application & Simulation Services Framework Documentation

Published

July 2, 2026

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

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

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

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

ImportantDocumentation Under Development

This documentation section is currently under development and may contain incomplete data. Some technical descriptions, parameters, and system operation scenarios for the digital business process simulator are subject to change.

  • Stable documentation version: Will be published upon final completion and validation of the method code.

This method is designed to authenticate a user in the system using a username/password pair.

Under the new architecture, this method acts as a Security Context Provider:

  1. Session Token Generation: Validates the password hash in the DBMS and generates a cryptographically signed Access Token (JWT).
  2. JWT Claims Injection: Embeds the home_group_id, account_type, and user_id parameters inside the token Payload. This eliminates the need for core transactional microservices (Cook, Consume, Waste) to perform redundant database JOIN queries during every inventory or food deduction, as the FastAPI gateway extracts the group context directly from the decoded token.

Interaction Protocol (HTTP Contract)

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

Header Specification (HTTP Headers)

Header Required Description Example Value
Content-Type Yes Format of the transmitted data application/json
X-Request-ID Yes End-to-end request ID for login session tracing req-auth-log-44bb

Request Body Specification (Request Body)

Parameter Type Required Description Example Value
username String Yes Unique user login (their email address) user@somedomain.kz
password String Yes Raw plaintext password for hash verification MySecretPassword123

Request JSON Example (Payload):

{
  "username": "user@somedomain.kz",
  "password": "MySecretPassword123"
}

Success Response Specification (Response Body)

HTTP 200 OK

Returned upon successful match of credentials.

{
  "status": "success",
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c3ItODgyMiIsImhvbWVfZ3JvdXBfaWQiOiJncm91cC03NzItYWxwaGEiLCJhY2NvdW50X3R5cCI6IkhPTUUiLCJleHAiOjE3ODMzMDk2MDB9.signature...",
  "expires_in": 3600
}

Anatomical Structure of Decoded JWT Payload (Claims):

When the transactional backend or a third-party AI microservice decodes the token, they can view the following standardized JSON dataset without making any database queries:

{
  "sub": "usr-8822-fa41",
  "home_group_id": "group-772-alpha",
  "account_type": "HOME",
  "iss": "auth-service",
  "iat": 1783306000,
  "exp": 1783309600
}

Метод предназначен для аутентификации пользователя в системе по паре логин/пароль.

В рамках новой архитектуры этот метод выполняет роль транслятора контекста безопасности (Security Context Provider):

  1. Генерация токена сессии: Проверяет хэш пароля в СУБД и генерирует криптографически подписанный Access Token (JWT) [2026-07-02].
  2. Внедрение JWT Claims: Содержит внутри Payload токена параметры home_group_id, account_type и user_id. Это избавляет основные транзакционные микросервисы (Cook, Consume, Waste) от необходимости делать лишние JOIN-запросы в базу данных пользователей при каждом списании продуктов, так как шлюз FastAPI вычитывает контекст группы прямо из расшифрованного токена.

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

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

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

Заголовок Обязательный Описание Пример значения
Content-Type Да Формат передаваемых данных application/json
X-Request-ID Да Сквозной ID запроса для трассировки сессии авторизации req-auth-log-44bb

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

Параметр Тип Обязательный Описание Пример значения
username String Да Уникальный логин пользователя (его email-адрес) user@somedomain.kz
password String Да Сырой текстовый пароль для сверки хэша MySecretPassword123

Пример JSON-запроса (Payload):

{
  "username": "user@somedomain.kz",
  "password": "MySecretPassword123"
}

Спецификация успешного ответа (Response Body)

HTTP 200 OK

Возвращается при успешном совпадении учетных данных.

{
  "status": "success",
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c3ItODgyMiIsImhvbWVfZ3JvdXBfaWQiOiJncm91cC03NzItYWxwaGEiLCJhY2NvdW50X3R5cCI6IkhPTUUiLCJleHAiOjE3ODMzMDk2MDB9.signature...",
  "expires_in": 3600
}

Анатомическая структура декодированного JWT Payload (Claims):

Когда транзакционный бэкенд или сторонний ИИ-микросервис расшифровывают токен, они без обращения к БД видят следующий стандартизированный JSON-датасет:

{
  "sub": "usr-8822-fa41",
  "home_group_id": "group-772-alpha",
  "account_type": "HOME",
  "iss": "auth-service",
  "iat": 1783306000,
  "exp": 1783309600
}

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

The diagram illustrates the authentication logic. The Authorization service verifies the password hash in PostgreSQL, extracts the space assignment parameters, and generates a JWT token containing embedded JWT Claims.

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/login (email, password)
    activate Nginx
    Nginx->>GW: Step 2: POST /backend-api/v1/auth/login
    activate GW
    GW->>Auth: Step 3: gRPC: LoginUser(LoginRequest)
    activate Auth
    
    Auth->>DB: Step 4: SQL SELECT id, password_hash FROM users...
    activate DB
    DB-->>Auth: Step 5: Password hash returned
    deactivate DB
    
    note over Auth: Step 5 (continued):<br/>Crypto-validation of password
    note over Auth: Step 6: TokenPair Generation<br/>with Claims injection (home_group_id, account_type)
    
    Auth->>DB: Step 7: SQL INSERT INTO user_sessions...
    activate DB
    DB-->>Auth: Session record confirmed
    deactivate DB
    
    Auth-->>GW: Step 8: gRPC: LoginResponse
    deactivate Auth
    GW-->>App: Step 9: HTTP 200 OK (access, refresh)
    deactivate GW
    deactivate Nginx
    
    note over App: Step 10: Internal method<br/>SecureStorage.write(...)

User Authentication Process (Login) with Enriched JWT Claims

На диаграмме представлена логика аутентификации. Сервис Authorization сверяет хэш пароля в PostgreSQL, извлекает параметры привязки к пространству и генерирует JWT-токен, содержащий зашитые JWT Claims.

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/login (email, password)
    activate Nginx
    Nginx->>GW: Шаг 2: POST /backend-api/v1/auth/login
    activate GW
    GW->>Auth: Шаг 3: gRPC: LoginUser(LoginRequest)
    activate Auth
    
    Auth->>DB: Шаг 4: SQL SELECT id, password_hash FROM users...
    activate DB
    DB-->>Auth: Шаг 5: Возврат хэша пароля
    deactivate DB
    
    note over Auth: Шаг 5 (продолжение):<br/>Крипто-валидация пароля
    note over Auth: Шаг 6: Генерация TokenPair<br/>с инъекцией Claims (home_group_id, account_type)
    
    Auth->>DB: Шаг 7: SQL INSERT INTO user_sessions...
    activate DB
    DB-->>Auth: Подтверждение записи сессии
    deactivate DB
    
    Auth-->>GW: Шаг 8: gRPC: LoginResponse
    deactivate Auth
    GW-->>App: Шаг 9: HTTP 200 OK (access, refresh)
    deactivate GW
    deactivate Nginx
    
    note over App: Шаг 10: Внутренний метод<br/>SecureStorage.write(...)

Процесс авторизации пользователя (Login) с обогащенными JWT Claims

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

Step Action Parameters / Requests / DTO Errors (Exceptions / Statuses)
Step 1 (App -> Nginx) The client sends user credentials to the authentication endpoint. HTTP POST /api/v1/auth/login
Payload (UserAuthRequestDTO):
{ "email": "user@example.com", "password": "secure_password" }
HTTP 400 Bad Request (invalid email format)
HTTP 429 Too Many Requests (Rate Limit exceeded)
Step 2 (Nginx -> Gateway) The proxy server performs basic routing of the request to the API gateway. HTTP POST /backend-api/v1/auth/login
Headers:
X-Request-ID: "trace-auth-lifecycle-uuid"
No business errors
Step 3 (Gateway -> Auth) The API gateway forwards the request into the internal network via a remote procedure call. Protocol: gRPC
Method: LoginUser(LoginRequest)
Parameters: email, password
gRPC Status: INVALID_ARGUMENT (malformed or missing payload parameters)
Step 4 (Auth -> DB_Auth) The service queries PostgreSQL to check user existence and fetch credentials for verification. SQL Query:
SELECT id, password_hash FROM users WHERE email = 'user@example.com' LIMIT 1;
No business errors
Step 5 (DB_Auth -> Auth) The database returns the search result to validate the hash within the service memory. DBMS Dataset (RecordSet): id (UUID) and password_hash string (Bcrypt/Argon2). gRPC Status: NOT_FOUND (user does not exist in the system)
Step 5 Continued (Auth -> Auth) Internal verification matching the entered plaintext password against the hash from the database. Cryptographic validation (comparison of salt and hash in the service memory). gRPC Status: UNAUTHENTICATED (invalid password provided)
Step 6 (Auth -> Auth) The service generates a token pair, injecting business user context into the Access Token to optimize cross-service requests. Internal method: GenerateTokenPair(user_id).
JWT Claims Payload:
{ "user_id": "uuid", "home_group_id": "uuid", "account_type": "premium" }
No business errors
Step 7 (Auth -> DB_Auth) The service persists the newly created session (or Refresh token) in the database. SQL Query:
INSERT INTO user_sessions (user_id, refresh_token_hash, expires_at) VALUES ('user-uuid', '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 back to the API gateway. Protocol: gRPC
Response: LoginResponse
Payload: access_token, refresh_token
No business errors
Step 9 (Gateway -> App) The gateway relays the successful HTTP response containing tokens through Nginx back to the client device. HTTP Status: 200 OK
Payload:
{ "access": "eyJhbGci...", "refresh": "def456..." }
No business errors
Step 10 (App -> App) The mobile app securely and persistently saves the tokens on the user’s device. 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/login
Payload (UserAuthRequestDTO):
{ "email": "user@example.com", "password": "secure_password" }
HTTP 400 Bad Request (некорректный формат email)
HTTP 429 Too Many Requests (превышен лимит Rate Limit запросов)
Шаг 2 (Nginx -> Gateway) Прокси-сервер выполняет базовую маршрутизацию запроса на шлюз. HTTP POST /backend-api/v1/auth/login
Headers:
X-Request-ID: "trace-auth-lifecycle-uuid"
Бизнес-ошибки отсутствуют
Шаг 3 (Gateway -> Auth) API-шлюз транслирует запрос во внутреннюю сеть через удаленный вызов процедур. Протокол: gRPC
Метод: LoginUser(LoginRequest)
Параметры: email, password
gRPC Status: INVALID_ARGUMENT (переданы пустые или некорректные параметры тела запроса)
Шаг 4 (Auth -> DB_Auth) Сервис запрашивает из PostgreSQL данные для проверки существования пользователя и сверки пароля. SQL-запрос:
SELECT id, password_hash FROM users WHERE email = 'user@example.com' LIMIT 1;
Бизнес-ошибки отсутствуют
Шаг 5 (DB_Auth -> Auth) База данных возвращает результат поиска для валидации хэша в памяти сервиса. Набор данных СУБД (RecordSet): id (UUID) и строка password_hash (Bcrypt/Argon2). gRPC Status: NOT_FOUND (пользователь с таким email не зарегистрирован в системе)
Шаг 5 (продолжение) (Auth -> Auth) Внутренняя проверка соответствия введенного пароля и хэша из БД. Криптографическая валидация (сравнение соли и хэша в памяти сервиса). gRPC Status: UNAUTHENTICATED (неверный пароль)
Шаг 6 (Auth -> Auth) Сервис генерирует пару токенов, внедряя в Access Token бизнес-контекст пользователя для оптимизации межсервисных запросов. Внутренний метод: GenerateTokenPair(user_id).
JWT Claims Payload:
{ "user_id": "uuid", "home_group_id": "uuid", "account_type": "premium" }
Бизнес-ошибки отсутствуют
Шаг 7 (Auth -> DB_Auth) Сервис сохраняет созданную сессию (или Refresh-токен) в базу данных. SQL-запрос:
INSERT INTO user_sessions (user_id, refresh_token_hash, expires_at) VALUES ('user-uuid', 'hash...', '2026-08-27');
Бизнес-ошибки отсутствуют
Подтверждение (DB_Auth -> Auth) База данных подтверждает успешную фиксацию строки сессии. Ответ СУБД: Статус INSERT 0 1 (успешная запись 1 строки). Бизнес-ошибки отсутствуют
Шаг 8 (Auth -> Gateway) Сервис возвращает структуру с токенами обратно на API-шлюз. Протокол: gRPC
Ответ: LoginResponse
Payload: access_token, refresh_token
Бизнес-ошибки отсутствуют
Шаг 9 (Gateway -> App) Шлюз транслирует успешный HTTP-ответ с токенами через Nginx на устройство клиента. HTTP Статус 200 OK
Payload:
{ "access": "eyJhbGci...", "refresh": "def456..." }
Бизнес-ошибки отсутствуют
Шаг 10 (App -> App) Мобильное приложение изолированно и персистентно сохраняет токены на устройстве. Внутренний метод: SecureStorage.write(...)
Запись в iOS Keychain или Android Keystore.
Бизнес-ошибки отсутствуют

Спецификация токена / JWT Claims Specification

  • sub (Subject) — the unique user_id of the operation initiator, used for audit logging.
  • home_group_id — the UUID/string identifier of the target household or office smart-refrigerator. All transactional SQL queries are filtered by this field using WHERE home_group_id = $1.
  • account_type — the environment scope flag (HOME or OFFICE), which controls the global configuration and feature flags of the digital refrigerator.
  • exp (Expiration Time) — the token lifespan (3600 seconds / 1 hour), after which the App is required to silently trigger the token rotation session.
  • sub (Subject) — уникальный user_id автора операции для логирования действий.
  • home_group_id — UUID/строковый идентификатор целевого холодильника семьи или офиса. По нему фильтруются все SQL-запросы WHERE home_group_id = $1.
  • account_type — флаг контура (HOME или OFFICE), управляющий настройками “цифрового холодильника”.
  • exp (Expiration Time) — время жизни токена (3600 секунд / 1 час), по истечении которого App обязан запустить фоновое обновление сессии.

Protobuf Контракт: LoginUser

Данный gRPC-контракт описывает процедуру аутентификации пользователя в системе.

syntax = "proto3";

package auth.v1;

option go_package = "auth/v1;authv1";

// Сервис управления сессиями и авторизацией
service AuthService {
  // Аутентификация пользователя по паре логин/пароль (Login)
  rpc LoginUser (LoginRequest) returns (LoginResponse);
}

// Запрос на аутентификацию (Шаг 3 диаграммы)
message LoginRequest {
  // Уникальный логин пользователя (его email-адрес)
  string email = 1;
  
  // Сырой текстовый пароль для сверки хэша
  string password = 2;
}

// Ответ с парой токенов доступа (Шаг 8 диаграммы)
message LoginResponse {
  // Криптографически подписанный токен доступа (содержит JWT Claims)
  string access_token = 1;
  
  // Токен для продления сессии
  string refresh_token = 2;
  
  // Время жизни access-токена в секундах (например, 3600)
  int32 expires_in = 3;
}