52 lines
1.8 KiB
Python
52 lines
1.8 KiB
Python
from fastapi import HTTPException, Depends
|
|
from hub.auth import get_current_user
|
|
|
|
from firm.db import get_db_client
|
|
from firm.current_firm import CurrentFirmModel
|
|
|
|
class Registry:
|
|
user = 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)
|
|
|
|
def set_user(self, user):
|
|
for firm in user.firms:
|
|
if firm.instance == self.instance and firm.firm == self.firm:
|
|
self.user = user
|
|
self.db.user = user
|
|
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
|
|
|
|
def get_authed_tenant_registry(registry=Depends(get_tenant_registry), user=Depends(get_current_user)) -> Registry:
|
|
try:
|
|
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:
|
|
HTTPException(status_code=409, detail="Firm configuration already exists")
|
|
|
|
try:
|
|
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
|