Files
chat/docs/EMERGENCY_API_AUTH.md
Andrey K. Choi 3050e084fa
All checks were successful
continuous-integration/drone/push Build is passing
main functions commit
2025-10-19 19:50:00 +09:00

233 lines
6.5 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 🔐 Emergency Service API - Руководство по авторизации
## Обзор
Все эндпоинты Emergency Service API требуют авторизацию через JWT Bearer токен.
## 🔑 Получение токена авторизации
### 1. Регистрация пользователя (если нет аккаунта)
```bash
curl -X POST "http://localhost:8001/api/v1/auth/register" \
-H "Content-Type: application/json" \
-d '{
"username": "testuser",
"email": "test@example.com",
"password": "testpass",
"full_name": "Test User",
"phone": "+1234567890"
}'
```
### 2. Получение JWT токена
```bash
curl -X POST "http://localhost:8001/api/v1/auth/login" \
-H "Content-Type: application/json" \
-d '{
"username": "testuser",
"password": "testpass"
}'
```
**Ответ:**
```json
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"token_type": "bearer",
"expires_in": 86400
}
```
## 🚨 Использование API Emergency Service
### Авторизация через Bearer токен
Все запросы должны включать заголовок:
```
Authorization: Bearer <your_jwt_token>
```
### Примеры использования
#### 📊 Получение статистики
```bash
TOKEN="your_jwt_token_here"
curl -X GET "http://localhost:8002/api/v1/stats" \
-H "Authorization: Bearer $TOKEN"
```
#### 🆘 Создание экстренного события
```bash
TOKEN="your_jwt_token_here"
curl -X POST "http://localhost:8002/api/v1/emergency/events" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"latitude": 55.7558,
"longitude": 37.6176,
"alert_type": "general",
"message": "Нужна помощь!",
"address": "Красная площадь, Москва",
"contact_emergency_services": true,
"notify_emergency_contacts": true
}'
```
#### 🔍 Получение детальной информации о событии
```bash
TOKEN="your_jwt_token_here"
EVENT_ID="123"
curl -X GET "http://localhost:8002/api/v1/emergency/events/$EVENT_ID" \
-H "Authorization: Bearer $TOKEN"
```
#### 💬 Ответ на событие
```bash
TOKEN="your_jwt_token_here"
EVENT_ID="123"
curl -X POST "http://localhost:8002/api/v1/emergency/events/$EVENT_ID/respond" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"response_type": "help_on_way",
"message": "Еду к вам, буду через 10 минут",
"eta_minutes": 10
}'
```
#### 🏁 Завершение события
```bash
TOKEN="your_jwt_token_here"
EVENT_ID="123"
curl -X PUT "http://localhost:8002/api/v1/emergency/events/$EVENT_ID/resolve" \
-H "Authorization: Bearer $TOKEN"
```
## 🔧 Автоматизация авторизации
### Bash скрипт для получения токена
```bash
#!/bin/bash
# Функция для получения токена
get_auth_token() {
local username="$1"
local password="$2"
TOKEN=$(curl -s -X POST "http://localhost:8001/api/v1/auth/login" \
-H "Content-Type: application/json" \
-d "{\"username\": \"$username\", \"password\": \"$password\"}" | \
jq -r '.access_token')
if [ "$TOKEN" = "null" ] || [ -z "$TOKEN" ]; then
echo "❌ Failed to authenticate"
exit 1
fi
echo "$TOKEN"
}
# Использование
TOKEN=$(get_auth_token "testuser" "testpass")
echo "✅ Token obtained: ${TOKEN:0:20}..."
# Теперь можно использовать TOKEN в запросах
curl -X GET "http://localhost:8002/api/v1/stats" \
-H "Authorization: Bearer $TOKEN"
```
### Python пример
```python
import requests
import json
def get_auth_token(username, password):
"""Получение JWT токена"""
auth_data = {
"username": username,
"password": password
}
response = requests.post(
"http://localhost:8001/api/v1/auth/login",
json=auth_data
)
if response.status_code == 200:
return response.json()["access_token"]
else:
raise Exception(f"Authentication failed: {response.status_code}")
def emergency_api_call(token, endpoint, method="GET", data=None):
"""Универсальная функция для вызова Emergency API"""
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
url = f"http://localhost:8002{endpoint}"
if method == "GET":
response = requests.get(url, headers=headers)
elif method == "POST":
response = requests.post(url, headers=headers, json=data)
elif method == "PUT":
response = requests.put(url, headers=headers, json=data)
return response.json()
# Пример использования
if __name__ == "__main__":
# Получаем токен
token = get_auth_token("testuser", "testpass")
print("✅ Token obtained")
# Получаем статистику
stats = emergency_api_call(token, "/api/v1/stats")
print("📊 Stats:", stats)
# Создаем событие
event_data = {
"latitude": 55.7558,
"longitude": 37.6176,
"alert_type": "general",
"message": "Test emergency",
"address": "Test Address"
}
event = emergency_api_call(token, "/api/v1/emergency/events", "POST", event_data)
print("🆘 Event created:", event["id"])
```
## 🔒 Безопасность
### Важные моменты:
1. **Храните токены безопасно** - не передавайте их в URL или логах
2. **Токены имеют срок действия** - обновляйте их регулярно
3. **Используйте HTTPS** в продакшн среде
4. **Не делитесь токенами** - каждый пользователь должен иметь свой токен
### Обработка ошибок авторизации:
```json
// 401 Unauthorized
{
"detail": "Could not validate credentials"
}
// 403 Forbidden
{
"detail": "Not authenticated"
}
```
## 📚 Документация API
После запуска сервиса документация доступна по адресу:
- **Swagger UI**: http://localhost:8002/docs
- **ReDoc**: http://localhost:8002/redoc
- **OpenAPI JSON**: http://localhost:8002/openapi.json
В Swagger UI теперь есть кнопка **🔓 Authorize** для ввода Bearer токена!