GITBOOK-14: Govor.API: документация по текущему коду и диагностика 03.10.2026

This commit is contained in:
stalcke2288969
2026-10-03 06:20:45 +00:00
committed by gitbook-bot
parent 4603be9f71
commit 6c8abb23e3
27 changed files with 827 additions and 1901 deletions
+29 -118
View File
@@ -4,138 +4,49 @@ description: >-
and login, with session management and invite-based registration.
---
# AuthController
# Регистрация и вход
### Controller Description
Оба метода доступны анонимно, Content-Type: application/json.
* **Route**: `api/auth`
* **Authorize**: Allows anonymous access (`[AllowAnonymous]`).
## POST /api/auth/register
### Endpoints
```json
{
"name": "Артём",
"password": "example-password",
"inviteLink": "<код приглашения>",
"deviceInfo": "Android test device"
}
```
#### <mark style="color:$info;">Register</mark>
Имя: 4–44 символа, только кириллица и цифры, первый символ — буква. Модерация запрещает зарезервированные имена, совпадения/подстроки из конфигурации и пять одинаковых символов подряд. Пароль: минимум 8 символов. DeviceInfo необязателен в запросе, но в БД ограничен 256 символами.
* **Description**: Registers a new user using a valid invite link and opens a user session, returning an authentication token.
* **Route**: `[POST] api/auth/register`
* **HTTP Method**: `POST`
* **Request**:
* **Content-Type**: `application/json`
* **Request Body**: `RegistrationRequest` object with the following structure:
Код создаётся как Guid.ToString("N"): 32 символа без дефисов. Поиск кода — по строковому равенству. InviteLink — код, а не URL.
```json
{
"name": "string",
"password": "string",
"inviteLink": "string",
"deviceInfo": "string"
}
```
* **Responses**:
* <mark style="color:$success;">**200 OK**</mark>: Returns the authentication token upon successful registration and session creation.
Проверяется существование приглашения, срок и число участников. Проверка IsActive отсутствует, лимит участников не защищён от конкурентной регистрации.
```json
{
"refreshToken": "string",
"accessToken": "string"
}
```
* <mark style="color:$danger;">**400 Bad Request**</mark>:
* If model validation fails.
* If the user already exists: `"Registration failed: user already exists."`
* If the invite link is invalid: `"Invite link invalid."`
* If the username is invalid: `"Invalid username: <error_message>"`
* <mark style="color:$warning;">**500 Internal Server Error**</mark>: Indicates an unexpected error.
Успех 200:
```json
"An unexpected error occurred. Please try again later."
```
```json
{"refreshToken":"<token>","accessToken":"<token>"}
```
#### <mark style="color:$info;">Login</mark>
Конфликт имени — 409; ошибки валидации — 400; отсутствующее приглашение — 404. Тело сервисных ошибок — ProblemDetails с errorCode. Регистрация и открытие сессии — отдельные сохранения: ошибка открытия сессии не откатывает созданного пользователя.
* **Description**: Authenticates an existing user and opens a session, returning an authentication token.
* **Route**: `[POST] api/auth/login`
* **HTTP Method**: `POST`
* **Request**:
* **Content-Type**: `application/json`
* **Request Body**: `LoginRequest` object with the following structure:
## POST /api/auth/login
```json
{
"name": "string",
"password": "string",
"deviceInfo": "string"
}
```
* **Responses**:
* <mark style="color:$success;">**200 OK**</mark>: Returns the authentication token upon successful login and session creation.
```json
{"name":"Артём","password":"example-password","deviceInfo":"Android test device"}
```
```json
{
"refreshToken": "string",
"accessToken": "string"
}
```
* <mark style="color:$danger;">**400 Bad Request**</mark>:
* If model validation fails.
* If the user does not exist: `"Login failed: user does not exist."`
* If the username or password is incorrect: `"Login failed: username or password is incorrect."`
* <mark style="color:$warning;">**500 Internal Server Error**</mark>: Indicates an unexpected error.
Успех 200 с той же парой токенов. Пользователь не найден — 404 (UserNotRegisteredException); неверный пароль — 400 (InvalidOperationException). Это текущее поведение, а не рекомендуемая политика ошибок входа: разные ответы раскрывают существование аккаунта.
```json
"An unexpected error occurred. Please try again later."
```
## Ограничения
### Data Models
Rate limiting и блокировка перебора в Program.cs не настроены. Для публичного запуска нужны единая ошибка входа, ограничение частоты и защита административных приглашений.
#### RegistrationRequest
***
* **Description**: Model for registration request data.
* **Structure**:
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера.
```json
{
"name": "string",
"password": "string",
"inviteLink": "string",
"deviceInfo": "string"
}
```
#### LoginRequest
* **Description**: Model for login request data.
* **Structure**:
```json
{
"name": "string",
"password": "string",
"deviceInfo": "string"
}
```
#### RefreshResult
* **Description**: Model for refresh token response data.
* **Structure**:
```json
{
"refreshToken": "string",
"accessToken": "string"
}
```
### Error Handling
* **Invalid User ID**: Not applicable (handled by session service).
* **Invalid Operations**: Registration fails if the user already exists, invite link is invalid, or username is invalid, returning `400 Bad Request`.
* **Unauthorized Access**: Not applicable (endpoint is `[AllowAnonymous]`).
* **Unexpected Errors**: General exceptions are caught, logged, and returned as `500 Internal Server Error`.
### Logging
* Logs successful registration and login events with username and user ID.
* Logs session opening events with username and user ID.
* Logs warnings for specific exceptions (e.g., user already exists, invalid invite link, login failures).
* Logs errors for unexpected exceptions during registration and login.
Источник: [Govor.API/Controllers/Authentication/AuthController.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Controllers/Authentication/AuthController.cs).