1b48675b92a2bf0d944a7090441dd8481b87b2d5
Some checks failed
Deploy on push / deploy (push) Failing after 2m22s
### 🔄 Изменения - **SQLAlchemy KeyError** - исправление ошибки `KeyError: Reaction` при инициализации - **Исправлена ошибка SQLAlchemy**: Устранена проблема `InvalidRequestError: When initializing mapper Mapper[Shout(shout)], expression Reaction failed to locate a name (Reaction)` ### 🧪 Тестирование - **Исправление тестов** - адаптация к новой структуре моделей - **RBAC инициализация** - добавление `rbac.initialize_rbac()` в `conftest.py` - **Создан тест для getSession**: Добавлен комплексный тест `test_getSession_cookies.py` с проверкой всех сценариев - **Покрытие edge cases**: Тесты проверяют работу с валидными/невалидными токенами, отсутствующими пользователями - **Мокирование зависимостей**: Использование unittest.mock для изоляции тестируемого кода ### 🔧 Рефакторинг - **Упрощена архитектура**: Убраны сложные конструкции с отложенными импортами, заменены на чистую архитектуру - **Перемещение моделей** - `Author` и связанные модели перенесены в `orm/author.py`: Вынесены базовые модели пользователей (`Author`, `AuthorFollower`, `AuthorBookmark`, `AuthorRating`) из `orm.author` в отдельный модуль - **Устранены циклические импорты**: Разорван цикл между `auth.core` → `orm.community` → `orm.author` через реструктуризацию архитектуры - **Создан модуль `utils/password.py`**: Класс `Password` вынесен в utils для избежания циклических зависимостей - **Оптимизированы импорты моделей**: Убран прямой импорт `Shout` из `orm/community.py`, заменен на строковые ссылки ### 🔧 Авторизация с cookies - **getSession теперь работает с cookies**: Мутация `getSession` теперь может получать токен из httpOnly cookies даже без заголовка Authorization - **Убрано требование авторизации**: `getSession` больше не требует декоратор `@login_required`, работает автономно - **Поддержка dual-авторизации**: Токен может быть получен как из заголовка Authorization, так и из cookie `session_token` - **Автоматическая установка cookies**: Middleware автоматически устанавливает httpOnly cookies при успешном `getSession` - **Обновлена GraphQL схема**: `SessionInfo` теперь содержит поля `success`, `error` и опциональные `token`, `author` - **Единообразная обработка токенов**: Все модули теперь используют централизованные функции для работы с токенами - **Улучшена обработка ошибок**: Добавлена детальная валидация токенов и пользователей в `getSession` - **Логирование операций**: Добавлены подробные логи для отслеживания процесса авторизации ### 📝 Документация - **Обновлена схема GraphQL**: `SessionInfo` тип теперь соответствует новому формату ответа - Обновлена документация RBAC - Обновлена документация авторизации с cookies
Discours.io Core
🚀 Modern community platform with GraphQL API, RBAC system, and comprehensive testing infrastructure.
🎯 Features
- 🔐 Authentication: JWT + OAuth (Google, GitHub, Facebook)
- 🏘️ Communities: Full community management with roles and permissions
- 🔒 RBAC System: Role-based access control with inheritance
- 🌐 GraphQL API: Modern API with comprehensive schema
- 🧪 Testing: Complete test suite with E2E automation
- 🚀 CI/CD: Automated testing and deployment pipeline
🚀 Quick Start
Prerequisites
- Python 3.11+
- Node.js 18+
- Redis
- uv (Python package manager)
Installation
# Clone repository
git clone <repository-url>
cd core
# Install Python dependencies
uv sync --group dev
# Install Node.js dependencies
cd panel
npm ci
cd ..
# Setup environment
cp .env.example .env
# Edit .env with your configuration
Development
# Start backend server
uv run python dev.py
# Start frontend (in another terminal)
cd panel
npm run dev
🧪 Testing
Run All Tests
uv run pytest tests/ -v
Test Categories
Run only unit tests
uv run pytest tests/ -m "not e2e" -v
Run only integration tests
uv run pytest tests/ -m "integration" -v
Run only e2e tests
uv run pytest tests/ -m "e2e" -v
Run browser tests
uv run pytest tests/ -m "browser" -v
Run API tests
uv run pytest tests/ -m "api" -v
Skip slow tests
uv run pytest tests/ -m "not slow" -v
Run tests with specific markers
uv run pytest tests/ -m "db and not slow" -v
Test Markers
unit- Unit tests (fast)integration- Integration testse2e- End-to-end testsbrowser- Browser automation testsapi- API-based testsdb- Database testsredis- Redis testsauth- Authentication testsslow- Slow tests (can be skipped)
E2E Testing
E2E tests automatically start backend and frontend servers:
- Backend:
http://localhost:8000 - Frontend:
http://localhost:3000
🚀 CI/CD Pipeline
GitHub Actions Workflow
The project includes a comprehensive CI/CD pipeline that:
-
🧪 Testing Phase
- Matrix testing across Python 3.11, 3.12, 3.13
- Unit, integration, and E2E tests
- Code coverage reporting
- Linting and type checking
-
🚀 Deployment Phase
- Staging: Automatic deployment on
devbranch - Production: Automatic deployment on
mainbranch - Dokku integration for seamless deployments
- Staging: Automatic deployment on
Local CI Testing
Test the CI pipeline locally:
# Run local CI simulation
chmod +x scripts/test-ci-local.sh
./scripts/test-ci-local.sh
CI Server Management
The ./ci-server.py script manages servers for CI:
# Start servers in CI mode
CI_MODE=true python3 ./ci-server.py
📊 Project Structure
core/
├── auth/ # Authentication system
├── orm/ # Database models
├── resolvers/ # GraphQL resolvers
├── services/ # Business logic
├── panel/ # Frontend (SolidJS)
├── tests/ # Test suite
├── scripts/ # CI/CD scripts
└── docs/ # Documentation
🔧 Configuration
Environment Variables
DATABASE_URL- Database connection stringREDIS_URL- Redis connection stringJWT_SECRET- JWT signing secretOAUTH_*- OAuth provider credentials
Database
- Development: SQLite (default)
- Production: PostgreSQL
- Testing: In-memory SQLite
📚 Documentation
🤝 Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
Development Workflow
# Create feature branch
git checkout -b feature/your-feature
# Make changes and test
uv run pytest tests/ -v
# Commit changes
git commit -m "feat: add your feature"
# Push and create PR
git push origin feature/your-feature
📈 Status
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
Languages
Python
74.6%
TypeScript
19.2%
CSS
6.1%