Initial monorepo structure
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""App package."""
|
||||
@@ -0,0 +1 @@
|
||||
"""API package."""
|
||||
@@ -0,0 +1 @@
|
||||
"""API v1 package."""
|
||||
@@ -0,0 +1,101 @@
|
||||
"""Auth routes."""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.security import get_password_hash, verify_password, create_access_token, decode_token
|
||||
from app.core.auth import get_current_user
|
||||
from app.models.user import User
|
||||
from app.models.associations import UserRole, UserModuleRole, ModuleRole
|
||||
from app.models.role import Role
|
||||
from app.schemas.schemas import RegisterRequest, LoginRequest, TokenResponse, UserResponse
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["Auth"])
|
||||
|
||||
|
||||
def _build_user_response(user: User, db: Session) -> dict:
|
||||
global_roles = [ur.role.name for ur in user.user_roles if ur.role]
|
||||
mod_roles = {}
|
||||
for umr in user.user_module_roles:
|
||||
if umr.module_role and umr.module_role.module:
|
||||
slug = umr.module_role.module.slug
|
||||
mod_roles.setdefault(slug, []).append(umr.module_role.role_name)
|
||||
return {
|
||||
"id": user.id,
|
||||
"email": user.email,
|
||||
"first_name": user.first_name,
|
||||
"last_name": user.last_name,
|
||||
"is_active": user.is_active,
|
||||
"is_superadmin": user.is_superadmin,
|
||||
"roles": global_roles,
|
||||
"module_roles": mod_roles,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/register", response_model=UserResponse, status_code=201)
|
||||
async def register(data: RegisterRequest, db: Session = Depends(get_db)):
|
||||
if db.query(User).filter(User.email == data.email).first():
|
||||
raise HTTPException(status_code=409, detail="Email already registered")
|
||||
user = User(
|
||||
email=data.email,
|
||||
password_hash=get_password_hash(data.password),
|
||||
first_name=data.first_name,
|
||||
last_name=data.last_name,
|
||||
)
|
||||
db.add(user)
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
return _build_user_response(user, db)
|
||||
|
||||
|
||||
@router.post("/login", response_model=TokenResponse)
|
||||
async def login(data: LoginRequest, db: Session = Depends(get_db)):
|
||||
user = db.query(User).filter(User.email == data.email).first()
|
||||
if not user or not verify_password(data.password, user.password_hash):
|
||||
raise HTTPException(status_code=401, detail="Invalid email or password")
|
||||
if not user.is_active:
|
||||
raise HTTPException(status_code=403, detail="User is deactivated")
|
||||
|
||||
user_data = _build_user_response(user, db)
|
||||
token = create_access_token(data={
|
||||
"sub": str(user.id),
|
||||
"email": user.email,
|
||||
"first_name": user.first_name,
|
||||
"last_name": user.last_name,
|
||||
"is_active": user.is_active,
|
||||
"roles": user_data["roles"],
|
||||
"module_roles": user_data["module_roles"],
|
||||
})
|
||||
return {
|
||||
"access_token": token,
|
||||
"token_type": "bearer",
|
||||
"expires_in": 28800,
|
||||
"user": user_data,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/validate")
|
||||
async def validate_token(token: str = None, db: Session = Depends(get_db)):
|
||||
"""Validate JWT for modules. Token passed as query param or body."""
|
||||
from fastapi import Request
|
||||
# Modules call this endpoint with the JWT
|
||||
# We just decode and return user data
|
||||
if not token:
|
||||
raise HTTPException(status_code=400, detail="Token required")
|
||||
payload = decode_token(token)
|
||||
if not payload:
|
||||
raise HTTPException(status_code=401, detail="Invalid token")
|
||||
user_id = payload.get("sub")
|
||||
if not user_id:
|
||||
raise HTTPException(status_code=401, detail="Invalid token")
|
||||
user = db.query(User).filter(User.id == int(user_id)).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
user_data = _build_user_response(user, db)
|
||||
return {"user_id": user.id, **user_data}
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
async def get_me(user: User = Depends(get_current_user), db: Session = Depends(get_db)):
|
||||
return _build_user_response(user, db)
|
||||
@@ -0,0 +1,10 @@
|
||||
"""Health routes."""
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
router = APIRouter(tags=["Health"])
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
async def health():
|
||||
return {"status": "healthy", "service": "Platform"}
|
||||
@@ -0,0 +1,125 @@
|
||||
"""Modules routes."""
|
||||
|
||||
import secrets
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
import httpx
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.auth import require_platform_admin
|
||||
from app.models.user import User
|
||||
from app.models.module import Module
|
||||
from app.models.associations import ModuleRole
|
||||
from app.schemas.schemas import ModuleCreate, ModuleResponse, ModuleRoleResponse
|
||||
|
||||
router = APIRouter(prefix="/modules", tags=["Modules"])
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_modules(db: Session = Depends(get_db)):
|
||||
modules = db.query(Module).order_by(Module.name).all()
|
||||
return [
|
||||
{
|
||||
"id": m.id, "name": m.name, "slug": m.slug, "description": m.description,
|
||||
"url": m.url, "icon": m.icon, "is_active": m.is_active,
|
||||
"roles_count": len(m.module_roles),
|
||||
}
|
||||
for m in modules
|
||||
]
|
||||
|
||||
|
||||
@router.post("", status_code=201)
|
||||
async def create_module(data: ModuleCreate, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
if db.query(Module).filter(Module.slug == data.slug).first():
|
||||
raise HTTPException(status_code=409, detail="Module slug already exists")
|
||||
module = Module(
|
||||
name=data.name,
|
||||
slug=data.slug,
|
||||
description=data.description,
|
||||
url=data.url,
|
||||
icon=data.icon,
|
||||
api_key=secrets.token_hex(32),
|
||||
)
|
||||
db.add(module)
|
||||
db.commit()
|
||||
db.refresh(module)
|
||||
return {
|
||||
"id": module.id, "name": module.name, "slug": module.slug, "description": module.description,
|
||||
"url": module.url, "icon": module.icon, "is_active": module.is_active, "api_key": module.api_key,
|
||||
}
|
||||
|
||||
|
||||
@router.put("/{module_id}")
|
||||
async def update_module(module_id: int, data: ModuleCreate, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
module = db.query(Module).filter(Module.id == module_id).first()
|
||||
if not module:
|
||||
raise HTTPException(status_code=404, detail="Module not found")
|
||||
module.name = data.name
|
||||
module.slug = data.slug
|
||||
module.description = data.description
|
||||
module.url = data.url
|
||||
module.icon = data.icon
|
||||
db.commit()
|
||||
return {
|
||||
"id": module.id, "name": module.name, "slug": module.slug, "description": module.description,
|
||||
"url": module.url, "icon": module.icon, "is_active": module.is_active, "api_key": module.api_key,
|
||||
}
|
||||
|
||||
|
||||
@router.delete("/{module_id}")
|
||||
async def delete_module(module_id: int, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
module = db.query(Module).filter(Module.id == module_id).first()
|
||||
if not module:
|
||||
raise HTTPException(status_code=404, detail="Module not found")
|
||||
db.delete(module)
|
||||
db.commit()
|
||||
return {"message": "Module deleted"}
|
||||
|
||||
|
||||
@router.post("/{module_id}/sync-roles")
|
||||
async def sync_roles(module_id: int, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
"""Import roles from module and sync all users."""
|
||||
module = db.query(Module).filter(Module.id == module_id).first()
|
||||
if not module:
|
||||
raise HTTPException(status_code=404, detail="Module not found")
|
||||
|
||||
# 1. Sync roles
|
||||
try:
|
||||
resp = httpx.get(f"{module.url.rstrip('/')}/api/v1/reference/roles", timeout=10)
|
||||
if resp.status_code != 200:
|
||||
raise HTTPException(status_code=502, detail=f"Module returned {resp.status_code}")
|
||||
roles_data = resp.json()
|
||||
except httpx.RequestError as e:
|
||||
raise HTTPException(status_code=502, detail=f"Cannot reach module: {e}")
|
||||
|
||||
# Clear old roles for this module
|
||||
db.query(ModuleRole).filter(ModuleRole.module_id == module_id).delete()
|
||||
|
||||
imported = 0
|
||||
for r in roles_data:
|
||||
role_name = r.get("name") if isinstance(r, dict) else r
|
||||
desc = r.get("description") if isinstance(r, dict) else None
|
||||
db.add(ModuleRole(module_id=module_id, role_name=role_name, description=desc))
|
||||
imported += 1
|
||||
|
||||
db.commit()
|
||||
|
||||
# 2. Sync all users to module
|
||||
from app.api.v1.users import _sync_all_users_to_modules
|
||||
_sync_all_users_to_modules(db)
|
||||
|
||||
return {
|
||||
"message": f"Imported {imported} roles and synced users",
|
||||
"roles": [r.get("name", r) if isinstance(r, dict) else r for r in roles_data],
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{module_id}/roles")
|
||||
async def get_module_roles(module_id: int, db: Session = Depends(get_db)):
|
||||
module = db.query(Module).filter(Module.id == module_id).first()
|
||||
if not module:
|
||||
raise HTTPException(status_code=404, detail="Module not found")
|
||||
return [
|
||||
{"id": mr.id, "module_id": mr.module_id, "role_name": mr.role_name, "description": mr.description}
|
||||
for mr in module.module_roles
|
||||
]
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Roles routes."""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.auth import require_platform_admin
|
||||
from app.models.user import User
|
||||
from app.models.role import Role
|
||||
from app.schemas.schemas import RoleCreate, RoleResponse
|
||||
|
||||
router = APIRouter(prefix="/roles", tags=["Roles"])
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_roles(db: Session = Depends(get_db)):
|
||||
roles = db.query(Role).order_by(Role.name).all()
|
||||
return [{"id": r.id, "name": r.name, "description": r.description, "is_system": r.is_system} for r in roles]
|
||||
|
||||
|
||||
@router.post("", status_code=201)
|
||||
async def create_role(data: RoleCreate, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
if db.query(Role).filter(Role.name == data.name).first():
|
||||
raise HTTPException(status_code=409, detail="Role already exists")
|
||||
role = Role(name=data.name, description=data.description)
|
||||
db.add(role)
|
||||
db.commit()
|
||||
db.refresh(role)
|
||||
return {"id": role.id, "name": role.name, "description": role.description, "is_system": role.is_system}
|
||||
|
||||
|
||||
@router.put("/{role_id}")
|
||||
async def update_role(role_id: int, data: RoleCreate, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
role = db.query(Role).filter(Role.id == role_id).first()
|
||||
if not role:
|
||||
raise HTTPException(status_code=404, detail="Role not found")
|
||||
if role.is_system:
|
||||
raise HTTPException(status_code=400, detail="Cannot modify system role")
|
||||
role.name = data.name
|
||||
role.description = data.description
|
||||
db.commit()
|
||||
return {"id": role.id, "name": role.name, "description": role.description, "is_system": role.is_system}
|
||||
|
||||
|
||||
@router.delete("/{role_id}")
|
||||
async def delete_role(role_id: int, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
role = db.query(Role).filter(Role.id == role_id).first()
|
||||
if not role:
|
||||
raise HTTPException(status_code=404, detail="Role not found")
|
||||
if role.is_system:
|
||||
raise HTTPException(status_code=400, detail="Cannot delete system role")
|
||||
db.delete(role)
|
||||
db.commit()
|
||||
return {"message": "Role deleted"}
|
||||
@@ -0,0 +1,309 @@
|
||||
"""Users routes."""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import Optional
|
||||
import httpx
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.auth import get_current_user, require_platform_admin
|
||||
from app.core.security import get_password_hash, create_access_token
|
||||
from app.models.user import User
|
||||
from app.models.associations import UserRole, ModuleRole, UserModuleRole
|
||||
from app.models.role import Role
|
||||
from app.models.module import Module
|
||||
from app.schemas.schemas import UserResponse, UserListResponse, RoleResponse
|
||||
|
||||
router = APIRouter(prefix="/users", tags=["Users"])
|
||||
|
||||
|
||||
def _sync_user_to_modules(db: Session, user: User):
|
||||
"""Push user data to all active modules."""
|
||||
modules = db.query(Module).filter(Module.is_active == True).all()
|
||||
|
||||
# Build module roles mapping for this user
|
||||
module_roles = {}
|
||||
for umr in user.user_module_roles:
|
||||
if umr.module_role and umr.module_role.module:
|
||||
slug = umr.module_role.module.slug
|
||||
module_roles.setdefault(slug, []).append(umr.module_role.role_name)
|
||||
|
||||
for mod in modules:
|
||||
# Get roles specific to this module
|
||||
roles_for_module = module_roles.get(mod.slug, [])
|
||||
|
||||
user_data = {
|
||||
"id": user.id,
|
||||
"email": user.email,
|
||||
"first_name": user.first_name,
|
||||
"last_name": user.last_name,
|
||||
"is_active": user.is_active,
|
||||
"roles": roles_for_module,
|
||||
}
|
||||
|
||||
try:
|
||||
httpx.post(
|
||||
f"{mod.url.rstrip('/')}/api/v1/users/sync",
|
||||
json=user_data,
|
||||
headers={"X-API-Key": mod.api_key},
|
||||
timeout=5,
|
||||
)
|
||||
except Exception:
|
||||
pass # Module may be offline, that's OK
|
||||
|
||||
|
||||
def _sync_user_deletion_to_modules(db: Session, user: User):
|
||||
"""Notify modules about user deletion."""
|
||||
modules = db.query(Module).filter(Module.is_active == True).all()
|
||||
for mod in modules:
|
||||
try:
|
||||
httpx.delete(
|
||||
f"{mod.url.rstrip('/')}/api/v1/users/{user.id}",
|
||||
headers={"X-API-Key": mod.api_key},
|
||||
timeout=5,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _sync_all_users_to_modules(db: Session):
|
||||
"""Sync all users to all active modules."""
|
||||
modules = db.query(Module).filter(Module.is_active == True).all()
|
||||
users = db.query(User).filter(User.is_active == True).all()
|
||||
user_data_list = [
|
||||
{
|
||||
"id": u.id,
|
||||
"email": u.email,
|
||||
"first_name": u.first_name,
|
||||
"last_name": u.last_name,
|
||||
"is_active": u.is_active,
|
||||
}
|
||||
for u in users
|
||||
]
|
||||
for mod in modules:
|
||||
try:
|
||||
httpx.post(
|
||||
f"{mod.url.rstrip('/')}/api/v1/users/sync-all",
|
||||
json={"users": user_data_list},
|
||||
headers={"X-API-Key": mod.api_key},
|
||||
timeout=10,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _build_user_response(user: User, db: Session) -> dict:
|
||||
global_roles = [ur.role.name for ur in user.user_roles if ur.role]
|
||||
mod_roles = {}
|
||||
for umr in user.user_module_roles:
|
||||
if umr.module_role and umr.module_role.module:
|
||||
slug = umr.module_role.module.slug
|
||||
mod_roles.setdefault(slug, []).append(umr.module_role.role_name)
|
||||
return {
|
||||
"id": user.id,
|
||||
"email": user.email,
|
||||
"first_name": user.first_name,
|
||||
"last_name": user.last_name,
|
||||
"is_active": user.is_active,
|
||||
"is_superadmin": user.is_superadmin,
|
||||
"roles": global_roles,
|
||||
"module_roles": mod_roles,
|
||||
}
|
||||
|
||||
|
||||
@router.get("", response_model=UserListResponse)
|
||||
async def list_users(
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(20, ge=1, le=100),
|
||||
search: Optional[str] = None,
|
||||
db: Session = Depends(get_db),
|
||||
admin: User = Depends(require_platform_admin),
|
||||
):
|
||||
query = db.query(User)
|
||||
if search:
|
||||
term = f"%{search}%"
|
||||
query = query.filter(User.email.ilike(term) | User.first_name.ilike(term) | User.last_name.ilike(term))
|
||||
total = query.count()
|
||||
users = query.offset((page - 1) * page_size).limit(page_size).all()
|
||||
return {
|
||||
"users": [_build_user_response(u, db) for u in users],
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"total_pages": (total + page_size - 1) // page_size,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
async def get_me(user: User = Depends(get_current_user), db: Session = Depends(get_db)):
|
||||
return _build_user_response(user, db)
|
||||
|
||||
|
||||
@router.get("/{user_id}")
|
||||
async def get_user(user_id: int, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
return _build_user_response(user, db)
|
||||
|
||||
|
||||
@router.post("", status_code=201)
|
||||
async def create_user(
|
||||
data: dict,
|
||||
db: Session = Depends(get_db),
|
||||
admin: User = Depends(require_platform_admin),
|
||||
):
|
||||
email = data.get("email")
|
||||
password = data.get("password")
|
||||
first_name = data.get("first_name", "")
|
||||
last_name = data.get("last_name", "")
|
||||
|
||||
if not email or not password:
|
||||
raise HTTPException(status_code=400, detail="email and password required")
|
||||
|
||||
if db.query(User).filter(User.email == email).first():
|
||||
raise HTTPException(status_code=409, detail="Email already exists")
|
||||
|
||||
user = User(
|
||||
email=email,
|
||||
password_hash=get_password_hash(password),
|
||||
first_name=first_name,
|
||||
last_name=last_name,
|
||||
is_active=True,
|
||||
is_superadmin=data.get("is_superadmin", False),
|
||||
)
|
||||
db.add(user)
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
|
||||
# Assign roles if provided
|
||||
for role_id in data.get("role_ids", []):
|
||||
db.add(UserRole(user_id=user.id, role_id=role_id))
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
|
||||
# Sync to modules
|
||||
_sync_user_to_modules(db, user)
|
||||
|
||||
return _build_user_response(user, db)
|
||||
|
||||
|
||||
@router.put("/{user_id}")
|
||||
async def update_user(
|
||||
user_id: int,
|
||||
data: dict,
|
||||
db: Session = Depends(get_db),
|
||||
admin: User = Depends(require_platform_admin),
|
||||
):
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
|
||||
if "first_name" in data:
|
||||
user.first_name = data["first_name"]
|
||||
if "last_name" in data:
|
||||
user.last_name = data["last_name"]
|
||||
if "email" in data:
|
||||
existing = db.query(User).filter(User.email == data["email"], User.id != user_id).first()
|
||||
if existing:
|
||||
raise HTTPException(status_code=409, detail="Email already exists")
|
||||
user.email = data["email"]
|
||||
if "is_active" in data:
|
||||
user.is_active = data["is_active"]
|
||||
if "is_superadmin" in data:
|
||||
user.is_superadmin = data["is_superadmin"]
|
||||
if "password" in data and data["password"]:
|
||||
user.password_hash = get_password_hash(data["password"])
|
||||
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
|
||||
# Sync to modules
|
||||
_sync_user_to_modules(db, user)
|
||||
|
||||
return _build_user_response(user, db)
|
||||
|
||||
|
||||
@router.delete("/{user_id}")
|
||||
async def delete_user(
|
||||
user_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
admin: User = Depends(require_platform_admin),
|
||||
):
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
if user.is_superadmin:
|
||||
raise HTTPException(status_code=403, detail="Cannot delete superadmin")
|
||||
|
||||
# Notify modules about deletion
|
||||
_sync_user_deletion_to_modules(db, user)
|
||||
|
||||
db.delete(user)
|
||||
db.commit()
|
||||
return {"message": "User deleted"}
|
||||
|
||||
|
||||
@router.get("/{user_id}/roles")
|
||||
async def get_user_roles(user_id: int, db: Session = Depends(get_db)):
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
return {"roles": [ur.role.name for ur in user.user_roles if ur.role]}
|
||||
|
||||
|
||||
@router.post("/{user_id}/roles/{role_id}")
|
||||
async def assign_role(user_id: int, role_id: int, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
existing = db.query(UserRole).filter(UserRole.user_id == user_id, UserRole.role_id == role_id).first()
|
||||
if not existing:
|
||||
db.add(UserRole(user_id=user_id, role_id=role_id))
|
||||
db.commit()
|
||||
return {"message": "Role assigned"}
|
||||
|
||||
|
||||
@router.delete("/{user_id}/roles/{role_id}")
|
||||
async def remove_role(user_id: int, role_id: int, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
ur = db.query(UserRole).filter(UserRole.user_id == user_id, UserRole.role_id == role_id).first()
|
||||
if ur:
|
||||
db.delete(ur)
|
||||
db.commit()
|
||||
return {"message": "Role removed"}
|
||||
|
||||
|
||||
@router.get("/{user_id}/module-roles")
|
||||
async def get_user_module_roles(user_id: int, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
result = {}
|
||||
for umr in user.user_module_roles:
|
||||
if umr.module_role and umr.module_role.module:
|
||||
slug = umr.module_role.module.slug
|
||||
result.setdefault(slug, []).append(umr.module_role.role_name)
|
||||
return {"module_roles": result}
|
||||
|
||||
|
||||
@router.post("/{user_id}/module-roles/{module_role_id}")
|
||||
async def assign_module_role(user_id: int, module_role_id: int, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
existing = db.query(UserModuleRole).filter(UserModuleRole.user_id == user_id, UserModuleRole.module_role_id == module_role_id).first()
|
||||
if not existing:
|
||||
db.add(UserModuleRole(user_id=user_id, module_role_id=module_role_id))
|
||||
db.commit()
|
||||
|
||||
# Sync user with updated roles to the module
|
||||
_sync_user_to_modules(db, db.query(User).filter(User.id == user_id).first())
|
||||
|
||||
return {"message": "Module role assigned"}
|
||||
|
||||
|
||||
@router.delete("/{user_id}/module-roles/{module_role_id}")
|
||||
async def remove_module_role(user_id: int, module_role_id: int, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
umr = db.query(UserModuleRole).filter(UserModuleRole.user_id == user_id, UserModuleRole.module_role_id == module_role_id).first()
|
||||
if umr:
|
||||
db.delete(umr)
|
||||
db.commit()
|
||||
|
||||
# Sync user with updated roles to the module
|
||||
_sync_user_to_modules(db, db.query(User).filter(User.id == user_id).first())
|
||||
|
||||
return {"message": "Module role removed"}
|
||||
@@ -0,0 +1 @@
|
||||
"""Core package."""
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Auth dependencies."""
|
||||
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.security import decode_token
|
||||
from app.models.user import User
|
||||
|
||||
security = HTTPBearer()
|
||||
|
||||
|
||||
def get_current_user_id(credentials: HTTPAuthorizationCredentials = Depends(security)) -> int:
|
||||
token = credentials.credentials
|
||||
payload = decode_token(token)
|
||||
if not payload:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
||||
user_id = payload.get("sub")
|
||||
if not user_id:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
||||
return int(user_id)
|
||||
|
||||
|
||||
def get_current_user(
|
||||
user_id: int = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db),
|
||||
) -> User:
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
|
||||
if not user.is_active:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="User is deactivated")
|
||||
return user
|
||||
|
||||
|
||||
def require_platform_admin(user: User = Depends(get_current_user), db: Session = Depends(get_db)) -> User:
|
||||
if user.is_superadmin:
|
||||
return user
|
||||
from app.models.associations import UserRole
|
||||
from app.models.role import Role
|
||||
has_role = db.query(UserRole).join(Role).filter(
|
||||
UserRole.user_id == user.id, Role.name == "platform_admin"
|
||||
).first()
|
||||
if not has_role:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Platform admin required")
|
||||
return user
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Database utilities."""
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker, Session
|
||||
from typing import Generator
|
||||
from app.settings import get_settings
|
||||
from app.models.base import Base
|
||||
|
||||
settings = get_settings()
|
||||
engine = create_engine(settings.DATABASE_URL, pool_pre_ping=True, echo=False)
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
|
||||
def get_db() -> Generator[Session, None, None]:
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def init_db():
|
||||
from app.models import user, role, module, associations
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
from app.models.role import Role
|
||||
system_roles = [
|
||||
("platform_admin", "Platform administrator", True),
|
||||
("user_manager", "Can manage users", True),
|
||||
]
|
||||
for name, desc, is_system in system_roles:
|
||||
if not db.query(Role).filter(Role.name == name).first():
|
||||
db.add(Role(name=name, description=desc, is_system=is_system))
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Security utilities."""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional, Dict, Any
|
||||
from jose import JWTError, jwt
|
||||
import bcrypt
|
||||
from app.settings import get_settings
|
||||
|
||||
|
||||
def get_password_hash(password: str) -> str:
|
||||
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
|
||||
|
||||
|
||||
def verify_password(plain: str, hashed: str) -> bool:
|
||||
try:
|
||||
return bcrypt.checkpw(plain.encode("utf-8"), hashed.encode("utf-8"))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def create_access_token(data: Dict[str, Any], expires_delta: Optional[timedelta] = None) -> str:
|
||||
to_encode = data.copy()
|
||||
expire = datetime.utcnow() + (expires_delta or timedelta(minutes=get_settings().JWT_ACCESS_TOKEN_EXPIRE_MINUTES))
|
||||
to_encode["exp"] = expire
|
||||
return jwt.encode(to_encode, get_settings().JWT_SECRET_KEY, algorithm=get_settings().JWT_ALGORITHM)
|
||||
|
||||
|
||||
def decode_token(token: str) -> Optional[Dict[str, Any]]:
|
||||
try:
|
||||
return jwt.decode(token, get_settings().JWT_SECRET_KEY, algorithms=[get_settings().JWT_ALGORITHM])
|
||||
except JWTError:
|
||||
return None
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Platform - Main Application."""
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import JSONResponse
|
||||
from app.settings import get_settings
|
||||
from app.core.database import init_db
|
||||
from app.api.v1 import auth, users, roles, modules, health
|
||||
|
||||
app = FastAPI(
|
||||
title=get_settings().APP_NAME,
|
||||
version=get_settings().APP_VERSION,
|
||||
description="Platform - Module Management System",
|
||||
openapi_url="/openapi.json",
|
||||
)
|
||||
|
||||
# CORS
|
||||
cors_origins = get_settings().APP_CORS_ORIGINS.split(",")
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=cors_origins,
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# Routes
|
||||
app.include_router(health.router, prefix="/api/v1")
|
||||
app.include_router(auth.router, prefix="/api/v1")
|
||||
app.include_router(users.router, prefix="/api/v1")
|
||||
app.include_router(roles.router, prefix="/api/v1")
|
||||
app.include_router(modules.router, prefix="/api/v1")
|
||||
|
||||
|
||||
@app.on_event("startup")
|
||||
async def startup():
|
||||
init_db()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
uvicorn.run("app.main:app", host="0.0.0.0", port=9000, reload=True)
|
||||
@@ -0,0 +1 @@
|
||||
"""Models package."""
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Association models."""
|
||||
|
||||
from sqlalchemy import Column, Integer, ForeignKey, String, Text
|
||||
from sqlalchemy.orm import relationship
|
||||
from app.models.base import Base, TimestampMixin
|
||||
|
||||
|
||||
class UserRole(Base, TimestampMixin):
|
||||
__tablename__ = "user_roles"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
|
||||
role_id = Column(Integer, ForeignKey("roles.id", ondelete="CASCADE"), nullable=False)
|
||||
|
||||
user = relationship("User", back_populates="user_roles")
|
||||
role = relationship("Role", back_populates="user_roles")
|
||||
|
||||
|
||||
class ModuleRole(Base, TimestampMixin):
|
||||
__tablename__ = "module_roles"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
module_id = Column(Integer, ForeignKey("modules.id", ondelete="CASCADE"), nullable=False)
|
||||
role_name = Column(String(100), nullable=False)
|
||||
description = Column(Text)
|
||||
|
||||
module = relationship("Module", back_populates="module_roles")
|
||||
user_module_roles = relationship("UserModuleRole", back_populates="module_role", cascade="all, delete-orphan")
|
||||
|
||||
|
||||
class UserModuleRole(Base, TimestampMixin):
|
||||
__tablename__ = "user_module_roles"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
|
||||
module_role_id = Column(Integer, ForeignKey("module_roles.id", ondelete="CASCADE"), nullable=False)
|
||||
|
||||
user = relationship("User", back_populates="user_module_roles")
|
||||
module_role = relationship("ModuleRole", back_populates="user_module_roles")
|
||||
@@ -0,0 +1,12 @@
|
||||
"""Base model."""
|
||||
|
||||
from datetime import datetime
|
||||
from sqlalchemy import Column, DateTime, Integer
|
||||
from sqlalchemy.orm import declarative_base
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
class TimestampMixin:
|
||||
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
@@ -0,0 +1,20 @@
|
||||
"""Module model."""
|
||||
|
||||
from sqlalchemy import Column, String, Boolean, Text, Integer
|
||||
from sqlalchemy.orm import relationship
|
||||
from app.models.base import Base, TimestampMixin
|
||||
|
||||
|
||||
class Module(Base, TimestampMixin):
|
||||
__tablename__ = "modules"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String(100), nullable=False)
|
||||
slug = Column(String(50), unique=True, nullable=False)
|
||||
description = Column(Text)
|
||||
url = Column(String(500), nullable=False)
|
||||
icon = Column(String(50), default="Box")
|
||||
is_active = Column(Boolean, default=True)
|
||||
api_key = Column(String(64), unique=True)
|
||||
|
||||
module_roles = relationship("ModuleRole", back_populates="module", cascade="all, delete-orphan")
|
||||
@@ -0,0 +1,16 @@
|
||||
"""Role model."""
|
||||
|
||||
from sqlalchemy import Column, String, Boolean, Text, Integer
|
||||
from sqlalchemy.orm import relationship
|
||||
from app.models.base import Base, TimestampMixin
|
||||
|
||||
|
||||
class Role(Base, TimestampMixin):
|
||||
__tablename__ = "roles"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String(100), unique=True, nullable=False)
|
||||
description = Column(Text)
|
||||
is_system = Column(Boolean, default=False)
|
||||
|
||||
user_roles = relationship("UserRole", back_populates="role", cascade="all, delete-orphan")
|
||||
@@ -0,0 +1,20 @@
|
||||
"""User model."""
|
||||
|
||||
from sqlalchemy import Column, String, Boolean, Integer
|
||||
from sqlalchemy.orm import relationship
|
||||
from app.models.base import Base, TimestampMixin
|
||||
|
||||
|
||||
class User(Base, TimestampMixin):
|
||||
__tablename__ = "users"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
email = Column(String(255), unique=True, index=True, nullable=False)
|
||||
password_hash = Column(String(255), nullable=False)
|
||||
first_name = Column(String(100), nullable=False)
|
||||
last_name = Column(String(100), nullable=False)
|
||||
is_active = Column(Boolean, default=True)
|
||||
is_superadmin = Column(Boolean, default=False)
|
||||
|
||||
user_roles = relationship("UserRole", back_populates="user", cascade="all, delete-orphan")
|
||||
user_module_roles = relationship("UserModuleRole", back_populates="user", cascade="all, delete-orphan")
|
||||
@@ -0,0 +1 @@
|
||||
"""Schemas package."""
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Auth schemas."""
|
||||
|
||||
from pydantic import BaseModel, EmailStr, Field
|
||||
from typing import Optional, List, Dict
|
||||
|
||||
|
||||
class RegisterRequest(BaseModel):
|
||||
email: EmailStr
|
||||
password: str = Field(..., min_length=6)
|
||||
first_name: str = Field(..., min_length=1, max_length=100)
|
||||
last_name: str = Field(..., min_length=1, max_length=100)
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
email: EmailStr
|
||||
password: str
|
||||
|
||||
|
||||
class TokenResponse(BaseModel):
|
||||
access_token: str
|
||||
token_type: str = "bearer"
|
||||
expires_in: int
|
||||
user: dict
|
||||
|
||||
|
||||
class UserResponse(BaseModel):
|
||||
id: int
|
||||
email: str
|
||||
first_name: str
|
||||
last_name: str
|
||||
is_active: bool
|
||||
is_superadmin: bool
|
||||
roles: List[str] = []
|
||||
module_roles: Dict[str, List[str]] = {}
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class UserListResponse(BaseModel):
|
||||
users: List[UserResponse]
|
||||
total: int
|
||||
page: int
|
||||
page_size: int
|
||||
total_pages: int
|
||||
|
||||
|
||||
class RoleResponse(BaseModel):
|
||||
id: int
|
||||
name: str
|
||||
description: Optional[str]
|
||||
is_system: bool
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class RoleCreate(BaseModel):
|
||||
name: str = Field(..., min_length=1, max_length=100)
|
||||
description: Optional[str] = None
|
||||
|
||||
|
||||
class ModuleResponse(BaseModel):
|
||||
id: int
|
||||
name: str
|
||||
slug: str
|
||||
description: Optional[str]
|
||||
url: str
|
||||
icon: str
|
||||
is_active: bool
|
||||
api_key: str
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class ModuleCreate(BaseModel):
|
||||
name: str = Field(..., min_length=1, max_length=100)
|
||||
slug: str = Field(..., min_length=1, max_length=50)
|
||||
description: Optional[str] = None
|
||||
url: str
|
||||
icon: str = "Box"
|
||||
|
||||
|
||||
class ModuleRoleResponse(BaseModel):
|
||||
id: int
|
||||
module_id: int
|
||||
role_name: str
|
||||
description: Optional[str]
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Platform settings."""
|
||||
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
from functools import lru_cache
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", case_sensitive=True)
|
||||
|
||||
APP_NAME: str = "Platform"
|
||||
APP_VERSION: str = "1.0.0"
|
||||
APP_DEBUG: bool = True
|
||||
APP_CORS_ORIGINS: str = "http://localhost:5173,http://localhost:5174,http://localhost:8000,http://localhost:8001"
|
||||
|
||||
DATABASE_URL: str = "sqlite:///./platform.db"
|
||||
|
||||
JWT_SECRET_KEY: str = "platform-secret-key-change-in-production"
|
||||
JWT_ALGORITHM: str = "HS256"
|
||||
JWT_ACCESS_TOKEN_EXPIRE_MINUTES: int = 480
|
||||
|
||||
|
||||
@lru_cache()
|
||||
def get_settings() -> Settings:
|
||||
return Settings()
|
||||
@@ -0,0 +1,10 @@
|
||||
fastapi==0.104.1
|
||||
uvicorn==0.24.0
|
||||
sqlalchemy==2.0.23
|
||||
pydantic==2.5.0
|
||||
pydantic-settings==2.1.0
|
||||
python-jose[cryptography]==3.3.0
|
||||
bcrypt==4.0.1
|
||||
httpx==0.25.2
|
||||
python-multipart==0.0.6
|
||||
email-validator==2.1.0
|
||||
Reference in New Issue
Block a user