jogosultsági szintek RBAC beállítva tesztelve
This commit is contained in:
@@ -33,7 +33,8 @@ router = APIRouter()
|
||||
@router.get("/health-monitor", tags=["Sentinel Monitoring"])
|
||||
async def get_system_health(
|
||||
db: AsyncSession = Depends(deps.get_db),
|
||||
admin: User = Depends(deps.get_current_admin)
|
||||
current_user: User = Depends(deps.get_current_active_user),
|
||||
_ = Depends(deps.RequirePermission("settings:view")),
|
||||
):
|
||||
stats = {}
|
||||
|
||||
@@ -63,7 +64,8 @@ async def get_system_health(
|
||||
@router.get("/pending-actions", response_model=List[Any], tags=["Sentinel Security"])
|
||||
async def list_pending_actions(
|
||||
db: AsyncSession = Depends(deps.get_db),
|
||||
admin: User = Depends(deps.get_current_admin)
|
||||
current_user: User = Depends(deps.get_current_active_user),
|
||||
_ = Depends(deps.RequirePermission("settings:view")),
|
||||
):
|
||||
stmt = select(PendingAction).where(PendingAction.status == ActionStatus.pending)
|
||||
result = await db.execute(stmt)
|
||||
@@ -73,7 +75,8 @@ async def list_pending_actions(
|
||||
async def approve_action(
|
||||
action_id: int,
|
||||
db: AsyncSession = Depends(deps.get_db),
|
||||
admin: User = Depends(deps.get_current_admin)
|
||||
current_user: User = Depends(deps.get_current_active_user),
|
||||
_ = Depends(deps.RequirePermission("settings:edit")),
|
||||
):
|
||||
try:
|
||||
await security_service.approve_action(db, admin.id, action_id)
|
||||
@@ -84,7 +87,8 @@ async def approve_action(
|
||||
@router.get("/parameters", tags=["Dynamic Configuration"])
|
||||
async def list_all_parameters(
|
||||
db: AsyncSession = Depends(deps.get_db),
|
||||
admin: User = Depends(deps.get_current_admin)
|
||||
current_user: User = Depends(deps.get_current_active_user),
|
||||
_ = Depends(deps.RequirePermission("settings:view")),
|
||||
):
|
||||
result = await db.execute(select(SystemParameter))
|
||||
return result.scalars().all()
|
||||
@@ -93,7 +97,8 @@ async def list_all_parameters(
|
||||
async def set_parameter(
|
||||
config: ConfigUpdate,
|
||||
db: AsyncSession = Depends(deps.get_db),
|
||||
admin: User = Depends(deps.get_current_admin)
|
||||
current_user: User = Depends(deps.get_current_active_user),
|
||||
_ = Depends(deps.RequirePermission("settings:edit")),
|
||||
):
|
||||
query = text("""
|
||||
INSERT INTO system.system_parameters (key, value, scope_level, scope_id, category, last_modified_by)
|
||||
@@ -124,7 +129,8 @@ async def get_scoped_parameter(
|
||||
region_id: Optional[str] = None,
|
||||
country_code: Optional[str] = None,
|
||||
db: AsyncSession = Depends(deps.get_db),
|
||||
admin: User = Depends(deps.get_current_admin)
|
||||
current_user: User = Depends(deps.get_current_active_user),
|
||||
_ = Depends(deps.RequirePermission("settings:view")),
|
||||
):
|
||||
"""
|
||||
Hierarchikus paraméterlekérdezés a következő prioritással:
|
||||
@@ -143,7 +149,8 @@ async def get_scoped_parameter(
|
||||
@router.post("/translations/sync", tags=["System Utilities"])
|
||||
async def sync_translations_to_json(
|
||||
db: AsyncSession = Depends(deps.get_db),
|
||||
admin: User = Depends(deps.get_current_admin)
|
||||
current_user: User = Depends(deps.get_current_active_user),
|
||||
_ = Depends(deps.RequirePermission("settings:edit")),
|
||||
):
|
||||
await TranslationService.export_to_json(db)
|
||||
return {"message": "JSON fájlok frissítve."}
|
||||
@@ -151,7 +158,8 @@ async def sync_translations_to_json(
|
||||
|
||||
@router.get("/ping", tags=["Admin Test"])
|
||||
async def admin_ping(
|
||||
current_user: User = Depends(deps.get_current_admin)
|
||||
current_user: User = Depends(deps.get_current_active_user),
|
||||
_ = Depends(deps.RequirePermission("settings:view")),
|
||||
):
|
||||
"""
|
||||
Egyszerű ping végpont admin jogosultság ellenőrzéséhez.
|
||||
@@ -166,8 +174,9 @@ async def admin_ping(
|
||||
async def ban_user(
|
||||
user_id: int,
|
||||
reason: str = Body(..., embed=True),
|
||||
current_admin: User = Depends(deps.get_current_admin),
|
||||
db: AsyncSession = Depends(deps.get_db)
|
||||
db: AsyncSession = Depends(deps.get_db),
|
||||
current_user: User = Depends(deps.get_current_active_user),
|
||||
_ = Depends(deps.RequirePermission("user:manage")),
|
||||
):
|
||||
"""
|
||||
Felhasználó tiltása (Ban Hammer).
|
||||
@@ -205,7 +214,7 @@ async def ban_user(
|
||||
|
||||
# 4. Audit log létrehozása
|
||||
audit_log = SecurityAuditLog(
|
||||
user_id=current_admin.id,
|
||||
user_id=current_user.id,
|
||||
action="ban_user",
|
||||
target_user_id=user_id,
|
||||
details=f"User banned. Reason: {reason}",
|
||||
@@ -226,8 +235,9 @@ async def ban_user(
|
||||
@router.post("/marketplace/services/{staging_id}/approve", tags=["Marketplace Moderation"])
|
||||
async def approve_staged_service(
|
||||
staging_id: int,
|
||||
current_admin: User = Depends(deps.get_current_admin),
|
||||
db: AsyncSession = Depends(deps.get_db)
|
||||
db: AsyncSession = Depends(deps.get_db),
|
||||
current_user: User = Depends(deps.get_current_active_user),
|
||||
_ = Depends(deps.RequirePermission("moderation:manage")),
|
||||
):
|
||||
"""
|
||||
Szerviz jóváhagyása a Piactéren (Kék Pipa).
|
||||
@@ -255,7 +265,7 @@ async def approve_staged_service(
|
||||
|
||||
# Audit log
|
||||
audit_log = SecurityAuditLog(
|
||||
user_id=current_admin.id,
|
||||
user_id=current_user.id,
|
||||
action="approve_service",
|
||||
target_staging_id=staging_id,
|
||||
details=f"Service staging approved: {staging.service_name}",
|
||||
@@ -294,8 +304,9 @@ class PenaltyRequest(BaseModel):
|
||||
async def trigger_ai_pipeline(
|
||||
service_id: int,
|
||||
background_tasks: BackgroundTasks,
|
||||
current_admin: User = Depends(deps.get_current_admin),
|
||||
db: AsyncSession = Depends(deps.get_db)
|
||||
db: AsyncSession = Depends(deps.get_db),
|
||||
current_user: User = Depends(deps.get_current_active_user),
|
||||
_ = Depends(deps.RequirePermission("services:manage")),
|
||||
):
|
||||
"""
|
||||
AI Pipeline manuális indítása egy adott szerviz profilra.
|
||||
@@ -318,7 +329,7 @@ async def trigger_ai_pipeline(
|
||||
|
||||
# Audit log
|
||||
audit_log = SecurityAuditLog(
|
||||
user_id=current_admin.id,
|
||||
user_id=current_user.id,
|
||||
action="trigger_ai_pipeline",
|
||||
target_service_id=service_id,
|
||||
details=f"AI pipeline manually triggered for service {service_id}",
|
||||
@@ -354,8 +365,9 @@ async def run_validation_pipeline(profile_id: int):
|
||||
async def update_service_location(
|
||||
service_id: int,
|
||||
location: LocationUpdate,
|
||||
current_admin: User = Depends(deps.get_current_admin),
|
||||
db: AsyncSession = Depends(deps.get_db)
|
||||
db: AsyncSession = Depends(deps.get_db),
|
||||
current_user: User = Depends(deps.get_current_active_user),
|
||||
_ = Depends(deps.RequirePermission("services:manage")),
|
||||
):
|
||||
"""
|
||||
Szerviz térképes mozgatása (Koordináta frissítés).
|
||||
@@ -379,7 +391,7 @@ async def update_service_location(
|
||||
|
||||
# Audit log
|
||||
audit_log = SecurityAuditLog(
|
||||
user_id=current_admin.id,
|
||||
user_id=current_user.id,
|
||||
action="update_service_location",
|
||||
target_service_id=service_id,
|
||||
details=f"Service location updated to lat={location.latitude}, lon={location.longitude}",
|
||||
@@ -401,8 +413,9 @@ async def update_service_location(
|
||||
async def apply_gamification_penalty(
|
||||
user_id: int,
|
||||
penalty: PenaltyRequest,
|
||||
current_admin: User = Depends(deps.get_current_admin),
|
||||
db: AsyncSession = Depends(deps.get_db)
|
||||
db: AsyncSession = Depends(deps.get_db),
|
||||
current_user: User = Depends(deps.get_current_active_user),
|
||||
_ = Depends(deps.RequirePermission("gamification:manage")),
|
||||
):
|
||||
"""
|
||||
Gamification büntetés kiosztása egy felhasználónak.
|
||||
@@ -446,7 +459,7 @@ async def apply_gamification_penalty(
|
||||
|
||||
# Audit log
|
||||
audit_log = SecurityAuditLog(
|
||||
user_id=current_admin.id,
|
||||
user_id=current_user.id,
|
||||
action="apply_gamification_penalty",
|
||||
target_user_id=user_id,
|
||||
details=f"Gamification penalty applied: level change {penalty.penalty_level}, reason: {penalty.reason}",
|
||||
@@ -485,7 +498,8 @@ async def list_users(
|
||||
is_active: Optional[bool] = Query(None, description="Aktív státusz szűrés"),
|
||||
is_deleted: Optional[bool] = Query(None, description="Törölt státusz szűrés"),
|
||||
db: AsyncSession = Depends(deps.get_db),
|
||||
current_admin: User = Depends(deps.get_current_admin),
|
||||
current_user: User = Depends(deps.get_current_active_user),
|
||||
_ = Depends(deps.RequirePermission("user:view")),
|
||||
):
|
||||
"""
|
||||
Felhasználók listázása lapozással és célzott kereséssel.
|
||||
@@ -646,7 +660,8 @@ async def list_users(
|
||||
async def bulk_user_action(
|
||||
request: BulkActionRequest,
|
||||
db: AsyncSession = Depends(deps.get_db),
|
||||
current_admin: User = Depends(deps.get_current_admin),
|
||||
current_user: User = Depends(deps.get_current_active_user),
|
||||
_ = Depends(deps.RequirePermission("user:manage")),
|
||||
):
|
||||
"""
|
||||
Csoportos műveletek felhasználókon.
|
||||
@@ -658,7 +673,7 @@ async def bulk_user_action(
|
||||
- **restore**: Lágy törlés visszaállítása (is_deleted=False, deleted_at=None). Rang >= 90 (Admin) szükséges.
|
||||
- **hard_delete**: Végleges törlés az adatbázisból. Rang >= 100 (Superadmin) szükséges!
|
||||
"""
|
||||
role_key = current_admin.role.value.upper() if hasattr(current_admin.role, "value") else str(current_admin.role).upper()
|
||||
role_key = current_user.role.value.upper() if hasattr(current_user.role, "value") else str(current_user.role).upper()
|
||||
from app.core.security import DEFAULT_RANK_MAP
|
||||
admin_rank = DEFAULT_RANK_MAP.get(role_key, 0)
|
||||
|
||||
@@ -698,7 +713,7 @@ async def bulk_user_action(
|
||||
affected_count = 0
|
||||
|
||||
for user in users:
|
||||
if user.role == UserRole.SUPERADMIN and user.id != current_admin.id:
|
||||
if user.role == UserRole.SUPERADMIN and user.id != current_user.id:
|
||||
continue
|
||||
|
||||
if request.action == "ban":
|
||||
@@ -717,7 +732,7 @@ async def bulk_user_action(
|
||||
affected_count += 1
|
||||
|
||||
audit_log = SecurityAuditLog(
|
||||
user_id=current_admin.id,
|
||||
user_id=current_user.id,
|
||||
action=f"bulk_{request.action}",
|
||||
details=f"Bulk action '{request.action}' on {affected_count} users. IDs: {request.user_ids}",
|
||||
is_critical=(request.action in ("hard_delete", "ban")),
|
||||
@@ -745,7 +760,8 @@ async def search_organizations(
|
||||
name: str = Query(..., min_length=2, description="Cégnév vagy garázsnév keresése (ILIKE)"),
|
||||
limit: int = Query(20, ge=1, le=100, description="Maximum találatok száma"),
|
||||
db: AsyncSession = Depends(deps.get_db),
|
||||
current_user: User = Depends(deps.get_current_admin),
|
||||
current_user: User = Depends(deps.get_current_active_user),
|
||||
_ = Depends(deps.RequirePermission("org:view")),
|
||||
):
|
||||
"""
|
||||
🔍 Szervezetek / Garázsok keresése név alapján.
|
||||
|
||||
@@ -2,8 +2,12 @@
|
||||
🏢 Admin Garages (Organizations) CRM API
|
||||
|
||||
Végpontok:
|
||||
GET /admin/organizations — Garázsok listázása előfizetési adatokkal
|
||||
GET /admin/organizations — Garázsok listázása előfizetési adatokkal
|
||||
GET /admin/organizations/{org_id}/details — Garázs részletes adatai (General Tab)
|
||||
PATCH /admin/organizations/{org_id}/subscription — Előfizetés módosítása
|
||||
POST /admin/organizations/{org_id}/members — Új tag hozzáadása a garázshoz
|
||||
PUT /admin/organizations/{org_id}/members/{member_id} — Tag adatainak módosítása
|
||||
DELETE /admin/organizations/{org_id}/members/{member_id} — Tag eltávolítása
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -13,16 +17,23 @@ from datetime import datetime
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from sqlalchemy import select, func, update as sa_update
|
||||
from sqlalchemy import select, func, update as sa_update, delete as sa_delete
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.orm import selectinload, joinedload, contains_eager
|
||||
from sqlalchemy.orm import selectinload, joinedload
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.api import deps
|
||||
from app.db.session import get_db
|
||||
from app.models.core_logic import SubscriptionTier, OrganizationSubscription
|
||||
from app.models.marketplace.organization import Organization, OrganizationMember
|
||||
from app.models.identity import User
|
||||
from app.models.fleet.organization import ContactPerson
|
||||
from app.models.identity import User, Person
|
||||
from app.schemas.organization import (
|
||||
OrganizationMemberCreate,
|
||||
OrganizationMemberUpdate,
|
||||
OrganizationMemberResponse,
|
||||
PersonBrief,
|
||||
)
|
||||
|
||||
logger = logging.getLogger("admin-organizations")
|
||||
router = APIRouter()
|
||||
@@ -86,6 +97,63 @@ class GarageListResponse(BaseModel):
|
||||
garages: List[GarageListItem]
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Pydantic Schemas — Garage Details
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class ContactPersonInfo(BaseModel):
|
||||
"""Kapcsolattartó személy adatai."""
|
||||
id: int
|
||||
full_name: str = ""
|
||||
role: str = ""
|
||||
department: Optional[str] = None
|
||||
phone: Optional[str] = None
|
||||
email: Optional[str] = None
|
||||
is_primary: bool = False
|
||||
|
||||
|
||||
class SubscriptionSummary(BaseModel):
|
||||
"""Előfizetés összefoglaló."""
|
||||
tier_name: str = "Free/Fallback"
|
||||
tier_level: int = 0
|
||||
valid_from: Optional[str] = None
|
||||
expires_at: Optional[str] = None
|
||||
is_active: bool = True
|
||||
asset_count: int = 0
|
||||
asset_limit: int = 1
|
||||
|
||||
|
||||
class GarageDetailsResponse(BaseModel):
|
||||
"""Garázs részletes adatai (General Tab)."""
|
||||
# Szervezet adatok
|
||||
id: int
|
||||
name: str
|
||||
full_name: str
|
||||
display_name: Optional[str] = None
|
||||
status: str
|
||||
is_active: bool
|
||||
is_verified: bool
|
||||
org_type: str
|
||||
# Cím adatok
|
||||
address_city: Optional[str] = None
|
||||
address_zip: Optional[str] = None
|
||||
address_street_name: Optional[str] = None
|
||||
address_street_type: Optional[str] = None
|
||||
address_house_number: Optional[str] = None
|
||||
tax_number: Optional[str] = None
|
||||
reg_number: Optional[str] = None
|
||||
# Előfizetés
|
||||
subscription: Optional[SubscriptionSummary] = None
|
||||
# Kapcsolattartó
|
||||
primary_contact: Optional[ContactPersonInfo] = None
|
||||
# Meta
|
||||
created_at: Optional[str] = None
|
||||
member_count: int = 0
|
||||
# P0: Full member list with nested person data
|
||||
members: List[OrganizationMemberResponse] = []
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# GET / — Garázsok listázása
|
||||
# =============================================================================
|
||||
@@ -104,7 +172,8 @@ async def list_organizations(
|
||||
status_filter: Optional[str] = Query(None, description="Szűrés státusz szerint (active/inactive/suspended/pending_verification)"),
|
||||
org_type_filter: Optional[str] = Query(None, description="Szűrés szervezet típus szerint"),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
admin: User = Depends(deps.get_current_admin),
|
||||
current_user: User = Depends(deps.get_current_active_user),
|
||||
_ = Depends(deps.RequirePermission("org:view")),
|
||||
) -> GarageListResponse:
|
||||
"""
|
||||
Garázsok / Szervezetek listázása lapozással és kereséssel.
|
||||
@@ -236,6 +305,200 @@ async def list_organizations(
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# GET /{org_id}/details — Garázs részletes adatai (General Tab)
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{org_id}/details",
|
||||
response_model=GarageDetailsResponse,
|
||||
summary="Garázs részletes adatai",
|
||||
description="Visszaadja egy garázs teljes adatait, előfizetési összefoglalóját, "
|
||||
"elsődleges kapcsolattartóját és taglistáját a General Tab számára.",
|
||||
)
|
||||
async def get_organization_details(
|
||||
org_id: int,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(deps.get_current_active_user),
|
||||
_ = Depends(deps.RequirePermission("org:view")),
|
||||
) -> GarageDetailsResponse:
|
||||
"""
|
||||
Garázs részletes adatainak lekérése.
|
||||
|
||||
Visszaadja:
|
||||
- Teljes szervezet adatokat (név, cím, adószám, státusz)
|
||||
- Előfizetés összefoglalót (tier név, lejárat, járműszám/korlát)
|
||||
- Elsődleges kapcsolattartó adatait (fleet.contact_persons)
|
||||
- Tagok teljes listáját (OrganizationMember) nested Person adatokkal
|
||||
"""
|
||||
# 1. Szervezet lekérése subscription_tier kapcsolattal
|
||||
org_stmt = (
|
||||
select(Organization)
|
||||
.options(
|
||||
selectinload(Organization.subscription_tier),
|
||||
)
|
||||
.where(Organization.id == org_id)
|
||||
)
|
||||
org_result = await db.execute(org_stmt)
|
||||
org = org_result.scalar_one_or_none()
|
||||
|
||||
if not org:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"Szervezet nem található ID-vel: {org_id}",
|
||||
)
|
||||
|
||||
# 2. Aktív előfizetés lekérése
|
||||
sub_stmt = (
|
||||
select(OrganizationSubscription)
|
||||
.options(selectinload(OrganizationSubscription.tier))
|
||||
.where(
|
||||
OrganizationSubscription.org_id == org_id,
|
||||
OrganizationSubscription.is_active == True,
|
||||
)
|
||||
.order_by(OrganizationSubscription.id.desc())
|
||||
.limit(1)
|
||||
)
|
||||
sub_result = await db.execute(sub_stmt)
|
||||
active_sub = sub_result.scalar_one_or_none()
|
||||
|
||||
# 3. Tagok lekérése eager loading-gal (User + Person)
|
||||
members_stmt = (
|
||||
select(OrganizationMember)
|
||||
.options(
|
||||
selectinload(OrganizationMember.user).selectinload(User.person),
|
||||
selectinload(OrganizationMember.person),
|
||||
)
|
||||
.where(
|
||||
OrganizationMember.organization_id == org_id,
|
||||
)
|
||||
.order_by(OrganizationMember.id)
|
||||
)
|
||||
members_result = await db.execute(members_stmt)
|
||||
member_rows = members_result.scalars().all()
|
||||
|
||||
# Taglétszám (aktív tagok száma)
|
||||
member_count = sum(1 for m in member_rows if m.status == "active")
|
||||
|
||||
# 4. Elsődleges kapcsolattartó lekérése
|
||||
contact_stmt = (
|
||||
select(ContactPerson)
|
||||
.options(selectinload(ContactPerson.person))
|
||||
.where(
|
||||
ContactPerson.organization_id == org_id,
|
||||
ContactPerson.is_primary == True,
|
||||
)
|
||||
.limit(1)
|
||||
)
|
||||
contact_result = await db.execute(contact_stmt)
|
||||
contact = contact_result.scalar_one_or_none()
|
||||
|
||||
# 5. Subscription összefoglaló
|
||||
subscription_summary = None
|
||||
if active_sub and active_sub.tier:
|
||||
rules = active_sub.tier.rules or {}
|
||||
asset_limit = (
|
||||
rules.get("max_vehicles")
|
||||
or active_sub.tier.feature_capabilities.get("max_vehicles")
|
||||
or 1
|
||||
)
|
||||
subscription_summary = SubscriptionSummary(
|
||||
tier_name=active_sub.tier.name,
|
||||
tier_level=active_sub.tier.tier_level,
|
||||
valid_from=active_sub.valid_from.isoformat() if active_sub.valid_from else None,
|
||||
expires_at=active_sub.valid_until.isoformat() if active_sub.valid_until else None,
|
||||
is_active=active_sub.is_active,
|
||||
asset_count=0,
|
||||
asset_limit=asset_limit,
|
||||
)
|
||||
elif org.subscription_tier:
|
||||
rules = org.subscription_tier.rules or {}
|
||||
asset_limit = (
|
||||
rules.get("max_vehicles")
|
||||
or org.subscription_tier.feature_capabilities.get("max_vehicles")
|
||||
or 1
|
||||
)
|
||||
subscription_summary = SubscriptionSummary(
|
||||
tier_name=org.subscription_tier.name,
|
||||
tier_level=org.subscription_tier.tier_level,
|
||||
expires_at=org.subscription_expires_at.isoformat() if org.subscription_expires_at else None,
|
||||
asset_limit=asset_limit,
|
||||
)
|
||||
|
||||
# 6. Kapcsolattartó adatok
|
||||
primary_contact = None
|
||||
if contact and contact.person:
|
||||
primary_contact = ContactPersonInfo(
|
||||
id=contact.id,
|
||||
full_name=f"{contact.person.last_name} {contact.person.first_name}",
|
||||
role=contact.role,
|
||||
department=contact.department,
|
||||
phone=contact.person.phone,
|
||||
is_primary=contact.is_primary,
|
||||
)
|
||||
|
||||
# 7. Tagok összeállítása nested Person adatokkal
|
||||
members_list: List[OrganizationMemberResponse] = []
|
||||
for m in member_rows:
|
||||
person_data = None
|
||||
# Try to get Person from the member's direct person relationship first
|
||||
person_obj = m.person
|
||||
# Fallback: get Person through the User relationship
|
||||
if not person_obj and m.user and m.user.person:
|
||||
person_obj = m.user.person
|
||||
|
||||
if person_obj:
|
||||
# Get email from the user record
|
||||
email = m.user.email if m.user else None
|
||||
person_data = PersonBrief(
|
||||
first_name=person_obj.first_name or "",
|
||||
last_name=person_obj.last_name or "",
|
||||
email=email,
|
||||
phone=person_obj.phone,
|
||||
)
|
||||
|
||||
members_list.append(OrganizationMemberResponse(
|
||||
id=m.id,
|
||||
user_id=m.user_id,
|
||||
organization_id=m.organization_id,
|
||||
role=m.role,
|
||||
status=m.status or "active",
|
||||
is_verified=m.is_verified,
|
||||
person=person_data,
|
||||
created_at=m.created_at.isoformat() if m.created_at else None,
|
||||
updated_at=m.updated_at.isoformat() if m.updated_at else None,
|
||||
))
|
||||
|
||||
logger.info(
|
||||
f"Admin {current_user.id} ({current_user.email}) fetched details for org {org_id} "
|
||||
f"({org.full_name}) — {len(members_list)} members"
|
||||
)
|
||||
|
||||
return GarageDetailsResponse(
|
||||
id=org.id,
|
||||
name=org.name,
|
||||
full_name=org.full_name,
|
||||
display_name=org.display_name,
|
||||
status=org.status,
|
||||
is_active=org.is_active,
|
||||
is_verified=org.is_verified,
|
||||
org_type=org.org_type.value if hasattr(org.org_type, "value") else str(org.org_type),
|
||||
address_city=org.address_city,
|
||||
address_zip=org.address_zip,
|
||||
address_street_name=org.address_street_name,
|
||||
address_street_type=org.address_street_type,
|
||||
address_house_number=org.address_house_number,
|
||||
tax_number=org.tax_number,
|
||||
reg_number=org.reg_number,
|
||||
subscription=subscription_summary,
|
||||
primary_contact=primary_contact,
|
||||
created_at=org.created_at.isoformat() if org.created_at else None,
|
||||
member_count=member_count,
|
||||
members=members_list,
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# PATCH /{org_id}/subscription — Előfizetés módosítása
|
||||
# =============================================================================
|
||||
@@ -251,7 +514,8 @@ async def update_org_subscription(
|
||||
org_id: int,
|
||||
payload: OrgSubscriptionUpdate,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
admin: User = Depends(deps.get_current_admin),
|
||||
current_user: User = Depends(deps.get_current_active_user),
|
||||
_ = Depends(deps.RequirePermission("org:edit")),
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Garázs előfizetésének módosítása.
|
||||
@@ -326,7 +590,7 @@ async def update_org_subscription(
|
||||
await db.refresh(new_sub)
|
||||
|
||||
logger.info(
|
||||
f"Admin {admin.id} ({admin.email}) updated subscription for org {org_id}: "
|
||||
f"Admin {current_user.id} ({current_user.email}) updated subscription for org {org_id}: "
|
||||
f"tier_id={payload.tier_id}, tier_name={tier.name}, "
|
||||
f"valid_until={valid_until.isoformat()}"
|
||||
)
|
||||
@@ -344,3 +608,257 @@ async def update_org_subscription(
|
||||
"is_active": new_sub.is_active,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# POST /{org_id}/members — Új tag hozzáadása a garázshoz
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@router.post(
|
||||
"/{org_id}/members",
|
||||
response_model=OrganizationMemberResponse,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
summary="Új tag hozzáadása",
|
||||
description="Hozzáad egy felhasználót a garázshoz a megadott szerepkörrel.",
|
||||
)
|
||||
async def add_organization_member(
|
||||
org_id: int,
|
||||
payload: OrganizationMemberCreate,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(deps.get_current_active_user),
|
||||
_ = Depends(deps.RequirePermission("org:manage-members")),
|
||||
) -> OrganizationMemberResponse:
|
||||
"""
|
||||
Új tag hozzáadása egy garázshoz.
|
||||
|
||||
- Ellenőrzi, hogy a szervezet létezik-e.
|
||||
- Ellenőrzi, hogy a user_id létezik-e az identity.users táblában.
|
||||
- Ellenőrzi, hogy a felhasználó még nem tagja a szervezetnek.
|
||||
- Létrehozza az OrganizationMember rekordot.
|
||||
"""
|
||||
# 1. Ellenőrizzük a szervezetet
|
||||
org_stmt = select(Organization).where(Organization.id == org_id)
|
||||
org_result = await db.execute(org_stmt)
|
||||
org = org_result.scalar_one_or_none()
|
||||
|
||||
if not org:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"Szervezet nem található ID-vel: {org_id}",
|
||||
)
|
||||
|
||||
# 2. Ellenőrizzük a felhasználót
|
||||
user_stmt = select(User).where(User.id == payload.user_id)
|
||||
user_result = await db.execute(user_stmt)
|
||||
user = user_result.scalar_one_or_none()
|
||||
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"Felhasználó nem található ID-vel: {payload.user_id}",
|
||||
)
|
||||
|
||||
# 3. Ellenőrizzük, hogy a felhasználó még nem tagja a szervezetnek
|
||||
existing_stmt = select(OrganizationMember).where(
|
||||
OrganizationMember.organization_id == org_id,
|
||||
OrganizationMember.user_id == payload.user_id,
|
||||
OrganizationMember.status != "archived",
|
||||
)
|
||||
existing_result = await db.execute(existing_stmt)
|
||||
existing = existing_result.scalar_one_or_none()
|
||||
|
||||
if existing:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail=f"A felhasználó (ID: {payload.user_id}) már tagja ennek a szervezetnek.",
|
||||
)
|
||||
|
||||
# 4. Létrehozzuk az új tag rekordot
|
||||
person_id = user.person_id
|
||||
new_member = OrganizationMember(
|
||||
organization_id=org_id,
|
||||
user_id=payload.user_id,
|
||||
person_id=person_id,
|
||||
role=payload.role,
|
||||
status=payload.status,
|
||||
is_verified=False,
|
||||
)
|
||||
db.add(new_member)
|
||||
await db.commit()
|
||||
await db.refresh(new_member)
|
||||
|
||||
# 5. Visszatöltjük a kapcsolódó adatokat a válaszhoz
|
||||
await db.refresh(new_member, attribute_names=["user", "person"])
|
||||
|
||||
# Person adatok összeállítása
|
||||
person_data = None
|
||||
person_obj = new_member.person
|
||||
if not person_obj and new_member.user and new_member.user.person:
|
||||
person_obj = new_member.user.person
|
||||
|
||||
if person_obj:
|
||||
person_data = PersonBrief(
|
||||
first_name=person_obj.first_name or "",
|
||||
last_name=person_obj.last_name or "",
|
||||
email=user.email,
|
||||
phone=person_obj.phone,
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"Admin {current_user.id} ({current_user.email}) added member user_id={payload.user_id} "
|
||||
f"to org {org_id} ({org.full_name}) with role={payload.role}"
|
||||
)
|
||||
|
||||
return OrganizationMemberResponse(
|
||||
id=new_member.id,
|
||||
user_id=new_member.user_id,
|
||||
organization_id=new_member.organization_id,
|
||||
role=new_member.role,
|
||||
status=new_member.status or "active",
|
||||
is_verified=new_member.is_verified,
|
||||
person=person_data,
|
||||
created_at=new_member.created_at.isoformat() if new_member.created_at else None,
|
||||
updated_at=new_member.updated_at.isoformat() if new_member.updated_at else None,
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# PUT /{org_id}/members/{member_id} — Tag adatainak módosítása
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@router.put(
|
||||
"/{org_id}/members/{member_id}",
|
||||
response_model=OrganizationMemberResponse,
|
||||
summary="Tag adatainak módosítása",
|
||||
description="Frissíti egy meglévő tag szerepkörét és/vagy státuszát.",
|
||||
)
|
||||
async def update_organization_member(
|
||||
org_id: int,
|
||||
member_id: int,
|
||||
payload: OrganizationMemberUpdate,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(deps.get_current_active_user),
|
||||
_ = Depends(deps.RequirePermission("org:manage-members")),
|
||||
) -> OrganizationMemberResponse:
|
||||
"""
|
||||
Meglévő tag adatainak módosítása.
|
||||
|
||||
- Ellenőrzi, hogy a tag rekord létezik és a megadott szervezethez tartozik.
|
||||
- Frissíti a role és/vagy status mezőket.
|
||||
"""
|
||||
# 1. Ellenőrizzük a tag rekordot
|
||||
member_stmt = (
|
||||
select(OrganizationMember)
|
||||
.options(
|
||||
selectinload(OrganizationMember.user).selectinload(User.person),
|
||||
selectinload(OrganizationMember.person),
|
||||
)
|
||||
.where(
|
||||
OrganizationMember.id == member_id,
|
||||
OrganizationMember.organization_id == org_id,
|
||||
)
|
||||
)
|
||||
member_result = await db.execute(member_stmt)
|
||||
member = member_result.scalar_one_or_none()
|
||||
|
||||
if not member:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"Tag nem található (ID: {member_id}) a szervezetben (ID: {org_id}).",
|
||||
)
|
||||
|
||||
# 2. Frissítjük a mezőket
|
||||
if payload.role is not None:
|
||||
member.role = payload.role
|
||||
if payload.status is not None:
|
||||
member.status = payload.status
|
||||
|
||||
await db.commit()
|
||||
await db.refresh(member)
|
||||
|
||||
# 3. Person adatok összeállítása
|
||||
person_data = None
|
||||
person_obj = member.person
|
||||
if not person_obj and member.user and member.user.person:
|
||||
person_obj = member.user.person
|
||||
|
||||
if person_obj:
|
||||
email = member.user.email if member.user else None
|
||||
person_data = PersonBrief(
|
||||
first_name=person_obj.first_name or "",
|
||||
last_name=person_obj.last_name or "",
|
||||
email=email,
|
||||
phone=person_obj.phone,
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"Admin {current_user.id} ({current_user.email}) updated member {member_id} in org {org_id}: "
|
||||
f"role={payload.role}, status={payload.status}"
|
||||
)
|
||||
|
||||
return OrganizationMemberResponse(
|
||||
id=member.id,
|
||||
user_id=member.user_id,
|
||||
organization_id=member.organization_id,
|
||||
role=member.role,
|
||||
status=member.status or "active",
|
||||
is_verified=member.is_verified,
|
||||
person=person_data,
|
||||
created_at=member.created_at.isoformat() if member.created_at else None,
|
||||
updated_at=member.updated_at.isoformat() if member.updated_at else None,
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# DELETE /{org_id}/members/{member_id} — Tag eltávolítása
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/{org_id}/members/{member_id}",
|
||||
status_code=status.HTTP_200_OK,
|
||||
summary="Tag eltávolítása",
|
||||
description="Eltávolít egy tagot a garázsból (soft delete: status → archived).",
|
||||
)
|
||||
async def remove_organization_member(
|
||||
org_id: int,
|
||||
member_id: int,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(deps.get_current_active_user),
|
||||
_ = Depends(deps.RequirePermission("org:manage-members")),
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Tag eltávolítása a garázsból.
|
||||
|
||||
Soft delete megközelítés: a rekord nem törlődik, csak a status mező
|
||||
'archived' értékre változik. Ez megőrzi a történeti adatokat.
|
||||
"""
|
||||
# 1. Ellenőrizzük a tag rekordot
|
||||
member_stmt = select(OrganizationMember).where(
|
||||
OrganizationMember.id == member_id,
|
||||
OrganizationMember.organization_id == org_id,
|
||||
)
|
||||
member_result = await db.execute(member_stmt)
|
||||
member = member_result.scalar_one_or_none()
|
||||
|
||||
if not member:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"Tag nem található (ID: {member_id}) a szervezetben (ID: {org_id}).",
|
||||
)
|
||||
|
||||
# 2. Soft delete: archived státusz
|
||||
member.status = "archived"
|
||||
await db.commit()
|
||||
|
||||
logger.info(
|
||||
f"Admin {current_user.id} ({current_user.email}) removed member {member_id} from org {org_id} "
|
||||
f"(status → archived)"
|
||||
)
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"message": f"Tag (ID: {member_id}) eltávolítva a szervezetből (ID: {org_id}).",
|
||||
}
|
||||
|
||||
@@ -111,7 +111,8 @@ async def list_packages(
|
||||
description="Szűrés záró dátumig (available_until a lifecycle-ben, ISO formátum: YYYY-MM-DD)",
|
||||
),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
admin: User = Depends(deps.get_current_admin),
|
||||
current_user: User = Depends(deps.get_current_active_user),
|
||||
_ = Depends(deps.RequirePermission("subscription:manage")),
|
||||
) -> SubscriptionTierListResponse:
|
||||
"""
|
||||
Összes előfizetési csomag listázása.
|
||||
@@ -183,7 +184,8 @@ async def list_packages(
|
||||
async def create_package(
|
||||
payload: SubscriptionTierCreate,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
admin: User = Depends(deps.get_current_admin),
|
||||
current_user: User = Depends(deps.get_current_active_user),
|
||||
_ = Depends(deps.RequirePermission("subscription:manage")),
|
||||
) -> SubscriptionTierResponse:
|
||||
"""
|
||||
Új előfizetési csomag létrehozása.
|
||||
@@ -239,7 +241,7 @@ async def create_package(
|
||||
await db.refresh(tier)
|
||||
|
||||
logger.info(
|
||||
f"Admin {admin.id} ({admin.email}) created subscription tier: "
|
||||
f"Admin {current_user.id} ({current_user.email}) created subscription tier: "
|
||||
f"name={tier.name}, id={tier.id}, "
|
||||
f"is_default_fallback={tier.is_default_fallback}, "
|
||||
f"trial_days_on_signup={tier.trial_days_on_signup}"
|
||||
@@ -263,7 +265,8 @@ async def update_package(
|
||||
tier_id: int,
|
||||
payload: SubscriptionTierUpdate,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
admin: User = Depends(deps.get_current_admin),
|
||||
current_user: User = Depends(deps.get_current_active_user),
|
||||
_ = Depends(deps.RequirePermission("subscription:manage")),
|
||||
) -> SubscriptionTierResponse:
|
||||
"""
|
||||
Meglévő előfizetési csomag részleges frissítése.
|
||||
@@ -363,7 +366,7 @@ async def update_package(
|
||||
await db.refresh(tier)
|
||||
|
||||
logger.info(
|
||||
f"Admin {admin.id} ({admin.email}) updated subscription tier: "
|
||||
f"Admin {current_user.id} ({current_user.email}) updated subscription tier: "
|
||||
f"id={tier.id}, name={tier.name}, "
|
||||
f"is_default_fallback={tier.is_default_fallback}, "
|
||||
f"trial_days_on_signup={tier.trial_days_on_signup}"
|
||||
@@ -386,7 +389,8 @@ async def update_package(
|
||||
async def delete_package(
|
||||
tier_id: int,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
admin: User = Depends(deps.get_current_admin),
|
||||
current_user: User = Depends(deps.get_current_active_user),
|
||||
_ = Depends(deps.RequirePermission("subscription:manage")),
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Csomag logikai törlése (soft-delete / kivezetés).
|
||||
@@ -420,7 +424,7 @@ async def delete_package(
|
||||
await db.refresh(tier)
|
||||
|
||||
logger.info(
|
||||
f"Admin {admin.id} ({admin.email}) deactivated subscription tier: "
|
||||
f"Admin {current_user.id} ({current_user.email}) deactivated subscription tier: "
|
||||
f"id={tier.id}, name={tier.name}"
|
||||
)
|
||||
|
||||
|
||||
@@ -7,9 +7,16 @@ Provides admin-facing endpoints for:
|
||||
showing which roles can perform which actions.
|
||||
- PATCH /admin/permissions/override/{org_id} — Updates custom permissions
|
||||
for a specific organization (scope-based override).
|
||||
- GET /admin/permissions/roles — Returns all SystemRole records.
|
||||
- GET /admin/permissions — Returns all SystemPermission records.
|
||||
- PUT /admin/permissions/roles/{role_id}/permissions — Updates the granted
|
||||
permissions for a role (bulk toggle).
|
||||
|
||||
All endpoints are protected by Depends(RequireRole(...)) so only
|
||||
authorized staff (SUPERADMIN, ADMIN) can access them.
|
||||
All endpoints are protected by Depends(RequirePermission(...)) so only
|
||||
authorized staff with the appropriate DB-driven permissions can access them.
|
||||
|
||||
P0 Phase 6: Removed AdminAction enum dependency. All permission lookups
|
||||
are now fully DB-driven via system.role_permissions.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,20 +25,17 @@ from typing import Any, Dict, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, Body
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select, update
|
||||
from sqlalchemy import select, update, delete
|
||||
from sqlalchemy.orm import selectinload
|
||||
|
||||
from app.api import deps
|
||||
from app.api.deps import RequireRole, get_db, get_current_user
|
||||
from app.api.deps import get_db, get_current_user
|
||||
from app.models.identity import User, UserRole
|
||||
from app.models.marketplace.organization import Organization
|
||||
from app.models.system.rbac import SystemRole, SystemPermission, SystemRolePermission
|
||||
from app.services.rbac_service import (
|
||||
rbac_service,
|
||||
AdminAction,
|
||||
ScopeType,
|
||||
ADMIN_SCOPE_ACTIONS,
|
||||
MODERATOR_SCOPE_ACTIONS,
|
||||
SALES_REP_SCOPE_ACTIONS,
|
||||
SERVICE_MGR_SCOPE_ACTIONS,
|
||||
)
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
@@ -72,6 +76,53 @@ class PermissionOverrideResponse(BaseModel):
|
||||
message: str
|
||||
|
||||
|
||||
# ── RBAC Phase 4: DB-Driven Role & Permission Schemas ──
|
||||
|
||||
|
||||
class SystemRoleOut(BaseModel):
|
||||
"""Output schema for a SystemRole."""
|
||||
id: int
|
||||
name: str
|
||||
description: Optional[str] = None
|
||||
rank: int
|
||||
is_system: bool
|
||||
is_active: bool
|
||||
permission_ids: List[int] = []
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class SystemPermissionOut(BaseModel):
|
||||
"""Output schema for a SystemPermission."""
|
||||
id: int
|
||||
code: str
|
||||
domain: str
|
||||
action: str
|
||||
description: Optional[str] = None
|
||||
is_system: bool
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class RolePermissionsUpdateRequest(BaseModel):
|
||||
"""Request body for updating a role's granted permissions."""
|
||||
permission_ids: List[int] = Field(
|
||||
...,
|
||||
description="List of permission IDs that should be granted to this role",
|
||||
)
|
||||
|
||||
|
||||
class RolePermissionsUpdateResponse(BaseModel):
|
||||
"""Response after updating role permissions."""
|
||||
status: str
|
||||
role_id: int
|
||||
role_name: str
|
||||
granted_permission_ids: List[int]
|
||||
message: str
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────
|
||||
# Endpoints
|
||||
# ──────────────────────────────────────────────
|
||||
@@ -84,30 +135,39 @@ class PermissionOverrideResponse(BaseModel):
|
||||
summary="Get the full RBAC permission matrix",
|
||||
)
|
||||
async def get_permission_matrix(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
_ = Depends(RequireRole([UserRole.SUPERADMIN, UserRole.ADMIN])),
|
||||
_ = Depends(deps.RequirePermission("permissions:view")),
|
||||
):
|
||||
"""
|
||||
🔐 Returns the complete RBAC permission matrix.
|
||||
|
||||
Shows which roles are permitted to perform which admin actions.
|
||||
Only SUPERADMIN and ADMIN roles can access this endpoint.
|
||||
Protected by RequirePermission("permissions:view").
|
||||
|
||||
P0 Phase 6: Fully DB-driven. All permission codes are fetched
|
||||
from system.permissions and role mappings from system.role_permissions.
|
||||
|
||||
Returns:
|
||||
- matrix: List of {role, actions[]} entries
|
||||
- all_actions: Complete list of all possible admin actions
|
||||
- all_actions: Complete list of all possible permission codes
|
||||
"""
|
||||
# Fetch all permission codes from the DB
|
||||
all_perms_result = await db.execute(
|
||||
select(SystemPermission.code).order_by(SystemPermission.code)
|
||||
)
|
||||
all_actions = [row[0] for row in all_perms_result.all()]
|
||||
|
||||
# Fetch role permissions for each role
|
||||
matrix = []
|
||||
for role in [UserRole.SUPERADMIN, UserRole.ADMIN, UserRole.MODERATOR,
|
||||
UserRole.SALES_REP, UserRole.SERVICE_MGR]:
|
||||
actions = rbac_service.get_permitted_actions(role)
|
||||
actions = await rbac_service.get_permitted_actions(db, role)
|
||||
matrix.append(PermissionMatrixEntry(
|
||||
role=role.value,
|
||||
actions=sorted(actions),
|
||||
))
|
||||
|
||||
all_actions = [a.value for a in AdminAction]
|
||||
|
||||
return PermissionMatrixResponse(
|
||||
matrix=matrix,
|
||||
all_actions=sorted(all_actions),
|
||||
@@ -125,7 +185,7 @@ async def override_org_permission(
|
||||
payload: PermissionOverrideRequest,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
_ = Depends(RequireRole([UserRole.SUPERADMIN, UserRole.ADMIN])),
|
||||
_ = Depends(deps.RequirePermission("permissions:edit")),
|
||||
):
|
||||
"""
|
||||
🔐 Updates custom permissions for a specific organization.
|
||||
@@ -138,6 +198,8 @@ async def override_org_permission(
|
||||
the requesting admin has scope-based access to the target
|
||||
organization before applying the override.
|
||||
|
||||
P0 Phase 6: Action validation is now DB-driven via system.permissions.
|
||||
|
||||
Args:
|
||||
org_id: The target organization ID.
|
||||
payload.action: The action to override (e.g., "EDIT_DATA").
|
||||
@@ -146,9 +208,17 @@ async def override_org_permission(
|
||||
Returns:
|
||||
Confirmation of the override operation.
|
||||
"""
|
||||
# 1. Validate that the action exists
|
||||
valid_actions = {a.value for a in AdminAction}
|
||||
if payload.action not in valid_actions:
|
||||
# 1. Validate that the action exists in the DB
|
||||
perm_stmt = select(SystemPermission.code).where(
|
||||
SystemPermission.code == payload.action
|
||||
)
|
||||
perm_result = await db.execute(perm_stmt)
|
||||
if not perm_result.scalar_one_or_none():
|
||||
# Fetch all valid codes for the error message
|
||||
all_codes_result = await db.execute(
|
||||
select(SystemPermission.code).order_by(SystemPermission.code)
|
||||
)
|
||||
valid_actions = [row[0] for row in all_codes_result.all()]
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"Invalid action '{payload.action}'. Valid actions: {sorted(valid_actions)}",
|
||||
@@ -159,7 +229,7 @@ async def override_org_permission(
|
||||
await rbac_service.check_admin_access(
|
||||
db=db,
|
||||
user=current_user,
|
||||
action=AdminAction.EDIT_DATA,
|
||||
action="permissions:edit",
|
||||
target_org_id=org_id,
|
||||
)
|
||||
except PermissionError as e:
|
||||
@@ -180,17 +250,12 @@ async def override_org_permission(
|
||||
)
|
||||
|
||||
# 4. Update custom permissions via the settings JSONB field
|
||||
# The Organization model has a `settings` JSONB column that stores
|
||||
# dynamic org-level configuration. We store permission overrides
|
||||
# under a "permission_overrides" key within settings.
|
||||
if not isinstance(org.settings, dict):
|
||||
org.settings = {}
|
||||
|
||||
# Ensure the permission_overrides sub-key exists
|
||||
if "permission_overrides" not in org.settings:
|
||||
org.settings["permission_overrides"] = {}
|
||||
|
||||
# Apply the override
|
||||
org.settings["permission_overrides"][payload.action] = payload.granted
|
||||
|
||||
# 5. Persist
|
||||
@@ -210,3 +275,222 @@ async def override_org_permission(
|
||||
granted=payload.granted,
|
||||
message=f"Permission '{payload.action}' {'granted' if payload.granted else 'revoked'} for organization {org_id}.",
|
||||
)
|
||||
|
||||
|
||||
# ── RBAC Phase 4: DB-Driven Role & Permission Endpoints ──
|
||||
|
||||
|
||||
@router.get(
|
||||
"/admin/permissions/roles",
|
||||
response_model=List[SystemRoleOut],
|
||||
tags=["Admin Permissions"],
|
||||
summary="Get all system roles with their granted permission IDs",
|
||||
)
|
||||
async def get_all_roles(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
_ = Depends(deps.RequirePermission("permissions:view")),
|
||||
):
|
||||
"""
|
||||
🔐 Returns all SystemRole records with their associated permission IDs.
|
||||
|
||||
Each role includes:
|
||||
- id, name, description, rank, is_system, is_active
|
||||
- permission_ids: List of permission IDs granted to this role
|
||||
|
||||
Protected by RequirePermission("permissions:view").
|
||||
"""
|
||||
stmt = (
|
||||
select(SystemRole)
|
||||
.options(selectinload(SystemRole.permissions))
|
||||
.order_by(SystemRole.rank.desc())
|
||||
)
|
||||
result = await db.execute(stmt)
|
||||
roles = result.unique().scalars().all()
|
||||
|
||||
role_list = []
|
||||
for role in roles:
|
||||
permission_ids = [
|
||||
rp.permission_id for rp in role.permissions if rp.granted
|
||||
]
|
||||
role_list.append(SystemRoleOut(
|
||||
id=role.id,
|
||||
name=role.name,
|
||||
description=role.description,
|
||||
rank=role.rank,
|
||||
is_system=role.is_system,
|
||||
is_active=role.is_active,
|
||||
permission_ids=permission_ids,
|
||||
))
|
||||
|
||||
return role_list
|
||||
|
||||
|
||||
@router.get(
|
||||
"/admin/permissions",
|
||||
response_model=List[SystemPermissionOut],
|
||||
tags=["Admin Permissions"],
|
||||
summary="Get all system permissions",
|
||||
)
|
||||
async def get_all_permissions(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
_ = Depends(deps.RequirePermission("permissions:view")),
|
||||
):
|
||||
"""
|
||||
🔐 Returns all SystemPermission records.
|
||||
|
||||
Each permission includes:
|
||||
- id, code, domain, action, description, is_system
|
||||
|
||||
Protected by RequirePermission("permissions:view").
|
||||
"""
|
||||
stmt = select(SystemPermission).order_by(SystemPermission.domain, SystemPermission.action)
|
||||
result = await db.execute(stmt)
|
||||
permissions = result.scalars().all()
|
||||
|
||||
return [
|
||||
SystemPermissionOut(
|
||||
id=p.id,
|
||||
code=p.code,
|
||||
domain=p.domain,
|
||||
action=p.action,
|
||||
description=p.description,
|
||||
is_system=p.is_system,
|
||||
)
|
||||
for p in permissions
|
||||
]
|
||||
|
||||
|
||||
@router.put(
|
||||
"/admin/permissions/roles/{role_id}/permissions",
|
||||
response_model=RolePermissionsUpdateResponse,
|
||||
tags=["Admin Permissions"],
|
||||
summary="Update granted permissions for a role",
|
||||
)
|
||||
async def update_role_permissions(
|
||||
role_id: int,
|
||||
payload: RolePermissionsUpdateRequest,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
_ = Depends(deps.RequirePermission("permissions:edit")),
|
||||
):
|
||||
"""
|
||||
🔐 Updates the granted permissions for a specific role.
|
||||
|
||||
This endpoint performs a full replacement of the role's granted
|
||||
permissions. The provided permission_ids list becomes the new set
|
||||
of granted permissions. Any existing mappings not in the list
|
||||
are removed.
|
||||
|
||||
SUPERADMIN roles (is_system=True, rank=100) are protected:
|
||||
- Their permissions cannot be modified through this endpoint
|
||||
to prevent accidental lockout.
|
||||
|
||||
Args:
|
||||
role_id: The target role ID.
|
||||
payload.permission_ids: The complete list of permission IDs to grant.
|
||||
|
||||
Returns:
|
||||
Confirmation with the updated permission IDs.
|
||||
"""
|
||||
# 1. Fetch the role
|
||||
stmt = select(SystemRole).where(SystemRole.id == role_id)
|
||||
result = await db.execute(stmt)
|
||||
role = result.scalar_one_or_none()
|
||||
|
||||
if not role:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"Role with id={role_id} not found.",
|
||||
)
|
||||
|
||||
# 2. Protect SUPERADMIN system roles
|
||||
if role.is_system and role.rank >= 100:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Cannot modify permissions for the SUPERADMIN system role. "
|
||||
"This would risk locking administrators out of the system.",
|
||||
)
|
||||
|
||||
# 3. Validate that all permission_ids exist
|
||||
if payload.permission_ids:
|
||||
perm_stmt = select(SystemPermission.id).where(
|
||||
SystemPermission.id.in_(payload.permission_ids)
|
||||
)
|
||||
perm_result = await db.execute(perm_stmt)
|
||||
existing_ids = {row[0] for row in perm_result.all()}
|
||||
|
||||
missing_ids = set(payload.permission_ids) - existing_ids
|
||||
if missing_ids:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"Invalid permission IDs: {sorted(missing_ids)}. These permissions do not exist.",
|
||||
)
|
||||
|
||||
# 4. Remove existing role-permission mappings
|
||||
delete_stmt = delete(SystemRolePermission).where(
|
||||
SystemRolePermission.role_id == role_id
|
||||
)
|
||||
await db.execute(delete_stmt)
|
||||
|
||||
# 5. Insert new mappings
|
||||
for perm_id in payload.permission_ids:
|
||||
db.add(SystemRolePermission(
|
||||
role_id=role_id,
|
||||
permission_id=perm_id,
|
||||
granted=True,
|
||||
))
|
||||
|
||||
await db.commit()
|
||||
|
||||
# 6. Invalidate cache
|
||||
rbac_service.invalidate_role_cache(role_id)
|
||||
|
||||
logger.info(
|
||||
f"Role permissions updated: role_id={role_id}, "
|
||||
f"permissions={payload.permission_ids}, "
|
||||
f"by_user={current_user.id}"
|
||||
)
|
||||
|
||||
return RolePermissionsUpdateResponse(
|
||||
status="success",
|
||||
role_id=role_id,
|
||||
role_name=role.name,
|
||||
granted_permission_ids=payload.permission_ids,
|
||||
message=f"Permissions updated for role '{role.name}' ({len(payload.permission_ids)} granted).",
|
||||
)
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────
|
||||
# RBAC Phase 2: Test Endpoint (Verification)
|
||||
# ──────────────────────────────────────────────
|
||||
|
||||
|
||||
@router.get(
|
||||
"/admin/rbac-test",
|
||||
tags=["Admin Permissions (RBAC)"],
|
||||
summary="RBAC Phase 2 verification endpoint",
|
||||
)
|
||||
async def rbac_test_endpoint(
|
||||
current_user: User = Depends(get_current_user),
|
||||
_ = Depends(deps.RequirePermission("fleet:view")),
|
||||
):
|
||||
"""
|
||||
🔐 RBAC Phase 2 verification endpoint.
|
||||
|
||||
Protected by Depends(RequirePermission("fleet:view")).
|
||||
- SUPERADMIN: Always passes (bypass).
|
||||
- Users with fleet:view permission: Passes.
|
||||
- Users without fleet:view permission: 403 Forbidden.
|
||||
|
||||
Returns the current user info if permission is granted.
|
||||
"""
|
||||
return {
|
||||
"status": "ok",
|
||||
"message": "RBAC Phase 2 permission check passed.",
|
||||
"user_id": current_user.id,
|
||||
"user_role": current_user.role.value,
|
||||
"role_id": current_user.role_id,
|
||||
"permission_checked": "fleet:view",
|
||||
}
|
||||
|
||||
@@ -27,7 +27,8 @@ async def list_service_catalog(
|
||||
limit: int = Query(50, ge=1, le=200, description="Maximum visszaadott rekordok száma"),
|
||||
is_active: bool | None = Query(None, description="Szűrés aktív/inaktív státuszra"),
|
||||
db: AsyncSession = Depends(deps.get_db),
|
||||
admin: User = Depends(deps.get_current_admin),
|
||||
current_user: User = Depends(deps.get_current_active_user),
|
||||
_ = Depends(deps.RequirePermission("services:manage")),
|
||||
):
|
||||
"""
|
||||
Szolgáltatás katalógus bejegyzések listázása lapozással.
|
||||
@@ -53,7 +54,8 @@ async def list_service_catalog(
|
||||
async def create_service_catalog(
|
||||
data: ServiceCatalogCreate,
|
||||
db: AsyncSession = Depends(deps.get_db),
|
||||
admin: User = Depends(deps.get_current_admin),
|
||||
current_user: User = Depends(deps.get_current_active_user),
|
||||
_ = Depends(deps.RequirePermission("services:manage")),
|
||||
):
|
||||
"""
|
||||
Új szolgáltatás katalógus bejegyzés létrehozása.
|
||||
@@ -86,7 +88,8 @@ async def update_service_catalog(
|
||||
service_id: int,
|
||||
data: ServiceCatalogUpdate,
|
||||
db: AsyncSession = Depends(deps.get_db),
|
||||
admin: User = Depends(deps.get_current_admin),
|
||||
current_user: User = Depends(deps.get_current_active_user),
|
||||
_ = Depends(deps.RequirePermission("services:manage")),
|
||||
):
|
||||
"""
|
||||
Meglévő szolgáltatás katalógus bejegyzés módosítása.
|
||||
|
||||
@@ -306,7 +306,7 @@ async def get_current_user_profile(
|
||||
"""
|
||||
from app.schemas.user import UserResponse
|
||||
from app.api.v1.endpoints.users import _build_user_response
|
||||
response_data = _build_user_response(current_user)
|
||||
response_data = await _build_user_response(current_user, db=db)
|
||||
return UserResponse.model_validate(response_data)
|
||||
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# /opt/docker/dev/service_finder/backend/app/api/v1/endpoints/finance_admin.py
|
||||
"""
|
||||
Finance Admin API endpoints for managing Issuers with strict RBAC protection.
|
||||
Only users with rank >= 90 (Superadmin/Finance Admin) can access these endpoints.
|
||||
Protected by DB-driven RequirePermission("finance:view") dependency.
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
@@ -10,36 +10,22 @@ from sqlalchemy import select
|
||||
from typing import List
|
||||
|
||||
from app.api import deps
|
||||
from app.models.identity import User, UserRole
|
||||
from app.models.identity import User
|
||||
from app.models.marketplace.finance import Issuer
|
||||
from app.schemas.finance import IssuerResponse, IssuerUpdate
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
async def check_finance_admin_access(
|
||||
current_user: User = Depends(deps.get_current_active_user)
|
||||
):
|
||||
"""
|
||||
RBAC protection: only users with rank >= 90 (Superadmin/Finance Admin) can access.
|
||||
In our system, this translates to role being 'superadmin' or 'admin'.
|
||||
"""
|
||||
if current_user.role not in [UserRole.SUPERADMIN, UserRole.ADMIN]:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Not enough permissions. Rank >= 90 (Superadmin/Finance Admin) required."
|
||||
)
|
||||
return current_user
|
||||
|
||||
|
||||
@router.get("/", response_model=List[IssuerResponse], tags=["finance-admin"])
|
||||
async def list_issuers(
|
||||
db: AsyncSession = Depends(deps.get_db),
|
||||
admin: User = Depends(check_finance_admin_access)
|
||||
current_user: User = Depends(deps.get_current_active_user),
|
||||
_ = Depends(deps.RequirePermission("finance:view")),
|
||||
):
|
||||
"""
|
||||
List all Issuers (billing entities).
|
||||
Only accessible by Superadmin/Finance Admin (rank >= 90).
|
||||
Protected by RequirePermission("finance:view").
|
||||
"""
|
||||
result = await db.execute(select(Issuer).order_by(Issuer.id))
|
||||
issuers = result.scalars().all()
|
||||
@@ -51,11 +37,12 @@ async def update_issuer(
|
||||
issuer_id: int,
|
||||
issuer_update: IssuerUpdate,
|
||||
db: AsyncSession = Depends(deps.get_db),
|
||||
admin: User = Depends(check_finance_admin_access)
|
||||
current_user: User = Depends(deps.get_current_active_user),
|
||||
_ = Depends(deps.RequirePermission("finance:edit")),
|
||||
):
|
||||
"""
|
||||
Update an Issuer's details (activate/deactivate, revenue limit, API config).
|
||||
Only accessible by Superadmin/Finance Admin (rank >= 90).
|
||||
Protected by RequirePermission("finance:edit").
|
||||
"""
|
||||
result = await db.execute(select(Issuer).where(Issuer.id == issuer_id))
|
||||
issuer = result.scalar_one_or_none()
|
||||
|
||||
@@ -14,11 +14,10 @@ from sqlalchemy.orm import selectinload
|
||||
from pydantic import BaseModel, Field, ConfigDict, EmailStr
|
||||
|
||||
from app.db.session import get_db
|
||||
from app.api.deps import get_current_user, RequireSystemCapability
|
||||
from app.api.deps import get_current_user
|
||||
from app.schemas.organization import CorpOnboardIn, CorpOnboardResponse, OrganizationUpdate, OrganizationResponse
|
||||
from app.schemas.subscription import SubscriptionTierResponse
|
||||
from app.services.billing_engine import upgrade_org_subscription
|
||||
from app.core.capabilities import Capability
|
||||
from app.models.marketplace.organization import Organization, OrgType, OrganizationMember, Branch, OrgUserRole, OrgRole
|
||||
from app.models.identity import User, OneTimePassword
|
||||
from app.core.config import settings
|
||||
|
||||
@@ -8,6 +8,7 @@ from typing import List, Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.api import deps
|
||||
from app.api.deps import get_db, get_current_user
|
||||
from app.models.identity import User, UserRole
|
||||
from app.services.security_service import security_service
|
||||
@@ -23,7 +24,8 @@ router = APIRouter()
|
||||
async def request_action(
|
||||
request: PendingActionCreate,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
current_user: User = Depends(get_current_user),
|
||||
_ = Depends(deps.RequirePermission("dual-control:request")),
|
||||
):
|
||||
"""
|
||||
Dual Control: Jóváhagyási kérelem indítása kiemelt művelethez.
|
||||
@@ -35,12 +37,6 @@ async def request_action(
|
||||
- SOFT_DELETE_USER: Felhasználó soft delete
|
||||
- ORGANIZATION_TRANSFER: Szervezet tulajdonjog átadása
|
||||
"""
|
||||
# Csak admin és superadmin kezdeményezhet kiemelt műveleteket
|
||||
if current_user.role not in [UserRole.ADMIN, UserRole.SUPERADMIN]:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Csak adminisztrátorok kezdeményezhetnek Dual Control műveleteket."
|
||||
)
|
||||
|
||||
try:
|
||||
action = await security_service.request_action(
|
||||
@@ -82,18 +78,14 @@ async def approve_action(
|
||||
action_id: int,
|
||||
approve_data: PendingActionApprove,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
current_user: User = Depends(get_current_user),
|
||||
_ = Depends(deps.RequirePermission("dual-control:approve")),
|
||||
):
|
||||
"""
|
||||
Dual Control: Művelet jóváhagyása.
|
||||
|
||||
Csak admin/superadmin hagyhat jóvá, és nem lehet a saját kérése.
|
||||
"""
|
||||
if current_user.role not in [UserRole.ADMIN, UserRole.SUPERADMIN]:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Csak adminisztrátorok hagyhatnak jóvá műveleteket."
|
||||
)
|
||||
|
||||
try:
|
||||
await security_service.approve_action(db, approver_id=current_user.id, action_id=action_id)
|
||||
@@ -115,18 +107,14 @@ async def reject_action(
|
||||
action_id: int,
|
||||
reject_data: PendingActionReject,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
current_user: User = Depends(get_current_user),
|
||||
_ = Depends(deps.RequirePermission("dual-control:approve")),
|
||||
):
|
||||
"""
|
||||
Dual Control: Művelet elutasítása.
|
||||
|
||||
Csak admin/superadmin utasíthat el, és nem lehet a saját kérése.
|
||||
"""
|
||||
if current_user.role not in [UserRole.ADMIN, UserRole.SUPERADMIN]:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Csak adminisztrátorok utasíthatnak el műveleteket."
|
||||
)
|
||||
|
||||
try:
|
||||
await security_service.reject_action(
|
||||
@@ -150,7 +138,8 @@ async def reject_action(
|
||||
async def get_action(
|
||||
action_id: int,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
current_user: User = Depends(get_current_user),
|
||||
_ = Depends(deps.RequirePermission("dual-control:view")),
|
||||
):
|
||||
"""
|
||||
Egy konkrét Dual Control művelet lekérdezése.
|
||||
@@ -164,7 +153,7 @@ async def get_action(
|
||||
if not action:
|
||||
raise HTTPException(status_code=404, detail="Művelet nem található.")
|
||||
|
||||
if current_user.role not in [UserRole.ADMIN, UserRole.SUPERADMIN] and action.requester_id != current_user.id:
|
||||
if current_user.id != action.requester_id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Nincs jogosultságod ehhez a művelethez."
|
||||
|
||||
@@ -5,6 +5,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select, update, and_
|
||||
from typing import List, Optional, Dict, Any
|
||||
|
||||
from app.api import deps
|
||||
from app.api.deps import get_db, get_current_user
|
||||
from app.schemas.system import (
|
||||
SystemParameterResponse,
|
||||
@@ -114,20 +115,14 @@ async def update_system_parameter(
|
||||
param_in: SystemParameterUpdate,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user=Depends(get_current_user),
|
||||
_ = Depends(deps.RequirePermission("system:manage")),
|
||||
scope_level: ParameterScope = Query("global", description="Scope szint (alapértelmezett: global)"),
|
||||
scope_id: Optional[str] = Query(None, description="Scope azonosító"),
|
||||
):
|
||||
"""
|
||||
Módosítja egy létező paraméter value (JSONB) vagy is_active mezőjét (Admin funkció).
|
||||
Csak superadmin vagy admin jogosultságú felhasználók használhatják.
|
||||
Protected by RequirePermission("system:manage").
|
||||
"""
|
||||
# Jogosultság ellenőrzése
|
||||
if current_user.role not in (UserRole.SUPERADMIN, UserRole.ADMIN):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Insufficient permissions. Only superadmin or admin can update system parameters."
|
||||
)
|
||||
|
||||
# Paraméter keresése
|
||||
query = select(SystemParameter).where(
|
||||
SystemParameter.key == key,
|
||||
|
||||
@@ -41,16 +41,17 @@ class NetworkResponse(BaseModel):
|
||||
level3: List[NetworkMemberL2L3]
|
||||
|
||||
|
||||
def _build_user_response(user: User, active_org_id: Optional[int] = None, db: Optional[AsyncSession] = None) -> dict:
|
||||
async def _build_user_response(user: User, active_org_id: Optional[int] = None, db: Optional[AsyncSession] = None) -> dict:
|
||||
"""
|
||||
Segédfüggvény a UserResponse dict előállításához.
|
||||
Beágyazza a Person és Address adatokat a 'person' mezőbe.
|
||||
RBAC Phase 3: system_capabilities és org_capabilities is bekerül a válaszba.
|
||||
P0: max_vehicles és max_garages a subscription_tier JSONB rules-ból.
|
||||
P0 Phase 6: system_capabilities now populated via DB-driven RBAC lookup.
|
||||
"""
|
||||
from app.models.marketplace.organization import Organization, OrganizationMember
|
||||
from app.models.marketplace.organization import OrgUserRole
|
||||
from app.core.capabilities import get_capabilities_for_role
|
||||
from app.services.rbac_service import rbac_service
|
||||
|
||||
# Determine active organization ID
|
||||
if active_org_id is None:
|
||||
@@ -102,9 +103,22 @@ def _build_user_response(user: User, active_org_id: Optional[int] = None, db: Op
|
||||
first_name = person.first_name if person else ""
|
||||
last_name = person.last_name if person else ""
|
||||
|
||||
# ── RBAC Phase 3: Resolve system capabilities ──
|
||||
# ── RBAC Phase 3/6: Resolve system capabilities via DB-driven RBAC ──
|
||||
role_key = user.role.value if hasattr(user.role, 'value') else str(user.role)
|
||||
system_capabilities = get_capabilities_for_role(role_key)
|
||||
system_capabilities: Dict[str, bool] = {}
|
||||
|
||||
if db is not None:
|
||||
# Use the role_id from the user's SystemRole mapping
|
||||
role_id = getattr(user, 'role_id', None)
|
||||
if role_id is not None:
|
||||
try:
|
||||
# Fetch all granted permission codes for this role from the DB
|
||||
perm_set = await rbac_service.get_role_permissions(db, role_id)
|
||||
# Convert the set of codes into a dict mapping code -> True
|
||||
system_capabilities = {code: True for code in perm_set}
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to resolve system_capabilities for user {user.id}: {e}")
|
||||
system_capabilities = {}
|
||||
|
||||
# ── RBAC Phase 3: Resolve org capabilities ──
|
||||
org_capabilities: Dict[str, Dict[str, bool]] = {}
|
||||
@@ -135,7 +149,7 @@ def _build_user_response(user: User, active_org_id: Optional[int] = None, db: Op
|
||||
"preferred_language": user.preferred_language or "hu",
|
||||
"person": person_data,
|
||||
"is_last_admin": False, # Default, will be overridden in read_users_me
|
||||
# RBAC Phase 3: Rendszerszintű képességek
|
||||
# RBAC Phase 3/6: Rendszerszintű képességek (DB-driven)
|
||||
"system_capabilities": system_capabilities,
|
||||
# RBAC Phase 3: Szervezeti képességek (feltöltve a read_users_me végpontban)
|
||||
"org_capabilities": {},
|
||||
@@ -150,8 +164,7 @@ async def read_users_me(
|
||||
"""Visszaadja a bejelentkezett felhasználó profilját beágyazott Person és Address adatokkal.
|
||||
RBAC Phase 3: system_capabilities és org_capabilities is bekerül a válaszba."""
|
||||
from app.models.marketplace.organization import Organization, OrganizationMember
|
||||
from app.models.marketplace.organization import OrgUserRole
|
||||
from app.core.capabilities import get_capabilities_for_role
|
||||
from app.models.marketplace.organization import OrgUserRole, OrgRole
|
||||
|
||||
# Determine active organization ID
|
||||
active_org_id = None
|
||||
@@ -252,7 +265,8 @@ async def read_users_me(
|
||||
max_garages = int(allowances.get("max_garages", 1))
|
||||
|
||||
# ── RBAC Phase 3: Build base response ──
|
||||
response_data = _build_user_response(current_user, active_org_id)
|
||||
# P0 Phase 6: Pass db so system_capabilities gets populated from DB
|
||||
response_data = await _build_user_response(current_user, active_org_id, db)
|
||||
response_data["is_last_admin"] = is_last_admin
|
||||
response_data["max_vehicles"] = max_vehicles
|
||||
response_data["max_garages"] = max_garages
|
||||
@@ -383,7 +397,7 @@ async def update_my_person(
|
||||
raise HTTPException(status_code=500, detail=f"Database error: {str(e)}")
|
||||
|
||||
# Build and return the full response
|
||||
response_data = _build_user_response(user)
|
||||
response_data = await _build_user_response(user)
|
||||
return UserResponse.model_validate(response_data)
|
||||
|
||||
|
||||
@@ -487,7 +501,7 @@ async def update_user_preferences(
|
||||
raise HTTPException(status_code=500, detail=f"Database error: {str(e)}")
|
||||
|
||||
# Return the Pydantic model instead of raw SQLAlchemy object
|
||||
response_data = _build_user_response(current_user)
|
||||
response_data = await _build_user_response(current_user)
|
||||
return UserResponse.model_validate(response_data)
|
||||
|
||||
|
||||
@@ -549,7 +563,7 @@ async def update_active_organization(
|
||||
access_token, _ = create_tokens(data=token_payload)
|
||||
|
||||
# Return user data with new token
|
||||
response_data = _build_user_response(current_user)
|
||||
response_data = await _build_user_response(current_user)
|
||||
return UserWithTokenResponse(
|
||||
user=UserResponse.model_validate(response_data),
|
||||
access_token=access_token,
|
||||
|
||||
Reference in New Issue
Block a user