Beispiel #1
0
def get_user(user_id):
    """
    Retrieves all of a given users data
    Args:
        user_id (str): a users uuid
    Returns:
        dict: a dictionary containing all of a users information
    Raises:
        BadRequestError: if the user_id isn't a valid uuid
        NotFoundError: if no record can be found for the given user id
    """
    try:
        UUID(user_id)
    except ValueError as e:
        logger.warning("Invalid uuid, received error: {}".format(e))
        raise BadRequestError

    with db_session() as session:
        logger.info("Retrieving user information...")
        result = session.query(UserData.field_type, UserData.field_data,
                               UserData.user_id).filter_by(user_id=user_id)

        if not result.count():
            logger.warning(
                "User {} was not found in the database".format(user_id))
            raise NotFoundError

        logger.info("User data retrieved")
        user_data = User(strict=True).dump(result).data

        return dict(meta=dict(limit=1, offset=0, count=1), data=user_data)
Beispiel #2
0
    def test_unpack_meta_data_works_no_meta_data(self):
        data = {
            'emailAddress': '*****@*****.**',
            'firstName': 'Nick',
            'lastName': 'Plutt'
        }

        result = User().unpack_meta_data(data=data)

        assert result == {
            'emailAddress':
            '*****@*****.**',
            'firstName':
            'nick',
            'lastName':
            'plutt',
            'metaData': [{
                'fieldData': 'Plutt',
                'fieldType': 'lastName'
            }, {
                'fieldData': '*****@*****.**',
                'fieldType': 'emailAddress'
            }, {
                'fieldData': 'Nick',
                'fieldType': 'firstName'
            }]
        }
Beispiel #3
0
def get_users(query_params):
    """
    Retrieves data for all user's who have an attribute that matches the
    searchText
    Args:
        query_params (dict): a dictionary containing all of the query params
    Returns:
        list: list of dicts containing users information
    Raises:
        None
    """
    query_params = query_params if query_params else dict()
    logger.info(
        "Retrieving user information with query params of {}...".format(
            query_params))

    limit = query_params.get('limit', 25)
    offset = query_params.get('offset', 0)
    search_text = query_params.get('searchText')
    search_field = query_params.get('searchField')

    with db_session() as session:
        logger.info("Constructing text search sub query...")
        search_sub_query = session.query(UserData.user_id)

        if search_text:
            logger.info("Searching fields for text...")
            search_text = unquote(search_text)
            search_sub_query = search(search_sub_query, search_text, sort=True)
        if search_field:
            logger.info("Filtering results by searched field...")
            search_field = unquote(search_field)
            search_sub_query = search_sub_query.filter_by(
                field_type=search_field)

        logger.info("Applying offset and limit on subquery...")
        search_sub_query = search_sub_query.distinct().offset(offset).limit(
            limit).subquery()

        logger.info("Retrieving users info from database...")
        result = session.query(
            UserData.field_type, UserData.field_data, UserData.user_id).filter(
                UserData.user_id == search_sub_query.c.user_id)

        logger.info("Users data retrieved")
        users_data = User(strict=True).dump(result, many=True).data

        return dict(meta=dict(limit=limit,
                              offset=offset,
                              count=len(users_data)),
                    data=users_data)
Beispiel #4
0
def create_user(json_body):
    """
    Inserts user into the users table and insert's the user's meta data
    into the meta_data table.
    Args:
        json_body (dict): a dict representing the json body
    Returns:
        chalice.Response: response object with status code and headers
    Raises:
        BadRequestError: if the provided data is malformed or invalid
        ConflictError: if the user already exists or if the user data is malformed
        ChaliceViewError: if something goes wrong when inserting the records
    """
    try:
        logger.info("Validating json body...")
        user_info, user_meta_data = User(strict=True).load(json_body).data
    except ValidationError as e:
        logger.warning("Invalid json body, received error: {}".format(e))
        raise BadRequestError

    with db_session() as session:
        try:
            user_insert = insert(Users)
            user_data_insert = insert(UserData)

            logger.info("Inserting data into the user table...")
            session.execute(user_insert, user_info)

            logger.info("Inserting data into the user_data table...")
            session.execute(user_data_insert, user_meta_data)

            session.commit()
        except IntegrityError as e:
            logger.warning(
                "User or user data already exists, received error: {}".format(
                    e))
            raise ConflictError
        except Exception as e:
            logger.critical("Something went wrong when retrieving user data, "
                            "received error: {}".format(e))
            raise ChaliceViewError

        logger.info("Data successfully inserted")

    return Response(
        body=None,
        status_code=201,
        headers=dict(Location='/users/{}'.format(str(user_info['user_id']))))
Beispiel #5
0
    def test_map_meta_data_to_model_one_works(self):
        data = [{
            'field_data': '*****@*****.**',
            'field_type': 'emailAddress',
            'user_id': UUID('9f1b15e8-dca7-427d-816d-44f519010c6b')
        }, {
            'field_data': 'Nick',
            'field_type': 'firstName',
            'user_id': UUID('9f1b15e8-dca7-427d-816d-44f519010c6b')
        }, {
            'field_data': 'Plutt',
            'field_type': 'lastName',
            'user_id': UUID('9f1b15e8-dca7-427d-816d-44f519010c6b')
        }, {
            'field_data': '200 Grand Avenue',
            'field_type': 'address',
            'user_id': UUID('9f1b15e8-dca7-427d-816d-44f519010c6b')
        }]

        input_data = []

        for d in data:
            record = MagicMock()
            record._asdict = MagicMock()
            record._asdict.return_value = d
            input_data.append(record)

        result = User().map_meta_data_to_model(data=input_data,
                                               pass_many=False)

        assert result == {
            'user_id':
            '9f1b15e8-dca7-427d-816d-44f519010c6b',
            'email_address':
            '*****@*****.**',
            'first_name':
            'Nick',
            'last_name':
            'Plutt',
            'meta_data': [{
                'field_data': '200 Grand Avenue',
                'field_type': 'address'
            }]
        }
Beispiel #6
0
    def test_split_model_works(self):
        data = {
            'user_id':
            UUID('befed934-3f35-4b81-ac41-d1ca8039daeb'),
            'email_address':
            '*****@*****.**',
            'first_name':
            'nick',
            'last_name':
            'plutt',
            'meta_data': [{
                'field_data': 'tacos',
                'field_type': 'favorite food'
            }, {
                'field_data': 'Plutt',
                'field_type': 'lastName'
            }, {
                'field_data': '*****@*****.**',
                'field_type': 'emailAddress'
            }, {
                'field_data': 'Nick',
                'field_type': 'firstName'
            }]
        }

        data_result, meta_data_result = User().split_model(data=data)

        assert data_result == {
            'email_address': '*****@*****.**',
            'first_name': 'nick',
            'last_name': 'plutt',
            'user_id': UUID('befed934-3f35-4b81-ac41-d1ca8039daeb')
        }

        assert meta_data_result == [{
            'field_data':
            'tacos',
            'field_type':
            'favorite food',
            'user_id':
            UUID('befed934-3f35-4b81-ac41-d1ca8039daeb')
        }, {
            'field_data':
            'Plutt',
            'field_type':
            'lastName',
            'user_id':
            UUID('befed934-3f35-4b81-ac41-d1ca8039daeb')
        }, {
            'field_data':
            '*****@*****.**',
            'field_type':
            'emailAddress',
            'user_id':
            UUID('befed934-3f35-4b81-ac41-d1ca8039daeb')
        }, {
            'field_data':
            'Nick',
            'field_type':
            'firstName',
            'user_id':
            UUID('befed934-3f35-4b81-ac41-d1ca8039daeb')
        }]
Beispiel #7
0
    def test_map_meta_data_to_model_many_works(self):
        data = [{
            'field_data': '*****@*****.**',
            'field_type': 'emailAddress',
            'user_id': UUID('9f1b15e8-dca7-427d-816d-44f519010c6b')
        }, {
            'field_data': 'Nick',
            'field_type': 'firstName',
            'user_id': UUID('9f1b15e8-dca7-427d-816d-44f519010c6b')
        }, {
            'field_data': 'Plutt',
            'field_type': 'lastName',
            'user_id': UUID('9f1b15e8-dca7-427d-816d-44f519010c6b')
        }, {
            'field_data': '200 Grand Avenue',
            'field_type': 'address',
            'user_id': UUID('9f1b15e8-dca7-427d-816d-44f519010c6b')
        }, {
            'field_data': '*****@*****.**',
            'field_type': 'emailAddress',
            'user_id': UUID('161e71f0-085c-4607-9631-b8a964f63fc4')
        }, {
            'field_data': 'John',
            'field_type': 'firstName',
            'user_id': UUID('161e71f0-085c-4607-9631-b8a964f63fc4')
        }, {
            'field_data': 'Bones',
            'field_type': 'lastName',
            'user_id': UUID('161e71f0-085c-4607-9631-b8a964f63fc4')
        }, {
            'field_data': '612-584-9642',
            'field_type': 'phone number',
            'user_id': UUID('161e71f0-085c-4607-9631-b8a964f63fc4')
        }]

        input_data = []

        for d in data:
            record = MagicMock()
            record._asdict = MagicMock()
            record._asdict.return_value = d
            input_data.append(record)

        result = User().map_meta_data_to_model(data=input_data, pass_many=True)

        assert result == [{
            'user_id':
            '9f1b15e8-dca7-427d-816d-44f519010c6b',
            'email_address':
            '*****@*****.**',
            'first_name':
            'Nick',
            'last_name':
            'Plutt',
            'meta_data': [{
                'field_data': '200 Grand Avenue',
                'field_type': 'address'
            }]
        }, {
            'user_id':
            '161e71f0-085c-4607-9631-b8a964f63fc4',
            'email_address':
            '*****@*****.**',
            'first_name':
            'John',
            'last_name':
            'Bones',
            'meta_data': [{
                'field_data': '612-584-9642',
                'field_type': 'phone number'
            }]
        }]