# 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 ```bash cd "c:/Users/furqa/OneDrive/Work/Maskan/SaaS Architecture/App/backend" ``` ### 2. Create Virtual Environment ```bash python -m venv venv .\venv\Scripts\activate # Windows # source venv/bin/activate # Linux/Mac ``` ### 3. Install Dependencies ```bash 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): ```env # 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_URL` from your settings - Imports all models for autogenerate support #### Create Initial Migration ```bash # 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 ```bash # 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 ```bash # Check current migration version alembic current # View migration history alembic history # Downgrade one version alembic downgrade -1 # Downgrade to specific version alembic downgrade # View SQL without running alembic upgrade head --sql ``` ### 6. Seed Database After running migrations, seed the database with initial data: ```bash # 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 ```bash # 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: ```bash curl http://localhost:8000/health ``` Response: ```json { "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): 1. Root `.env` 2. Backend `.env` 3. Root `.env.{APP_ENV}` 4. 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 1. Verify PostgreSQL is running 2. Check `DATABASE_URL` in your `.env.{APP_ENV}` file 3. Ensure database exists: `createdb your_database_name` 4. Check database user permissions ### Migration Issues 1. Ensure `APP_ENV` is set correctly 2. Verify database connection works 3. Check that all models are imported in `alembic/env.py` 4. Delete `alembic/versions/*.py` and recreate if needed ### Import Errors 1. Ensure virtual environment is activated 2. Install all dependencies: `pip install -r requirements.txt` 3. Check Python version (3.10+ required) ## License [Your License Here] ## Support For issues and questions, please contact [your-email@example.com]