This repository contains the backend code for a comprehensive Login Tracking Dashboard built using Django and Django Rest Framework. The project is developed using Test-Driven Development (TDD) methodology and provides advanced user authentication, detailed login analytics, and comprehensive dashboard functionality. This backend serves as the foundation for monitoring user login activities, tracking authentication patterns, and providing valuable insights through a powerful REST API.
The primary focus of this project is the Login Tracking Dashboard, which offers real-time analytics and statistics about user login behavior, trends, and patterns. The system includes secure authentication mechanisms, user management, and role-based dashboard access to ensure data security and proper access control.
This backend project is designed to pair with a React frontend application built with TypeScript, Vite, and Vitest.
- Frontend Repository: tdd_react_typescript_vite_vitest_project
The frontend and backend communicate over a shared Docker network (tdd-network). See the Frontend Integration section for details.
This project was built using Test-Driven Development (TDD), a software development approach where tests are written before the actual implementation code. The TDD process follows a simple cycle:
- Write a failing test that defines the desired functionality
- Write the minimum code necessary to make the test pass
- Refactor the code to improve design while keeping tests passing
- High Code Quality: Comprehensive test coverage ensures reliable functionality
- Better Design: Tests drive clean, modular architecture
- Regression Prevention: Changes can be made confidently without breaking existing features
- Documentation: Tests serve as living documentation of system behavior
The TDD approach was particularly valuable for building the Login Tracking Dashboard, ensuring that all analytics features work correctly and can be extended safely.
- Real-time Login Statistics: Track total logins, login frequency, success and failed attempts
- Weekly/Monthly Analytics: Detailed breakdown of login patterns by week and month
- Login Trends: Visual charts showing login trends over time including success rates
- User-specific Dashboard: Individual users can view their own login activity including success/failure rates
- Admin Dashboard: Comprehensive admin interface with user management capabilities
- Login Comparison: Compare login activities across different time periods
- Distribution Analysis: Analyze login distribution by time of day, day of week, etc.
- Login Attempt Analytics: Monitor login success and failure rates, including attempt patterns
- Custom Date Range Filters: Filter dashboard data by specific date ranges for flexible analysis
- Combined Chart Data: Admin can view combined login trends/comparison/distribution data for multiple users using
user_ids[]parameter - Role-based Chart Filtering: Filter charts and dashboard data by user role (
admin/regular) - Batch User Statistics: Admin can retrieve statistics for multiple users with optional active status filtering
- Custom User Model: Extends Django's
AbstractBaseUserwith built-in login statistics tracking (login_count,weekly_logins,monthly_logins), email verification system (email_verified, verification tokens), password reset tokens, and automatic profile image cleanup on account deletion - User Registration & Authentication: Secure user registration and login system with email verification requirement
- Profile Management: Users can manage their profiles, upload profile images (JPG/JPEG/PNG only, max 2MB), and view personal statistics
- Role-based Access: Different dashboard views for regular users and administrators
- User Filtering: List users with role-based filtering (
admin/regular) andmeparameter - Pagination: Customizable pagination for user listings and login activity
| Feature | Regular User | Admin User |
|---|---|---|
| View own login statistics | β | β |
| View own login activity | β | β |
| Access personal dashboard | β | β |
| Edit own profile | β | β |
| View all users' statistics | β | β |
| View all login activities | β | β |
| Access admin dashboard | β | β |
| View user-specific analytics | β | β |
| View other user profiles | β | β |
| View own login patterns (success/failed attempts) | β | β |
| Monitor system-wide security events | β | β |
| Access comprehensive charts | Limited | Full access |
| View combined chart data (multiple users) | β | β |
| Filter data by user role | β | β |
| Access batch user statistics | β | β |
| View other users' login activity | β | β |
- JWT Token Authentication: Secure token-based authentication using DRF SimpleJWT
- JWT Token Blacklisting: Logout endpoint blacklists refresh tokens, preventing reuse
- Email-based Login: Users can log in using their email address instead of username (via custom
EmailBackendauthentication backend) - Custom JWT Exception Handler: Standardized, user-friendly error messages for invalid or expired tokens
- Email Verification: Token-based email verification system for account activation (24-hour token expiration)
- Welcome Email: Automated welcome email sent after successful email verification
- Password Reset: Secure password reset functionality with token validation (1-hour token expiration)
- RSA Encrypted Login Credentials: Login passwords are encrypted using RSA-OAEP with SHA-256 before being sent over the network. The public key is served at
GET /api/user/public-key/, and the private key never leaves the server. RSA keys are auto-generated on server startup β no manual setup required. - Login Activity Tracking: Detailed tracking of all login attempts via
LoginTrackingMiddleware, including success/failed attempts, IP addresses, and user agents - Login Activity Model: Persistent storage of login attempts with timestamp, IP address, user agent, and success status
- Security Monitoring: Monitor suspicious login activities, failed login attempts, and security patterns
- Role-based Permissions: Custom permission classes (
IsSuperUser,IsStaffOrSuperUser) for fine-grained access control - Admin Bulk Email Verification: Admin action to mark multiple users as email verified
- Gmail SMTP Integration: Configured to send emails via Gmail SMTP server (
smtp.gmail.com, port 587, TLS enabled) - HTML Email Templates: Professionally designed HTML email templates for:
- Verification Email β Account activation link with 24-hour expiry
- Password Reset Email β Secure password reset link with 1-hour expiry
- Welcome Email β Automated welcome message after successful verification
- Frontend-friendly URLs: Email links point to the React frontend application (not the backend API), configured via
FRONTEND_BASE_URLenvironment variable - Environment Configuration: Email credentials configured through
.envfile (EMAIL_HOST_USER,EMAIL_HOST_PASSWORD,DEFAULT_FROM_EMAIL)
- RESTful API: Comprehensive REST API for all dashboard functionalities
- Auto-generated Documentation: API documentation using drf-spectacular
- Swagger UI: Interactive API documentation interface
- Redoc: Alternative API documentation format
- Docker Support: Containerized deployment with Docker and Docker Compose
- MySQL Database: Robust database support for production environments
- Media File Handling: Secure handling of user profile images with automatic cleanup on user deletion
- Relative URL File Field: Custom file field that returns relative media URLs (e.g.,
/media/uploads/user/image.jpg) β frontend-friendly - Environment Configuration: Flexible configuration using environment variables
- CORS Configuration: Configured to allow requests from frontend development server (
http://localhost:5173) - Timezone: Configured to
Asia/Kolkata - Max Upload Size: 2MB limit for profile image uploads
Docker is the recommended approach for running this application as it provides consistent environments and easier setup. Docker ensures that all dependencies are properly managed and the application runs reliably across different systems.
- Docker and Docker Compose
- MySQL database (included in Docker setup)
Build the Docker image:
docker-compose buildRun the application:
docker-compose upStop and remove containers:
docker-compose downDelete volumes (including database data):
docker-compose down --vRun database migrations:
docker-compose run --rm app sh -c "python manage.py wait_for_db && python manage.py migrate"Create a superuser:
docker-compose run --rm app sh -c "python manage.py createsuperuser"Run tests:
docker-compose run --rm app sh -c "python manage.py test"Run linting:
docker-compose run --rm app flake8Run tests and linting together:
docker-compose run --rm app sh -c "python manage.py test && flake8"This setup is optional and can be used if you prefer running the application directly on your system.
Prerequisites
- Python 3.9+
- MySQL database
- Clone the repository:
git clone https://github.com/Nikhilcs36/tdd_backend_python_django_project.git
cd tdd_backend_python_django_project- Create and activate virtual environment:
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate- Install dependencies:
pip install -r requirements.txt- Set up environment variables:
Copy the
.env.examplefile to.envand configure your database and email settings:
cp .env.example .env- Run database migrations:
cd app
python manage.py migrate- Create superuser (optional, for admin access):
python manage.py createsuperuser- Start the development server:
python manage.py runserverGET /api/user/public-key/- Get RSA public key for login credential encryptionPOST /api/user/token/- Obtain JWT token (acceptsemailandpassword; also supportsencrypted_password)POST /api/user/token/refresh/- Refresh JWT tokenPOST /api/user/create/- User registrationPOST /api/user/logout/- User logout (blacklists refresh token)POST /api/user/verify-email/- Email verificationPOST /api/user/resend-verification/- Resend verification emailPOST /api/user/password-reset/- Request password resetPOST /api/user/reset-password/<token>/- Reset password with token
GET /api/user/me/- Get current user profilePUT /api/user/me/- Update current user profile (supports image upload)GET /api/user/users/- List all users (admin only, supportsroleandmefilters)GET /api/user/users/<id>/- Get specific user details (superuser only)PUT /api/user/users/<id>/- Update specific user (superuser only)DELETE /api/user/users/<id>/- Delete specific user (superuser only)
GET /api/user/dashboard/stats/- User dashboard statistics (supportsstart_date,end_date)GET /api/user/dashboard/login-activity/- User login activity (supportsstart_date,end_date, pagination)GET /api/user/dashboard/charts/trends/- Login trends chart data (supportsuser_ids[],role,me, date filters)GET /api/user/dashboard/charts/comparison/- Login comparison data (supportsuser_ids[],role,me, date filters)GET /api/user/dashboard/charts/distribution/- Login distribution data (supportsuser_ids[],role,me, date filters)
GET /api/user/admin/dashboard/- Admin dashboard overview (supportsuser_ids[],role,filter,me, date filters)GET /api/user/admin/charts/- Admin charts data (user growth, daily login activity, success ratio)GET /api/user/admin/dashboard/users/stats/- Batch user statistics (admin only, supportsuser_ids[],is_active)
GET /api/user/<user_id>/dashboard/stats/- User-specific statistics (role-based access)GET /api/user/<user_id>/dashboard/login-activity/- User-specific login activity (role-based access)
GET /api/schema/- API schemaGET /api/docs/- Swagger UI documentationGET /api/redoc/- ReDoc documentation
- Development Server: Access the application at
http://localhost:8000 - API Documentation: View interactive API docs at
http://localhost:8000/api/docs/ - Admin Interface: Access Django admin at
http://localhost:8000/admin/
- User Registration: Register a new user account
- Email Verification: Verify your email address (check your email for the verification link)
- Login: Authenticate using your email and password
- View Dashboard: Access your personal dashboard with login statistics
- Admin Access: Administrators can access comprehensive admin dashboard
Integrate with the API using JWT authentication:
# Get authentication token
curl -X POST http://localhost:8000/api/user/token/ \
-H "Content-Type: application/json" \
-d '{"email": "your_email@example.com", "password": "your_password"}'
# Use token to access protected endpoints
curl -H "Authorization: JWT YOUR_JWT_TOKEN" \
http://localhost:8000/api/user/dashboard/stats/This backend is designed to work with the frontend React application over a shared Docker network.
Backend Container: backend (port 8000)
Frontend Container: Connects to backend at http://backend:8000
- Create the shared Docker network (one-time):
docker network create tdd-network- Start the backend:
docker-compose up -d- Start the frontend (separate project):
The frontend
docker-compose.ymlshould use the sametdd-networknetwork.
See
BACKEND_SETUP.mdandFRONTEND_SETUP.mdfor detailed setup guides.
The backend is configured to accept requests from the frontend development server:
- Frontend URL:
http://localhost:5173 - CORS credentials are enabled for authenticated requests
You can customize the application by modifying the following files:
app/core/models.py- Database models for User and LoginActivityapp/core/views.py- Core application views and logicapp/core/admin.py- Admin interface configurationapp/core/email_service.py- Email sending logic and URL buildingapp/core/authentication.py- Custom email-based authentication backendapp/core/exceptions.py- Custom exception handler for JWT errorsapp/core/middleware.py- Login tracking middlewareapp/core/templates/email/- HTML email templates
app/user/models.py- User-related models (if any extensions)app/user/views.py- User authentication and management viewsapp/user/views_dashboard.py- Dashboard views and analyticsapp/user/serializers.py- API serializers for user dataapp/user/serializers_dashboard.py- Dashboard data serializersapp/user/urls.py- URL routing for user endpointsapp/user/permissions.py- Custom permission classesapp/user/validators.py- Username, email, and password validatorsapp/user/pagination.py- Custom pagination classesapp/user/fields.py- Custom serializer fields (RelativeURLFileField)
app/app/settings.py- Django project settingsapp/app/urls.py- Main URL configuration.env- Environment variables configuration
- Modify dashboard statistics in
app/user/views_dashboard.py - Customize charts and analytics endpoints
- Add new dashboard metrics and visualizations
The application provides a comprehensive admin interface for managing users and monitoring login activities.
- Create superuser account:
python manage.py createsuperuser- Start development server:
python manage.py runserver- Access admin interface: Visit
http://localhost:8000/admin/
- User Management: View, edit, and manage user accounts
- Email Verification: View and manage email verification status
- Bulk Email Verification: Mark multiple users as email verified via admin action
- Login Activity Monitoring: Monitor all user login activities
- Dashboard Analytics: Access comprehensive admin dashboard
- Security Monitoring: Track security events and suspicious activities
This project is licensed under the MIT License - see the MIT License for details.
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
For support and questions, please contact nikhilcs36@gmail.com or open an issue in the GitHub repository.
- Built with Django and Django REST Framework
- JWT authentication using djangorestframework-simplejwt
- API documentation with drf-spectacular
- Containerized deployment with Docker