Skip to main content

CODITECT Cloud Backend

FastAPI backend for CODITECT Cloud Platform with multi-tenant architecture, JWT authentication, and Row-Level Security.

Architecture Overview

  • Framework: FastAPI (async Python web framework)
  • Database: PostgreSQL 14+ with asyncpg driver
  • Authentication: JWT (access + refresh tokens)
  • Security: Row-Level Security (RLS) for tenant isolation
  • ORM: SQLAlchemy 2.0 (async)
  • Validation: Pydantic v2

Project Structure

src/
├── main.py # FastAPI app entry point
├── config.py # Configuration management
├── database.py # SQLAlchemy engine & RLS
├── dependencies.py # FastAPI dependencies (auth, DB)
├── models/ # SQLAlchemy ORM models
│ ├── organization.py # Organization model
│ ├── user.py # User model
│ ├── license.py # License model
│ └── project.py # Project model
├── schemas/ # Pydantic request/response schemas
│ ├── auth.py # Authentication schemas
│ ├── organization.py # Organization schemas
│ ├── user.py # User schemas
│ ├── license.py # License schemas
│ └── project.py # Project schemas
├── routers/ # API route handlers
│ ├── auth.py # /api/v1/auth/* endpoints
│ ├── organizations.py # /api/v1/organizations/* (placeholder)
│ ├── users.py # /api/v1/users/* (placeholder)
│ ├── licenses.py # /api/v1/licenses/* (placeholder)
│ └── projects.py # /api/v1/projects/* (placeholder)
└── services/ # Business logic layer
├── auth_service.py # Password hashing, JWT
├── rls_service.py # RLS session management
└── license_service.py # License validation

tests/
├── conftest.py # Pytest fixtures
├── test_health.py # Health check tests
└── (more tests to be added)

Quick Start

Prerequisites

  • Python 3.11+
  • PostgreSQL 14+ (Cloud SQL instance already deployed)
  • Cloud SQL Proxy (for local development)

1. Clone Repository

cd /path/to/coditect-rollout-master/submodules/coditect-cloud-backend

2. Create Virtual Environment

python3 -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate

3. Install Dependencies

pip install -r requirements.txt

4. Configure Environment

# Copy environment template
cp .env.example .env

# Edit .env with your actual values
vim .env

Required Configuration:

# Database (from Cloud SQL deployment)
DATABASE_HOST=<CLOUD_SQL_PRIVATE_IP> # Or 127.0.0.1 if using Cloud SQL Proxy
DATABASE_PORT=5432
DATABASE_NAME=coditect_dev
DATABASE_USER=postgres
DATABASE_PASSWORD=<PASSWORD_FROM_DEPLOYMENT>
DATABASE_SCHEMA=coditect_shared

# Security (CHANGE IN PRODUCTION!)
JWT_SECRET_KEY=<GENERATE_RANDOM_SECRET_KEY>

# Application
DEBUG=true
ENVIRONMENT=development

Generate JWT Secret Key:

python3 -c "import secrets; print(secrets.token_urlsafe(64))"

5. Start Cloud SQL Proxy (Local Development)

If connecting to Cloud SQL from local machine:

# In a separate terminal
cloud-sql-proxy coditect-week1-pilot:us-central1:coditect-shared-db \
--port=5432

6. Verify Database Connection

# Test database connectivity
python3 -c "
from src.database import init_db
import asyncio
asyncio.run(init_db())
print('Database connection successful!')
"

7. Run Development Server

# Run with auto-reload
uvicorn src.main:app --reload --host 0.0.0.0 --port 8000

# Or using Python directly
python3 -m src.main

Server will be available at:

API Endpoints

Implemented Endpoints (Phase 2.2)

Authentication

  • POST /api/v1/auth/signup - Register new user and organization
  • POST /api/v1/auth/login - Authenticate user (email or username)
  • GET /api/v1/auth/me - Get current user info
  • POST /api/v1/auth/refresh - Refresh access token

Health & Info

  • GET /health - Health check
  • GET / - API root information

Placeholder Endpoints (To Be Implemented)

  • Organizations: /api/v1/organizations/*
  • Users: /api/v1/users/*
  • Licenses: /api/v1/licenses/*
  • Projects: /api/v1/projects/*

Authentication Flow

1. User Signup

curl -X POST http://localhost:8000/api/v1/auth/signup \
-H "Content-Type: application/json" \
-d '{
"email": "john@example.com",
"username": "johndoe",
"password": "SecureP@ss123",
"full_name": "John Doe",
"organization_name": "Acme Corp",
"organization_slug": "acme-corp"
}'

Response:

{
"user": { "id": "...", "email": "john@example.com", ... },
"organization": { "id": "...", "name": "Acme Corp", ... },
"access_token": "eyJ...",
"refresh_token": "eyJ...",
"token_type": "bearer",
"expires_in": 3600
}

2. User Login

curl -X POST http://localhost:8000/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "john@example.com",
"password": "SecureP@ss123"
}'

3. Authenticated Request

curl -X GET http://localhost:8000/api/v1/auth/me \
-H "Authorization: Bearer <ACCESS_TOKEN>"

4. Token Refresh

curl -X POST http://localhost:8000/api/v1/auth/refresh \
-H "Content-Type: application/json" \
-d '{
"refresh_token": "<REFRESH_TOKEN>"
}'

Row-Level Security (RLS)

All database queries automatically enforce RLS policies through session variables:

# Automatically set by authentication middleware
await set_rls_context(
session,
user_id="123e4567-...",
organization_id="223e4567-...",
role="MEMBER"
)

# RLS policies in PostgreSQL ensure users only see their organization's data
result = await session.execute(select(Project)) # Only returns user's org projects

Testing

Run All Tests

pytest tests/ -v

Run with Coverage

pytest tests/ --cov=src --cov-report=html
open htmlcov/index.html # View coverage report

Run Specific Test

pytest tests/test_health.py -v

Development Workflow

Code Quality

# Format code with Black
black src/ tests/

# Lint with Flake8
flake8 src/ tests/

# Type check with MyPy
mypy src/

Database Migrations (Future)

Alembic is installed for schema migrations:

# Initialize Alembic (when needed)
alembic init alembic

# Create migration
alembic revision --autogenerate -m "Description"

# Apply migration
alembic upgrade head

Security Considerations

Password Security

  • Bcrypt hashing with cost factor 12 (configurable)
  • Minimum password requirements enforced:
    • 8+ characters
    • Uppercase letter
    • Lowercase letter
    • Number
    • Special character

JWT Tokens

  • Access tokens: Short-lived (1 hour default)
  • Refresh tokens: Long-lived (7 days default)
  • Both tokens contain: user_id, organization_id, role
  • Algorithm: HS256 (configurable)

Database Security

  • RLS policies enforce tenant isolation
  • Parameterized queries prevent SQL injection
  • Connection pooling with pre-ping health checks
  • Soft delete support (users retain deleted_at timestamp)

CORS

Configure allowed origins in .env:

CORS_ORIGINS=http://localhost:3000,https://app.coditect.az1.ai

Deployment

Production Checklist

  • Change JWT_SECRET_KEY to cryptographically random value
  • Set DEBUG=false
  • Set ENVIRONMENT=production
  • Configure production database credentials
  • Use GCP Secret Manager for secrets
  • Enable HTTPS only
  • Configure proper CORS origins
  • Set up monitoring and logging
  • Configure rate limiting
  • Enable database connection pooling
  • Set up backup and recovery

Cloud Run Deployment

# Build container
docker build -t gcr.io/coditect-week1-pilot/cloud-backend:v1.0.0 .

# Push to GCR
docker push gcr.io/coditect-week1-pilot/cloud-backend:v1.0.0

# Deploy to Cloud Run
gcloud run deploy coditect-cloud-backend \
--image gcr.io/coditect-week1-pilot/cloud-backend:v1.0.0 \
--platform managed \
--region us-central1 \
--allow-unauthenticated \
--set-env-vars DATABASE_HOST=<PRIVATE_IP> \
--vpc-connector <VPC_CONNECTOR>

Troubleshooting

Database Connection Issues

# Test database connectivity
psql -h <DATABASE_HOST> -U postgres -d coditect_dev

# Verify schema exists
psql -h <DATABASE_HOST> -U postgres -d coditect_dev \
-c "SELECT schema_name FROM information_schema.schemata WHERE schema_name = 'coditect_shared';"

JWT Token Errors

  • Verify JWT_SECRET_KEY matches between token generation and validation
  • Check token expiration times
  • Ensure clock synchronization (NTP) on servers

Import Errors

# Ensure you're in the project root directory
cd /path/to/coditect-cloud-backend

# Ensure virtual environment is activated
source venv/bin/activate

# Reinstall dependencies
pip install -r requirements.txt

Environment Variables Reference

VariableDefaultDescription
DATABASE_HOST-PostgreSQL host (required)
DATABASE_PORT5432PostgreSQL port
DATABASE_NAMEcoditect_devDatabase name
DATABASE_USERpostgresDatabase user
DATABASE_PASSWORD-Database password (required)
DATABASE_SCHEMAcoditect_sharedSchema name
JWT_SECRET_KEY-JWT signing key (required)
JWT_ALGORITHMHS256JWT algorithm
JWT_ACCESS_TOKEN_EXPIRE_MINUTES60Access token lifetime (minutes)
JWT_REFRESH_TOKEN_EXPIRE_DAYS7Refresh token lifetime (days)
BCRYPT_COST_FACTOR12Bcrypt hashing rounds
DEBUGfalseEnable debug mode
ENVIRONMENTproductionEnvironment name
LOG_LEVELINFOLogging level
LOG_FORMATjsonLog format (json/text)

Next Steps

Phase 2.3 (Week 1, Next)

  • Implement organizations CRUD endpoints
  • Implement users CRUD endpoints
  • Implement projects CRUD endpoints
  • Implement licenses CRUD endpoints
  • Add comprehensive test coverage
  • Add API rate limiting
  • Add request/response logging
  • Add OpenAPI spec validation

Future Enhancements

  • Email verification
  • Password reset flow
  • OAuth2 integration (Google, GitHub)
  • WebSocket support for real-time updates
  • Background task processing (Celery)
  • Caching layer (Redis)
  • File upload/storage (GCS)
  • Analytics and metrics

Resources

Support

For issues or questions:

  • Create GitHub issue in coditect-cloud-backend repository
  • Contact: support@az1.ai
  • Slack: #coditect-backend (internal)

Status: Phase 2.2 Complete - Authentication endpoints implemented Last Updated: 2025-11-17 Version: 1.0.0