Imporve the role based forntend protected roles

This commit is contained in:
Urtzi Alfaro
2025-09-09 07:32:59 +02:00
parent ddb75f8e55
commit 5269a083b6
15 changed files with 286 additions and 91 deletions

View File

@@ -132,7 +132,7 @@ class SecurityManager:
if "role" in user_data:
payload["role"] = user_data["role"]
else:
payload["role"] = "user" # Default role if not specified
payload["role"] = "admin" # Default role if not specified
logger.debug(f"Creating access token with payload keys: {list(payload.keys())}")

View File

@@ -18,7 +18,7 @@ class UserRegistration(BaseModel):
password: str = Field(..., min_length=8, max_length=128)
full_name: str = Field(..., min_length=1, max_length=255)
tenant_name: Optional[str] = Field(None, max_length=255)
role: Optional[str] = Field("user", pattern=r'^(user|admin|manager)$')
role: Optional[str] = Field("admin", pattern=r'^(user|admin|manager|super_admin)$')
class UserLogin(BaseModel):
"""User login request"""
@@ -56,7 +56,7 @@ class UserData(BaseModel):
is_verified: bool
created_at: str # ISO format datetime string
tenant_id: Optional[str] = None
role: Optional[str] = "user"
role: Optional[str] = "admin"
class TokenResponse(BaseModel):
"""
@@ -101,7 +101,7 @@ class UserResponse(BaseModel):
language: Optional[str] = None # ✅ Added missing field
timezone: Optional[str] = None # ✅ Added missing field
tenant_id: Optional[str] = None
role: Optional[str] = "user"
role: Optional[str] = "admin"
class Config:
from_attributes = True # ✅ Enable ORM mode for SQLAlchemy objects
@@ -189,7 +189,7 @@ class UserContext(BaseModel):
user_id: str
email: str
tenant_id: Optional[str] = None
roles: list[str] = ["user"]
roles: list[str] = ["admin"]
is_verified: bool = False
class TokenClaims(BaseModel):

View File

@@ -55,7 +55,9 @@ class EnhancedAuthService:
raise ValueError("Password does not meet security requirements")
# Create user data
user_role = user_data.role if user_data.role else "user"
# Default to admin role for first-time registrations during onboarding flow
# Users creating their own bakery should have admin privileges
user_role = user_data.role if user_data.role else "admin"
hashed_password = SecurityManager.hash_password(user_data.password)
create_data = {

View File

@@ -413,7 +413,7 @@ class EnhancedUserService:
user_repo = UserRepository(User, session)
# Validate role
valid_roles = ["user", "admin", "super_admin"]
valid_roles = ["user", "admin", "manager", "super_admin"]
if new_role not in valid_roles:
raise ValidationError(f"Invalid role. Must be one of: {valid_roles}")

View File

@@ -67,6 +67,32 @@ async def register_bakery_enhanced(
detail="Bakery registration failed"
)
@router.get("/tenants/{tenant_id}/my-access", response_model=TenantAccessResponse)
async def get_current_user_tenant_access(
tenant_id: UUID = Path(..., description="Tenant ID"),
current_user: Dict[str, Any] = Depends(get_current_user_dep)
):
"""Get current user's access to tenant with role and permissions"""
try:
# Create tenant service directly
from app.core.config import settings
database_manager = create_database_manager(settings.DATABASE_URL, "tenant-service")
tenant_service = EnhancedTenantService(database_manager)
access_info = await tenant_service.verify_user_access(current_user["user_id"], str(tenant_id))
return access_info
except Exception as e:
logger.error("Current user access verification failed",
user_id=current_user["user_id"],
tenant_id=str(tenant_id),
error=str(e))
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Access verification failed"
)
@router.get("/tenants/{tenant_id}/access/{user_id}", response_model=TenantAccessResponse)
async def verify_tenant_access_enhanced(
tenant_id: UUID = Path(..., description="Tenant ID"),