Ejemplo n.º 1
0
def environment(request):
    environment_name = request.matchdict['environment_name']
    try:
        environment = DBSession.query(Environment.id, Environment.name).filter(
            Environment.name == environment_name).one()
    except database_exceptions.NoResultFound:
        raise httpexceptions.HTTPNotFound()
    problems = DBSession.query(Problem).distinct().join(Occurrence).filter(
        Occurrence.problem_id == Problem.id,
        Occurrence.environment_id == environment.id).order_by(
            Problem.last_occurrence)
    return {
        'environment': {
            'id': environment.id,
            'name': environment.name,
        },
        'problems': [{
            'id':
            problem.id,
            'description':
            problem.description,
            'tags':
            problem.get_split_tags(),
            'last_occurrence':
            pytz.utc.normalize(pytz.utc.localize(problem.last_occurrence)),
            'occurrence_count':
            problem.occurrence_count,
            'url':
            request.route_url('alpaca.problems.problem',
                              problem_id=problem.id),
        } for problem in problems],
    }
Ejemplo n.º 2
0
def account(request):
    change_password_form = forms.ChangePasswordForm(csrf_context=request)
    if request.method == 'POST':
        change_password_form.process(request.POST)
        if change_password_form.validate():
            try:
                user = DBSession.query(User).filter(
                    User.id == authenticated_userid(request)).one()
            except database_exceptions.NoResultFound:
                raise httpexceptions.HTTPNotFound()
            user.set_password(change_password_form.password.data)
            DBSession.add(user)
            request.session.flash(get_localizer(request).translate(
                _("Your password has been successfuly changed.")),
                                  queue='success')
            return httpexceptions.HTTPFound(
                request.route_url('alpaca.users.account'))
        else:
            request.session.flash(get_localizer(request).translate(
                _("There were some problems with your request."
                  " Please check the form for error messages.")),
                                  queue='error')
    return {
        'change_password_form': change_password_form,
    }
Ejemplo n.º 3
0
def account(request):
    change_password_form = forms.ChangePasswordForm(
        csrf_context=request
    )
    if request.method == 'POST':
        change_password_form.process(request.POST)
        if change_password_form.validate():
            try:
                user = DBSession.query(User).filter(
                    User.id == authenticated_userid(request)
                ).one()
            except database_exceptions.NoResultFound:
                raise httpexceptions.HTTPNotFound()
            user.set_password(change_password_form.password.data)
            DBSession.add(user)
            request.session.flash(
                get_localizer(request).translate(_(
                    "Your password has been successfuly changed."
                )),
                queue='success'
            )
            return httpexceptions.HTTPFound(
                request.route_url('alpaca.users.account')
            )
        else:
            request.session.flash(
                get_localizer(request).translate(_(
                    "There were some problems with your request."
                    " Please check the form for error messages."
                )),
                queue='error'
            )
    return {
        'change_password_form': change_password_form,
    }
Ejemplo n.º 4
0
def add_environments(event):
    environment_set = DBSession.query(
        Environment.id, Environment.name).order_by(Environment.name)
    event['all_environments'] = [{
        'id': environment.id,
        'name': environment.name
    } for environment in environment_set]
Ejemplo n.º 5
0
def sign_in(request):
    destination = request.GET.get(
        'destination',
        request.route_url('alpaca.problems.dashboard')
    )
    sign_in_form = forms.AuthenticationForm(csrf_context=request)
    if request.method == 'POST':
        sign_in_form.process(request.POST)
        if sign_in_form.validate():
            try:
                user = DBSession.query(User).filter(
                    User.email == sign_in_form.email.data
                ).one()
            except database_exceptions.NoResultFound:
                pass
            else:
                if user.valid_password(sign_in_form.password.data):
                    return httpexceptions.HTTPFound(
                        destination,
                        headers=security.remember(request, user.id)
                    )
        request.session.flash(
            get_localizer(request).translate(_(
                "Invalid credentials."
            )),
            queue='error'
        )
    return {
        'sign_in_form': sign_in_form,
    }
Ejemplo n.º 6
0
 def validate_name(self, field):
     count = DBSession.query(Environment).filter(
         Environment.name == field.data
     ).count()
     if count != 0:
         raise validators.ValidationError(
             _("There is already an environment having this name.")
         )
Ejemplo n.º 7
0
 def validate_email(self, field):
     count = DBSession.query(User).filter(
         User.email == field.data
     ).count()
     if count != 0:
         raise validators.ValidationError(
             _("There is already an account registered with this e-mail"
               " address.")
         )
Ejemplo n.º 8
0
def environment(request):
    environment_name = request.matchdict['environment_name']
    try:
        environment = DBSession.query(
            Environment.id,
            Environment.name
        ).filter(
            Environment.name == environment_name
        ).one()
    except database_exceptions.NoResultFound:
        raise httpexceptions.HTTPNotFound()
    problems = DBSession.query(
        Problem
    ).distinct().join(
        Occurrence
    ).filter(
        Occurrence.problem_id == Problem.id,
        Occurrence.environment_id == environment.id
    ).order_by(
        Problem.last_occurrence
    )
    return {
        'environment': {
            'id': environment.id,
            'name': environment.name,
        },
        'problems': [
            {
                'id': problem.id,
                'description': problem.description,
                'tags': problem.get_split_tags(),
                'last_occurrence': pytz.utc.normalize(pytz.utc.localize(
                    problem.last_occurrence
                )),
                'occurrence_count': problem.occurrence_count,
                'url': request.route_url(
                    'alpaca.problems.problem',
                    problem_id=problem.id
                ),
            }
            for problem in problems
        ],
    }
Ejemplo n.º 9
0
def add_environments(event):
    environment_set = DBSession.query(
        Environment.id,
        Environment.name
    ).order_by(Environment.name);
    event['all_environments'] = [
        {
            'id':   environment.id,
            'name': environment.name
        }
        for environment in environment_set
    ]
Ejemplo n.º 10
0
def set_tags(request):
    problem_id = request.matchdict['problem_id']
    try:
        problem = DBSession.query(
            Problem, ).filter(Problem.id == problem_id).one()
    except database_exceptions.NoResultFound:
        raise httpexceptions.HTTPNotFound()
    tags_cstruct = request.POST.getall('tags[]')
    try:
        tags = ProblemTagsSchema().deserialize(tags_cstruct)
    except colander.Invalid as error:
        raise httpexceptions.HTTPBadRequest('\r\n'.join(
            (_("Invalid tags."), '\r\n'.join(
                ('%s: %s' % (node_name, message)
                 for node_name, message in error.asdict().iteritems())))))
    problem.tags = ','.join(tags)
    DBSession.add(problem)
    return Response()
Ejemplo n.º 11
0
def sign_in(request):
    destination = request.GET.get(
        'destination', request.route_url('alpaca.problems.dashboard'))
    sign_in_form = forms.AuthenticationForm(csrf_context=request)
    if request.method == 'POST':
        sign_in_form.process(request.POST)
        if sign_in_form.validate():
            try:
                user = DBSession.query(User).filter(
                    User.email == sign_in_form.email.data).one()
            except database_exceptions.NoResultFound:
                pass
            else:
                if user.valid_password(sign_in_form.password.data):
                    return httpexceptions.HTTPFound(destination,
                                                    headers=security.remember(
                                                        request, user.id))
        request.session.flash(get_localizer(request).translate(
            _("Invalid credentials.")),
                              queue='error')
    return {
        'sign_in_form': sign_in_form,
    }
Ejemplo n.º 12
0
def set_tags(request):
    problem_id = request.matchdict['problem_id']
    try:
        problem = DBSession.query(
            Problem,
        ).filter(
            Problem.id == problem_id
        ).one()
    except database_exceptions.NoResultFound:
        raise httpexceptions.HTTPNotFound()
    tags_cstruct = request.POST.getall('tags[]')
    try:
        tags = ProblemTagsSchema().deserialize(tags_cstruct)
    except colander.Invalid as error:
        raise httpexceptions.HTTPBadRequest('\r\n'.join((
            _("Invalid tags."),
            '\r\n'.join((
                '%s: %s' % (node_name, message)
                for node_name, message in error.asdict().iteritems()
            ))
        )))
    problem.tags = ','.join(tags)
    DBSession.add(problem)
    return Response()
Ejemplo n.º 13
0
def problem(request):
    problem_id = int(request.matchdict['problem_id'])
    try:
        problem = DBSession.query(
            Problem, ).filter(Problem.id == problem_id).one()
    except database_exceptions.NoResultFound:
        raise httpexceptions.HTTPNotFound()

    try:
        occurrence_id = request.matchdict['occurrence_id']
    except KeyError:
        occurrence = DBSession.query(Occurrence).filter(
            Occurrence.problem_id == problem.id).order_by(
                sql.desc(Occurrence.date)).first()
    else:
        try:
            occurrence = DBSession.query(Occurrence).filter(
                Occurrence.problem_id == problem.id,
                Occurrence.id == occurrence_id).one()
        except database_exceptions.NoResultFound:
            request.session.flash(get_localizer(request).translate(
                _("Details of the problem occurrence your URL pointed to were"
                  " removed to limit history size. Please investigate the"
                  " problem using latest occurrence data.")),
                                  queue='warning')
            raise httpexceptions.HTTPSeeOther('#'.join(
                (request.route_url('alpaca.problems.problem',
                                   problem_id=problem.id), 'top')))
    affected_environments = DBSession.query(
        Environment.id, Environment.name).distinct().join(Occurrence).filter(
            Occurrence.problem_id == problem.id).order_by(Environment.name)
    problem_occurrences = DBSession.query(
        Occurrence.id).filter(Occurrence.problem_id == problem.id).order_by(
            sql.desc(Occurrence.date))
    return {
        'problem': {
            'id':
            problem.id,
            'hash':
            problem.hash,
            'first_occurrence':
            pytz.utc.normalize(pytz.utc.localize(problem.first_occurrence)),
            'last_occurrence':
            pytz.utc.normalize(pytz.utc.localize(problem.last_occurrence)),
            'occurrence_count':
            problem.occurrence_count,
            'tags':
            problem.get_split_tags(),
            'occurrences': [{
                'id':
                problem_occurrence.id,
                'url':
                request.route_url('alpaca.problems.problem_occurrence',
                                  problem_id=problem.id,
                                  occurrence_id=problem_occurrence.id),
            } for problem_occurrence in problem_occurrences],
        },
        'occurrence': {
            'id': occurrence.id,
            'date': pytz.utc.normalize(pytz.utc.localize(occurrence.date)),
            'message': occurrence.message,
            'stack_trace': occurrence.get_normalized_stack_trace(),
            'environment_data': occurrence.get_normalized_environment_data(),
            'environment': {
                'id':
                occurrence.environment.id,
                'name':
                occurrence.environment.name,
                'url':
                request.route_url(
                    'alpaca.problems.environment',
                    environment_name=occurrence.environment.name),
            }
        },
        'affected_environments': [{
            'id':
            environment.id,
            'name':
            environment.name,
            'url':
            request.route_url('alpaca.problems.environment',
                              environment_name=environment.name),
        } for environment in affected_environments],
    }
Ejemplo n.º 14
0
def configuration(request):
    environments = DBSession.query(Environment).order_by('name')
    users = DBSession.query(User).order_by('email')
    # Changing permissions
    if 'change-permissions-submit' in request.POST:
        post_keys = filter(
            lambda key: key.startswith('role_administrator-'),
            request.POST.iterkeys()
        )
        user_ids = []
        for post_key in post_keys:
            try:
                user_ids.append(int(post_key.split('-')[-1]))
            except (KeyError, ValueError):
                continue
        DBSession.query(User).filter(
            User.id != authenticated_userid(request)
        ).update({
            'role_administrator': False,
        })
        DBSession.query(User).filter(
            User.id != authenticated_userid(request),
            User.id.in_(user_ids)
        ).update({
            'role_administrator': True,
        }, synchronize_session=False)
        request.session.flash(
            get_localizer(request).translate(_(
                "User permissions have been successfuly saved."
            )),
            queue='success'
        )
        return httpexceptions.HTTPFound(
            request.route_url('alpaca.configuration.configuration')
        )
    # Adding user
    add_user_form = forms.AddUserForm(csrf_context=request)
    if 'add-user-submit' in request.POST:
        add_user_form.process(request.POST)
        if add_user_form.validate():
            user = User()
            add_user_form.populate_obj(user)
            new_password = user.generate_random_password()
            DBSession.add(user)
            request.session.flash(
                get_localizer(request).translate(_(
                    "New user <code>${email}</code> has been successfuly"
                    " created. Its temporary password is:"
                    " <code>${password}</code>",
                    mapping={
                        'email': user.email,
                        'password': new_password,
                    }
                )),
                queue='success'
            )
            return httpexceptions.HTTPFound(
                request.route_url('alpaca.configuration.configuration')
            )
        else:
            request.session.flash(
                get_localizer(request).translate(_(
                    "There were some problems with your request."
                    " Please check the form for error messages."
                )),
                queue='error'
            )
    # Resetting user password
    if 'reset-user-password-submit' in request.POST:
        reset_user_password_form = forms.ResetUserPasswordForm(
            request.POST,
            csrf_context=request
        )
        if reset_user_password_form.validate():
            try:
                user = DBSession.query(User).filter(
                    User.id == reset_user_password_form.user_id.data
                ).one()
            except database_exceptions.NoResultFound:
                raise httpexceptions.HTTPNotFound()
            new_password = user.generate_random_password()
            DBSession.add(user)
            request.session.flash(
                get_localizer(request).translate(_(
                    "New password for user <code>${email}</code> is:"
                    " <code>${password}</code>",
                    mapping={
                        'email': user.email,
                        'password': new_password,
                    }
                )),
                queue='success'
            )
        return httpexceptions.HTTPFound(
            request.route_url('alpaca.configuration.configuration')
        )
    # Deleting user
    if 'delete-user-submit' in request.POST:
        delete_user_form = forms.DeleteUserForm(
            request.POST,
            csrf_context=request
        )
        if delete_user_form.validate():
            DBSession.query(User).filter(
                User.id == delete_user_form.user_id.data
            ).delete()
            request.session.flash(
                get_localizer(request).translate(_(
                    "User has been successfuly deleted."
                )),
                queue='success'
            )
            return httpexceptions.HTTPFound(
                request.route_url('alpaca.configuration.configuration')
            )
        else:
            request.session.flash(
                get_localizer(request).translate(_(
                    "There were some problems with your request."
                    " Please check the form for error messages."
                )),
                queue='error'
            )
    # Adding environment
    add_environment_form = forms.AddEnvironmentForm(csrf_context=request)
    if 'add-environment-submit' in request.POST:
        add_environment_form.process(request.POST)
        if add_environment_form.validate():
            environment = Environment()
            add_environment_form.populate_obj(environment)
            environment.regenerate_api_key()
            DBSession.add(environment)
            request.session.flash(
                get_localizer(request).translate(_(
                    "New environment <code>${name}</code> has been successfuly"
                    " created. Its API key is: <code>${api_key}</code>",
                    mapping={
                        'name': environment.name,
                        'api_key': environment.api_key,
                    }
                )),
                queue='success'
            )
            return httpexceptions.HTTPFound(
                request.route_url('alpaca.configuration.configuration')
            )
        else:
            request.session.flash(
                get_localizer(request).translate(_(
                    "There were some problems with your request."
                    " Please check the form for error messages."
                )),
                queue='error'
            )
    # Regenerating environment API key
    if 'regenerate-environment-api-key-submit' in request.POST:
        regenerate_api_key_form = forms.RegenerateEnvironmentApiKeyForm(
            request.POST,
            csrf_context=request
        )
        if regenerate_api_key_form.validate():
            try:
                environment = DBSession.query(Environment).filter(
                    (Environment.id ==
                        regenerate_api_key_form.environment_id.data)
                ).one()
            except database_exceptions.NoResultFound:
                raise httpexceptions.HTTPNotFound()
            environment.regenerate_api_key()
            DBSession.add(environment)
            request.session.flash(
                get_localizer(request).translate(_(
                    "New API key for environment <code>${name}</code> is:"
                    " <code>${api_key}</code>",
                    mapping={
                        'name': environment.name,
                        'api_key': environment.api_key,
                    }
                )),
                queue='success'
            )
        return httpexceptions.HTTPFound(
            request.route_url('alpaca.configuration.configuration')
        )
    # Deleting environment
    if 'delete-environment-submit' in request.POST:
        delete_environment_form = forms.DeleteEnvironmentForm(
            request.POST,
            csrf_context=request
        )
        if delete_environment_form.validate():
            DBSession.query(Environment).filter(
                Environment.id == delete_environment_form.environment_id.data
            ).delete()
            request.session.flash(
                get_localizer(request).translate(_(
                    "Environment has been successfuly deleted."
                )),
                queue='success'
            )
            return httpexceptions.HTTPFound(
                request.route_url('alpaca.configuration.configuration')
            )
        else:
            request.session.flash(
                get_localizer(request).translate(_(
                    "There were some problems with your request."
                    " Please check the form for error messages."
                )),
                queue='error'
            )
    return {
        'environments': [
            {
                'id': environment.id,
                'name': environment.name,
                'url': request.route_url(
                    'alpaca.problems.environment',
                    environment_name=environment.name
                ),
                'delete_form': forms.DeleteEnvironmentForm(
                    environment_id=environment.id,
                    csrf_context=request
                ),
                'regenerate_api_key_form': (
                    forms.RegenerateEnvironmentApiKeyForm(
                        environment_id=environment.id,
                        csrf_context=request
                    )
                ),
            }
            for environment in environments
        ],
        'users': [
            {
                'id': user.id,
                'email': user.email,
                'role_administrator': user.role_administrator,
                'delete_form': forms.DeleteUserForm(
                    user_id=user.id,
                    csrf_context=request
                ),
                'reset_password_form': forms.ResetUserPasswordForm(
                    user_id=user.id,
                    csrf_context=request
                ),
            }
            for user in users
        ],
        'add_environment_form': add_environment_form,
        'add_user_form': add_user_form,
    }
Ejemplo n.º 15
0
 def validate_name(self, field):
     count = DBSession.query(Environment).filter(
         Environment.name == field.data).count()
     if count != 0:
         raise validators.ValidationError(
             _("There is already an environment having this name."))
Ejemplo n.º 16
0
 def validate_email(self, field):
     count = DBSession.query(User).filter(User.email == field.data).count()
     if count != 0:
         raise validators.ValidationError(
             _("There is already an account registered with this e-mail"
               " address."))
Ejemplo n.º 17
0
def problem(request):
    problem_id = int(request.matchdict['problem_id'])
    try:
        problem = DBSession.query(
            Problem,
        ).filter(
            Problem.id == problem_id
        ).one()
    except database_exceptions.NoResultFound:
        raise httpexceptions.HTTPNotFound()

    try:
        occurrence_id = request.matchdict['occurrence_id']
    except KeyError:
        occurrence = DBSession.query(
            Occurrence
        ).filter(
            Occurrence.problem_id == problem.id
        ).order_by(
            sql.desc(Occurrence.date)
        ).first()
    else:
        try:
            occurrence = DBSession.query(
                Occurrence
            ).filter(
                Occurrence.problem_id == problem.id,
                Occurrence.id == occurrence_id
            ).one()
        except database_exceptions.NoResultFound:
            request.session.flash(
                get_localizer(request).translate(_(
                    "Details of the problem occurrence your URL pointed to were"
                    " removed to limit history size. Please investigate the"
                    " problem using latest occurrence data."
                )),
                queue='warning'
            )
            raise httpexceptions.HTTPSeeOther(
                '#'.join((
                    request.route_url(
                        'alpaca.problems.problem',
                        problem_id=problem.id
                    ),
                    'top'
                ))
            )
    affected_environments = DBSession.query(
        Environment.id,
        Environment.name
    ).distinct().join(
        Occurrence
    ).filter(
        Occurrence.problem_id == problem.id
    ).order_by(
        Environment.name
    )
    problem_occurrences = DBSession.query(
        Occurrence.id
    ).filter(
        Occurrence.problem_id == problem.id
    ).order_by(
        sql.desc(Occurrence.date)
    )
    return {
        'problem': {
            'id': problem.id,
            'hash': problem.hash,
            'first_occurrence': pytz.utc.normalize(pytz.utc.localize(
                problem.first_occurrence
            )),
            'last_occurrence': pytz.utc.normalize(pytz.utc.localize(
                problem.last_occurrence
            )),
            'occurrence_count': problem.occurrence_count,
            'tags': problem.get_split_tags(),
            'occurrences': [
                {
                    'id': problem_occurrence.id,
                    'url': request.route_url(
                        'alpaca.problems.problem_occurrence',
                        problem_id=problem.id,
                        occurrence_id=problem_occurrence.id
                    ),
                }
                for problem_occurrence in problem_occurrences
            ],
        },
        'occurrence': {
            'id': occurrence.id,
            'date': pytz.utc.normalize(pytz.utc.localize(occurrence.date)),
            'message': occurrence.message,
            'stack_trace': occurrence.get_normalized_stack_trace(),
            'environment_data': occurrence.get_normalized_environment_data(),
            'environment': {
                'id': occurrence.environment.id,
                'name': occurrence.environment.name,
                'url': request.route_url(
                    'alpaca.problems.environment',
                    environment_name=occurrence.environment.name
                ),
            }
        },
        'affected_environments': [
            {
                'id': environment.id,
                'name': environment.name,
                'url': request.route_url(
                    'alpaca.problems.environment',
                    environment_name=environment.name
                ),
            }
            for environment in affected_environments
        ],
    }
Ejemplo n.º 18
0
def configuration(request):
    environments = DBSession.query(Environment).order_by('name')
    users = DBSession.query(User).order_by('email')
    # Changing permissions
    if 'change-permissions-submit' in request.POST:
        post_keys = filter(lambda key: key.startswith('role_administrator-'),
                           request.POST.iterkeys())
        user_ids = []
        for post_key in post_keys:
            try:
                user_ids.append(int(post_key.split('-')[-1]))
            except (KeyError, ValueError):
                continue
        DBSession.query(User).filter(
            User.id != authenticated_userid(request)).update({
                'role_administrator':
                False,
            })
        DBSession.query(User).filter(User.id != authenticated_userid(request),
                                     User.id.in_(user_ids)).update(
                                         {
                                             'role_administrator': True,
                                         },
                                         synchronize_session=False)
        request.session.flash(get_localizer(request).translate(
            _("User permissions have been successfuly saved.")),
                              queue='success')
        return httpexceptions.HTTPFound(
            request.route_url('alpaca.configuration.configuration'))
    # Adding user
    add_user_form = forms.AddUserForm(csrf_context=request)
    if 'add-user-submit' in request.POST:
        add_user_form.process(request.POST)
        if add_user_form.validate():
            user = User()
            add_user_form.populate_obj(user)
            new_password = user.generate_random_password()
            DBSession.add(user)
            request.session.flash(get_localizer(request).translate(
                _(
                    "New user <code>${email}</code> has been successfuly"
                    " created. Its temporary password is:"
                    " <code>${password}</code>",
                    mapping={
                        'email': user.email,
                        'password': new_password,
                    })),
                                  queue='success')
            return httpexceptions.HTTPFound(
                request.route_url('alpaca.configuration.configuration'))
        else:
            request.session.flash(get_localizer(request).translate(
                _("There were some problems with your request."
                  " Please check the form for error messages.")),
                                  queue='error')
    # Resetting user password
    if 'reset-user-password-submit' in request.POST:
        reset_user_password_form = forms.ResetUserPasswordForm(
            request.POST, csrf_context=request)
        if reset_user_password_form.validate():
            try:
                user = DBSession.query(User).filter(
                    User.id == reset_user_password_form.user_id.data).one()
            except database_exceptions.NoResultFound:
                raise httpexceptions.HTTPNotFound()
            new_password = user.generate_random_password()
            DBSession.add(user)
            request.session.flash(get_localizer(request).translate(
                _(
                    "New password for user <code>${email}</code> is:"
                    " <code>${password}</code>",
                    mapping={
                        'email': user.email,
                        'password': new_password,
                    })),
                                  queue='success')
        return httpexceptions.HTTPFound(
            request.route_url('alpaca.configuration.configuration'))
    # Deleting user
    if 'delete-user-submit' in request.POST:
        delete_user_form = forms.DeleteUserForm(request.POST,
                                                csrf_context=request)
        if delete_user_form.validate():
            DBSession.query(User).filter(
                User.id == delete_user_form.user_id.data).delete()
            request.session.flash(get_localizer(request).translate(
                _("User has been successfuly deleted.")),
                                  queue='success')
            return httpexceptions.HTTPFound(
                request.route_url('alpaca.configuration.configuration'))
        else:
            request.session.flash(get_localizer(request).translate(
                _("There were some problems with your request."
                  " Please check the form for error messages.")),
                                  queue='error')
    # Adding environment
    add_environment_form = forms.AddEnvironmentForm(csrf_context=request)
    if 'add-environment-submit' in request.POST:
        add_environment_form.process(request.POST)
        if add_environment_form.validate():
            environment = Environment()
            add_environment_form.populate_obj(environment)
            environment.regenerate_api_key()
            DBSession.add(environment)
            request.session.flash(get_localizer(request).translate(
                _(
                    "New environment <code>${name}</code> has been successfuly"
                    " created. Its API key is: <code>${api_key}</code>",
                    mapping={
                        'name': environment.name,
                        'api_key': environment.api_key,
                    })),
                                  queue='success')
            return httpexceptions.HTTPFound(
                request.route_url('alpaca.configuration.configuration'))
        else:
            request.session.flash(get_localizer(request).translate(
                _("There were some problems with your request."
                  " Please check the form for error messages.")),
                                  queue='error')
    # Regenerating environment API key
    if 'regenerate-environment-api-key-submit' in request.POST:
        regenerate_api_key_form = forms.RegenerateEnvironmentApiKeyForm(
            request.POST, csrf_context=request)
        if regenerate_api_key_form.validate():
            try:
                environment = DBSession.query(Environment).filter(
                    (Environment.id ==
                     regenerate_api_key_form.environment_id.data)).one()
            except database_exceptions.NoResultFound:
                raise httpexceptions.HTTPNotFound()
            environment.regenerate_api_key()
            DBSession.add(environment)
            request.session.flash(get_localizer(request).translate(
                _(
                    "New API key for environment <code>${name}</code> is:"
                    " <code>${api_key}</code>",
                    mapping={
                        'name': environment.name,
                        'api_key': environment.api_key,
                    })),
                                  queue='success')
        return httpexceptions.HTTPFound(
            request.route_url('alpaca.configuration.configuration'))
    # Deleting environment
    if 'delete-environment-submit' in request.POST:
        delete_environment_form = forms.DeleteEnvironmentForm(
            request.POST, csrf_context=request)
        if delete_environment_form.validate():
            DBSession.query(Environment).filter(
                Environment.id ==
                delete_environment_form.environment_id.data).delete()
            request.session.flash(get_localizer(request).translate(
                _("Environment has been successfuly deleted.")),
                                  queue='success')
            return httpexceptions.HTTPFound(
                request.route_url('alpaca.configuration.configuration'))
        else:
            request.session.flash(get_localizer(request).translate(
                _("There were some problems with your request."
                  " Please check the form for error messages.")),
                                  queue='error')
    return {
        'environments': [{
            'id':
            environment.id,
            'name':
            environment.name,
            'url':
            request.route_url('alpaca.problems.environment',
                              environment_name=environment.name),
            'delete_form':
            forms.DeleteEnvironmentForm(environment_id=environment.id,
                                        csrf_context=request),
            'regenerate_api_key_form': (forms.RegenerateEnvironmentApiKeyForm(
                environment_id=environment.id, csrf_context=request)),
        } for environment in environments],
        'users': [{
            'id':
            user.id,
            'email':
            user.email,
            'role_administrator':
            user.role_administrator,
            'delete_form':
            forms.DeleteUserForm(user_id=user.id, csrf_context=request),
            'reset_password_form':
            forms.ResetUserPasswordForm(user_id=user.id, csrf_context=request),
        } for user in users],
        'add_environment_form':
        add_environment_form,
        'add_user_form':
        add_user_form,
    }
Ejemplo n.º 19
0
Archivo: api.py Proyecto: artfb/alpaca
def report(request):
    if 'Alpaca-Environment' not in request.headers:
        raise httpexceptions.HTTPBadRequest(
            "Missing Alpaca-Environment header."
        )
    try:
        environment = DBSession.query(Environment).filter(
            Environment.name == request.headers['Alpaca-Environment']
        ).one()
    except database_exceptions.NoResultFound:
        raise httpexceptions.HTTPBadRequest(
            "Unknown environment."
        )
    if 'Alpaca-Signature' not in request.headers:
        raise httpexceptions.HTTPBadRequest(
            "Missing Alpaca-Signature header."
        )
    if request.content_type == 'application/x-pickle.python':
        try:
            report_cstruct = pickle.loads(request.body)
        except pickle.UnpicklingError as error:
            raise httpexceptions.HTTPBadRequest(
                "Cannot parse request body: %s" % str(error)
            )
    elif request.content_type == 'application/json':
        try:
            report_cstruct = simplejson.loads(request.body)
        except simplejson.JSONDecodeError as error:
            raise httpexceptions.HTTPBadRequest(
                "Cannot parse request body: %s" % str(error)
            )
    else:
        raise httpexceptions.HTTPBadRequest("Unsupported Content-Type.")
    try:
        report = ReportSchema().deserialize(report_cstruct)
    except colander.Invalid as error:
        raise httpexceptions.HTTPBadRequest('\r\n'.join((
            "Invalid report.",
            '\r\n'.join((
                '%s: %s' % (node_name, message)
                for node_name, message in error.asdict().iteritems()
            ))
        )))
    if report['date'].tzinfo is None:
        report['date'] = pytz.utc.normalize(pytz.utc.localize(
            report['date']
        ))
    else:
        report['date'] = report['date'].astimezone(pytz.utc)
    try:
        problem = DBSession.query(
            Problem,
        ).filter(
            Problem.hash == report['hash']
        ).one()
    except database_exceptions.NoResultFound:
        problem = Problem()
        problem.hash = report['hash']
        problem.occurrence_count = 1
        problem.first_occurrence = report['date'].replace(tzinfo=None)
    else:
        problem.occurrence_count += 1
    finally:
        problem.description = report['message'].split('\n')[0].strip()
        problem.last_occurrence = report['date'].replace(tzinfo=None)
        DBSession.add(problem)
    occurrence = Occurrence()
    occurrence.problem = problem
    occurrence.environment = environment
    occurrence.date = report['date'].replace(tzinfo=None)
    occurrence.message = report['message']
    occurrence.stack_trace = report['stack_trace']
    occurrence.environment_data = report['environment_data']
    DBSession.add(occurrence)
    DBSession.query(
        Occurrence
    ).filter(
        Occurrence.id.in_(
            DBSession.query(
                Occurrence.id
            ).join(
                Problem
            ).filter(
                Occurrence.problem_id == Problem.id,
                Problem.hash == report['hash']
            ).order_by(
                sql.desc(Occurrence.date)
            ).offset(
                30
            ).subquery()
        )
    ).delete(synchronize_session=False)
    # Call `expire_all()` to avoid having inconsistent state after calling
    # `delete()` with `synchronize_session=False`.
    DBSession.expire_all()
    return Response()