def post(self, password_reset_code):
        form = PasswordResetForm(request.form)
        if form.validate():
            with backend.transaction():
                try:
                    user = backend.get(
                        User,
                        {'password_reset_code': password_reset_code}
                    )
                except User.DoesNotExist:
                    return {'message': 'Unknown user'}, 404

                user.set_password(form.password.data)
                backend.update(user, ['password', 'password_set'], unset_fields=['password_reset_code'])
                access_token = user.get_access_token()
                backend.save(access_token)

                send_mail(
                    email_to=user.email,
                    template="password_reset_successful",
                    template_context={
                        "user_name": user.name
                    }
                )

                return {'message': 'success'}, 200

        return ({'message': 'Invalid data',
                 'errors': form.errors},
                403)
Exemplo n.º 2
0
def auto_tag(project):
    """ First step of the analysis for Git projects. Determines if automatic tags have already been added and, if not
    adds them from the requirements.txt file, if one exists in the repository.
    :param project: project to auto tag
    :return:
    """
    logger.debug("Adding automatic tags to {}".format(project.pk))
    repository = project.git.eager.repository

    # auto tag the project (but only once)
    if project.get('automatic_tags_added'):
        return

    default_branch = project.git.get_default_branch()
    if default_branch is None:
        return
    tags = extract_tags_from_requirements_txt(repository, default_branch)

    with backend.transaction():
        for tag_name in tags:
            try:
                tag = backend.get(Tag, {'name': tag_name})
            except Tag.DoesNotExist:
                tag = Tag({'name': tag_name})
                backend.save(tag)

            project.tags.append(tag)

    project.automatic_tags_added = True
    with backend.transaction():
        backend.update(project, ['automatic_tags_added'])
def add_relevant_issue_classes(project):
    """ Adds relevant issue classes to the given project. Only adds issue classes that were created after the last time
    this function was ran, avoiding re-adding issue classes that the user may have removed from the project.
    :param project: project to add the issue classes to
    :return:
    """
    issue_classes = get_relevant_issue_classes(project)
    logger.info("Adding %d issue_classes to project %s" %
                (len(issue_classes), project.pk))

    with backend.transaction():
        for issue_class in issue_classes:
            project_issue_class_query = {
                'project': project,
                'issue_class': issue_class
            }
            try:
                backend.get(ProjectIssueClass, project_issue_class_query)
                continue
            except ProjectIssueClass.DoesNotExist:
                project_issue_class = ProjectIssueClass(
                    project_issue_class_query)
                project_issue_class.enabled = True
                backend.save(project_issue_class)

        # re-sync the issue classes associated with the project with the database
        project.revert()
    def post(self):
        form = LoginForm(request.form)
        if form.validate():
            with backend.transaction():
                try:
                    # TODO manually specifying includes is not ideal
                    user = backend.get(User, {'email': form.email.data.lower()},
                                       include=UserProfile.includes)
                    if user.delete is True:
                        return {'message': "Your account is scheduled for deletion. "
                                           "You can sign-up again in a few minutes."}, 403
                    if not user.check_password(form.password.data):
                        return ({'message': 'Invalid password'},
                                403)

                    access_token = user.get_access_token()

                    backend.save(access_token)

                    user_profile = UserProfile.export(user)
                    response = self.make_response({
                        'access_token': access_token.token,
                        'message': 'Success!',
                        'user': user_profile,
                    })

                    expires = (datetime.datetime.now() + datetime.timedelta(days=7)) if form.remember_me.data else None
                    response.set_cookie('access_token', value=access_token.token, expires=expires)

                    return response

                except User.DoesNotExist:
                    return {'message': 'Unknown user'}, 404
        return {'message': 'Invalid data', 'errors': form.errors}, 403
Exemplo n.º 5
0
def project(test, fixtures, name):

    project = Project({
        'name': name,
        'permalink': 'test:{}'.format(name),
        'source': 'test'
    })
    with backend.transaction():
        backend.save(project)
    return project
Exemplo n.º 6
0
 def post(self, project_id, issue_class_id):
     """
     Add a new issue class to a project
     """
     with backend.transaction():
         project_issue_class = self._get_project_issue_class()
         if project_issue_class.pk:
             backend.update(project_issue_class, {'enabled': True})
         else:
             project_issue_class.enabled = True
             backend.save(project_issue_class)
     return {'message': 'success'}, 201
Exemplo n.º 7
0
def _import_issue_classes():

    issue_update_keys = ('severity', 'description', 'title')
    analyzer_update_keys = ('language', )

    logger.info("Importing issue classes from checkmate...")
    analyzers = settings.checkmate_settings.analyzers
    for analyzer, params in analyzers.items():
        logger.info("Importing issue classes for analyzer {}".format(analyzer))
        if not all([key in params for key in analyzer_update_keys]):
            logger.warning(
                "Skipping analyzer {} as it does not contain a '{}' field".
                format(key))
            continue
        for code, issue_params in params.get('issues_data', {}).items():
            if not all([key in issue_params for key in issue_update_keys]):
                logger.warning(
                    "Skipping issue class for code {}, as it does not contain a '{}' field"
                    .format(code, key))
                continue
            logger.info("Importing issue class for code {}".format(code))
            try:
                issue_class = backend.get(IssueClass, {
                    'analyzer': analyzer,
                    'code': code
                })
            except IssueClass.DoesNotExist:
                issue_class = IssueClass({
                    'analyzer': analyzer,
                    'code': code,
                })
            for key in issue_update_keys:
                issue_class[key] = issue_params[key]
            for key in analyzer_update_keys:
                issue_class[key] = params[key]
            with backend.transaction():
                backend.save(issue_class)
                issue_class.categories.delete()
            for category in issue_params.get('categories', []):
                try:
                    issue_category = backend.get(IssueCategory,
                                                 {'name': category})
                except IssueCategory.DoesNotExist:
                    issue_category = IssueCategory({'name': category})
                    with backend.transaction():
                        backend.save(issue_category)
                issue_class.categories.append(issue_category)
            for tag_name in issue_params.get('tags', ['generic']):
                try:
                    tag = backend.get(Tag, {'name': tag_name})
                except Tag.DoesNotExist:
                    tag = Tag({'name': tag_name})
                    with backend.transaction():
                        backend.save(tag)
                issue_class.tags.append(tag)
            with backend.transaction():
                backend.save(issue_class)
Exemplo n.º 8
0
def user(
    test,
    fixtures,
    name,
    email,
    password,
    superuser=False,
):

    user = User({'name': name, 'email': email})
    user.set_password(password)
    user.unencrypted_password = password
    with backend.transaction():
        backend.save(user)

    access_token = AccessToken({'user': user, 'token': uuid.uuid4().hex})
    with backend.transaction():
        backend.save(access_token)
    return user
def create_project(project_data, git_data, user):
    """
    Creates a new project with the given data and performs the necessary initialization steps.

    :param data: data to use to create the project
    :return: object representing the newly created project
    """

    project = Project(project_data)
    project.pk = uuid.uuid4().hex

    settings.hooks.call("project.create.before", project)

    if not project.get('permalink'):
        project.permalink = project.pk

    git = GitRepository(git_data)
    git.project = project
    project.git = git
    #we make the user owner of the project
    user_role = UserRole({'project': project, 'user': user, 'role': 'owner'})

    with backend.transaction():
        backend.save(project)
        backend.save(git)
        backend.save(user_role)

    #we run git-specific initialization tasks
    generate_key_pair(project)
    initialize_repository(project)
    update_remote(project)

    settings.hooks.call("project.create.after", project)

    return project
Exemplo n.º 10
0
    def post(self, project_id, role, user_id):

        with backend.transaction():
            try:
                user = self._get_user(user_id)
            except AttributeError:
                return ({'message': 'invalid user'},
                        404)

            if role not in ('admin', 'collaborator', 'owner'):
                return ({'message': 'invalid role: %s' % role},
                        403)
            try:
                user_role = backend.get(UserRole, {'project': request.project,
                                                   'user': user})
                if user_role.role == 'owner' and user_role.user == request.user and role != 'owner':
                    if len(backend.filter(UserRole, {'project': request.project,'role' : 'owner'})) == 1:
                        return {'message' : 'You are the last owner of this project, cannot remove you.'}, 400
            except UserRole.DoesNotExist:
                user_role = UserRole({'project': request.project, 'user': user})
            user_role.role = role
            backend.save(user_role)
        return ProjectRoles.get(self, project_id=project_id)
Exemplo n.º 11
0
    def post(self):
        form = SignupForm(request.form)
        if form.validate():
            with backend.transaction():
                email_matches = backend.filter(User, {'email': form.email.data})
                if len(email_matches) > 0:
                    for user in email_matches:
                        if user.delete is True:
                            return ({'message': 'Your account is scheduled for deletion. Try again in a few minutes".'},
                                    403)
                    return {'message': "A user with this e-mail address already exists. "
                                       "Please try resetting your password.",
                            'resetPasswordLink': True}, 403

                try:
                    user = backend.get(User, {'name': form.name.data.lower()})
                    return {'errors': {'name': {'message': 'This login has already been chosen by another user'}},
                            'message': 'Login already in use.'}, 403
                except User.DoesNotExist:
                    pass
                except User.MultipleDocumentsReturned:
                    return {'errors': {'name': {'message': 'This login has already been chosen by another user'}},
                            'message': 'Login already in use.'}, 403
                user = User({
                    'email': form.email.data.lower(),
                    'name': form.name.data.lower(),
                    'email_validated': False,
                    'email_validation_code': uuid.uuid4().hex,
                    'terms_accepted': form.terms.data,
                    'terms_accepted_at': datetime.datetime.utcnow(),
                    'terms_accepted_from_ip': request.remote_addr,
                    'email_settings': {
                        'newsletter': True,
                        'notifications': True,
                    },
                })
                user.set_password(form.password.data)
                backend.save(user)
                access_token = AccessToken({'user': user,
                                            'token': uuid.uuid4().hex})
                backend.save(access_token)

                user_profile = UserProfile.export(user)

                response = self.make_response({
                    'access_token': access_token.token,
                    'message': 'Success!',
                    'user': user_profile,
                })

                response.set_cookie(
                    'access_token',
                    value=access_token.token,
                    expires=(datetime.datetime.utcnow() + datetime.timedelta(days=7)),
                )

                activation_url = u"{}{}/user/validate/{}".format(
                    settings.get('url'),
                    settings.get('frontend.url'),
                    user.email_validation_code,
                )

                # Activate email
                send_mail(
                    email_to=user.email,
                    template="verify_email",
                    template_context={
                        "user_name": user.name,
                        "activation_url": activation_url,
                    })

                logger.warning("Hooray, a new user has just signed up: %s" % user.name)

                return response
        return {'message': 'Invalid data', 'errors': form.errors}, 403