Esempio n. 1
0
    def test_updateItem_none(self):
        print("Running updateItem_none test case")
        self.assertIsNotNone(self.table)
        self.assertEqual(self.table.table_status, "ACTIVE")

        # No Key
        jsonData = {
            "UpdateExpression": "SET active = :a",
            "ExpressionAttributeValues": {
                ":a": "T"
            },
            "ReturnValues": "UPDATED_NEW"
        }

        response = db.updateItem(jsonData, self.table)
        self.assertIsNone(response)

        # Key not in table
        jsonData = {
            "Key": {
                "email": "*****@*****.**"
            },
            "UpdateExpression": "REMOVE active",
            "ReturnValues": "UPDATED_NEW"
        }

        response = db.updateItem(jsonData, self.table)
        self.assertIsNone(response)
Esempio n. 2
0
    def test_updateItem_json(self):
        print("Running updateItem_json test")
        self.assertIsNotNone(self.table)
        self.assertEqual(self.table.table_status, "ACTIVE")

        jsonData = {
            "Key": {
                "email": "*****@*****.**"
            },
            "UpdateExpression": "SET active = :a",
            "ExpressionAttributeValues": {
                ":a": "T"
            },
            "ReturnValues": "UPDATED_NEW"
        }

        response = db.updateItem(jsonData, self.table)
        self.assertIsNotNone(response.get('Attributes'))
        self.assertEqual(response.get('Attributes').get('active'), 'T')

        # No ExpressionAttributeValues
        jsonData = {
            "Key": {
                "email": "*****@*****.**"
            },
            "UpdateExpression": "REMOVE active",
            "ReturnValues": "UPDATED_NEW"
        }

        db.updateItem(jsonData, self.table)
        response = self.table.get_item(Key={
            "email": "*****@*****.**"
        }).get("Item")
        self.assertIsNone(response.get('active'))
Esempio n. 3
0
def addResetPasswordIdToUser(email, resetPasswordId, dbInstance):
  success = False;
  table = dbUtils.getTable('users', dbInstance)
  if table is not None:
    user = getUserByEmail(email,dbInstance)
    if user is not None:
      jsonData = {
        'Key': {'email': email},
        'UpdateExpression': 'SET resetPasswordId = :a',
        'ExpressionAttributeValues': { ':a': resetPasswordId },
        'ReturnValues' : 'UPDATED_NEW'
      }
      dbUtils.updateItem(jsonData, table)
      success = True
  return success
Esempio n. 4
0
def activate(activationId, dbInstance):
  response = ControllerResponse()
  table = dbUtils.getTable('users', dbInstance)
  items = []

  if table is None:
    MentiiLogging.getLogger().error('Unable to get table users in activate')
    response.addError('Could not access table. Error', 'The DB did not give us the table')
    return response

  #Scan for the email associated with this activationId
  scanResponse = dbUtils.scanFilter('activationId', activationId, table)

  if scanResponse is not None:
    #scanResponse is a dictionary that has a list of 'Items'
    items = scanResponse['Items']

  if not items or 'email' not in items[0].keys():
    response.addError('No user with activationid', 'The DB did not return a user with the passed in activationId')
  else:
    email = items[0]['email']

    jsonData = {
      'Key': {'email': email},
      'UpdateExpression': 'SET active = :a',
      'ExpressionAttributeValues': { ':a': 'T' },
      'ReturnValues' : 'UPDATED_NEW'
    }

    #Update using the email we have
    res = dbUtils.updateItem(jsonData, table)
    response.addToPayload('status', 'Success')

  return response
Esempio n. 5
0
def createClass(dynamoDBInstance, classData, email=None, userRole=None):
    response = ControllerResponse()

    #g will be not be available during testing
    #and email and userRole will need to be passed to the function
    if g:  # pragma: no cover
        email = g.authenticatedUser['email']
        userRole = g.authenticatedUser['userRole']
    #role is confirmed here incase createClass is called from somewhere other
    #than app.py create_class()
    if userRole != 'teacher' and userRole != 'admin':
        response.addError('Role error', 'Only teachers can create classes')
    elif classData is None or not checkClassDataValid(classData):
        response.addError('createClass call Failed.',
                          'Invalid class data given.')
    else:
        classTable = dbUtils.getTable('classes', dynamoDBInstance)
        userTable = dbUtils.getTable('users', dynamoDBInstance)
        if classTable is None or userTable is None:
            response.addError('createClass call Failed.',
                              'Unable to locate necessary table(s).')
        else:
            classCode = str(uuid.uuid4())
            newClass = {
                'code': classCode,
                'title': classData['title'],
                'description': classData['description']
            }

            if 'department' in classData.keys() and classData['department']:
                newClass['department'] = classData['department']
            if 'section' in classData.keys() and classData['section']:
                newClass['classSection'] = classData['section']

            result = dbUtils.putItem(newClass, classTable)

            if result is None:
                response.addError('createClass call Failed.',
                                  'Unable to create class in classes table.')
            else:
                # Note: if teaching attribute does not previously exist, a set of class codes will be created
                # otherwise, the class code will be added to the set of class codes
                codeSet = set([classCode])
                jsonData = {
                    'Key': {
                        'email': email
                    },
                    'UpdateExpression': 'ADD teaching :classCode',
                    'ExpressionAttributeValues': {
                        ':classCode': codeSet
                    },
                    'ReturnValues': 'UPDATED_NEW'
                }
                res = dbUtils.updateItem(jsonData, userTable)
                if res is None:
                    response.addError('createClass call failed',
                                      'Unable to update user data')
                else:
                    response.addToPayload('Success', 'Class Created')
    return response
Esempio n. 6
0
def removeClassFromStudent(dynamoDBInstance, response, email, classCode):
    usersTable = dbUtils.getTable('users', dynamoDBInstance)
    if usersTable is None:
        MentiiLogging.getLogger().error(
            'Unable to get users table in removeStudentFromClass')
        response.addError('Remove Student From Class Failed.',
                          'Unable to locate necessary table(s).')
    else:
        # check that user exists and user has that class
        user = user_ctrl.getUserByEmail(email, dynamoDBInstance)
        if user is None:
            MentiiLogging.getLogger().error(
                'Unable to get user by email in removeStudentFromClass')
            response.addError('Failed to remove student from class',
                              'Unable to find user')
        else:
            classCodes = user['classCodes']  #set
            if classCode not in classCodes:
                response.addError('Failed to remove class from student',
                                  'Class not found')
            else:
                classCodes.remove(classCode)
                jsonData = buildUpdateJsonData('email', email, 'classCodes',
                                               classCodes)
                res = dbUtils.updateItem(jsonData, usersTable)
                if res is None:
                    MentiiLogging.getLogger().error(
                        'Unable to update classes in removeStudentFromClass')
                    response.addError('Failed to remove student from class',
                                      'Unable to update user data')
                else:
                    MentiiLogging.getLogger().info(
                        'Class removal success. Removed class from student')
    return response
Esempio n. 7
0
    def test_updateItem_not_previously_existed(self):
        print("Running updateItem_not_previously_existed test")
        self.assertIsNotNone(self.table)
        self.assertEqual(self.table.table_status, "ACTIVE")

        jsonData = '{\
      "Key": {"email": "*****@*****.**"},\
      "UpdateExpression": "SET active = :a",\
      "ExpressionAttributeValues": { ":a": "F" },\
      "ReturnValues" : "UPDATED_NEW"\
    }'

        response = db.updateItem(jsonData, self.table)
        self.assertIsNone(response)
Esempio n. 8
0
def undoClassCodeRemoval(dynamoDBInstance, email, classCode):
    # add classCode back to student if there was an error removing student from class
    usersTable = dbUtils.getTable('users', dynamoDBInstance)
    user = user_ctrl.getUserByEmail(email, dynamoDBInstance)
    jsonData = {}
    # if the classCodes attribute was removed, add the attribute
    if user.get('classCodes') is None:
        user_ctrl.addClassCodeToStudent(email, classCode, dynamoDBInstance)
    # update classCodes attribute
    else:
        classes = user.get('classCodes')  #set
        classes.add(classCode)
        #update item
        jsonData = {
            'Key': {
                'email': email
            },
            'UpdateExpression': 'SET classCodes = :cc',
            'ExpressionAttributeValues': {
                ':cc': classes
            },
            'ReturnValues': 'UPDATED_NEW'
        }
    dbUtils.updateItem(jsonData, usersTable)
Esempio n. 9
0
    def test_updateItem_string(self):
        print("Running updateItem_string test")
        self.assertIsNotNone(self.table)
        self.assertEqual(self.table.table_status, "ACTIVE")

        jsonData = '{\
      "Key": {"email": "*****@*****.**"},\
      "UpdateExpression": "SET active = :a",\
      "ExpressionAttributeValues": { ":a": "F" },\
      "ReturnValues" : "UPDATED_NEW"\
    }'

        response = db.updateItem(jsonData, self.table)
        self.assertIsNotNone(response.get('Attributes'))
        self.assertEqual(response.get('Attributes').get('active'), 'F')
Esempio n. 10
0
def updatePasswordForEmailAndResetId(email, password, resetPasswordId, dbInstance):
  res = None
  user = getUserByEmail(email, dbInstance)
  if user is not None:
    storedResetPasswordId = user.get('resetPasswordId', None)
    if storedResetPasswordId == resetPasswordId:
      table = dbUtils.getTable('users', dbInstance)
      if table is not None:
        hashedPassword = hashPassword(password)
        jsonData = {
          'Key': {'email': email},
          'UpdateExpression': 'SET password = :a REMOVE resetPasswordId',
          'ExpressionAttributeValues': { ':a': hashedPassword },
          'ReturnValues' : 'UPDATED_NEW'
        }
        res = dbUtils.updateItem(jsonData, table)
  return res
Esempio n. 11
0
def addClassCodeToStudent(email, classCode, dynamoDBInstance):
  userTable = dbUtils.getTable('users', dynamoDBInstance)
  if userTable:
    codeSet = set([classCode])
    addClassToUser = {
      'Key': {'email': email},
      'UpdateExpression': 'ADD classCodes :i',
      'ExpressionAttributeValues': { ':i': codeSet },
      'ReturnValues' : 'UPDATED_NEW'
    }
    res = dbUtils.updateItem(addClassToUser, userTable)
    if (  res and
          'Attributes' in res and
          'classCodes' in res['Attributes'] and
          classCode in res['Attributes']['classCodes']
    ):
      return res['Attributes']['classCodes']
  return None
Esempio n. 12
0
def changeUserRole(jsonData, dbInstance, adminRole=None):
  response = ControllerResponse()

  #g will be not be available during testing
  #and adminRole will need to be passed to the function
  if g: # pragma: no cover
    adminRole = g.authenticatedUser['userRole']
  #adminRole is confirmed here incase changeUserRole is called from somewhere
  #other than app.py changeUserRole()
  if adminRole != 'admin':
    response.addError('Role Error', 'Only admins can change user roles')
  elif 'email' not in jsonData.keys() or 'userRole' not in jsonData.keys():
    response.addError('Key Missing Error', 'Email or role missing from json data')
  else:
    email = jsonData['email']
    userRole = jsonData['userRole']

    userTable = dbUtils.getTable('users', dbInstance)
    if userTable is None:
      MentiiLogging.getLogger().error('Unable to get table "users" in changeUserRole')
      response.addError('No Access to Data', 'Unable to get data from database')
    else:
      if userRole != 'student' and userRole != 'teacher' and userRole != 'admin':
        MentiiLogging.getLogger().error('Invalid role: ' + userRole + ' specified. Unable to change user role')
        response.addError('Invalid Role Type', 'Invaid role specified')
      else:

        data = {
            'Key': {'email': email},
            'UpdateExpression': 'SET userRole = :ur',
            'ExpressionAttributeValues': { ':ur': userRole },
            'ReturnValues' : 'UPDATED_NEW'
        }

        result = dbUtils.updateItem(data, userTable)

        if result is None:
          MentiiLogging.getLogger().error('Unable to update the user with email: ' + email + ' in changeUserRole')
          response.addError('Result Update Error', 'Could not update the user role in database')
        else:
          response.addToPayload('Result:', result)
          response.addToPayload('success', 'true')

  return response
Esempio n. 13
0
def addStudentToClass(classCode, email, dynamoDBInstance):
  classTable = dbUtils.getTable('classes', dynamoDBInstance)
  if classTable:
    emailSet = set([email])
    addUserToClass = {
      'Key': {'code': classCode},
      'UpdateExpression': 'ADD students :i',
      'ExpressionAttributeValues': { ':i': emailSet },
      'ReturnValues' : 'ALL_NEW'
    }
    res = dbUtils.updateItem(addUserToClass, classTable)
    if (  res and
          'Attributes' in res and
          'students' in res['Attributes'] and
          email in res['Attributes']['students'] and
          'title' in res['Attributes']
    ):
      return res['Attributes']
  return None
Esempio n. 14
0
def removeStudentFromClass(dynamoDBInstance, response, email, classCode):
    classesTable = dbUtils.getTable('classes', dynamoDBInstance)
    if classesTable is None:
        MentiiLogging.getLogger().error(
            'Unable to get classes table in removeStudentFromClass')
        response.addError('Remove Student From Class Failed.',
                          'Unable to locate necessary table(s).')
    else:
        # check that class exists and class has that user
        cl = getClassByCode(classCode, dynamoDBInstance)
        if cl is None:
            MentiiLogging.getLogger().error(
                'Unable to get class by classCode in removeStudentFromClass')
            response.addError('Failed to remove student from class',
                              'Unable to get class')
        else:
            students = cl['students']  #set
            if email not in students:
                response.addError('Failed to remove student from class',
                                  'Student not found')
            else:
                students.remove(email)
                jsonData = buildUpdateJsonData('code', classCode, 'students',
                                               students)
                res = dbUtils.updateItem(jsonData, classesTable)
                if res is None:
                    MentiiLogging.getLogger().error(
                        'Unable to update classes in removeStudentFromClass')
                    response.addError('Failed to remove student from class',
                                      'Unable to update classes data')
                if response.hasErrors():
                    undoClassCodeRemoval(dynamoDBInstance, email, classCode)
                else:
                    MentiiLogging.getLogger().info(
                        'Student removal success. Removed student from class')
    return response
Esempio n. 15
0
def updateClassDetails(jsonData, dynamodb, email=None, userRole=None):
    response = ControllerResponse()
    classesTable = dbUtils.getTable('classes', dynamodb)

    if classesTable is None:
        MentiiLogging.getLogger().error(
            'Unable to get classes table in getPublicClassList')
        response.addError('Failed to get class list',
                          'A database error occured')
    else:
        # get data from request body
        code = jsonData.get('code')
        title = jsonData.get('title')
        desc = jsonData.get('description')
        dept = jsonData.get('department')  # optional
        sec = jsonData.get('section')  # optional

        if g:  # pragma: no cover
            email = g.authenticatedUser['email']
            userRole = g.authenticatedUser['userRole']
        #check if teacher is teacher of the class
        if ((userRole == 'teacher' or userRole == 'admin')
                and code in getTaughtClassCodesFromUser(dynamodb, email)):

            updateExprString = 'SET title =:t, description =:dn'
            expresionAttrDict = {':t': title, ':dn': desc}

            removeString = ''
            # if empty string is given, remove the attribute
            if dept == '' and sec == '':
                removeString = removeString + ' REMOVE department, classSection'
            else:
                if dept == '':
                    removeString = removeString + ' REMOVE department'
                else:
                    updateExprString = updateExprString + ', department = :dt'
                    expresionAttrDict[':dt'] = dept
                if sec == '':
                    removeString = removeString + ' REMOVE classSection'
                else:
                    updateExprString = updateExprString + ', classSection = :s'
                    expresionAttrDict[':s'] = sec

            updateExprString = updateExprString + removeString

            # update item
            updateData = {
                'Key': {
                    'code': code
                },
                'UpdateExpression': updateExprString,
                'ExpressionAttributeValues': expresionAttrDict,
                'ReturnValues': 'UPDATED_NEW'
            }

            res = dbUtils.updateItem(updateData, classesTable)
            if res is None:
                response.addError('updateClassDetails has error',
                                  'Unable to update class details')
            else:
                response.addToPayload('Success', 'Class Details Updated')
        else:
            response.addError('Teacher permissions incorrect',
                              'Unable to update class details')
    return response