59 lines
2.1 KiB
Python
59 lines
2.1 KiB
Python
from fastapi import HTTPException, Depends
|
|
|
|
from hub.auth import get_current_user
|
|
|
|
from firm.current_firm import CurrentFirmModel, Partner
|
|
from firm.db import get_db_client
|
|
from firm.entity.models import Entity
|
|
|
|
|
|
class Registry:
|
|
user = None
|
|
partner = None
|
|
|
|
def __init__(self, db_client, instance, firm):
|
|
self.db = db_client[f"tenant_{instance}_{firm}"]
|
|
self.instance = instance
|
|
self.firm = firm
|
|
|
|
self.current_firm = CurrentFirmModel.get_current(self.db)
|
|
|
|
async def set_user(self, user):
|
|
for firm in user.firms:
|
|
if firm.instance == self.instance and firm.firm == self.firm:
|
|
partner = await Partner.get_by_user_id(self.db, user.id)
|
|
partner_entity = await Entity.get(self.db, partner.entity_id)
|
|
self.user = user
|
|
self.partner = partner_entity
|
|
self.db.partner = partner_entity
|
|
return
|
|
|
|
raise PermissionError
|
|
|
|
async def get_tenant_registry(instance: str, firm: str, db_client=Depends(get_db_client)) -> Registry:
|
|
registry = Registry(db_client, instance, firm)
|
|
if await registry.current_firm is None:
|
|
raise HTTPException(status_code=405, detail=f"Firm needs to be initialized first")
|
|
|
|
return registry
|
|
|
|
async def get_authed_tenant_registry(registry=Depends(get_tenant_registry), user=Depends(get_current_user)) -> Registry:
|
|
try:
|
|
await registry.set_user(user)
|
|
except PermissionError:
|
|
raise HTTPException(status_code=404, detail="This firm doesn't exist or you are not allowed to access it.")
|
|
|
|
return registry
|
|
|
|
async def get_uninitialized_registry(instance: str, firm: str, db_client=Depends(get_db_client), user=Depends(get_current_user)) -> Registry:
|
|
registry = Registry(db_client, instance, firm)
|
|
if await registry.current_firm is not None:
|
|
raise HTTPException(status_code=409, detail="Firm configuration already exists")
|
|
|
|
try:
|
|
await registry.set_user(user)
|
|
except PermissionError:
|
|
raise HTTPException(status_code=404, detail="This firm doesn't exist or you are not allowed to access it.")
|
|
|
|
return registry
|