A real-time chat application built with Python, Django, Redis, and WebSockets. This application allows users to send and receive messages in real-time with proper authentication, email verification, and message throttling.
- User Authentication: Registration, login, and email verification
- Real-time Messaging: WebSocket-based real-time chat functionality
- Redis Integration: Fast message storage and retrieval using Redis
- PostgreSQL Database: User management and conversation metadata
- Email Verification: MailHog integration for email verification
- API Throttling: Rate limiting for message sending (10 messages per minute)
- Comprehensive Logging: All API calls are logged with detailed information
- Docker Support: Complete containerization with Docker Compose
- Testing: Unit tests and integration tests included
- CI/CD: GitHub Actions workflow for automated testing
- Backend: Python 3.11, Django 4.2.7
- Database: PostgreSQL 15
- Cache/Message Store: Redis 7
- Real-time Communication: Django Channels with WebSockets
- Email Service: MailHog (for development)
- Containerization: Docker & Docker Compose
- API: Django REST Framework
- Authentication: Token-based authentication
chat-project/
├── apps/
│ ├── accounts/ # User authentication and management
│ └── chat/ # Chat functionality and WebSocket consumers
├── chat_project/ # Django project settings
├── templates/ # Email templates
├── tests/ # Test files
├── .github/workflows/ # GitHub Actions CI/CD
├── docker-compose.yml # Docker services configuration
├── Dockerfile # Docker image configuration
├── requirements.txt # Python dependencies
└── README.md # This file
- Python 3.11+
- Docker and Docker Compose
- Git
-
Clone the repository
git clone <repository-url> cd chat-project
-
Create environment file
cp env.example .env
-
Start the services
docker-compose up --build
-
Run migrations
docker-compose exec web python manage.py migrate -
Create superuser (optional)
docker-compose exec web python manage.py createsuperuser -
Access the application
- API: http://localhost:8000/api/
- Admin: http://localhost:8000/admin/
- MailHog UI: http://localhost:8025/
-
Create virtual environment
python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate
-
Install dependencies
pip install -r requirements.txt
-
Set up PostgreSQL
- Install PostgreSQL
- Create database:
createdb chatdb - Update DATABASE_URL in .env file
-
Set up Redis
- Install Redis
- Start Redis server:
redis-server
-
Set up MailHog
# Download and run MailHog # Or use: go install github.com/mailhog/MailHog@latest mailhog
-
Run migrations
python manage.py migrate
-
Start the development server
python manage.py runserver
POST /api/auth/register/- User registrationPOST /api/auth/login/- User loginGET /api/auth/profile/- Get user profilePOST /api/auth/verify-email/<token>/- Email verificationPOST /api/auth/resend-verification/- Resend verification email
GET /api/chat/rooms/- List user's chat roomsPOST /api/chat/rooms/- Create new chat roomGET /api/chat/rooms/<id>/- Get chat room detailsPUT /api/chat/rooms/<id>/- Update chat roomDELETE /api/chat/rooms/<id>/- Delete chat roomGET /api/chat/rooms/<id>/messages/- Get messagesPOST /api/chat/rooms/<id>/send/- Send messagePOST /api/chat/rooms/<id>/participants/- Add participantDELETE /api/chat/rooms/<id>/participants/<user_id>/- Remove participantDELETE /api/chat/messages/<message_id>/- Delete message
ws://localhost:8000/ws/chat/<chat_room_id>/- WebSocket connection for real-time chat
curl -X POST http://localhost:8000/api/auth/register/ \
-H "Content-Type: application/json" \
-d '{
"first_name": "John",
"last_name": "Doe",
"email": "[email protected]",
"username": "johndoe",
"password": "securepassword123",
"password_confirm": "securepassword123"
}'curl -X POST http://localhost:8000/api/auth/login/ \
-H "Content-Type: application/json" \
-d '{
"email": "[email protected]",
"password": "securepassword123"
}'curl -X POST http://localhost:8000/api/chat/rooms/ \
-H "Content-Type: application/json" \
-H "Authorization: Token <your-token>" \
-d '{
"name": "My Chat Room",
"participant_emails": ["[email protected]"]
}'curl -X POST http://localhost:8000/api/chat/rooms/<room-id>/send/ \
-H "Content-Type: application/json" \
-H "Authorization: Token <your-token>" \
-d '{
"content": "Hello, World!"
}'Connect to WebSocket for real-time messaging:
const chatSocket = new WebSocket("ws://localhost:8000/ws/chat/<room-id>/");
chatSocket.onmessage = function (e) {
const data = JSON.parse(e.data);
if (data.type === "chat_message") {
// Handle incoming message
console.log("New message:", data.content);
}
};
// Send message
chatSocket.send(
JSON.stringify({
type: "chat_message",
content: "Hello from WebSocket!",
})
);
// Send typing indicator
chatSocket.send(
JSON.stringify({
type: "typing",
})
);This project uses multiple code quality tools to ensure consistent code style and catch potential issues.
- Black: Code formatter (line length: 100)
- isort: Import sorter (line length: 100)
- flake8: Python linter (max line length: 100, max complexity: 10)
- djlint: Django template linter and formatter (max line length: 100)
# Run all code quality checks
./scripts/lint.sh
# Individual checks
black --check . # Check Python formatting
isort --check . # Check import sorting
flake8 . # Check Python linting
djlint --check . # Check template formatting# Run all formatters
./scripts/format.sh
# Individual formatters
black . # Format Python code
isort . # Sort imports
djlint --reformat . # Format templatespyproject.toml: Black, isort, and djlint configuration.flake8: Flake8 linter configuration.djlintrc: Additional djlint configuration
For more information, see CODE_QUALITY.md.
This project uses updated dependencies to address security vulnerabilities:
- Django 4.2.23: Latest LTS with 20+ security fixes
- Django REST Framework 3.15.2: XSS vulnerability fixed
- Gunicorn 23.0.0: HTTP smuggling vulnerabilities fixed
- Pillow 10.3.0: Code execution vulnerabilities fixed
- Black 24.3.0: ReDoS vulnerability fixed
- regex 2025.9.18: ReDoS vulnerability fixed
Security scanning is integrated into the CI/CD pipeline using safety scan.
For detailed security information, see SECURITY_UPDATES.md.
# With Docker
docker-compose exec web python manage.py test
# Without Docker
python manage.py testpip install coverage
coverage run --source='.' manage.py test
coverage report
coverage htmlCreate a .env file with the following variables:
DEBUG=True
SECRET_KEY=your-secret-key-here
DATABASE_URL=postgresql://chatuser:chatpass@localhost:5433/chatdb
REDIS_URL=redis://localhost:6379/0
# Email settings for MailHog
EMAIL_HOST=localhost
EMAIL_PORT=1025
EMAIL_USE_TLS=False
EMAIL_USE_SSL=False
# Site settings
SITE_URL=http://localhost:8000The application uses PostgreSQL with the following default settings:
- Host: localhost
- Port: 5433 (to avoid conflicts with existing PostgreSQL)
- Database: chatdb
- User: chatuser
- Password: chatpass
Redis is used for:
- Real-time message storage
- WebSocket channel layers
- Caching
Default Redis configuration:
- Host: localhost
- Port: 6380 (to avoid conflicts with existing Redis)
- Database: 0
The application implements rate limiting:
- Anonymous users: 100 requests per hour
- Authenticated users: 1000 requests per hour
- Message sending: 10 messages per minute per user
All API calls are logged with the following information:
- Request method and path
- User information
- IP address
- User agent
- Response status and duration
- Timestamp
Logs are stored in:
logs/django.log- General application logslogs/api.log- API-specific logs
- Email verification for user registration
- Token-based authentication
- CORS protection
- SQL injection protection
- XSS protection
- CSRF protection
- Rate limiting
- Input validation
-
Set production environment variables
DEBUG=False SECRET_KEY=your-production-secret-key DATABASE_URL=postgresql://user:pass@host:port/db REDIS_URL=redis://host:port/0 ALLOWED_HOSTS=yourdomain.com,www.yourdomain.com
-
Use production email service
EMAIL_HOST=smtp.your-provider.com EMAIL_PORT=587 EMAIL_USE_TLS=True EMAIL_HOST_USER=[email protected] EMAIL_HOST_PASSWORD=your-email-password
-
Deploy with Docker
docker-compose -f docker-compose.prod.yml up -d
- Heroku: Use Heroku Postgres and Redis add-ons
- AWS: Use RDS for PostgreSQL and ElastiCache for Redis
- Google Cloud: Use Cloud SQL and Memorystore
- Azure: Use Azure Database for PostgreSQL and Azure Cache for Redis
The application includes comprehensive logging and monitoring:
- API request/response logging
- Error tracking
- Performance monitoring
- User activity logging
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Run the test suite
- Submit a pull request
This project is licensed under the MIT License.
For support and questions, please open an issue in the repository.
- Initial release
- User authentication with email verification
- Real-time chat functionality
- Redis integration
- Docker support
- Comprehensive testing
- CI/CD pipeline