Add configuration files and update project documentation
- Introduced .editorconfig for consistent coding styles across the project. - Added .golangci.yml for Go linting configuration. - Updated AGENTS.md to clarify project structure and components. - Enhanced CONTRIBUTING.md with Makefile usage for common tasks. - Updated Dockerfiles to use Go 1.24 and improved build instructions. - Refined README.md and deployment documentation for clarity. - Added testing documentation in testing.md for backend and frontend tests. - Introduced Makefile for streamlined development commands and tasks.
This commit is contained in:
103
docs/api.md
103
docs/api.md
@@ -1,58 +1,77 @@
|
||||
# HTTP API
|
||||
|
||||
API доступно по префиксу `/map/api/`. Для запросов, требующих авторизации, используется cookie `session` (устанавливается при логине).
|
||||
The API is available under the `/map/api/` prefix. Requests requiring authentication use a `session` cookie (set on login).
|
||||
|
||||
## Авторизация
|
||||
## Authentication
|
||||
|
||||
- **POST /map/api/login** — вход. Тело: `{"user":"...","pass":"..."}`. При успехе возвращается JSON с данными пользователя и выставляется cookie сессии. При первом запуске возможен bootstrap: логин `admin` и пароль из `HNHMAP_BOOTSTRAP_PASSWORD` создают первого админа. Для пользователей, созданных через OAuth (без пароля), возвращается 401 с `{"error":"Use OAuth to sign in"}`.
|
||||
- **GET /map/api/me** — текущий пользователь (по сессии). Ответ: `username`, `auths`, при необходимости `tokens`, `prefix`.
|
||||
- **POST /map/api/logout** — выход (инвалидация сессии).
|
||||
- **GET /map/api/setup** — проверка, нужна ли первичная настройка. Ответ: `{"setupRequired": true|false}`.
|
||||
- **POST /map/api/login** — sign in. Body: `{"user":"...","pass":"..."}`. On success returns JSON with user data and sets a session cookie. On first run, bootstrap is available: logging in as `admin` with the password from `HNHMAP_BOOTSTRAP_PASSWORD` creates the first admin user. For users created via OAuth (no password), returns 401 with `{"error":"Use OAuth to sign in"}`.
|
||||
- **GET /map/api/me** — current user (by session). Response: `username`, `auths`, and optionally `tokens`, `prefix`.
|
||||
- **POST /map/api/logout** — sign out (invalidates the session).
|
||||
- **GET /map/api/setup** — check if initial setup is needed. Response: `{"setupRequired": true|false}`.
|
||||
|
||||
### OAuth
|
||||
|
||||
- **GET /map/api/oauth/providers** — список настроенных OAuth-провайдеров. Ответ: `["google", ...]`.
|
||||
- **GET /map/api/oauth/{provider}/login** — редирект на страницу авторизации провайдера. Query: `redirect` — путь для редиректа после успешного входа (например `/profile`).
|
||||
- **GET /map/api/oauth/{provider}/callback** — callback от провайдера (вызывается автоматически). Обменивает `code` на токены, создаёт или находит пользователя, создаёт сессию и редиректит на `/profile` или `redirect` из state.
|
||||
- **GET /map/api/oauth/providers** — list of configured OAuth providers. Response: `["google", ...]`.
|
||||
- **GET /map/api/oauth/{provider}/login** — redirect to the provider's authorization page. Query: `redirect` — path to redirect to after successful login (e.g. `/profile`).
|
||||
- **GET /map/api/oauth/{provider}/callback** — callback from the provider (called automatically). Exchanges the `code` for tokens, creates or finds the user, creates a session, and redirects to `/profile` or the `redirect` from state.
|
||||
|
||||
## Кабинет
|
||||
## User account
|
||||
|
||||
- **POST /map/api/me/tokens** — сгенерировать новый токен загрузки (требуется право `upload`). Ответ: `{"tokens": ["...", ...]}`.
|
||||
- **POST /map/api/me/password** — сменить пароль. Тело: `{"pass":"..."}`.
|
||||
- **POST /map/api/me/tokens** — generate a new upload token (requires `upload` permission). Response: `{"tokens": ["...", ...]}`.
|
||||
- **POST /map/api/me/password** — change password. Body: `{"pass":"..."}`.
|
||||
|
||||
## Карта и данные
|
||||
## Map data
|
||||
|
||||
- **GET /map/api/config** — конфиг для клиента (title, auths). Требуется сессия.
|
||||
- **GET /map/api/v1/characters** — список персонажей на карте (требуется право `map` и при необходимости `markers`).
|
||||
- **GET /map/api/v1/markers** — маркеры (требуется право `map` и при необходимости `markers`).
|
||||
- **GET /map/api/maps** — список карт (с учётом прав и скрытых карт).
|
||||
- **GET /map/api/config** — client configuration (title, auths). Requires a session.
|
||||
- **GET /map/api/v1/characters** — list of characters on the map (requires `map` permission; `markers` permission needed to see data).
|
||||
- **GET /map/api/v1/markers** — markers (requires `map` permission; `markers` permission needed to see data).
|
||||
- **GET /map/api/maps** — list of maps (filtered by permissions and hidden status).
|
||||
|
||||
## Админ (все эндпоинты ниже требуют право `admin`)
|
||||
## Admin (all endpoints below require `admin` permission)
|
||||
|
||||
- **GET /map/api/admin/users** — список имён пользователей.
|
||||
- **POST /map/api/admin/users** — создать/обновить пользователя. Тело: `{"user":"...","pass":"...","auths":["admin","map",...]}`.
|
||||
- **GET /map/api/admin/users/:name** — данные пользователя.
|
||||
- **DELETE /map/api/admin/users/:name** — удалить пользователя.
|
||||
- **GET /map/api/admin/settings** — настройки (prefix, defaultHide, title).
|
||||
- **POST /map/api/admin/settings** — сохранить настройки. Тело: `{"prefix":"...","defaultHide":true|false,"title":"..."}` (поля опциональны).
|
||||
- **GET /map/api/admin/maps** — список карт для админки.
|
||||
- **POST /map/api/admin/maps/:id** — обновить карту (name, hidden, priority).
|
||||
- **POST /map/api/admin/maps/:id/toggle-hidden** — переключить скрытие карты.
|
||||
- **POST /map/api/admin/wipe** — очистить гриды, маркеры, тайлы, карты в БД.
|
||||
- **POST /map/api/admin/rebuildZooms** — пересобрать зум-уровни тайлов.
|
||||
- **GET /map/api/admin/export** — скачать экспорт данных (ZIP).
|
||||
- **POST /map/api/admin/merge** — загрузить и применить merge (ZIP с гридами и маркерами).
|
||||
- **GET /map/api/admin/wipeTile** — удалить тайл. Query: `map`, `x`, `y`.
|
||||
- **GET /map/api/admin/setCoords** — сдвинуть координаты гридов. Query: `map`, `fx`, `fy`, `tx`, `ty`.
|
||||
- **GET /map/api/admin/hideMarker** — скрыть маркер. Query: `id`.
|
||||
- **GET /map/api/admin/users** — list of usernames.
|
||||
- **POST /map/api/admin/users** — create or update a user. Body: `{"user":"...","pass":"...","auths":["admin","map",...]}`.
|
||||
- **GET /map/api/admin/users/:name** — user data.
|
||||
- **DELETE /map/api/admin/users/:name** — delete a user.
|
||||
- **GET /map/api/admin/settings** — settings (prefix, defaultHide, title).
|
||||
- **POST /map/api/admin/settings** — save settings. Body: `{"prefix":"...","defaultHide":true|false,"title":"..."}` (all fields optional).
|
||||
- **GET /map/api/admin/maps** — list of maps for the admin panel.
|
||||
- **POST /map/api/admin/maps/:id** — update a map (name, hidden, priority).
|
||||
- **POST /map/api/admin/maps/:id/toggle-hidden** — toggle map visibility.
|
||||
- **POST /map/api/admin/wipe** — wipe grids, markers, tiles, and maps from the database.
|
||||
- **POST /map/api/admin/rebuildZooms** — rebuild tile zoom levels.
|
||||
- **GET /map/api/admin/export** — download data export (ZIP).
|
||||
- **POST /map/api/admin/merge** — upload and apply a merge (ZIP with grids and markers).
|
||||
- **GET /map/api/admin/wipeTile** — delete a tile. Query: `map`, `x`, `y`.
|
||||
- **GET /map/api/admin/setCoords** — shift grid coordinates. Query: `map`, `fx`, `fy`, `tx`, `ty`.
|
||||
- **GET /map/api/admin/hideMarker** — hide a marker. Query: `id`.
|
||||
|
||||
## Коды ответов
|
||||
## Game client
|
||||
|
||||
- **200** — успех.
|
||||
- **400** — неверный запрос (метод, тело, параметры).
|
||||
- **401** — не авторизован (нет или недействительная сессия).
|
||||
- **403** — нет прав.
|
||||
- **404** — не найдено.
|
||||
- **500** — внутренняя ошибка.
|
||||
The game client (e.g. Purus Pasta) communicates via `/client/{token}/...` endpoints using token-based authentication.
|
||||
|
||||
Формат ошибок — текст в теле ответа или стандартные HTTP-статусы без тела.
|
||||
- **GET /client/{token}/checkVersion** — check client protocol version. Query: `version`. Returns 200 if matching, 400 otherwise.
|
||||
- **GET /client/{token}/locate** — get grid coordinates. Query: `gridID`. Response: `mapid;x;y`.
|
||||
- **POST /client/{token}/gridUpdate** — report visible grids and receive upload requests.
|
||||
- **POST /client/{token}/gridUpload** — upload a tile image (multipart).
|
||||
- **POST /client/{token}/positionUpdate** — update character positions.
|
||||
- **POST /client/{token}/markerUpdate** — upload markers.
|
||||
|
||||
## SSE (Server-Sent Events)
|
||||
|
||||
- **GET /map/updates** — real-time tile and merge updates. Requires a session with `map` permission. Sends `data:` messages with tile cache arrays and `event: merge` messages for map merges.
|
||||
|
||||
## Tile images
|
||||
|
||||
- **GET /map/grids/{mapid}/{zoom}/{x}_{y}.png** — tile image. Requires a session with `map` permission. Returns the tile image or a transparent 1×1 PNG if the tile does not exist.
|
||||
|
||||
## Response codes
|
||||
|
||||
- **200** — success.
|
||||
- **400** — bad request (wrong method, body, or parameters).
|
||||
- **401** — unauthorized (missing or invalid session).
|
||||
- **403** — forbidden (insufficient permissions).
|
||||
- **404** — not found.
|
||||
- **500** — internal error.
|
||||
|
||||
Error format: JSON body `{"error": "message", "code": "CODE"}`.
|
||||
|
||||
Reference in New Issue
Block a user