Example #1
0
def add_sample(_):
    """Add sample."""
    try:
        post_data = request.get_json()
        library = SampleGroup.from_uuid(post_data['library_uuid'])
        sample = library.sample(post_data['name'], force_new=True)
    except TypeError:
        raise ParseError('Missing Sample creation payload.')
    except KeyError:
        raise ParseError('Invalid Sample creation payload.')
    except NoResultFound:
        raise InvalidRequest('Library does not exist!')
    except IntegrityError:
        raise InvalidRequest(
            'A Sample with that name already exists in the library.')
    return sample.serializable(), 201
Example #2
0
def add_samples_to_group(authn, group_uuid):
    """Add samples to a sample group."""
    try:
        post_data = request.get_json()
        sample_group = SampleGroup.query.filter_by(uuid=UUID(group_uuid)).one()
    except ValueError:
        raise ParseError('Invalid Sample Group UUID.')
    except NoResultFound:
        raise NotFound('Sample Group does not exist')
    authn_user = User.query.filter_by(uuid=authn.sub).first()
    organization = Organization.query.filter_by(
        uuid=sample_group.organization_uuid).first()
    if authn_user.uuid not in organization.writer_uuids():
        raise PermissionDenied(
            'You do not have permission to write to that organization.')
    for sample_uuid in [UUID(uuid) for uuid in post_data.get('sample_uuids')]:
        try:
            sample = Sample.query.filter_by(uuid=sample_uuid).first()
            sample_group.samples.append(sample)
        except NoResultFound:
            raise InvalidRequest(
                f'Sample UUID \'{sample_uuid}\' does not exist')
        except IntegrityError as integrity_error:
            current_app.logger.exception(
                f'Sample \'{sample_uuid}\' could not be added to Sample Group.'
            )
            raise InternalError(str(integrity_error))
    sample_group.save()
    result = sample_group.serializable()
    return result, 200
Example #3
0
def add_organization_user(authn, organization_uuid):     # pylint: disable=too-many-return-statements
    """Add user to organization."""
    try:
        post_data = request.get_json()
        organization = Organization.from_uuid(UUID(organization_uuid))
        admin = User.from_uuid(authn.sub)
    except TypeError:
        raise ParseError('Missing membership payload.')
    except ValueError:
        raise ParseError('Invalid organization UUID.')
    except NoResultFound:
        raise NotFound('Organization does not exist')
    try:
        user = User.from_uuid(post_data['user_uuid'])
    except KeyError:
        raise ParseError('Invalid membership payload.')
    except NoResultFound:
        raise NotFound('User does not exist')

    if admin.uuid in organization.admin_uuids():
        if user.uuid in organization.reader_uuids():
            raise InvalidRequest('User is already part of organization.')
        role = post_data.get('role', 'read')
        try:
            organization.add_user(user, role_in_org=role)
            result = {'message': f'${user.username} added to ${organization.name}'}
            return result, 200
        except IntegrityError as integrity_error:
            current_app.logger.exception('IntegrityError encountered.')
            raise InternalError(str(integrity_error))
    raise PermissionDenied('You do not have permission to add a user to that organization.')
Example #4
0
def add_samples_to_group(resp, group_uuid):  # pylint: disable=unused-argument
    """Add samples to a sample group."""
    try:
        post_data = request.get_json()
        sample_group_id = UUID(group_uuid)
        sample_group = SampleGroup.query.filter_by(id=sample_group_id).one()
    except ValueError:
        raise ParseError('Invalid Sample Group UUID.')
    except NoResultFound:
        raise NotFound('Sample Group does not exist')

    try:
        sample_uuids = [UUID(uuid) for uuid in post_data.get('sample_uuids')]
        for sample_uuid in sample_uuids:
            sample = Sample.objects.get(uuid=sample_uuid)
            sample_group.sample_ids.append(sample.uuid)
        db.session.commit()
        result = sample_group_schema.dump(sample_group).data
        return result, 200
    except NoResultFound:
        db.session.rollback()
        raise InvalidRequest(f'Sample UUID \'{sample_uuid}\' does not exist')
    except IntegrityError as integrity_error:
        current_app.logger.exception('Samples could not be added to Sample Group.')
        db.session.rollback()
        raise InternalError(str(integrity_error))
Example #5
0
def add_sample_group(resp):  # pylint: disable=unused-argument
    """Add sample group."""
    try:
        post_data = request.get_json()
        name = post_data['name']
    except TypeError:
        raise ParseError('Missing Sample Group creation payload.')
    except KeyError:
        raise ParseError('Invalid Sample Group creation payload.')

    sample_group = SampleGroup.query.filter_by(name=name).first()
    if sample_group is not None:
        raise InvalidRequest('Sample Group with that name already exists.')

    try:
        analysis_result = AnalysisResultMeta().save()
        sample_group = SampleGroup(name=name, analysis_result=analysis_result)
        db.session.add(sample_group)
        db.session.commit()
        result = sample_group_schema.dump(sample_group).data
        return result, 201
    except IntegrityError as integrity_error:
        current_app.logger.exception('Sample Group could not be created.')
        db.session.rollback()
        raise InternalError(str(integrity_error))
Example #6
0
def add_sample(resp):  # pylint: disable=unused-argument
    """Add sample."""
    try:
        post_data = request.get_json()
        sample_group_uuid = post_data['sample_group_uuid']
        sample_name = post_data['name']
    except TypeError:
        raise ParseError('Missing Sample creation payload.')
    except KeyError:
        raise ParseError('Invalid Sample creation payload.')

    try:
        sample_group = SampleGroup.query.filter_by(id=sample_group_uuid).one()
    except NoResultFound:
        raise InvalidRequest('Sample Group does not exist!')

    sample = Sample.objects(name=sample_name).first()
    if sample is not None:
        raise InvalidRequest('A Sample with that name already exists.')

    try:
        analysis_result = AnalysisResultMeta().save()
        sample = Sample(name=sample_name,
                        analysis_result=analysis_result,
                        metadata={
                            'name': sample_name
                        }).save()
        sample_group.sample_ids.append(sample.uuid)
        db.session.commit()
        result = sample_schema.dump(sample).data
        return result, 201
    except ValidationError as validation_error:
        current_app.logger.exception('Sample could not be created.')
        raise InternalError(str(validation_error))
    except IntegrityError as integrity_error:
        current_app.logger.exception(
            'Sample could not be added to Sample Group.')
        db.session.rollback()
        raise InternalError(str(integrity_error))
Example #7
0
def get_result(display_module, result_uuid):
    """Define handler for API requests that defers to display module type."""
    try:
        uuid = UUID(result_uuid)
        analysis_result = AnalysisResultMeta.objects.get(uuid=uuid)
    except ValueError:
        raise ParseError('Invalid UUID provided.')
    except DoesNotExist:
        raise NotFound('Analysis Result does not exist.')

    if display_module.name() not in analysis_result:
        raise InvalidRequest(
            f'{display_module.name()} is not in this AnalysisResult.')

    module_results = getattr(analysis_result, display_module.name()).fetch()
    result = display_module.get_data(module_results)
    for transmission_hook in display_module.transmission_hooks():
        result = transmission_hook(result)

    # Conversion to dict is necessary to avoid object not callable TypeError
    result_dict = jsonify(result)
    return result_dict, 200
Example #8
0
def register_user():
    """Register user."""
    try:
        post_data = request.get_json()
        username = post_data['username']
        email = post_data['email']
        password = post_data['password']
    except TypeError:
        raise ParseError('Missing registration payload.')
    except KeyError:
        raise ParseError('Invalid registration payload.')

    # Check for existing user
    user = User.query.filter(
        or_(User.username == username, User.email == email)).first()
    if user is not None:
        raise InvalidRequest('Sorry. That user already exists.')

    try:
        # Add new user to db
        new_user = User(
            username=username,
            email=email,
            password=password,
        )
        db.session.add(new_user)
        db.session.commit()
    except IntegrityError as integrity_error:
        current_app.logger.exception('There was a problem with registration.')
        db.session.rollback()
        raise InternalError(str(integrity_error))

    # Generate auth token
    auth_token = new_user.encode_auth_token(new_user.id)
    result = {'auth_token': auth_token.decode()}
    return result, 201