A comprehensive user management system with Multi-Factor Authentication (MFA), Admin Portal, and Library Management capabilities built with FastAPI, PostgreSQL, and modern web technologies.
- User Registration & Authentication - Secure user signup/login with JWT tokens
- Multi-Factor Authentication (MFA) - TOTP-based 2FA with QR codes and backup codes
- Role-Based Access Control - Client, Admin, and Super Admin roles
- Email Verification - Account verification via email
- Password Security - Strong password requirements and secure hashing
- Digital Library Access - Browse and search extensive book collection
- Book Borrowing & Returns - Seamless borrowing process with due date tracking
- Personal Dashboard - View borrowed books, due dates, and reading history
- Notifications Center - Due date reminders and library announcements
- Profile Management - Update personal information and preferences
- Mobile Responsive - Full functionality on all devices
- User Management - Create, update, delete, and manage all users
- Library Administration - Complete book catalog management
- Loan Monitoring - Track all borrowing activities and overdue books
- Analytics Dashboard - Comprehensive statistics and reports
- Bulk Operations - Perform actions on multiple users/books simultaneously
- Audit Trail - Track all admin actions and changes
- Book Catalog - Complete book management with ISBN, categories, and metadata
- Inventory Tracking - Real-time availability and copy management
- Loan System - Book borrowing with due dates and renewal options
- Search & Filtering - Advanced book search by title, author, genre, and availability
- Overdue Management - Automated notifications and tracking
- Categories & Collections - Organize books by genre, topic, and collections
- JWT Authentication - Secure token-based authentication
- Role-Based Authorization - Granular permission system
- Password Encryption - Bcrypt hashing with salt
- Session Management - Secure session handling
- Input Validation - Comprehensive data validation and sanitization
user_management/
βββ services/
β βββ user-service/
β βββ app/
β β βββ api/ # API endpoints
β β β βββ v1/ # Version 1 API
β β β βββ admin.py # Admin management
β β β βββ library.py # Library management
β β β βββ mfa.py # Multi-factor auth
β β β βββ notifications.py
β β βββ core/ # Core configuration
β β βββ models/ # Database models
β β βββ schemas/ # Pydantic schemas
β β βββ services/ # Business logic
β β βββ templates/ # Email templates
β βββ scripts/ # Utility scripts
β βββ requirements.txt
βββ frontend/ # Frontend application
βββ docs/ # Documentation
βββ docker-compose.yml
- Backend: FastAPI 0.104.1, Python 3.9+
- Database: PostgreSQL 13+
- Authentication: JWT with MFA (TOTP)
- Email: SMTP with HTML templates
- Security: bcrypt, pyotp, rate limiting
- Documentation: OpenAPI/Swagger
- Containerization: Docker & Docker Compose
- Python 3.9 or higher
- PostgreSQL 13 or higher
- Docker and Docker Compose (optional)
- SMTP server for email functionality
git clone <repository-url>
cd user_management
Create a .env
file in the root directory:
# Database Configuration
DATABASE_URL=postgresql://user:password@localhost:5432/user_management_db
POSTGRES_USER=user
POSTGRES_PASSWORD=password
POSTGRES_DB=user_management_db
# Security
SECRET_KEY=your-super-secret-key-here
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30
MFA_TOKEN_EXPIRE_MINUTES=10
# Application
APP_NAME=User Management System
VERSION=1.0.0
API_V1_STR=/api/v1
DEBUG=True
# Email Configuration
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USERNAME=[email protected]
SMTP_PASSWORD=your-app-password
SMTP_USE_TLS=True
FROM_EMAIL=[email protected]
FROM_NAME=User Management System
# Redis (for background tasks)
REDIS_URL=redis://localhost:6379/0
# Start all services
docker-compose up -d
# View logs
docker-compose logs -f user-service
# Stop services
docker-compose down
cd services/user-service
pip install -r requirements.txt
pip install -r requirements-test.txt # For testing
# Start PostgreSQL
sudo systemctl start postgresql
# Create database
createdb user_management_db
# Run the admin creation script
python scripts/create_admin.py
cd services/user-service
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
The project includes comprehensive testing capabilities:
Run the comprehensive API test suite:
cd services/user-service
python test_runner.py
This will test:
- β Authentication (signup, login, security)
- β User profile management (get, update, avatar upload)
- β Admin functionality (dashboard, user management)
- β Security measures (token validation, access control)
- β Error handling and validation
cd services/user-service
pytest tests/ -v
The test suite covers:
- User registration and authentication
- JWT token management
- Profile updates and avatar uploads
- Admin user management and deletion
- Role-based access control
- Input validation and error handling
- Security measures and edge cases
After running the setup script, you'll have access to:
Super Admin user
- Username:
super
- Email:
[email protected]
- Password:
SuperAdminPassword123!
- Role: Super Admin
Client user
- Username:
client
- Email:
[email protected]
- Password:
ClientPassword123?
- Role: Client
Login: Use either username or email with the password above. Important: Change this password immediately after first login!
For Gmail SMTP:
- Enable 2-factor authentication
- Generate an app password
- Use the app password in
SMTP_PASSWORD
Users can enable MFA by:
- Going to their profile settings
- Scanning the QR code with an authenticator app
- Entering the verification code
- Saving the backup codes
Once the service is running, access the interactive API documentation:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
POST /api/v1/signup
- User registration (no email verification required)POST /api/v1/login
- User login with username or email (returns MFA token if enabled)POST /api/v1/auth/mfa/verify
- Complete MFA verification
Login Methods: Users can log in using either their username or email address with their password.
POST /api/v1/auth/mfa/setup
- Setup MFA for userGET /api/v1/auth/mfa/status
- Get MFA statusPOST /api/v1/auth/mfa/disable
- Disable MFA
GET /api/v1/admin/dashboard
- Admin dashboard statsGET /api/v1/admin/users
- List all usersPOST /api/v1/admin/users
- Create user as adminDELETE /api/v1/admin/users/{id}
- Delete user
GET /api/v1/library/books
- List booksPOST /api/v1/library/books
- Add book (Admin)POST /api/v1/library/loans
- Borrow bookPUT /api/v1/library/loans/{id}/return
- Return book
GET /api/v1/notifications/
- Get user notificationsPUT /api/v1/notifications/{id}/read
- Mark as readPOST /api/v1/notifications/admin/send
- Send notification (Admin)
The frontend application provides comprehensive web interfaces for both clients and administrators.
- Dashboard Overview - Personal library statistics and activity
- Book Browser - Search and filter books with advanced options
- My Books - Manage borrowed books, renewals, and returns
- Notifications - Due date reminders and library announcements
- Profile Management - Update personal information
- Admin Dashboard - System statistics and monitoring
- User Management (
admin-users.html
) - CRUD operations for all users - Library Management (
admin-library.html
) - Complete book catalog administration - Analytics - Borrowing patterns and system usage reports
- Home Page:
http://localhost:3001/
- Welcome page with registration/login - Login:
http://localhost:3001/login.html
- Authentication page - Registration:
http://localhost:3001/signup.html
- New user registration - Client Portal:
http://localhost:3001/client-dashboard.html
- Main client interface - Admin Portal:
http://localhost:3001/admin-dashboard.html
- Administrative interface
The application automatically redirects users based on their role:
- Clients: Redirected to client dashboard after login
- Admin/Super Admin: Redirected to admin dashboard after login
- Unauthenticated: Redirected to login page
- Responsive Design - Mobile-friendly Bootstrap 5 interface
- Real-time Updates - Dynamic content loading and updates
- Form Validation - Client-side and server-side validation
- Error Handling - Comprehensive error messages and recovery
- Security - JWT token-based authentication with automatic refresh
To run the frontend development server:
cd frontend
python -m http.server 3001
Access the application at http://localhost:3001
The setup script can create sample users for testing:
- john_client / [email protected] / ClientPass123!
- jane_librarian / [email protected] / AdminPass123!
- bob_reader / [email protected] / ReaderPass123!
- Login with a user account
- Setup MFA in profile settings
- Use Google Authenticator or similar app
- Test login with MFA verification
- Login as admin
- Add books to the library
- Login as regular user
- Borrow and return books
- Check notifications for due dates
- Password Security: Bcrypt hashing with salt
- JWT Tokens: Secure token-based authentication
- MFA Protection: TOTP-based two-factor authentication
- Rate Limiting: Protection against brute force attacks
- Role-Based Access: Granular permission control
- Input Validation: Comprehensive request validation
- SQL Injection Protection: ORM-based queries
The system includes pre-built email templates for:
- Welcome emails
- Email verification
- Password reset
- Book due reminders
- Overdue notices
- Admin notifications
Templates are customizable and support variables.
The system uses multiple interconnected tables:
- users - User accounts and authentication
- mfa_secrets - MFA secrets and backup codes
- email_verifications - Email verification tokens
- books - Book catalog and metadata
- book_categories - Book categorization
- book_loans - Borrowing and return tracking
- notifications - User notifications and emails
- Environment Variables: Use secure, production values
- Database: Use managed PostgreSQL service
- Email: Configure proper SMTP service
- Redis: Set up Redis for background tasks
- HTTPS: Enable SSL/TLS certificates
- Rate Limiting: Configure appropriate limits
- Monitoring: Set up logging and monitoring
# Build for production
docker-compose -f docker-compose.prod.yml up -d
curl -X POST "http://localhost:8000/api/v1/signup" \
-H "Content-Type: application/json" \
-d '{
"username": "newuser",
"email": "[email protected]",
"password": "SecurePass123!",
"first_name": "John",
"last_name": "Doe"
}'
curl -X POST "http://localhost:8000/api/v1/login" \
-H "Content-Type: application/json" \
-d '{
"email": "[email protected]",
"password": "SecurePass123!"
}'
curl -X POST "http://localhost:8000/api/v1/auth/mfa/setup" \
-H "Authorization: Bearer <token>" \
-H "Content-Type: application/json" \
-d '{"verification_code": "123456"}'
- Database Connection: Check PostgreSQL is running and credentials are correct
- Email Not Sending: Verify SMTP configuration and credentials
- MFA Setup Failed: Ensure QR code is scanned correctly
- Permission Denied: Check user roles and authentication
# Docker logs
docker-compose logs user-service
# Application logs
tail -f logs/app.log
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
This project is licensed under the MIT License - see the LICENSE file for details.
For support and questions:
- Create an issue on GitHub
- Check the documentation in
/docs
- Review the API documentation at
/docs
Built with β€οΈ using FastAPI and modern Python technologies