def validateToken(request): # get the request payloads body = json.loads(request.body) # check if required fields are present in request payload missingKeys = validateKeys(payload=body, requiredKeys=['token']) if missingKeys: return badRequestResponse( ErrorCodes.MISSING_FIELDS, message= f"The following key(s) are missing in the request payload: {missingKeys}" ) # check if token is valid and hasn't expired token = body['token'] isValid = (getUserPasswordResetTokenByResetToken(token) != None) if isValid == False: return badRequestResponse( ErrorCodes.GENERIC_INVALID_PARAMETERS, message=getGenericInvalidParametersErrorPacket( 0, "invalid reset token"), body={"isValid": isValid}) elif isValid == True: return successResponse(message="Token is valid", body={"isValid": isValid})
def resetToken(request): # get the request payload body = json.loads(request.body) # check if required fields are present in request payload missingKeys = validateKeys(payload=body, requiredKeys=['email']) if missingKeys: return badRequestResponse( ErrorCodes.MISSING_FIELDS, message= f"The following key(s) are missing in the request payload: {missingKeys}" ) # check if email is in valid formats email = body['email'] if validateEmailFormat(email) is False: return badRequestResponse( errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message="Email format is invalid") # confirm if an account is associated with the email user = getUserByEmailOnly(email) if user is None: return resourceNotFoundResponse( ErrorCodes.USER_DOES_NOT_EXIST, message=getUserDoesNotExistErrorPacket()) # generate user access token userToken = setupUserPasswordResetToken(user) if userToken == None: return resourceNotFoundResponse( ErrorCodes.USER_DOES_NOT_EXIST, message=getUserDoesNotExistErrorPacket()) # create and send notification to email channel createEmailMessage = sendEmail(email=email, token=userToken) return successResponse( message= "An email was sent to your account if you have an account with us", body={})
def passwordReset(request): body = json.loads(request.body) # check if required fields are present in request payload missingKeys = validateKeys( payload=body, requiredKeys=['token', 'password']) if missingKeys: return badRequestResponse(ErrorCodes.MISSING_FIELDS, message=f"The following key(s) are missing in the request payload: {missingKeys}") userPasswordResetToken = getUserPasswordResetTokenByResetToken(body['token']) if userPasswordResetToken is None: return badRequestResponse(ErrorCodes.GENERIC_INVALID_PARAMETERS, message=getGenericInvalidParametersErrorPacket(0, "invalid reset token")) # reset user's password password = body['password'] passwordReset = resetPassword(userPasswordResetToken.user, password) if passwordReset == False: return internalServerErrorResponse(ErrorCodes.PASSWORD_RESET_FAILED, message=getPasswordResetFailedErrorPacket()) return successResponse(message="Password Reset was successful")
def login(request): body = json.loads(request.body) # check if required fields are present in request payload missingKeys = validateKeys(payload=body, requiredKeys=['email', 'password']) if missingKeys: return badRequestResponse( errorCode=ErrorCodes.MISSING_FIELDS, message= f"The following key(s) are missing in the request payload: {missingKeys}" ) email = body['email'] password = body['password'] # check if email is not empty if not validateThatStringIsEmpty(email): return badRequestResponse( errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message=getGenericInvalidParametersErrorPacket( message="Email field cannot be empty")) # check if password is not empty if not validateThatStringIsEmpty(password): return badRequestResponse( errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message=getGenericInvalidParametersErrorPacket( message="Password field cannot be empty")) user = authenticateUser(email, password) if user is None: return badRequestResponse(ErrorCodes.INVALID_CREDENTIALS, message=getInvalidCredentialsErrorPacket()) userAccessToken = generateUserAccessToken(user) return successResponse(message="successfully authenticated", body=generateLoginResponse(user, userAccessToken))
def createProduct(request): # verify that the calling user has a valid token token = request.headers.get('accessToken') user = getUserByAccessToken(token) body = json.loads(request.body) if token is None: return badRequestResponse(errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message="accessToken is missing in the request headers") if user is None: return unAuthenticatedResponse(ErrorCodes.UNAUTHENTICATED_REQUEST, message=getUnauthenticatedErrorPacket()) # check if required fields are present in requets payload missingKeys = validateKeys(payload=body,requiredKeys=[ 'productName','productPrice','quantity']) if missingKeys: return badRequestResponse(ErrorCodes.MISSING_FIELDS, message=f"The following key(s) are missing in the request payload: {missingKeys}") # save passed information in varaibles productName = body['productName'] productPrice = body['productPrice'] quantity = body['quantity'] business = Business.objects.get(user=user) if user.userCategoryType != 'manager': return unAuthorizedResponse(ErrorCodes.UNAUTHORIZED_REQUEST, message=getUnauthorizedErrorPacket()) createdProduct = createNewProduct(business=business,productName=productName,productPrice=productPrice,quantity=quantity) if createdProduct == None: return internalServerErrorResponse(ErrorCodes.PRODUCT_CREATION_FAILED, message=getProductCreationFailedErrorPacket()) return successResponse(message="successfully added product", body=transformProduct(createdProduct))
def createProgram(request): try: body = request.POST image = request.FILES['image'] if 'image' in request.FILES else False token = request.headers.get('accessToken') user = getUserByAccessToken(token) if image == False: return badRequestResponse( errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message=f"please provide a valid image file") # check if all required fields are present in request payload missingKeys = validateKeys(payload=body, requiredKeys=[ 'name', 'description', 'code', "locations", "sdgs", "budget", "totalNumberOfBeneficiaries", "activeMarker" ]) if missingKeys: return badRequestResponse( errorCode=ErrorCodes.MISSING_FIELDS, message= f"The following key(s) are missing in the request payload: {missingKeys}" ) if not validateThatListIsEmpty(body['locations']): return badRequestResponse( errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message=f"Program must contain a list of locations") if not validateThatListIsEmpty(body['sdgs']): return badRequestResponse( errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message=f"Program must contain a list of sdgs and indicators") is_program_exist = getProgramByDetail(body['name'], body['description'], body['code'], user) if is_program_exist.exists(): return badRequestResponse( errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message=f"Program already exists") # validation for sdg for sdg in json.loads(body['sdgs']): missingSdgkey = validateKeys(payload=sdg, requiredKeys=['id', 'indicators']) if missingSdgkey: return badRequestResponse( ErrorCodes.MISSING_FIELDS, message= f"The following key(s) are missing in the request locations array payload: {missingSdgkey}" ) # check that sdg exist sdg_id = sdg['id'] sdg_exist = getSdgById(sdg_id) if sdg_exist is None: return badRequestResponse( ErrorCodes.GENERIC_INVALID_PARAMETERS, message=f"sgd {sdg_id} does not exist") # check that indicator exist sdg_indicators = sdg['indicators'] for sdg_indicator in sdg_indicators: sdg_inidcator_exist = getIndicator(sdg_indicator) if sdg_inidcator_exist is None: return badRequestResponse( ErrorCodes.GENERIC_INVALID_PARAMETERS, message= f"selected sdg indicator {sdg_indicator} does not exist" ) token = request.headers.get('accessToken') user = getUserByAccessToken(token) if user is None: return badRequestResponse( errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message=f"User does not exist") if not validateThatStringIsEmptyAndClean(body['name']): return badRequestResponse( errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message= f"Program name can neither contain special characters nor be empty" ) if not validateThatStringIsEmpty(body['description']): return badRequestResponse( errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message= f"Program description can neither contain special characters nor be empty", body={}) if not validateThatStringIsEmptyAndClean(body['code']): return badRequestResponse( errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message= f"Program code can neither contain special characters nor be empty" ) if not validateThatStringIsEmptyAndClean(body['budget']): return badRequestResponse( errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message= f"budget can neither contain special characters nor be empty") if not validateThatStringIsEmptyAndClean( body['totalNumberOfBeneficiaries']): return badRequestResponse( errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message= f"Beneficiaries can neither contain special characters nor be empty" ) # load the fields from Json name = body['name'] description = body['description'] code = body['code'] locations = json.loads(body['locations']) sdgs = json.loads(body['sdgs']) budget = body['budget'] totalNumberOfBeneficiaries = body['totalNumberOfBeneficiaries'] activeMarker = json.loads(body['activeMarker']) validate_image = validateImage(image.name) if validate_image is not None: return badRequestResponse( errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message=validate_image) image_link = upload_file(image, image.name) program = CreateProgramRecord(name, image_link, description, code, locations, sdgs, user, budget, totalNumberOfBeneficiaries, activeMarker) programFormList = None if program is None: return internalServerErrorResponse( errorCode=ErrorCodes.PROGRAM_CREATION_FAILED, message=f"Program failed to create") else: return successResponse(message="successfully created program", body=transformProgram( program, program.location_set.all(), program.program_sdg_set.all(), programFormList)) except AttributeError as ex: return internalServerErrorResponse(errorCode=ErrorCodes.MISSING_FIELDS, message=f"missing attributes") except Exception as ex: # Log Exception return internalServerErrorResponse( errorCode=ErrorCodes.PROGRAM_CREATION_FAILED, message=f"program failed to create")
def createprogramIndicatorTarget(request): try: body = json.loads(request.body) missingKeys = validateKeys( payload=body, requiredKeys=['programIndicatorId', 'name', 'type', 'value']) if missingKeys: return badRequestResponse( ErrorCodes.MISSING_FIELDS, message= f"The following key(s) are missing in the request payload: {missingKeys}" ) type = body['type'] value = body['value'] programIndicatorId = body['programIndicatorId'] name = body['name'] if not validateThatStringIsEmpty(type): return badRequestResponse( errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message= "type can neither contain special characters nor be empty") # Validate the type as 'numeric' or 'percentage' if not IndicatorTypeEnum.has_value(type): return badRequestResponse( ErrorCodes.GENERIC_INVALID_PARAMETERS, message="please indicate type as 'number' or 'percentage' ") # check value if type is percentage if type == IndicatorTypeEnum.PERCENTAGE.value: if value < 0 or value > 100: return badRequestResponse( ErrorCodes.GENERIC_INVALID_PARAMETERS, message= "The value of a percentage based indicator cannot be less than 0 or more than 100" ) else: if value < 0: return badRequestResponse( ErrorCodes.GENERIC_INVALID_PARAMETERS, message= "The value of a number based indicator cannot be less than 0" ) programIndicator = getProgramIndicator(programIndicatorId) # Validate Indicator Field if programIndicator is None: return badRequestResponse( ErrorCodes.PROGRAM_INDICATOR_DOES_NOT_EXIST, message="please provide a valid program indicatorId") program_indicator_target = createprogramIndicatorTargetRecord( programIndicator, name, type, value) if program_indicator_target is None: return internalServerErrorResponse( errorCode=ErrorCodes.PROGRAM_INDICATOR_TARGET_CREATION_FAILED, message="Failed to create program indicator target") else: return successResponse( message="successfully created your target", body=transformProgramIndicatorTarget(program_indicator_target)) except Exception as ex: pass
def updateProgram(request, programId): token = request.headers.get('accessToken') user = getUserByAccessToken(token) if user is None: return badRequestResponse( errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message=f"User does not exist") programToUpdate = getProgramById(programId) if programToUpdate is None: return resourceNotFoundResponse(ErrorCodes.GENERIC_INVALID_PARAMETERS, message="Program does not exist ") body = request.POST image = request.FILES['image'] if 'image' in request.FILES else False if image == False: return badRequestResponse( errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message=f"please provide a valid image file") # check if all required fields are present in request payload missingKeys = validateKeys(payload=body, requiredKeys=[ 'name', 'description', 'code', "locations", "sdgs", "budget", "totalNumberOfBeneficiaries", "activeMarker" ]) if missingKeys: return badRequestResponse( errorCode=ErrorCodes.MISSING_FIELDS, message= f"The following key(s) are missing in the request payload: {missingKeys}" ) if not validateThatListIsEmpty(body['locations']): return badRequestResponse( errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message=f"Program must contain a list of locations") if not validateThatListIsEmpty(body['sdgs']): return badRequestResponse( errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message=f"Program must contain a list of sdgs and indicators") # validation for sdg for sdg in json.loads(body['sdgs']): missingSdgkey = validateKeys(payload=sdg, requiredKeys=['id', 'indicators']) if missingSdgkey: return badRequestResponse( ErrorCodes.MISSING_FIELDS, message= f"The following key(s) are missing in the request locations array payload: {missingSdgkey}" ) # check that sdg exist sdg_id = sdg['id'] sdg_exist = getSdgById(sdg_id) if sdg_exist is None: return badRequestResponse(ErrorCodes.GENERIC_INVALID_PARAMETERS, message=f"sgd {sdg_id} does not exist") # check that sdg indicator exist sdg_indicators = sdg['indicators'] for sdg_indicator in sdg_indicators: sdg_inidcator_exist = getIndicator(sdg_indicator) if sdg_inidcator_exist is None: return badRequestResponse( ErrorCodes.GENERIC_INVALID_PARAMETERS, message= f"selected sdg indicator {sdg_indicator} does not exist") if not validateThatStringIsEmptyAndClean(body['name']): return badRequestResponse( errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message= f"Program name can neither contain special characters nor be empty" ) if not validateThatStringIsEmpty(body['description']): return badRequestResponse( errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message= f"Program description can neither contain special characters nor be empty", body={}) if not validateThatStringIsEmptyAndClean(body['code']): return badRequestResponse( errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message= f"Program code can neither contain special characters nor be empty" ) if not validateThatStringIsEmptyAndClean(body['budget']): return badRequestResponse( errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message= f"budget can neither contain special characters nor be empty") if not validateThatStringIsEmptyAndClean( body['totalNumberOfBeneficiaries']): return badRequestResponse( errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message= f"Beneficiaries can neither contain special characters nor be empty" ) name = body['name'] description = body['description'] code = body['code'] locations = json.loads(body['locations']) sdgs = json.loads(body['sdgs']) budget = body['budget'] totalNumberOfBeneficiaries = body['totalNumberOfBeneficiaries'] activeMarker = json.loads(body['activeMarker']) validate_image = validateImage(image.name) if validate_image is not None: return badRequestResponse( errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message=validate_image) image_link = upload_file(image, image.name) updatedProgram = updatedProgramRecord(programToUpdate, name, description, image_link, code, locations, sdgs, user, budget, totalNumberOfBeneficiaries, activeMarker) if updatedProgram.form_program_set.all() is not None: updatedFormlist = updatedProgram.form_program_set.all() else: updatedFormlist = None # raise an error response if update wasn't successful if updatedProgram == None: return internalServerErrorResponse( ErrorCodes.PROGRAM_UPDATE_FAILED, message="Program update was unsuccessful") return successResponse(message="successfully updated program", body=transformProgram( updatedProgram, updatedProgram.location_set.all(), updatedProgram.program_sdg_set.all(), updatedFormlist))
def createUser(request): # get Json information passed in body = json.loads(request.body) #check if required fields are present in request payload missingKeys = validateKeys(payload=body, requiredKeys=['users']) if missingKeys: return badRequestResponse(ErrorCodes.MISSING_FIELDS, message=f"The following key(s) are missing in the request payload: {missingKeys}") user_list=[] users = body['users'] for user in users: index = users.index fields = ['firstName','lastName','userName','email','phone','password','userCategoryType'] #check if required fields are present in request payload missingKeys = validateKeys(payload=user, requiredKeys=fields) if missingKeys: return badRequestResponse(ErrorCodes.MISSING_FIELDS, message=f"The following key(s) are missing in the request payload: {missingKeys} for {index(user)}") #validate if the email is in the correct format if not validateEmailFormat(user['email']): return badRequestResponse(errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message=getGenericInvalidParametersErrorPacket("Email format is invalid")) #validate if the phone is in the correct formats if not validatePhoneFormat(user['phone']): return badRequestResponse(errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message=getGenericInvalidParametersErrorPacket("Phone format is invalid")) if not validateThatStringIsEmptyAndClean(user['firstName']): return badRequestResponse(errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message=getGenericInvalidParametersErrorPacket( "First name cannot be empty or contain special characters")) if not validateThatStringIsEmptyAndClean(user['lastName']): return badRequestResponse(errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message=getGenericInvalidParametersErrorPacket("Last name cannot be empty or contain special characters")) if not validateThatStringIsEmpty(user['password']): return badRequestResponse(errorCode = ErrorCodes.GENERIC_INVALID_PARAMETERS, message=getGenericInvalidParametersErrorPacket("Password cannot be empty")) #check if user with that username exists if getUserByUserName(user['userName']) is not None: return resourceConflictResponse(errorCode=ErrorCodes.USER_ALREADY_EXIST, message=getUserAlreadyExistErrorPacket('username')) #check if user with that email exists if getUserByEmail(user['email']) is not None: return resourceConflictResponse(errorCode=ErrorCodes.USER_ALREADY_EXIST, message=getUserAlreadyExistErrorPacket('email')) #Check if user with that phone exists if getUserByPhone(user['phone']) is not None: return resourceConflictResponse(errorCode=ErrorCodes.USER_ALREADY_EXIST, message=getUserAlreadyExistErrorPacket('phone')) # check that the user category type specified is correct confirmedUserCategoryTypeValidity = False for categoryType in UserCategoryType: if categoryType.value == user['userCategoryType'].lower(): confirmedUserCategoryTypeValidity = True userCategoryType = categoryType.value if not confirmedUserCategoryTypeValidity: return badRequestResponse(errorCode=ErrorCodes.USER_CATEGORY_TYPE_INVALID, message=getUserCategoryInvalidErrorPacket()) createdUser = createUserRecord(firstName=user['firstName'],lastName=user['lastName'], userName=user['userName'], email=user['email'], password=user['password'], phone=user['phone'], userCategoryType=user['userCategoryType'] ) if createdUser == None: return internalServerErrorResponse(ErrorCodes.USER_CREATION_FAILED, message=getUserCreationFailedErrorPacket()) print(createdUser) createAccount = createUserAccount(user=createdUser) user_list.append(createdUser) return successResponse(message="successfully created user", body=transformUsersList(user_list)) """
def updateUser(request, userID): # verify that the calling user has a valid token body = json.loads(request.body) token = request.headers.get('accessToken') user = getUserByAccessToken(token) if token is None: return badRequestResponse(errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message="accessToken is missing in the request headers") if user is None: return unAuthenticatedResponse(ErrorCodes.UNAUTHENTICATED_REQUEST, message=getUnauthenticatedErrorPacket()) # validate to ensure that all required fields are present if 'password' in body: keys = ['email', 'userName', 'firstName', 'lastName', 'password', 'phone', 'userCategoryType'] else: keys = ['email', 'userName', 'firstName', 'lastName', 'phone', 'userCategoryType'] # check if required fields are present in request payload missingKeys = validateKeys(payload=body, requiredKeys=keys) if missingKeys: return badRequestResponse(ErrorCodes.MISSING_FIELDS, message=f"The following key(s) are missing in the request payload: {missingKeys}") # check if userToBeUpdated already exists userToBeUpdated = getUserById(userID) if userToBeUpdated is None: return resourceNotFoundResponse(ErrorCodes.USER_DOES_NOT_EXIST, getUserDoesNotExistErrorPacket()) # validate if the email is in the correct format if not validateEmailFormat(body['email']): return badRequestResponse(errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message=getGenericInvalidParametersErrorPacket("Email format is invalid")) # validate if the phone is in the correct format if not validatePhoneFormat(body['phone']): return badRequestResponse(errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message=getGenericInvalidParametersErrorPacket("Phone format is invalid")) if not validateThatStringIsEmptyAndClean(body['firstName']): return badRequestResponse(errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message=getGenericInvalidParametersErrorPacket( "First name cannot be empty or contain special characters")) if not validateThatStringIsEmptyAndClean(body['lastName']): return badRequestResponse(errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message=getGenericInvalidParametersErrorPacket("Last name cannot be empty or contain special characters")) # check that the user category type specified is correct confirmedUserCategoryTypeValidity = False for categoryType in UserCategoryType: if categoryType.value == body['userCategoryType'].lower(): confirmedUserCategoryTypeValidity = True userCategoryType = categoryType.value if not confirmedUserCategoryTypeValidity: return badRequestResponse(errorCode=ErrorCodes.USER_CATEGORY_TYPE_INVALID, message=getUserCategoryInvalidErrorPacket()) # check that username specified does not belong to another user userName = getUserByUserName( userName=body['userName']) if userName != None: if userName.id != userToBeUpdated.id: return resourceConflictResponse(errorCode=ErrorCodes.USER_ALREADY_EXIST, message=getUserAlreadyExistErrorPacket(value="username")) # check that email specified does not belong to another user userEmail = getUserByEmail(body['email']) if userEmail != None: if userEmail.id != userToBeUpdated.id: return resourceConflictResponse(errorCode=ErrorCodes.USER_ALREADY_EXIST, message=getUserAlreadyExistErrorPacket(value="email")) # check that phone specified does not belong to another user userPhone = getUserByPhone(phone=body['phone']) if userPhone != None: if userPhone.id != userToBeUpdated.id: return resourceConflictResponse(errorCode=ErrorCodes.USER_ALREADY_EXIST, message=getUserAlreadyExistErrorPacket(value="phone")) if 'password' in body: updatedUser = updateUserRecord(userToBeUpdated, firstName=body['firstName'], lastName=body['lastName'], userName=body['userName'], email=body['email'], password=body['password'], phone=body['phone'], userCategoryType=body['userCategoryType'] ) else: updatedUser = updateUserRecord(userToBeUpdated, firstName=body['firstName'], lastName=body['lastName'], userName=body['userName'], email=body['email'], phone=body['phone'], userCategoryType=body['userCategoryType'] ) if updatedUser == None: return internalServerErrorResponse(ErrorCodes.USER_UPDATE_FAILED, message=getUserUpdateFailedErrorPacket()) return successResponse(message="successfully updated user", body=transformUser(updatedUser))
def createBusiness(request): # verify that the calling user has a valid token token = request.headers.get('accessToken') user = getUserByAccessToken(token) if token is None: return badRequestResponse( errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message="accessToken is missing in the request headers") if user is None: return unAuthenticatedResponse(ErrorCodes.UNAUTHENTICATED_REQUEST, message=getUnauthenticatedErrorPacket()) # Check if user has the privilege to create the resource if user.userCategoryType != 'manager': return unAuthorizedResponse(ErrorCodes.UNAUTHORIZED_REQUEST, message=getUnauthorizedErrorPacket()) # get Json information passed in body = json.loads(request.body) # check if required fields are present in request payload missingKeys = validateKeys(payload=body, requiredKeys=[ 'businessName', 'businessEmail', 'businessPhone', 'street', 'city', 'state', 'country', 'zipCode' ]) if missingKeys: return badRequestResponse( ErrorCodes.MISSING_FIELDS, message= f"The following key(s) are missing in the request payload: {missingKeys}" ) # validate if the email is in the correct format if not validateEmailFormat(body['businessEmail']): return badRequestResponse( errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message=getGenericInvalidParametersErrorPacket( "Email format is invalid")) # validate if the phone is in the correct format if not validatePhoneFormat(body['businessPhone']): return badRequestResponse( errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS, message=getGenericInvalidParametersErrorPacket( "Phone format is invalid")) # check if business with that email exists if getBusinessByEmail(body['businessEmail']) is not None: return resourceConflictResponse( errorCode=ErrorCodes.BUSINESS_ALREADY_EXIST, message=getBusinessAlreadyExistErrorPacket("businessEmail")) # Check if business with that phone exists if getBusinessByPhone(body['businessPhone']) is not None: return resourceConflictResponse( errorCode=ErrorCodes.BUSINESS_ALREADY_EXIST, message=getBusinessAlreadyExistErrorPacket('businessPhone')) businessName = body['businessName'] businessEmail = body['businessEmail'] businessPhone = body['businessPhone'] street = body['street'] city = body['city'] state = body['state'] country = body['country'] zipCode = body['zipCode'] createdBusiness = createNewBusiness(user=user, businessName=businessName, businessEmail=businessEmail, businessPhone=businessPhone) if createdBusiness == None: return internalServerErrorResponse( ErrorCodes.BUSINESS_CREATION_FAILED, message=getBusinessCreationFailedErrorPacket()) businessAddress = createBusinessAddress( user=user, business=createdBusiness, street=street, city=city, state=state, country=country, zipCode=zipCode, ) if businessAddress == None: return internalServerErrorResponse( ErrorCodes.Business_ADDRESS_CREATION_FIELD, message=getBusinessCreationAddressFailedErrorPacket()) return successResponse(message="successfully created restaurant", body=transformBusiness(createdBusiness))