Example #1
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 #2
0
def add_sample_metadata(resp):  # pylint: disable=unused-argument
    """Update metadata for sample."""
    try:
        post_data = request.get_json()
        sample_name = post_data['sample_name']
        metadata = post_data['metadata']
    except TypeError:
        raise ParseError('Missing Sample metadata payload.')
    except KeyError:
        raise ParseError('Invalid Sample metadata payload.')

    try:
        sample = Sample.objects.get(name=sample_name)
    except DoesNotExist:
        raise NotFound('Sample does not exist.')

    try:
        sample.metadata = metadata
        sample.save()
        result = sample_schema.dump(sample).data
        return result, 200
    except ValidationError as validation_error:
        current_app.logger.exception('Sample metadata could not be updated.')
        raise ParseError(
            f'Invalid Sample metadata payload: {str(validation_error)}')
Example #3
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 #4
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 #5
0
def get_all_analysis_results():
    """Get all analysis result models."""
    try:
        result = [ar.serializable() for ar in SampleAnalysisResult.all()]
        result += [ar.serializable() for ar in SampleGroupAnalysisResult.all()]
        return result, 200
    except DoesNotExist:
        raise NotFound('Analysis Result does not exist.')
Example #6
0
def get_single_sample_group(group_uuid):
    """Get single sample group model."""
    try:
        sample_group = SampleGroup.query.filter_by(uuid=UUID(group_uuid)).one()
        return sample_group.serializable(), 200
    except ValueError:
        raise ParseError('Invalid Sample Group UUID.')
    except NoResultFound:
        raise NotFound('Sample Group does not exist')
Example #7
0
def get_single_sample(sample_uuid):
    """Get single sample details."""
    try:
        sample = Sample.from_uuid(UUID(sample_uuid))
        return sample.serializable(), 200
    except ValueError:
        raise ParseError('Invalid UUID provided.')
    except DoesNotExist:
        raise NotFound('Sample does not exist.')
Example #8
0
def get_single_organization(organization_uuid):
    """Get single organization details."""
    try:
        org = Organization.from_uuid(UUID(organization_uuid))
        return org.serializable(), 200
    except ValueError:
        raise ParseError('Invalid organization UUID.')
    except NoResultFound:
        raise NotFound('Organization does not exist')
Example #9
0
def fetch_organization(organization_uuid):
    """Get organization from UUID string."""
    try:
        organization_uuid = uuid.UUID(organization_uuid)
        organization = User.query.filter_by(uuid=organization_uuid).one()
        return organization
    except ValueError:
        raise ParseError('Invalid organization UUID.')
    except NoResultFound:
        raise NotFound('Organization does not exist')
Example #10
0
def get_single_result(result_uuid):
    """Get single analysis result."""
    try:
        analysis_result = get_analysis_result(result_uuid)
        result = analysis_result.serializable()
        return result, 200
    except ValueError:
        raise ParseError('Invalid UUID provided.')
    except DoesNotExist:
        raise NotFound('Analysis Result does not exist.')
Example #11
0
def get_all_analysis_results():
    """Get all analysis result models."""
    try:
        analysis_results = AnalysisResultMeta.objects.all()
        result = analysis_result_schema.dump(analysis_results, many=True).data
        return result, 200
    except ValueError:
        raise ParseError('Invalid UUID provided.')
    except DoesNotExist:
        raise NotFound('Analysis Result does not exist.')
Example #12
0
def get_single_result(group_uuid):
    """Get single sample group model."""
    try:
        sample_group_id = UUID(group_uuid)
        sample_group = SampleGroup.query.filter_by(id=sample_group_id).one()
        result = sample_group_schema.dump(sample_group).data
        return result, 200
    except ValueError:
        raise ParseError('Invalid Sample Group UUID.')
    except NoResultFound:
        raise NotFound('Sample Group does not exist')
Example #13
0
def get_single_result(result_uuid):
    """Get single analysis result."""
    try:
        uuid = UUID(result_uuid)
        analysis_result = AnalysisResultMeta.objects.get(uuid=uuid)
        result = analysis_result_schema.dump(analysis_result).data
        return result, 200
    except ValueError:
        raise ParseError('Invalid UUID provided.')
    except DoesNotExist:
        raise NotFound('Analysis Result does not exist.')
Example #14
0
def get_single_sample(sample_uuid):
    """Get single sample details."""
    try:
        uuid = UUID(sample_uuid)
        sample = Sample.objects.get(uuid=uuid)
        fields = ('uuid', 'name', 'analysis_result_uuid', 'created_at')
        result = SampleSchema(only=fields).dump(sample).data
        return result, 200
    except ValueError:
        raise ParseError('Invalid UUID provided.')
    except DoesNotExist:
        raise NotFound('Sample does not exist.')
Example #15
0
def get_samples_for_group(group_uuid):
    """Get single sample group's list of samples."""
    try:
        sample_group = SampleGroup.query.filter_by(uuid=UUID(group_uuid)).one()
        result = {
            'samples':
            [sample.serializable() for sample in sample_group.samples],
        }
        return result, 200
    except ValueError:
        raise ParseError('Invalid Sample Group UUID.')
    except NoResultFound:
        raise NotFound('Sample Group does not exist')
Example #16
0
def get_samples_for_group_by_name(group_name):
    """Get single sample group's list of samples."""
    try:
        sample_group = SampleGroup.from_name(group_name)
        result = {
            'samples':
            [sample.serializable() for sample in sample_group.samples],
        }
        return result, 200
    except ValueError:
        raise ParseError('Invalid Sample Group UUID.')
    except NoResultFound:
        raise NotFound('Sample Group does not exist')
Example #17
0
def get_samples_for_group(group_uuid):
    """Get single sample group's list of samples."""
    try:
        sample_group_id = UUID(group_uuid)
        sample_group = SampleGroup.query.filter_by(id=sample_group_id).one()
        samples = sample_group.samples
        current_app.logger.info(f'Found {len(samples)} samples for group {group_uuid}')
        result = SampleSchema(only=('uuid', 'name')).dump(samples, many=True).data
        return result, 200
    except ValueError:
        raise ParseError('Invalid Sample Group UUID.')
    except NoResultFound:
        raise NotFound('Sample Group does not exist')
Example #18
0
def get_sample_group_uuid(sample_group_name):
    """Return the UUID associated with a single sample."""
    try:
        sample_group = SampleGroup.query.filter_by(name=sample_group_name).one()
    except NoResultFound:
        raise NotFound('Sample Group does not exist')

    sample_group_uuid = sample_group.id
    result = {
        'sample_group_name': sample_group_name,  # recapitulate for convenience
        'sample_group_uuid': sample_group_uuid,
    }
    return result, 200
Example #19
0
def get_sample_uuid(sample_name):
    """Return the UUID associated with a single sample."""
    try:
        sample = Sample.objects.get(name=sample_name)
    except DoesNotExist:
        raise NotFound('Sample does not exist.')

    sample_uuid = sample.uuid
    result = {
        'sample_name': sample_name,  # recapitulate for convenience
        'sample_uuid': sample_uuid,
    }
    return result, 200
Example #20
0
def get_group_analysis_result_fields_by_name(group_name, module_name):
    """Get all fields of the specified analysis result."""
    try:
        group = SampleGroup.from_name(group_name)
        analysis_result = SampleGroupAnalysisResult.from_name_group(
            module_name, group.uuid)
        result = {
            field.field_name: field.data
            for field in analysis_result.module_fields
        }
        return result, 200
    except NoResultFound:
        raise NotFound('Analysis Result does not exist.')
Example #21
0
def get_analysis_result_fields_by_name(lib_name, sample_name, module_name):
    """Get all fields of the specified analysis result."""
    try:
        library = SampleGroup.from_name(lib_name)
        sample = Sample.from_name_library(sample_name, library.uuid)
        analysis_result = SampleAnalysisResult.from_name_sample(
            module_name, sample.uuid)
        result = {
            field.field_name: field.data
            for field in analysis_result.module_fields
        }
        return result, 200
    except NoResultFound:
        raise NotFound('Analysis Result does not exist.')
Example #22
0
def run_sample_group_display_modules(uuid):  # pylint: disable=invalid-name
    """Run display modules for sample group."""
    try:
        safe_uuid = UUID(uuid)
        _ = SampleGroup.query.filter_by(uuid=safe_uuid).first()
    except ValueError:
        raise ParseError('Invalid UUID provided.')
    except NoResultFound:
        raise NotFound('Sample Group does not exist.')

    analysis_names = request.args.getlist('analysis_names')
    TaskConductor(uuid, analysis_names).shake_that_baton()
    result = {'middleware': analysis_names}
    return result, 202
Example #23
0
def post_single_sample_metadata(sample_uuid):
    """Upload metadata for a single sample."""
    try:
        post_data = request.get_json()
        sample = Sample.from_uuid(UUID(sample_uuid))
        sample.set_sample_metadata(post_data['metadata'])
        return sample.serializable(), 200
    except ValueError:
        raise ParseError('Invalid UUID provided.')
    except DoesNotExist:
        raise NotFound('Sample does not exist.')
    except TypeError:
        raise ParseError('Missing Sample metadata payload.')
    except KeyError:
        raise ParseError('Invalid Sample metadata payload.')
Example #24
0
def get_single_sample_metadata(sample_uuid):
    """Get single sample metadata."""
    try:
        sample = Sample.from_uuid(UUID(sample_uuid))
        result = {
            'sample': {
                'uuid': sample.uuid,
                'name': sample.name,
                'metadata': sample.sample_metadata,
            },
        }
        return result, 200
    except ValueError:
        raise ParseError('Invalid UUID provided.')
    except DoesNotExist:
        raise NotFound('Sample does not exist.')
Example #25
0
def get_organizations():
    """Get all organizations."""
    if 'name' in request.args:
        name_query = request.args.get('name')
        try:
            organization = Organization.from_name(name_query)
        except NoResultFound:
            raise NotFound('Organization does not exist')
        return organization.serializable(), 200

    limit = request.args.get('limit', PAGE_SIZE)
    offset = request.args.get('offset', 0)
    organizations = Organization.query.all()
    organizations = sorted(organizations, key=lambda el: str(User.created_at))
    organizations = organizations[offset:(offset + limit)]
    result = {'organizations': [org.serializable() for org in organizations]}
    return result, 200
Example #26
0
def get_all_samples(authn):  # pylint: disable=unused-argument
    """Get all samples that the user is allowed to see."""
    try:
        org_uuids = {membership.uuid for membership in authn.memberships}
        sample_groups = SampleGroup.query.filter(
            and_(
                SampleGroup.is_library,
                or_(SampleGroup.is_public, SampleGroup.organization_uuid
                    in org_uuids))).all()
        samples = []
        for sample_group in sample_groups:
            for sample in sample_group.samples:
                samples.append(sample.serializable())
        result = {'samples': samples}
        return result, 200
    except NoResultFound:
        raise NotFound('No accessible samples found.')
Example #27
0
def jira_issue_transition_update():
    if not helper.check_github_ip(src_ip=request.access_route[0]):
        raise NotAcceptable('Github IP whitelist check failed! IP: {}'.format(
            request.access_route[0]))

    if not helper.check_github_pull_request_payload(payload=request.json):
        raise NotAcceptable('Json payload is not valid')

    # detect issue_id
    issue_id = jiraservice.get_issue_id_from_github_payload(
        payload=request.json)

    if not issue_id:
        raise NotAcceptable('Issue could not detect')

    # new pull request state (approve,changes_request,commented)
    pr_state = request.json['review']['state']

    # get new transition id from env with project prefix.
    transition_id = helper.get_transition_id(pr_state)
    if not transition_id:
        raise NotFound('New transition id not found on your env')

    # send update request to jira API
    response = jiraservice.issue_transition_update(
        issue_id=issue_id, new_transition_id=transition_id)

    if pr_state in [APPROVED, CHANGES_REQUESTED]:
        pr_number = request.json['pull_request']['number']
        issue_owner_username = request.json['pull_request']['user']['login']
        reviewer_username = request.json['review']['user']['login']
        helper.save_pull_request_review(
            issue_id=issue_id,
            pr_id=pr_number,
            issue_owner_username=issue_owner_username,
            reviewer_username=reviewer_username,
            action=pr_state)

    if response:
        return jsonify({'ack': 'OK'})
    else:
        return jsonify({'ack': 'NOT OK'})

    if __name__ == '__main__':
        application.run(debug=True)
Example #28
0
 def wrapper(*args, **kwargs):
     try:
         return func(*args, **kwargs)
     except HttpException as e:
         if isinstance(e, UnauthorizedException):
             raise PermissionDenied(e.args)
         elif isinstance(e, NotFoundException):
             raise NotFound(e.args)
         elif isinstance(e, BadRequestException):
             raise ParseError(e.args)
         else:
             if has_sentry:
                 sentry_sdk.capture_exception(e)
             raise APIException(e.args)
     except Exception as e:
         if has_sentry:
             sentry_sdk.capture_exception(e)
         raise APIException('%s: %s' % (e.__class__.__name__, str(e)))
Example #29
0
def add_organization(authn):
    """Add organization."""
    try:
        post_data = request.get_json()
        org_name = post_data['name']
        primary_admin = User.from_uuid(authn.sub)
        is_public = post_data.get('is_public', True)
    except NoResultFound:
        raise NotFound('User does not exist')
    except TypeError:
        raise ParseError('Missing organization payload.')
    except KeyError:
        raise ParseError('Invalid organization payload.')
    try:
        org = Organization.from_user(primary_admin, org_name, is_public=is_public)
        return org.serializable(), 201
    except IntegrityError:
        current_app.logger.exception('There was a problem adding an organization.')
        raise InternalError(str(integrity_error))
Example #30
0
def login_user():
    """Log user in."""
    try:
        post_data = request.get_json()
        email = post_data['email']
        password = post_data['password']
    except TypeError:
        raise ParseError('Missing login payload.')
    except KeyError:
        raise ParseError('Invalid login payload.')

    # Fetch the user data
    user = User.query.filter_by(email=email).first()
    if user and bcrypt.check_password_hash(user.password, password):
        auth_token = user.encode_auth_token(user.id)
        if auth_token:
            result = {'auth_token': auth_token.decode()}
            return result, 200
    raise NotFound('User does not exist.')