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 deleteUser(request, userID): # 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 is UserID exists userToBeDeleted = getUserById(userID) if userToBeDeleted == None: return resourceNotFoundResponse(ErrorCodes.USER_DOES_NOT_EXIST, message=getUserDoesNotExistErrorPacket()) # check if user has the privileges to delete the resource if user.userCategoryType != 'controller' or user != userToBeDeleted: return unAuthorizedResponse(ErrorCodes.UNAUTHORIZED_REQUEST, message=getUnauthorizedErrorPacket()) userDeleted = deleteUserRecord(userToBeDeleted) if userDeleted is None: return internalServerErrorResponse(ErrorCodes.USER_DELETION_FAILED, message=getUserDeletionFailedErrorPacket()) return successResponse(message="Successfully deleted user", body={})
def getBusinessProductByBusinessID(request,businessID): # verify that 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 business with given ID exists businessToBeRetrieved = getBusinessById(businessID) if businessToBeRetrieved == None: return resourceNotFoundResponse(ErrorCodes.BUSINESS_DOES_NOT_EXIST,message=getBusinessDoesNotExistErrorPacket()) products = getProductForBusiness(business=businessToBeRetrieved) if request.GET.get('pageBy') == '-1': paginationDetails = { "totalPages": 1, "limit": -1, "currentPage": 1 } return paginatedResponse(message="list of all Products", body=transformProductList(products), pagination=paginationDetails ) if request.GET.get('pageBy'): pageBy = request.GET.get('pageBy') else: pageBy = 10 paginator = Paginator(products, pageBy) if request.GET.get('page'): pageNum = request.GET.get('page') else: pageNum = 1 # try if the page requested exists or is empty try: paginated_products = paginator.page(pageNum) paginationDetails = { "totalPages": paginator.num_pages, "limit": pageBy, "currentPage": pageNum } except Exception as err: logger.error(err) paginated_products = [] paginationDetails = {} return paginatedResponse(message="list of all products", body=transformProductList(paginated_products), pagination=paginationDetails)
def uploadFile(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()) listOfFileRecord = list() if request.FILES.__contains__("image"): image = request.FILES.get("image") imgName = image.name # verify if the file format to upload is supported if not imgName.lower().endswith(('jpg', 'jpeg', 'png')): return badRequestResponse( ErrorCodes.FILE_FORMAT_INVALID, message="The file format isn't supported for Restaurant Logos") listOfFileRecord.append((image, 'others')) for item in listOfFileRecord: file = item[0] typeOfFile = item[1] name = file.name # take the file and store it in a temporary folder fileName = str(datetime.now().timestamp()) + name filePath = '' + fileName if not uploadFileToS3(filepath=filePath, s3FileName=fileName): return internalServerErrorResponse( ErrorCodes.FILE_UPLOAD_FAILED, message=DefaultErrorMessages.FILE_UPLOAD_FAILED) return successResponse(message="successfully uploaded file", body="done")
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 getAllUsers(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 read the resource if user.userCategoryType != 'controller': return unAuthorizedResponse(ErrorCodes.UNAUTHORIZED_REQUEST, message=getUnauthorizedErrorPacket()) # retrieve a list of all users allUsersList = listAllUsers() # Paginate the retrieved users if request.GET.get('pageBy'): pageBy = request.GET.get('pageBy') else: pageBy = 10 paginator = Paginator(allUsersList, pageBy) if request.GET.get('page'): pageNum = request.GET.get('page') else: pageNum = 1 # try if the page requested exists or is empty try: paginated_UsersList = paginator.page(pageNum) paginationDetails = { "totalPages": paginator.num_pages, "limit": pageBy, "currentPage": pageNum } except Exception as e: print(e) paginated_UsersList = [] paginationDetails = {} return paginatedResponse(message="successfully retrieved users", body=transformUsersList(paginated_UsersList), pagination=paginationDetails )
def getUser(request, userID): # 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 the user exists and retrieve userToBeRetrieved = getUserById(userID) if userToBeRetrieved == None: return resourceNotFoundResponse(ErrorCodes.USER_DOES_NOT_EXIST, message=getUserDoesNotExistErrorPacket()) return successResponse(message="successfully retrieved user", body=transformUser(userToBeRetrieved))
def getBusinessLogoByBusinessID(request, businessID): # 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 business with given ID exists businessToBeRetrieved = getBusinessById(businessID) if businessToBeRetrieved == None: return resourceNotFoundResponse( ErrorCodes.BUSINESS_DOES_NOT_EXIST, message=getBusinessDoesNotExistErrorPacket()) logo = getBusinessLogo(business=businessToBeRetrieved) if logo == None: return resourceNotFoundResponse( ErrorCodes.LOGO_DOES_NOT_EXIST, message=getLogoDoesNotExistErrorPacket()) # get business address address = getBusinessAddress(business=businessToBeRetrieved) if address == None: return resourceNotFoundResponse( ErrorCodes.ADDRESS_DOES_NOT_EXIST, message=getAddressDoesNotExistErrorPacket()) img = logo.logo.url img = img[8:] logo_img = img return successResponse(message="successfully returned restaurant info", body=transformLogo(logo=logo, address=address, logoImg=logo_img))
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))