Esempio n. 1
0
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)
Esempio n. 3
0
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 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")
Esempio n. 5
0
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 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))
Esempio n. 8
0
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))