from typing import Annotated from fastapi import Depends, FastAPI, HTTPException, status, Response from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer import hsadmin import config app = FastAPI() security = HTTPBearer() def check_token(token: str) -> bool: """Check if the token is valid""" return token == config.token @app.put("/list/{listname}", status_code=status.HTTP_201_CREATED) def create_list(token: Annotated[HTTPAuthorizationCredentials, Depends(security)], listname: str, response: Response): # Authenticate if not check_token(token.credentials): raise HTTPException(status_code=401, detail="Invalid token") # Create email api = hsadmin.login() # If the email already exists, return an error if hsadmin.email_exists(api, config.domain, listname): response.status_code = status.HTTP_409_CONFLICT return {"Success": "false", "Message": "list already exists"} # Create the email result = hsadmin.add_email(api, config.listsuser, config.domain, listname) if result == True: return {"Success": "true"} # If the email could not be created, return an error response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR return {"Success": "false", "Message": result} @app.delete("/list/{listname}", status_code=status.HTTP_200_OK) def delete_list(token: Annotated[HTTPAuthorizationCredentials, Depends(security)], listname: str, response: Response): # Authenticate if not check_token(token.credentials): raise HTTPException(status_code=401, detail="Invalid token") # Delete email api = hsadmin.login() if not hsadmin.email_exists(api, config.domain, listname): response.status_code = status.HTTP_404_NOT_FOUND return {"Success": "false", "Message": "list does not exist"} result = hsadmin.remove_email(api, config.listsuser, config.domain, listname) if result == True: return {"Success": "true"} # If the email could not be deleted, return an error response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR return {"Success": "false", "Message": result}