Fix milestones 422 + acc-mgr user + reset-apikey endpoint

- Fix: /milestones?project_id= now accepts project_code (str) not just int
- Add: built-in acc-mgr user created on wizard init (account-manager role, no login, undeletable)
- Add: POST /users/{id}/reset-apikey with permission-based access control
- Add: GET /auth/me/apikey-permissions for frontend capability check
- Add: user.reset-self-apikey and user.reset-apikey permissions
- Protect admin and acc-mgr accounts from deletion
- Block acc-mgr from login (/auth/token returns 403)
This commit is contained in:
zhi
2026-03-22 05:39:03 +00:00
parent d17072881b
commit 88931d822d
4 changed files with 155 additions and 2 deletions

View File

@@ -173,6 +173,11 @@ def delete_user(
raise HTTPException(status_code=404, detail="User not found")
if current_user.id == user.id:
raise HTTPException(status_code=400, detail="You cannot delete your own account")
# Protect built-in accounts from deletion
if user.is_admin:
raise HTTPException(status_code=400, detail="Admin accounts cannot be deleted")
if user.username == "acc-mgr":
raise HTTPException(status_code=400, detail="The acc-mgr account is a built-in account and cannot be deleted")
try:
db.delete(user)
db.commit()
@@ -182,6 +187,65 @@ def delete_user(
return None
@router.post("/{identifier}/reset-apikey")
def reset_user_apikey(
identifier: str,
db: Session = Depends(get_db),
current_user: models.User = Depends(get_current_user),
):
"""Reset (regenerate) a user's API key.
Permission rules:
- user.reset-apikey: can reset any user's API key
- user.reset-self-apikey: can reset only own API key
- admin: can reset any user's API key
"""
import secrets
from app.models.apikey import APIKey
target_user = _find_user_by_id_or_username(db, identifier)
if not target_user:
raise HTTPException(status_code=404, detail="User not found")
is_self = current_user.id == target_user.id
can_reset_any = _has_global_permission(db, current_user, "user.reset-apikey")
can_reset_self = _has_global_permission(db, current_user, "user.reset-self-apikey")
if not (can_reset_any or (is_self and can_reset_self)):
raise HTTPException(status_code=403, detail="API key reset permission required")
# Find existing active API key for target user, or create one
existing_key = db.query(APIKey).filter(
APIKey.user_id == target_user.id,
APIKey.is_active == True,
).first()
new_key_value = secrets.token_hex(32)
if existing_key:
# Deactivate old key
existing_key.is_active = False
db.flush()
# Create new key
new_key = APIKey(
key=new_key_value,
name=f"{target_user.username}-key",
user_id=target_user.id,
is_active=True,
)
db.add(new_key)
db.commit()
db.refresh(new_key)
return {
"user_id": target_user.id,
"username": target_user.username,
"api_key": new_key_value,
"message": "API key has been reset. Please save this key — it will not be shown again.",
}
class WorkLogResponse(BaseModel):
id: int
task_id: int