Compare commits
1 Commits
3cf2b1bc49
...
4b20444a5e
| Author | SHA1 | Date | |
|---|---|---|---|
| 4b20444a5e |
@@ -5,7 +5,6 @@ WORKDIR /app
|
||||
# Install system dependencies
|
||||
RUN apt-get update && apt-get install -y \
|
||||
build-essential \
|
||||
curl \
|
||||
default-libmysqlclient-dev \
|
||||
pkg-config \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
"""Role-based access control helpers."""
|
||||
from functools import wraps
|
||||
from fastapi import HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
from app.models.models import ProjectMember, User
|
||||
|
||||
|
||||
# Role hierarchy: admin > mgr > dev > ops > viewer
|
||||
ROLE_LEVELS = {
|
||||
"admin": 50,
|
||||
"mgr": 40,
|
||||
"dev": 30,
|
||||
"ops": 20,
|
||||
"viewer": 10,
|
||||
}
|
||||
|
||||
|
||||
def get_member_role(db: Session, user_id: int, project_id: int) -> str | None:
|
||||
"""Get user's role in a project. Returns None if not a member."""
|
||||
member = db.query(ProjectMember).filter(
|
||||
ProjectMember.user_id == user_id,
|
||||
ProjectMember.project_id == project_id,
|
||||
).first()
|
||||
if member:
|
||||
return member.role
|
||||
# Check if user is global admin
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if user and user.is_admin:
|
||||
return "admin"
|
||||
return None
|
||||
|
||||
|
||||
def check_project_role(db: Session, user_id: int, project_id: int, min_role: str = "viewer"):
|
||||
"""Raise 403 if user doesn't have the minimum required role in the project."""
|
||||
role = get_member_role(db, user_id, project_id)
|
||||
if role is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Not a member of this project"
|
||||
)
|
||||
if ROLE_LEVELS.get(role, 0) < ROLE_LEVELS.get(min_role, 0):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=f"Requires role '{min_role}' or higher, you have '{role}'"
|
||||
)
|
||||
return role
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Comments router with RBAC and notifications."""
|
||||
"""Comments router."""
|
||||
from typing import List
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
@@ -6,47 +6,16 @@ from sqlalchemy.orm import Session
|
||||
from app.core.config import get_db
|
||||
from app.models import models
|
||||
from app.schemas import schemas
|
||||
from app.api.deps import get_current_user_or_apikey
|
||||
from app.api.rbac import check_project_role
|
||||
from app.models.notification import Notification as NotificationModel
|
||||
|
||||
router = APIRouter(tags=["Comments"])
|
||||
|
||||
|
||||
def _notify_if_needed(db, issue_id, user_ids, ntype, title):
|
||||
"""Helper to notify multiple users."""
|
||||
issue = db.query(models.Issue).filter(models.Issue.id == issue_id).first()
|
||||
if not issue:
|
||||
return
|
||||
for uid in set(user_ids):
|
||||
if uid:
|
||||
n = NotificationModel(user_id=uid, type=ntype, title=title, entity_type="issue", entity_id=issue_id)
|
||||
db.add(n)
|
||||
db.commit()
|
||||
|
||||
|
||||
@router.post("/comments", response_model=schemas.CommentResponse, status_code=status.HTTP_201_CREATED)
|
||||
def create_comment(comment: schemas.CommentCreate, db: Session = Depends(get_db), current_user: models.User = Depends(get_current_user_or_apikey)):
|
||||
# Get project_id from issue first
|
||||
issue = db.query(models.Issue).filter(models.Issue.id == comment.issue_id).first()
|
||||
if not issue:
|
||||
raise HTTPException(status_code=404, detail="Issue not found")
|
||||
check_project_role(db, current_user.id, issue.project_id, min_role="viewer")
|
||||
|
||||
def create_comment(comment: schemas.CommentCreate, db: Session = Depends(get_db)):
|
||||
db_comment = models.Comment(**comment.model_dump())
|
||||
db.add(db_comment)
|
||||
db.commit()
|
||||
db.refresh(db_comment)
|
||||
|
||||
# Notify reporter and assignee (but not the commenter themselves)
|
||||
notify_users = []
|
||||
if issue.reporter_id != current_user.id:
|
||||
notify_users.append(issue.reporter_id)
|
||||
if issue.assignee_id and issue.assignee_id != current_user.id:
|
||||
notify_users.append(issue.assignee_id)
|
||||
if notify_users:
|
||||
_notify_if_needed(db, issue.id, notify_users, "comment_added", f"New comment on: {issue.title[:50]}")
|
||||
|
||||
return db_comment
|
||||
|
||||
|
||||
@@ -68,15 +37,10 @@ def update_comment(comment_id: int, comment_update: schemas.CommentUpdate, db: S
|
||||
|
||||
|
||||
@router.delete("/comments/{comment_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_comment(comment_id: int, db: Session = Depends(get_db), current_user: models.User = Depends(get_current_user_or_apikey)):
|
||||
def delete_comment(comment_id: int, db: Session = Depends(get_db)):
|
||||
comment = db.query(models.Comment).filter(models.Comment.id == comment_id).first()
|
||||
if not comment:
|
||||
raise HTTPException(status_code=404, detail="Comment not found")
|
||||
# Get issue to check project role
|
||||
issue = db.query(models.Issue).filter(models.Issue.id == comment.issue_id).first()
|
||||
if not issue:
|
||||
raise HTTPException(status_code=404, detail="Issue not found")
|
||||
check_project_role(db, current_user.id, issue.project_id, min_role="dev")
|
||||
db.delete(comment)
|
||||
db.commit()
|
||||
return None
|
||||
|
||||
@@ -11,9 +11,6 @@ from app.models import models
|
||||
from app.schemas import schemas
|
||||
from app.services.webhook import fire_webhooks_sync
|
||||
from app.models.notification import Notification as NotificationModel
|
||||
from app.api.deps import get_current_user_or_apikey
|
||||
from app.api.rbac import check_project_role
|
||||
from app.services.activity import log_activity
|
||||
|
||||
router = APIRouter(tags=["Issues"])
|
||||
|
||||
@@ -29,8 +26,7 @@ def _notify_user(db, user_id, ntype, title, message=None, entity_type=None, enti
|
||||
# ---- CRUD ----
|
||||
|
||||
@router.post("/issues", response_model=schemas.IssueResponse, status_code=status.HTTP_201_CREATED)
|
||||
def create_issue(issue: schemas.IssueCreate, bg: BackgroundTasks, db: Session = Depends(get_db), current_user: models.User = Depends(get_current_user_or_apikey)):
|
||||
check_project_role(db, current_user.id, issue.project_id, min_role="dev")
|
||||
def create_issue(issue: schemas.IssueCreate, bg: BackgroundTasks, db: Session = Depends(get_db)):
|
||||
db_issue = models.Issue(**issue.model_dump())
|
||||
db.add(db_issue)
|
||||
db.commit()
|
||||
@@ -39,7 +35,6 @@ def create_issue(issue: schemas.IssueCreate, bg: BackgroundTasks, db: Session =
|
||||
bg.add_task(fire_webhooks_sync, event,
|
||||
{"issue_id": db_issue.id, "title": db_issue.title, "type": db_issue.issue_type, "status": db_issue.status},
|
||||
db_issue.project_id, db)
|
||||
log_activity(db, "issue.created", "issue", db_issue.id, current_user.id, {"title": db_issue.title})
|
||||
return db_issue
|
||||
|
||||
|
||||
@@ -102,7 +97,7 @@ def get_issue(issue_id: int, db: Session = Depends(get_db)):
|
||||
|
||||
|
||||
@router.patch("/issues/{issue_id}", response_model=schemas.IssueResponse)
|
||||
def update_issue(issue_id: int, issue_update: schemas.IssueUpdate, db: Session = Depends(get_db), current_user: models.User = Depends(get_current_user_or_apikey)):
|
||||
def update_issue(issue_id: int, issue_update: schemas.IssueUpdate, db: Session = Depends(get_db)):
|
||||
issue = db.query(models.Issue).filter(models.Issue.id == issue_id).first()
|
||||
if not issue:
|
||||
raise HTTPException(status_code=404, detail="Issue not found")
|
||||
@@ -114,11 +109,10 @@ def update_issue(issue_id: int, issue_update: schemas.IssueUpdate, db: Session =
|
||||
|
||||
|
||||
@router.delete("/issues/{issue_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_issue(issue_id: int, db: Session = Depends(get_db), current_user: models.User = Depends(get_current_user_or_apikey)):
|
||||
def delete_issue(issue_id: int, db: Session = Depends(get_db)):
|
||||
issue = db.query(models.Issue).filter(models.Issue.id == issue_id).first()
|
||||
if not issue:
|
||||
raise HTTPException(status_code=404, detail="Issue not found")
|
||||
log_activity(db, "issue.deleted", "issue", issue.id, current_user.id, {"title": issue.title})
|
||||
db.delete(issue)
|
||||
db.commit()
|
||||
return None
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Projects router with RBAC."""
|
||||
"""Projects router."""
|
||||
from typing import List
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
@@ -6,9 +6,6 @@ from sqlalchemy.orm import Session
|
||||
from app.core.config import get_db
|
||||
from app.models import models
|
||||
from app.schemas import schemas
|
||||
from app.api.deps import get_current_user_or_apikey
|
||||
from app.api.rbac import check_project_role
|
||||
from app.services.activity import log_activity
|
||||
|
||||
router = APIRouter(prefix="/projects", tags=["Projects"])
|
||||
|
||||
@@ -19,10 +16,6 @@ def create_project(project: schemas.ProjectCreate, db: Session = Depends(get_db)
|
||||
db.add(db_project)
|
||||
db.commit()
|
||||
db.refresh(db_project)
|
||||
# Auto-add creator as admin member
|
||||
db_member = models.ProjectMember(project_id=db_project.id, user_id=project.owner_id, role="admin")
|
||||
db.add(db_member)
|
||||
db.commit()
|
||||
return db_project
|
||||
|
||||
|
||||
@@ -40,13 +33,7 @@ def get_project(project_id: int, db: Session = Depends(get_db)):
|
||||
|
||||
|
||||
@router.patch("/{project_id}", response_model=schemas.ProjectResponse)
|
||||
def update_project(
|
||||
project_id: int,
|
||||
project_update: schemas.ProjectUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: models.User = Depends(get_current_user_or_apikey),
|
||||
):
|
||||
check_project_role(db, current_user.id, project_id, min_role="mgr")
|
||||
def update_project(project_id: int, project_update: schemas.ProjectUpdate, db: Session = Depends(get_db)):
|
||||
project = db.query(models.Project).filter(models.Project.id == project_id).first()
|
||||
if not project:
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
@@ -58,12 +45,7 @@ def update_project(
|
||||
|
||||
|
||||
@router.delete("/{project_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_project(
|
||||
project_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: models.User = Depends(get_current_user_or_apikey),
|
||||
):
|
||||
check_project_role(db, current_user.id, project_id, min_role="admin")
|
||||
def delete_project(project_id: int, db: Session = Depends(get_db)):
|
||||
project = db.query(models.Project).filter(models.Project.id == project_id).first()
|
||||
if not project:
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
@@ -75,13 +57,7 @@ def delete_project(
|
||||
# ---- Members ----
|
||||
|
||||
@router.post("/{project_id}/members", response_model=schemas.ProjectMemberResponse, status_code=status.HTTP_201_CREATED)
|
||||
def add_project_member(
|
||||
project_id: int,
|
||||
member: schemas.ProjectMemberCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: models.User = Depends(get_current_user_or_apikey),
|
||||
):
|
||||
check_project_role(db, current_user.id, project_id, min_role="mgr")
|
||||
def add_project_member(project_id: int, member: schemas.ProjectMemberCreate, db: Session = Depends(get_db)):
|
||||
project = db.query(models.Project).filter(models.Project.id == project_id).first()
|
||||
if not project:
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
@@ -106,13 +82,7 @@ def list_project_members(project_id: int, db: Session = Depends(get_db)):
|
||||
|
||||
|
||||
@router.delete("/{project_id}/members/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def remove_project_member(
|
||||
project_id: int,
|
||||
user_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: models.User = Depends(get_current_user_or_apikey),
|
||||
):
|
||||
check_project_role(db, current_user.id, project_id, min_role="admin")
|
||||
def remove_project_member(project_id: int, user_id: int, db: Session = Depends(get_db)):
|
||||
member = db.query(models.ProjectMember).filter(
|
||||
models.ProjectMember.project_id == project_id, models.ProjectMember.user_id == user_id
|
||||
).first()
|
||||
|
||||
107
app/init_wizard.py
Normal file
107
app/init_wizard.py
Normal file
@@ -0,0 +1,107 @@
|
||||
"""
|
||||
HarborForge initialization via AbstractWizard.
|
||||
|
||||
On startup, reads config from AbstractWizard and creates:
|
||||
- Admin user (if not exists)
|
||||
- Default project (if configured)
|
||||
"""
|
||||
import os
|
||||
import logging
|
||||
import httpx
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.models import models
|
||||
from app.api.deps import get_password_hash
|
||||
|
||||
logger = logging.getLogger("harborforge.init")
|
||||
|
||||
WIZARD_URL = os.getenv("WIZARD_URL", "http://wizard:8080")
|
||||
WIZARD_CONFIG = os.getenv("WIZARD_CONFIG", "harborforge.json")
|
||||
|
||||
|
||||
def fetch_wizard_config() -> dict | None:
|
||||
"""Fetch initialization config from AbstractWizard."""
|
||||
url = f"{WIZARD_URL}/api/v1/config/{WIZARD_CONFIG}"
|
||||
try:
|
||||
resp = httpx.get(url, timeout=10)
|
||||
if resp.status_code == 200:
|
||||
data = resp.json()
|
||||
# AbstractWizard wraps in {"data": ...}
|
||||
return data.get("data", data)
|
||||
elif resp.status_code == 404:
|
||||
logger.info("No wizard config found at %s, skipping initialization", url)
|
||||
return None
|
||||
else:
|
||||
logger.warning("Wizard returned %d: %s", resp.status_code, resp.text)
|
||||
return None
|
||||
except httpx.ConnectError:
|
||||
logger.info("AbstractWizard not available at %s, skipping", WIZARD_URL)
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.warning("Failed to fetch wizard config: %s", e)
|
||||
return None
|
||||
|
||||
|
||||
def init_admin_user(db: Session, admin_cfg: dict) -> None:
|
||||
"""Create admin user if not exists."""
|
||||
username = admin_cfg.get("username", "admin")
|
||||
existing = db.query(models.User).filter(models.User.username == username).first()
|
||||
if existing:
|
||||
logger.info("Admin user '%s' already exists (id=%d), skipping", username, existing.id)
|
||||
return
|
||||
|
||||
password = admin_cfg.get("password", "changeme")
|
||||
user = models.User(
|
||||
username=username,
|
||||
email=admin_cfg.get("email", f"{username}@harborforge.local"),
|
||||
full_name=admin_cfg.get("full_name", "Admin"),
|
||||
hashed_password=get_password_hash(password),
|
||||
is_admin=True,
|
||||
is_active=True,
|
||||
)
|
||||
db.add(user)
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
logger.info("Created admin user '%s' (id=%d)", username, user.id)
|
||||
|
||||
|
||||
def init_default_project(db: Session, project_cfg: dict, admin_user_id: int) -> None:
|
||||
"""Create default project if configured and not exists."""
|
||||
name = project_cfg.get("name", "Default")
|
||||
existing = db.query(models.Project).filter(models.Project.name == name).first()
|
||||
if existing:
|
||||
logger.info("Project '%s' already exists (id=%d), skipping", name, existing.id)
|
||||
return
|
||||
|
||||
project = models.Project(
|
||||
name=name,
|
||||
description=project_cfg.get("description", ""),
|
||||
owner_id=admin_user_id,
|
||||
)
|
||||
db.add(project)
|
||||
db.commit()
|
||||
db.refresh(project)
|
||||
logger.info("Created default project '%s' (id=%d)", name, project.id)
|
||||
|
||||
|
||||
def run_init(db: Session) -> None:
|
||||
"""Main initialization entry point."""
|
||||
config = fetch_wizard_config()
|
||||
if not config:
|
||||
return
|
||||
|
||||
logger.info("Running HarborForge initialization from AbstractWizard")
|
||||
|
||||
# Admin user
|
||||
admin_cfg = config.get("admin")
|
||||
if admin_cfg:
|
||||
init_admin_user(db, admin_cfg)
|
||||
|
||||
# Default project
|
||||
project_cfg = config.get("default_project")
|
||||
if project_cfg:
|
||||
admin = db.query(models.User).filter(models.User.is_admin == True).first()
|
||||
if admin:
|
||||
init_default_project(db, project_cfg, admin.id)
|
||||
|
||||
logger.info("Initialization complete")
|
||||
10
app/main.py
10
app/main.py
@@ -46,6 +46,14 @@ app.include_router(misc_router)
|
||||
# Run database migration on startup
|
||||
@app.on_event("startup")
|
||||
def startup():
|
||||
from app.core.config import Base, engine
|
||||
from app.core.config import Base, engine, SessionLocal
|
||||
from app.models import webhook, apikey, activity, milestone, notification, worklog
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
# Initialize from AbstractWizard (admin user, default project, etc.)
|
||||
from app.init_wizard import run_init
|
||||
db = SessionLocal()
|
||||
try:
|
||||
run_init(db)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
"""Activity logging helper — auto-record CRUD operations."""
|
||||
import json
|
||||
from sqlalchemy.orm import Session
|
||||
from app.models.activity import ActivityLog
|
||||
|
||||
|
||||
def log_activity(db: Session, action: str, entity_type: str, entity_id: int, user_id: int = None, details: dict = None):
|
||||
"""Record an activity log entry."""
|
||||
entry = ActivityLog(
|
||||
action=action,
|
||||
entity_type=entity_type,
|
||||
entity_id=entity_id,
|
||||
user_id=user_id,
|
||||
details=json.dumps(details) if details else None,
|
||||
)
|
||||
db.add(entry)
|
||||
db.commit()
|
||||
return entry
|
||||
Reference in New Issue
Block a user