47 lines
1.3 KiB
Python
47 lines
1.3 KiB
Python
from typing import Optional
|
|
|
|
import starlette.status
|
|
from fastapi import HTTPException
|
|
|
|
from constants import DEALS_VIEWER, DEAL_EDITOR
|
|
from models import User
|
|
from schemas.auth import UserUnion
|
|
|
|
|
|
def raise_403():
|
|
raise HTTPException(status_code=starlette.status.HTTP_403_FORBIDDEN, detail='Forbidden')
|
|
|
|
|
|
def verify_user(user: UserUnion, raising: bool = True) -> bool:
|
|
if type(user) is User:
|
|
return True
|
|
if raising:
|
|
raise_403()
|
|
return False
|
|
|
|
|
|
def verify_user_viewer(user: UserUnion, client_id: Optional[int] = None, raising: bool = True) -> bool:
|
|
is_regular_user: bool = type(user) is User
|
|
is_viewer: bool = isinstance(user, dict) and user['sub'] == DEALS_VIEWER
|
|
if client_id is not None:
|
|
is_viewer = is_viewer and int(user['client_id']) == client_id
|
|
|
|
if is_regular_user or is_viewer:
|
|
return True
|
|
if raising:
|
|
raise_403()
|
|
return False
|
|
|
|
|
|
def verify_user_deal_editor(user: UserUnion, deal_id: Optional[int] = None, raising: bool = True) -> bool:
|
|
is_regular_user: bool = type(user) is User
|
|
is_deal_editor: bool = isinstance(user, dict) and user['sub'] == DEAL_EDITOR
|
|
if deal_id is not None:
|
|
is_deal_editor = is_deal_editor and int(user['deal_id']) == deal_id
|
|
|
|
if is_regular_user or is_deal_editor:
|
|
return True
|
|
if raising:
|
|
raise_403()
|
|
return False
|