The aim of this project is to provide a comprehensive Login Tracking Dashboard that helps administrators monitor user authentication activity, analyze login patterns, manage users through role-based dashboards, and generate comprehensive reports.
- Authentication Monitoring: Track all user login attempts — successful and failed — in real time, with detailed logging of IP addresses, user agents, and timestamps.
- Login Analytics: Analyze login patterns through daily, weekly, and monthly trends, distribution analysis by time of day and day of week, and comparison across time periods.
- User Management: Manage users with tiered dashboards — regular users view their own activity while administrators have full visibility with advanced filtering by role, date range, and user IDs.
- Reporting: Generate and download comprehensive login activity summary reports in professionally formatted Excel (.xlsx), available in individual and grouped modes.
- Secure Authentication: Enforce JWT token-based authentication with RSA-encrypted credentials, token blacklisting, email verification, and automatic staff access progression.
- Administrative Insights: Provide admins with combined chart data across multiple users, batch user statistics, role-based filtering, and a comprehensive Django admin interface with granular permissions.
- Gamification & Engagement: Provide a circle drawing game backend for score submission, personal score tracking, and admin leaderboards, with feature flag controls for enabling/disabling game sections.
- REST API Foundation: Deliver a well-structured, test-driven REST API with Swagger/ReDoc documentation, designed to pair seamlessly with a React frontend over Docker.
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.
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
- Optional Name Field: The
namefield on the user model is optional and excluded from the admin user creation form
- Circle Drawing Game Backend: Submit and track scores for a circle drawing game
- Score Submission: Authenticated users can submit their game scores
- My Scores: Users can view their own scores with best score tracking, paginated
- Game Leaderboard: Admin-only leaderboard showing the best score per user, ordered by score descending
- Feature Flags: The game section and leaderboard can be independently enabled/disabled via environment variables (
GAME_SECTION_ENABLED,GAME_LEADERBOARD_ENABLED) - Role-based Access: Score submission and personal score viewing are available to all authenticated users; leaderboard requires admin/staff privileges
- Excel Report Generation: Download comprehensive login activity summary reports in professionally formatted Excel (.xlsx) format
- Individual Mode: Single user report — regular users can download their own report; admins can download for any user
- Grouped Mode: Combined report for multiple users (admin only)
- Flexible Filtering: Filter by date range, user role, user IDs, or predefined filters (
all,admin_only,regular_users,me) - Feature Flag: Report download can be enabled/disabled via
ENABLE_REPORT_DOWNLOADenvironment variable - Detailed Report Data: Includes report metadata (user info, date period), recent login activities, top user agents, summary statistics (total/successful/failed logins, success rate), daily login trends, weekly/monthly comparison, success/failure distribution ratio, and grouped summary with combined totals for admin overview
- Professional Formatting: Styled Excel output with headers, borders, auto-adjusted column widths, and separate sheets for different data views
| 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 | ❌ | ✅ |
| Submit game scores | ✅ | ✅ |
| View own game scores | ✅ | ✅ |
| Access game leaderboard | ❌ | ✅ |
| Download own login report (individual mode) | ✅ | ✅ |
| Download any user's login report | ❌ | ✅ |
| Download grouped reports | ❌ | ✅ |
View auto staff access countdown (logins_remaining_for_staff) |
✅ | ✅ |
| Switch active role | ❌ | ✅ |
- 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. - Auto Staff Access: After 3 successful logins, users are automatically granted staff access (
is_staff=True) via middleware. Login response includeslogins_remaining_for_staffcountdown (3, 2, 1, 0),staff_access_grantedstatus,active_role('regular'/'staff'/'superuser'), androle_labelfor frontend role-based UI control. - Role Switching: Authenticated users with staff or superuser privileges can switch their active role via
POST /api/user/switch-role/. Superusers can switch between 'regular', 'staff', and 'superuser'. Staff users can switch between 'regular' and 'staff'. - Automatic Token Cleanup: Expired blacklisted JWT tokens are automatically cleaned every 24 hours via background scheduler. Tokens expired more than 1 day ago are deleted to prevent DB bloat.
- 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
- GAME_SECTION_ENABLED: Enable/disable the entire game section (default:
True) - GAME_LEADERBOARD_ENABLED: Enable/disable the game leaderboard (default:
True) - ENABLE_REPORT_DOWNLOAD: Enable/disable login report download (default:
True)
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). Returns user details includinglogins_remaining_for_staff(countdown: 3, 2, 1, 0),staff_access_granted,active_role('regular'/'staff'/'superuser'), androle_labelfor frontend role-based UI controlPOST /api/user/token/refresh/- Refresh JWT tokenPOST /api/user/switch-role/- Switch active role (superusers: 'regular'/'staff'/'superuser'; staff users: 'regular'/'staff'). Requires{"role": "..."}in request bodyPOST /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/user/dashboard/report/download/?mode=<mode>- Download login activity summary report in Excel format- Parameters:
mode(required:individualorgrouped),user_ids[],start_date,end_date,filter(all/admin_only/regular_users/me),role(admin/regular),selected_user_id - Permissions: Regular users can download their own report in individual mode; admins can download for any user(s)
- Parameters:
POST /api/game/scores/- Submit a game score (authenticated users)GET /api/game/my-scores/- List my game scores with best score (authenticated users, paginated)GET /api/game/leaderboard/- Game leaderboard — best score per user (admin/staff only, paginated)
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/
For a quick hands-on experience, the project includes a seed_data management command that populates the database with demo users, realistic login activity (spanning the last 3 months), and sample game scores. This lets you explore the dashboard with data already in place — no manual setup required.
Docker runs seed_data automatically on startup (see the command in docker-compose.yml), so no manual step is needed on a fresh database.
If you ever need to re-seed after wiping the database (e.g., docker-compose down -v), run:
Docker:
docker-compose run --rm app sh -c "python manage.py seed_data"Local (manual only — not automatic):
cd app
python manage.py seed_dataNote: The command only runs on an empty database. If users already exist, it skips to avoid duplicates.
| Username | Password | Role | Notes | |
|---|---|---|---|---|
admin |
admin@demo.com | Admin@123 |
Superuser | Full access, 100 login records, 6 game scores |
normal |
normal@demo.com | Test@123456 |
Regular | Verified, staff access granted, 25 login records, 4 game scores |
staff |
staff@demo.com | Test@123456 |
Staff | Verified, 10 login records, 3 game scores |
abcd |
abcd@demo.com | Test@123456 |
Regular | Unverified — use this to test email verification flow |
testuser |
testuser@demo.com | Test@123456 |
Regular | Verified, no login activity — clean slate dashboard |
Tip:
abcdis intentionally left unverified. Sinceabcd@demo.comis not a real inbox, you can manually approve email verification by logging into the Django admin athttp://localhost:8000/admin/with the superuser credentials (admin@demo.com/Admin@123), editing theabcduser, and checking Email verified.
While the demo users let you jump straight into the dashboard, we recommend going through the normal registration flow to experience the complete lifecycle:
- Register a new account via
POST /api/user/create/ - Verify your email via the verification link sent to your inbox (requires SMTP configured in
.env) - Log in — after 3 successful logins, you'll automatically receive staff access
- Explore your personal dashboard, charts, and login activity as it builds up naturally
This flow gives you the full picture of how the application works end-to-end, including email verification, welcome emails, auto staff access, and real-time login tracking.
- 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
- Submit a Score: Authenticated users can submit a game score via
POST /api/game/scores/ - View Scores: Access your own scores via
GET /api/game/my-scores/(includes best score) - Leaderboard: Admins can view the global leaderboard via
GET /api/game/leaderboard/
- Individual Report:
GET /api/user/dashboard/report/download/?mode=individual— downloads your own login report - Grouped Report (Admin):
GET /api/user/dashboard/report/download/?mode=grouped— downloads combined report for all users - Custom Filtering: Add
start_date,end_date,user_ids[],role, orfilterparameters to customize the report
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 configuration (UserAdmin with role badges, LoginActivityAdmin with granular permissions)app/core/apps.py- App config that starts the daily token cleanup scheduler on Django startupapp/core/token_cleanup_scheduler.py- Background scheduler that automatically cleans expired blacklisted JWT tokens every 24 hoursapp/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 templatesapp/core/templates/admin/base_site.html- Custom admin template with role-based permission bannerapp/templates/admin/base_site.html- Custom admin template with role-based permission banner and responsive header stylingapp/sites.py- StaffOnlyAuthenticationForm that blocks regular users from logging into Django admin
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/views_report.py- Report download views and logicapp/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 classes (IsSuperUser,IsStaffOrSuperUser)app/user/validators.py- Username, email, and password validatorsapp/user/pagination.py- Custom pagination classesapp/user/fields.py- Custom serializer fields (RelativeURLFileField)app/user/mixins.py- Shared mixins for date filtering and user filteringapp/user/reports/- Report generation modules:data_collector.py- Collects login data for reportsexcel_generator.py- Generates formatted Excel reports
app/game/models.py- GameScore modelapp/game/views.py- Game views (score submission, my scores, leaderboard) with feature flag supportapp/game/serializers.py- Game score serializersapp/game/urls.py- URL routing for game endpoints
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
GAME_SECTION_ENABLED(default:True): Set toFalsein.envto disable all game featuresGAME_LEADERBOARD_ENABLED(default:True): Set toFalsein.envto disable the leaderboardENABLE_REPORT_DOWNLOAD(default:True): Set toFalsein.envto disable report downloads
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/
The admin site features a custom header: "Login Tracking Dashboard" with a "Dashboard" index title.
- 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
- Login Activity Records: View-only admin interface for login activity records with search by username/IP, filter by success status and date range, sorted by most recent
- Game Score Records: View-only admin interface for game scores with search by username/email, sorted by highest score
- Dashboard Analytics: Access comprehensive admin dashboard
- Security Monitoring: Track security events and suspicious activities
- Role-based Access Control: Only superusers can add, edit, or delete users; staff users have view-only access
- Staff-Only Login: Regular users are blocked from logging into the Django admin panel. Only users with
is_stafforis_superuserprivileges can access the admin login page. Non-staff users see a clear error message: "Your account does not have admin access. Please log in again with a staff or superuser account."
- Frontend "View site" Link: The "View site" link in the admin header redirects to the frontend application (configured via
FRONTEND_BASE_URL) instead of the backend root URL - Role Badge Display: The user list page shows a colour-coded role badge for each user:
- Superuser (red) — Full administrative access: Create, Read, Update, and Delete any user record
- Staff (yellow) — Read-only administrative access: View user list, view user details. Cannot add, edit, or delete users
- Regular (green) — Own data only. Regular users cannot access the Django admin panel
- Permission Info Banner: A permission banner is displayed at the top of every admin page, showing the logged-in user's role and a description of their access level
| Model | Superuser | Staff |
|---|---|---|
| User | Full CRUD (add, change, view, delete) | View-only (can view user list & details) |
| LoginActivity | View & Delete (no add/edit) | View-only (no add/edit/delete) |
| GameScore | View & Delete (no add/edit) | View-only (no add/edit/delete) |
- LoginActivityAdmin: View-only for staff (search by username/email/IP, filter by success/date). Only superusers can delete records. No one can add or edit login activity records via admin.
- GameScoreAdmin: View-only for staff (search by username/email, filter by score/date). Only superusers can delete records. No one can add or edit game scores via admin.
- Bulk Email Verification: Admin action to mark multiple users as email verified
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