9fff9fa9c1fa7fb29be576a5d95d8d3e87878772
fix: audit logs for tenants, user, roles, modules and environment and modules of tenant and modules.
fix: audit logs for tenants, user, roles, modules and environment and modules of tenant and modules.
SaaS Architecture Backend
A multi-tenant SaaS backend built with FastAPI, PostgreSQL, and SQLAlchemy.
Features
- 🔐 Authentication & Authorization: JWT-based authentication with role-based access control (RBAC)
- 👥 Multi-Tenancy: Complete tenant isolation with tenant-scoped data
- 🎨 Theming: Color palette management per tenant
- 🔄 Database Migrations: Alembic for schema version control
- 🌍 Multi-Environment: Support for local, development, production, and testing environments
Tech Stack
- Framework: FastAPI 0.122.0
- Database: PostgreSQL with SQLAlchemy 2.0.44
- Migrations: Alembic 1.17.2
- Authentication: JWT (PyJWT) + bcrypt
- Server: Uvicorn
Prerequisites
- Python 3.12+
- PostgreSQL 12+
- Python 3.10+
- PostgreSQL 12+
Getting Started
1. Clone and Setup
cd "c:/Users/furqa/OneDrive/Work/Maskan/SaaS Architecture/App/backend"
2. Create Virtual Environment
python -m venv venv
.\venv\Scripts\activate # Windows
# source venv/bin/activate # Linux/Mac
3. Install Dependencies
pip install -r requirements.txt
pip install -r requirements.txt
4. Environment Configuration
Create environment-specific configuration files:
.env.local- Local development.env.development- Development server.env.production- Production.env.testing- Testing environment
Minimum required variables (see app/config/settings.py for all options):
# Server
APP_ENV=local
HOST=0.0.0.0
PORT=8000
# Database
DATABASE_URL=postgresql://user:password@localhost:5432/dbname
# Security
SECRET_KEY=your-secret-key-here
ACCESS_TOKEN_SECRET=your-access-token-secret
REFRESH_TOKEN_SECRET=your-refresh-token-secret
# Frontend
FRONTEND_URL=http://localhost:5173
CORS_ALLOWED_ORIGINS=http://localhost:5173,http://localhost:3000
# Email
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your-email@gmail.com
SMTP_PASSWORD=your-app-password
EMAIL_FROM=noreply@yourapp.com
# Super Admin (for initial setup)
SUPER_ADMIN_EMAIL=admin@yourapp.com
SUPER_ADMIN_PASSWORD=SecurePassword123!
SUPER_ADMIN_FIRST_NAME=Admin
SUPER_ADMIN_LAST_NAME=User
5. Database Migrations
Alembic is configured to work with your multi-environment setup. It automatically:
- Loads the correct
.env.{APP_ENV}file - Uses the
DATABASE_URLfrom your settings - Imports all models for autogenerate support
Create Initial Migration
# Set environment (local, development, production, testing)
$env:APP_ENV="local" # Windows PowerShell
# export APP_ENV=local # Linux/Mac
# Create initial migration
alembic revision --autogenerate -m "Initial schema"
Run Migrations
# Using manage.py (recommended - handles APP_ENV automatically)
python manage.py migrate --env local
python manage.py migrate --env development
python manage.py migrate --env production
python manage.py migrate --env testing
# Or using alembic directly
$env:APP_ENV="local" # Set environment first
alembic upgrade head
Other Migration Commands
# Check current migration version
alembic current
# View migration history
alembic history
# Downgrade one version
alembic downgrade -1
# Downgrade to specific version
alembic downgrade <revision_id>
# View SQL without running
alembic upgrade head --sql
6. Seed Database
After running migrations, seed the database with initial data:
# Seed super admin user
python manage.py seed superadmin --env local
# Seed default color palettes
python manage.py seed palettes --env local
7. Run the Application
# Using manage.py (recommended)
python manage.py run --env local # Local environment
python manage.py run --env development # Development environment
python manage.py run --env production # Production environment
python manage.py run --env testing # Testing environment
# Or using Python directly
python run.py
The API will be available at http://localhost:8000
API Documentation
Once the application is running, visit:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
- OpenAPI JSON: http://localhost:8000/openapi.json
Project Structure
backend/
├── alembic/ # Database migrations
│ ├── versions/ # Migration scripts
│ └── env.py # Alembic environment config
├── app/
│ ├── config/ # Configuration
│ │ ├── database.py # Database connection
│ │ └── settings.py # Application settings
│ ├── controllers/ # Business logic controllers
│ │ ├── auth/
│ │ └── theme/
│ ├── middleware/ # Custom middleware
│ ├── models/ # SQLAlchemy models
│ │ ├── auth/ # User, Tenant, Role, Access
│ │ └── theme/ # ColorPalette
│ ├── routes/ # API endpoints
│ │ ├── auth/
│ │ └── theme/
│ ├── schemas/ # Pydantic schemas
│ │ ├── auth/
│ │ └── theme/
│ ├── services/ # Service layer
│ │ ├── auth/
│ │ └── theme/
│ └── __init__.py # FastAPI app factory
├── scripts/ # Utility scripts
│ ├── seed_palettes.py
│ └── seed_superadmin.py
├── alembic.ini # Alembic configuration
├── alembic.ini # Alembic configuration
├── manage.py # Management CLI script
├── requirements.txt # Python dependencies
└── run.py # Application entry point
Database Models
Authentication & Authorization
- Tenant: Multi-tenant isolation
- User: User accounts (tenant-scoped)
- Role: User roles (tenant-scoped)
- Access: Permission definitions (hierarchical)
- RoleAccess: Role-to-permission mapping
Theming
- ColorPalette: Tenant color themes
Health Check
The application includes a health check endpoint:
curl http://localhost:8000/health
Response:
{
"status": "healthy",
"environment": "local",
"database": "healthy",
"version": "1.0.0"
}
Development Notes
Environment Variables Loading Order
The application loads environment variables in this order (later overrides earlier):
- Root
.env - Backend
.env - Root
.env.{APP_ENV} - Backend
.env.{APP_ENV}
Multi-Tenancy
The system implements tenant isolation at the database level:
- Each tenant has their own users and roles
- Color palettes can be tenant-specific or global
- The super admin user is tenant-independent
Role-Based Access Control
The RBAC system supports:
- Hierarchical permissions (Access has parent-child relationships)
- Category-based organization
- Flexible role-to-permission mapping
- Tenant-scoped roles
Troubleshooting
Database Connection Issues
- Verify PostgreSQL is running
- Check
DATABASE_URLin your.env.{APP_ENV}file - Ensure database exists:
createdb your_database_name - Check database user permissions
Migration Issues
- Ensure
APP_ENVis set correctly - Verify database connection works
- Check that all models are imported in
alembic/env.py - Delete
alembic/versions/*.pyand recreate if needed
Import Errors
- Ensure virtual environment is activated
- Install all dependencies:
pip install -r requirements.txt - Check Python version (3.10+ required)
License
[Your License Here]
Support
For issues and questions, please contact [your-email@example.com]
Languages
Python
99.8%
Mako
0.2%