def lambda_handler(event, context):
    print("Line Break")
    print(context)
    auth = MFAuth()
    authResponse = auth.getAdminResoursePolicy(event)
    print(authResponse)
    return authResponse
def lambda_handler(event, context):

    if event['httpMethod'] == 'GET':
        items = scan_dynamodb_app_table()
        newitem = sorted(items, key=lambda i: i['app_name'])
        return {
            'headers': {
                'Access-Control-Allow-Origin': '*'
            },
            'body': json.dumps(newitem)
        }
    elif event['httpMethod'] == 'POST':
        auth = MFAuth()
        authResponse = auth.getUserResourceCrationPolicy(event)
        if authResponse['action'] == 'allow':
            try:
                body = json.loads(event['body'])
                if 'app_name' not in body:
                    return {
                        'headers': {
                            'Access-Control-Allow-Origin': '*'
                        },
                        'statusCode': 400,
                        'body': 'attribute app_name is required'
                    }
                if "app_id" in body:
                    return {
                        'headers': {
                            'Access-Control-Allow-Origin': '*'
                        },
                        'statusCode':
                        400,
                        'body':
                        "You cannot create app_id, this is managed by the system"
                    }
                # Check if attribute is defined in the App schema
                app_attributes = []
                for app_schema in schema_table.scan()['Items']:
                    if app_schema['schema_name'] == "app":
                        app_attributes = app_schema['attributes']
                for key in body.keys():
                    check = False
                    for attribute in app_attributes:
                        if key == attribute['name']:
                            check = True
                    if check == False:
                        message = "App attribute: " + key + " is not defined in the App schema"
                        return {
                            'headers': {
                                'Access-Control-Allow-Origin': '*'
                            },
                            'statusCode': 400,
                            'body': message
                        }
                # Check if attribute in the body matches the list value defined in schema
                for attribute in app_attributes:
                    if 'listvalue' in attribute:
                        listvalue = attribute['listvalue'].split(',')
                        for key in body.keys():
                            if key == attribute['name']:
                                if body[key] not in listvalue:
                                    message = "App attribute " + key + " for app " + body[
                                        'app_name'] + " is '" + body[
                                            key] + "', does not match the list values '" + attribute[
                                                'listvalue'] + "' defined in the App schema"
                                    return {
                                        'headers': {
                                            'Access-Control-Allow-Origin': '*'
                                        },
                                        'statusCode': 400,
                                        'body': message
                                    }
            except Exception as e:
                print(e)
                return {
                    'headers': {
                        'Access-Control-Allow-Origin': '*'
                    },
                    'statusCode': 400,
                    'body': 'malformed json input'
                }

            # Check if there is a duplicate app_name
            itemlist = scan_dynamodb_app_table()
            for app in itemlist:
                if app['app_name'].lower() == str(body['app_name']).lower():
                    return {
                        'headers': {
                            'Access-Control-Allow-Origin': '*'
                        },
                        'statusCode': 400,
                        'body':
                        'app_name: ' + body['app_name'] + ' already exist'
                    }

            # Validate Wave_id
            if 'wave_id' in body:
                waves = waves_table.scan(ConsistentRead=True)
                check = False
                for wave in waves['Items']:
                    if wave['wave_id'] == str(body['wave_id']):
                        check = True
                if check == False:
                    message = 'wave Id: ' + body['wave_id'] + ' does not exist'
                    return {
                        'headers': {
                            'Access-Control-Allow-Origin': '*'
                        },
                        'statusCode': 400,
                        'body': message
                    }

            # Get vacant app_id
            ids = []
            for item in itemlist:
                ids.append(int(item['app_id']))
            ids.sort()
            app_id = 1
            for id in ids:
                if app_id == id:
                    app_id += 1
            body['app_id'] = str(app_id)

            # Update item
            resp = apps_table.put_item(Item=body)
            if (resp['ResponseMetadata']['HTTPStatusCode'] == 200):
                new_item = {}
                query_resp = apps_table.query(
                    KeyConditionExpression=Key('app_id').eq(str(app_id)))
                if 'Items' in query_resp:
                    new_item = query_resp['Items']
                else:
                    new_item = "Creating app " + body['app_name'] + " failed"
            return {
                'headers': {
                    'Access-Control-Allow-Origin': '*'
                },
                'body': json.dumps(new_item)
            }
        else:
            return {
                'headers': {
                    'Access-Control-Allow-Origin': '*'
                },
                'statusCode': 401,
                'body': json.dumps(authResponse)
            }
Ejemplo n.º 3
0
def lambda_handler(event, context):

    if event['httpMethod'] == 'GET':
        if 'appid' in event['pathParameters']:
            resp = servers_table.query(
                    IndexName='app_id-index',
                    KeyConditionExpression=Key('app_id').eq(event['pathParameters']['appid'])
                )
            if resp['Count'] is not 0:
                return {'headers': {'Access-Control-Allow-Origin': '*'},
                        'body': json.dumps(resp['Items'])}
            else:
                return {'headers': {'Access-Control-Allow-Origin': '*'},
                        'statusCode': 400, 'body': 'App Id: ' + str(event['pathParameters']['appid']) + ' does not exist'}
        elif 'serverid' in event['pathParameters']:
            resp = servers_table.get_item(Key={'server_id': event['pathParameters']['serverid']})
            if 'Item' in resp:
                return {'headers': {'Access-Control-Allow-Origin': '*'},
                        'body': json.dumps(resp['Item'])}
            else:
                return {'headers': {'Access-Control-Allow-Origin': '*'},
                        'statusCode': 400, 'body': 'Server Id: ' + str(event['pathParameters']['serverid']) + ' does not exist'}

    elif event['httpMethod'] == 'PUT':
        auth = MFAuth()
        authResponse = auth.getUserAttributePolicy(event)
        if authResponse['action'] == 'allow':
                try:
                    body = json.loads(event['body'])
                    server_attributes = []
                    if "server_id" in body:
                        return {'headers': {'Access-Control-Allow-Origin': '*'},
                                'statusCode': 400, 'body': "You cannot modify server_id, it is managed by the system"}
                except Exception as e:
                    print(e)
                    return {'headers': {'Access-Control-Allow-Origin': '*'},
                            'statusCode': 400, 'body': 'malformed json input'}
                # check if server id exist
                existing_attr = servers_table.get_item(Key={'server_id': event['pathParameters']['serverid']})
                print(existing_attr)
                if 'Item' not in existing_attr:
                  return {'headers': {'Access-Control-Allow-Origin': '*'},
                          'statusCode': 400, 'body': 'server Id: ' + str(event['pathParameters']['serverid']) + ' does not exist'}

                # Check if there is a duplicate server_name
                servers = scan_dynamodb_server_table()
                for server in servers:
                  if 'server_name' in body:
                    if server['server_name'].lower() == str(body['server_name']).lower() and server['server_id'] != str(event['pathParameters']['serverid']):
                        return {'headers': {'Access-Control-Allow-Origin': '*'},
                                'statusCode': 400, 'body': 'server_name: ' +  body['server_name'] + ' already exist'}

                # Validate App_id
                if 'app_id' in body:
                    apps = scan_dynamodb_app_table()
                    check = False
                    for app in apps:
                        if app['app_id'] == str(body['app_id']):
                            check = True
                    if check == False:
                        message = 'app Id: ' + body['app_id'] + ' does not exist'
                        return {'headers': {'Access-Control-Allow-Origin': '*'},
                                'statusCode': 400, 'body': message}

                # Check if attribute is defined in the Server schema
                for server_schema in schema_table.scan()['Items']:
                    if server_schema['schema_name'] == "server":
                        server_attributes = server_schema['attributes']
                for key in body.keys():
                    check = False
                    for attribute in server_attributes:
                        if key == attribute['name']:
                           check = True
                    if check == False:
                        message = "Server attribute: " + key + " is not defined in the Server schema"
                        return {'headers': {'Access-Control-Allow-Origin': '*'},
                                'statusCode': 400, 'body': message}

                # Check if attribute in the body matches the list value defined in schema
                for attribute in server_attributes:
                    if 'listvalue' in attribute:
                        listvalue = attribute['listvalue'].split(',')
                        for key in body.keys():
                            if key == attribute['name']:
                                if body[key] not in listvalue:
                                    message = "Server attribute " + key + " for server " + body['server_name'] + " is '" + body[key] + "', does not match the list values '" + attribute['listvalue'] + "' defined in the Server schema"
                                    return {'headers': {'Access-Control-Allow-Origin': '*'},
                                            'statusCode': 400, 'body': message}

                # Merge new attributes with existing one
                for key in body.keys():
                    existing_attr['Item'][key] = body[key]
                new_attr = existing_attr
                keys = list(new_attr['Item'].keys())
                # Delete empty keys
                for key in keys:
                    if new_attr['Item'][key] == '':
                       del new_attr['Item'][key]
                       continue
                    if isinstance(new_attr['Item'][key], list):
                       if len(new_attr['Item'][key]) == 1 and new_attr['Item'][key][0] == '':
                            del new_attr['Item'][key]
                print(new_attr)
                resp = servers_table.put_item(
                Item=new_attr['Item']
                )
                return {'headers': {'Access-Control-Allow-Origin': '*'},
                        'body': json.dumps(resp)}
        else:
            return {'headers': {'Access-Control-Allow-Origin': '*'},
                    'statusCode': 401,
                    'body': json.dumps(authResponse)}

    elif event['httpMethod'] == 'DELETE':
        auth = MFAuth()
        authResponse = auth.getUserResourceCrationPolicy(event)
        if authResponse['action'] == 'allow':
            resp = servers_table.get_item(Key={'server_id': event['pathParameters']['serverid']})
            if 'Item' in resp:
                respdel = servers_table.delete_item(Key={'server_id': event['pathParameters']['serverid']})
                if respdel['ResponseMetadata']['HTTPStatusCode'] == 200:
                    return {'headers': {'Access-Control-Allow-Origin': '*'},
                            'statusCode': 200, 'body': "Server " + str(resp['Item']) + " was successfully deleted"}
                else:
                    return {'headers': {'Access-Control-Allow-Origin': '*'},
                            'statusCode': respdel['ResponseMetadata']['HTTPStatusCode'], 'body': json.dumps(respdel)}
            else:
                return {'headers': {'Access-Control-Allow-Origin': '*'},
                        'statusCode': 400, 'body': 'server Id: ' + str(event['pathParameters']['serverid']) + ' does not exist'}
        else:
            return {'headers': {'Access-Control-Allow-Origin': '*'},
                    'statusCode': 401,
                    'body': json.dumps(authResponse)}
def lambda_handler(event, context):

    if event['httpMethod'] == 'GET':
        resp = apps_table.get_item(Key={'app_id': event['pathParameters']['appid']})
        if 'Item' in resp:
            return {'headers': {'Access-Control-Allow-Origin': '*'},
                    'body': json.dumps(resp['Item'])}
        else:
            return {'headers': {'Access-Control-Allow-Origin': '*'},
                    'statusCode': 400, 'body': 'app Id: ' + str(event['pathParameters']['appid']) + ' does not exist'}

    elif event['httpMethod'] == 'PUT':
        auth = MFAuth()
        authResponse = auth.getUserAttributePolicy(event)
        if authResponse['action'] == 'allow':
            try:
                body = json.loads(event['body'])
                app_attributes = []
                if "app_id" in body:
                    return {'headers': {'Access-Control-Allow-Origin': '*'},
                            'statusCode': 400, 'body': "You cannot modify app_id, this is managed by the system"}

                # check if app id exist
                existing_attr = apps_table.get_item(Key={'app_id': event['pathParameters']['appid']})
                print(existing_attr)
                if 'Item' not in existing_attr:
                  return {'headers': {'Access-Control-Allow-Origin': '*'},
                          'statusCode': 400, 'body': 'app Id: ' + str(event['pathParameters']['appid']) + ' does not exist'}

                # Validate Wave_id
                if 'wave_id' in body:
                    waves = waves_table.scan()
                    check = False
                    for wave in waves['Items']:
                        if wave['wave_id'] == str(body['wave_id']):
                           check = True
                    if check == False:
                        message = 'wave Id: ' + body['wave_id'] + ' does not exist'
                        return {'headers': {'Access-Control-Allow-Origin': '*'},
                                'statusCode': 400, 'body': message}

                # Check if there is a duplicate app_name
                apps = apps_table.scan()
                for app in apps['Items']:
                  if 'app_name' in body:
                    if app['app_name'].lower() == str(body['app_name']).lower() and app['app_id'] != str(event['pathParameters']['appid']):
                        return {'headers': {'Access-Control-Allow-Origin': '*'},
                                'statusCode': 400, 'body': 'app_name: ' +  body['app_name'] + ' already exist'}

                # Check if attribute is defined in the App schema
                for app_schema in schema_table.scan()['Items']:
                    if app_schema['schema_name'] == "app":
                        app_attributes = app_schema['attributes']
                for key in body.keys():
                    check = False
                    for attribute in app_attributes:
                        if key == attribute['name']:
                           check = True
                    if check == False:
                        message = "App attribute: " + key + " is not defined in the App schema"
                        return {'headers': {'Access-Control-Allow-Origin': '*'},
                                'statusCode': 400, 'body': message}

                # Check if attribute in the body matches the list value defined in schema
                for attribute in app_attributes:
                    if 'listvalue' in attribute:
                        listvalue = attribute['listvalue'].split(',')
                        for key in body.keys():
                            if key == attribute['name']:
                                if body[key] not in listvalue:
                                    message = "App attribute " + key + " for app " + body['app_name'] + " is '" + body[key] + "', does not match the list values '" + attribute['listvalue'] + "' defined in the App schema"
                                    return {'headers': {'Access-Control-Allow-Origin': '*'},
                                            'statusCode': 400, 'body': message}

                # Merge new attributes with existing one
                for key in body.keys():
                    existing_attr['Item'][key] = body[key]
                print(existing_attr)
                resp = apps_table.put_item(
                Item=existing_attr['Item']
                )
                return {'headers': {'Access-Control-Allow-Origin': '*'},
                        'body': json.dumps(resp)}
            except Exception as e:
                print(e)
                return {'headers': {'Access-Control-Allow-Origin': '*'},
                        'statusCode': 400, 'body': 'malformed json input'}
        else:
            return {'headers': {'Access-Control-Allow-Origin': '*'},
                    'statusCode': 401,
                    'body': json.dumps(authResponse)}

    elif event['httpMethod'] == 'DELETE':
        auth = MFAuth()
        authResponse = auth.getUserResourceCrationPolicy(event)
        if authResponse['action'] == 'allow':
            resp = apps_table.get_item(Key={'app_id': event['pathParameters']['appid']})
            if 'Item' in resp:
                respdel = apps_table.delete_item(Key={'app_id': event['pathParameters']['appid']})
                if respdel['ResponseMetadata']['HTTPStatusCode'] == 200:
                    # Remove App Id from servers
                    servers = servers_table.query(
                            IndexName='app_id-index',
                            KeyConditionExpression=Key('app_id').eq(event['pathParameters']['appid'])
                        )
                    if servers['Count'] is not 0:
                        serverids = []
                        for server in servers['Items']:
                          serverids.append(str(server['server_id']))
                        for id in serverids:
                            serverattr = servers_table.get_item(Key={'server_id': id})
                            del serverattr['Item']['app_id']
                            serverupdate = servers_table.put_item(
                                Item=serverattr['Item']
                                )
                    return {'headers': {'Access-Control-Allow-Origin': '*'},
                            'statusCode': 200, 'body': "App " + str(resp['Item']) + " was successfully deleted"}
                else:
                    return {'headers': {'Access-Control-Allow-Origin': '*'},
                            'statusCode': respdel['ResponseMetadata']['HTTPStatusCode'], 'body': json.dumps(respdel)}
            else:
                return {'headers': {'Access-Control-Allow-Origin': '*'},
                        'statusCode': 400, 'body': 'app Id: ' + str(event['pathParameters']['appid']) + ' does not exist'}
        else:
            return {'headers': {'Access-Control-Allow-Origin': '*'},
                    'statusCode': 401,
                    'body': json.dumps(authResponse)}
Ejemplo n.º 5
0
def lambda_handler(event, context):

    if event['httpMethod'] == 'GET':
        resp = waves_table.scan()
        item = resp['Items']
        newitem = sorted(item, key=lambda i: i['wave_id'])
        return {
            'headers': {
                'Access-Control-Allow-Origin': '*'
            },
            'body': json.dumps(newitem)
        }

    elif event['httpMethod'] == 'POST':
        auth = MFAuth()
        authResponse = auth.getUserResourceCrationPolicy(event)
        if authResponse['action'] == 'allow':
            try:
                body = json.loads(event['body'])
                if 'wave_name' not in body:
                    return {
                        'headers': {
                            'Access-Control-Allow-Origin': '*'
                        },
                        'statusCode': 400,
                        'body': 'attribute wave_name is required'
                    }
            except Exception as e:
                print(e)
                return {
                    'headers': {
                        'Access-Control-Allow-Origin': '*'
                    },
                    'statusCode': 400,
                    'body': 'malformed json input'
                }

            # Check if there is a duplicate wave_name
            itemlist = waves_table.scan()
            for item in itemlist['Items']:
                if body['wave_name'] in item['wave_name']:
                    return {
                        'headers': {
                            'Access-Control-Allow-Origin': '*'
                        },
                        'statusCode':
                        400,
                        'body':
                        'wave_name: ' + body['wave_name'] + ' already exist'
                    }

            # Get vacant wave_id
            ids = []
            for item in itemlist['Items']:
                ids.append(int(item['wave_id']))
            ids.sort()
            wave_id = 1
            for id in ids:
                if wave_id == id:
                    wave_id += 1
            body['wave_id'] = str(wave_id)

            # Update item
            resp = waves_table.put_item(Item=body)
            return {
                'headers': {
                    'Access-Control-Allow-Origin': '*'
                },
                'body': json.dumps(resp)
            }
        else:
            return {
                'headers': {
                    'Access-Control-Allow-Origin': '*'
                },
                'statusCode': 401,
                'body': json.dumps(authResponse)
            }
Ejemplo n.º 6
0
def lambda_handler(event, context):

    if event['httpMethod'] == 'GET':
        resp = waves_table.scan()
        item = resp['Items']
        newitem = sorted(item, key=lambda i: i['wave_id'])
        return {
            'headers': {
                'Access-Control-Allow-Origin': '*'
            },
            'body': json.dumps(newitem)
        }

    elif event['httpMethod'] == 'POST':
        auth = MFAuth()
        authResponse = auth.getUserResourceCrationPolicy(event)
        if authResponse['action'] == 'allow':
            try:
                body = json.loads(event['body'])
                if 'wave_name' not in body:
                    return {
                        'headers': {
                            'Access-Control-Allow-Origin': '*'
                        },
                        'statusCode': 400,
                        'body': 'attribute wave_name is required'
                    }

                # Check if attribute is defined in the Wave schema
                wave_attributes = []
                for wave_schema in schema_table.scan()['Items']:
                    if wave_schema['schema_name'] == "wave":
                        wave_attributes = wave_schema['attributes']
                for key in body.keys():
                    check = False
                    for attribute in wave_attributes:
                        if key == attribute['name']:
                            check = True
                    if check == False:
                        message = "Wave attribute: " + key + " is not defined in the Wave schema"
                        return {
                            'headers': {
                                'Access-Control-Allow-Origin': '*'
                            },
                            'statusCode': 400,
                            'body': message
                        }
                # Check if attribute in the body matches the list value defined in schema
                for attribute in wave_attributes:
                    if 'listvalue' in attribute:
                        listvalue = attribute['listvalue'].split(',')
                        for key in body.keys():
                            if key == attribute['name']:
                                if body[key] not in listvalue:
                                    message = "Wave attribute " + key + " for wave " + body[
                                        'wave_name'] + " is '" + body[
                                            key] + "', does not match the list values '" + attribute[
                                                'listvalue'] + "' defined in the Wave schema"
                                    return {
                                        'headers': {
                                            'Access-Control-Allow-Origin': '*'
                                        },
                                        'statusCode': 400,
                                        'body': message
                                    }
            except Exception as e:
                print(e)
                return {
                    'headers': {
                        'Access-Control-Allow-Origin': '*'
                    },
                    'statusCode': 400,
                    'body': 'malformed json input'
                }

            # Check if there is a duplicate wave_name
            itemlist = waves_table.scan()
            for item in itemlist['Items']:
                if body['wave_name'].lower() == item['wave_name'].lower():
                    return {
                        'headers': {
                            'Access-Control-Allow-Origin': '*'
                        },
                        'statusCode':
                        400,
                        'body':
                        'wave_name: ' + body['wave_name'] + ' already exist'
                    }

            # Get vacant wave_id
            ids = []
            for item in itemlist['Items']:
                ids.append(int(item['wave_id']))
            ids.sort()
            wave_id = 1
            for id in ids:
                if wave_id == id:
                    wave_id += 1
            body['wave_id'] = str(wave_id)

            # Update item
            resp = waves_table.put_item(Item=body)
            return {
                'headers': {
                    'Access-Control-Allow-Origin': '*'
                },
                'body': json.dumps(resp)
            }
        else:
            return {
                'headers': {
                    'Access-Control-Allow-Origin': '*'
                },
                'statusCode': 401,
                'body': json.dumps(authResponse)
            }
def lambda_handler(event, context):

    if event['httpMethod'] == 'GET':
        resp = waves_table.get_item(Key={'wave_id': event['pathParameters']['waveid']})
        if 'Item' in resp:
            return {'headers': {'Access-Control-Allow-Origin': '*'},
                    'body': json.dumps(resp['Item'])}
        else:
            return {'headers': {'Access-Control-Allow-Origin': '*'},
                    'statusCode': 400, 'body': 'wave Id: ' + str(event['pathParameters']['waveid']) + ' does not exist'}

    elif event['httpMethod'] == 'PUT':
        auth = MFAuth()
        authResponse = auth.getUserResourceCrationPolicy(event)
        if authResponse['action'] == 'allow':
            try:
                body = json.loads(event['body'])
                if "wave_id" in body:
                    return {'headers': {'Access-Control-Allow-Origin': '*'},
                            'statusCode': 400, 'body': "You cannot modify wave_id, this is managed by the system"}

                # check if wave id exist
                existing_attr = waves_table.get_item(Key={'wave_id': event['pathParameters']['waveid']})
                print(existing_attr)
                if 'Item' not in existing_attr:
                  return {'headers': {'Access-Control-Allow-Origin': '*'},
                          'statusCode': 400, 'body': 'wave Id: ' + str(event['pathParameters']['waveid']) + ' does not exist'}

                # Check if there is a duplicate wave_name
                waves = waves_table.scan()
                for wave in waves['Items']:
                  if 'wave_name' in body:
                    if wave['wave_name'].lower() == str(body['wave_name']).lower() and wave['wave_id'] != str(event['pathParameters']['waveid']):
                        return {'headers': {'Access-Control-Allow-Origin': '*'},
                                'statusCode': 400, 'body': 'wave_name: ' +  body['wave_name'] + ' already exist'}

                # Merge new attributes with existing one
                for key in body.keys():
                    existing_attr['Item'][key] = body[key]
                print(existing_attr)
                resp = waves_table.put_item(
                Item=existing_attr['Item']
                )
                return {'headers': {'Access-Control-Allow-Origin': '*'},
                        'body': json.dumps(resp)}
            except Exception as e:
                print(e)
                return {'headers': {'Access-Control-Allow-Origin': '*'},
                        'statusCode': 400, 'body': 'malformed json input'}
        else:
            return {'headers': {'Access-Control-Allow-Origin': '*'},
                    'statusCode': 401,
                    'body': json.dumps(authResponse)}

    elif event['httpMethod'] == 'DELETE':
        auth = MFAuth()
        authResponse = auth.getUserResourceCrationPolicy(event)
        if authResponse['action'] == 'allow':
            resp = waves_table.get_item(Key={'wave_id': event['pathParameters']['waveid']})
            if 'Item' in resp:
                respdel = waves_table.delete_item(Key={'wave_id': event['pathParameters']['waveid']})
                if respdel['ResponseMetadata']['HTTPStatusCode'] == 200:
                    # Remove Wave Id from apps
                    apps = apps_table.scan()
                    if apps['Count'] is not 0:
                        for app in apps['Items']:
                           newapp = app
                           if 'wave_id' in app:
                               if str(app['wave_id']) == str(event['pathParameters']['waveid']):
                                   del newapp['wave_id']
                                   appupdate = apps_table.put_item(
                                                    Item=newapp
                                                    )
                    return {'headers': {'Access-Control-Allow-Origin': '*'},
                            'statusCode': 200, 'body': "Wave " + str(resp['Item']) + " was successfully deleted"}
                else:
                    return {'headers': {'Access-Control-Allow-Origin': '*'},
                            'statusCode': respdel['ResponseMetadata']['HTTPStatusCode'], 'body': json.dumps(respdel)}
            else:
                return {'headers': {'Access-Control-Allow-Origin': '*'},
                        'statusCode': 400, 'body': 'wave Id: ' + str(event['pathParameters']['waveid']) + ' does not exist'}
        else:
            return {'headers': {'Access-Control-Allow-Origin': '*'},
                    'statusCode': 401,
                    'body': json.dumps(authResponse)}
def lambda_handler(event, context):

    if event['httpMethod'] == 'GET':
        resp = servers_table.scan()
        item = resp['Items']
        newitem = sorted(item, key = lambda i: i['server_name'])
        return {'headers': {'Access-Control-Allow-Origin': '*'},
                'body': json.dumps(newitem)}

    elif event['httpMethod'] == 'POST':
        auth = MFAuth()
        authResponse = auth.getUserResourceCrationPolicy(event)
        if authResponse['action'] == 'allow':
            try:
                body = json.loads(event['body'])
                if 'server_name' not in body:
                    return {'headers': {'Access-Control-Allow-Origin': '*'},
                            'statusCode': 400, 'body': 'attribute server_name is required'}
                if 'app_id' not in body:
                    return {'headers': {'Access-Control-Allow-Origin': '*'},
                            'statusCode': 400, 'body': 'attribute app_id is required'}
                if 'server_id' in body:
                    return {'headers': {'Access-Control-Allow-Origin': '*'},
                            'statusCode': 400, 'body': "You cannot create server_id, this is managed by the system"}

                # Check if attribute is defined in the Server schema
                server_attributes = []
                for server_schema in schema_table.scan()['Items']:
                    if server_schema['schema_name'] == "server":
                        server_attributes = server_schema['attributes']
                for key in body.keys():
                    check = False
                    for attribute in server_attributes:
                        if key == attribute['name']:
                           check = True
                    if check == False:
                        message = "Server attribute: " + key + " is not defined in the Server schema"
                        return {'headers': {'Access-Control-Allow-Origin': '*'},
                                'statusCode': 400, 'body': message}

                # Check if attribute in the body matches the list value defined in schema
                for attribute in server_attributes:
                    if 'listvalue' in attribute:
                        listvalue = attribute['listvalue'].split(',')
                        for key in body.keys():
                            if key == attribute['name']:
                                if body[key] not in listvalue:
                                    message = "Server attribute " + key + " for server " + body['server_name'] + " is '" + body[key] + "', does not match the list values '" + attribute['listvalue'] + "' defined in the Server schema"
                                    return {'headers': {'Access-Control-Allow-Origin': '*'},
                                            'statusCode': 400, 'body': message}
            except Exception as e:
                print(e)
                return {'headers': {'Access-Control-Allow-Origin': '*'},
                        'statusCode': 400, 'body': 'malformed json input'}

            # Check if there is a duplicate server_name
            itemlist = servers_table.scan()
            for item in itemlist['Items']:
                if body['server_name'] in item['server_name']:
                    return {'headers': {'Access-Control-Allow-Origin': '*'},
                            'statusCode': 400, 'body': 'server_name: ' +  body['server_name'] + ' already exist'}

            # Validate App_id
            apps = apps_table.scan()
            check = False
            for app in apps['Items']:
               if app['app_id'] == str(body['app_id']):
                   check = True
            if check == False:
                 message = 'app Id: ' + body['app_id'] + ' does not exist'
                 return {'headers': {'Access-Control-Allow-Origin': '*'},
                         'statusCode': 400, 'body': message}

            # Get vacant server_id
            ids = []
            for item in itemlist['Items']:
                ids.append(int(item['server_id']))
            ids.sort()
            server_id = 1
            for id in ids:
               if server_id == id:
                  server_id += 1
            body['server_id'] = str(server_id)

            # Update item
            resp = servers_table.put_item(
            Item=body
            )
            if (resp['ResponseMetadata']['HTTPStatusCode'] == 200):
                new_item = {}
                items = servers_table.scan()['Items']
                for item in items:
                    if str(item['server_id']) == str(server_id):
                        new_item = item
            return {'headers': {'Access-Control-Allow-Origin': '*'},
                    'body': json.dumps(new_item)}
        else:
            return {'headers': {'Access-Control-Allow-Origin': '*'},
                    'statusCode': 401,
                    'body': json.dumps(authResponse)}