def _create_check(self,
                      contact_id,
                      test_suite_handle,
                      redirect_to_contact=True):
        check_nperm_func('add.contactcheck_%s' % test_suite_handle,
                         raise_err=True)
        try:
            contact_id = int(contact_id)
        except (TypeError, ValueError):
            context = {
                'main':
                _('Requires integer as parameter (got %s).' % contact_id)
            }
            raise CustomView(self._render('base', ctx=context))

        log_req = create_log_request(
            'ContactCheckEnqueue',
            properties=[['test_suit_handle', test_suite_handle]],
            references=[('contact', int(contact_id))])
        try:
            cherrypy.session['Verification'].enqueueContactCheck(
                contact_id, test_suite_handle, log_req.request_id)
            log_req.result = 'Success'
            messages.success(
                _('New %s contact check has been created.' %
                  test_suite_handle))
            if redirect_to_contact:
                raise cherrypy.HTTPRedirect(f_urls['contact'] +
                                            'detail/?id=%s' % contact_id)
        finally:
            log_req.close()
    def _table_data_generator(self, test_suit=None, contact_id=None):
        checks = c2u(self._get_contact_checks(test_suit, contact_id))

        for check in checks:
            if not check_nperm_func(
                    'read.contactcheck_%s' % check.test_suite_handle):
                continue
            to_resolve = self._get_to_resolve_date(check)
            if to_resolve:
                to_resolve = to_resolve.isoformat()

            check_link = '<a href="{0}detail/{1}/"><img src="/img/icons/open.png" title="{3}" /></a>'
            if (check.current_status not in self.UNCLOSABLE_CHECK_STATUSES
                    and check_nperm_func(
                        'change.contactcheck_%s' % check.test_suite_handle)):
                cache_key = (RESOLVE_LOCK_CACHE_KEY %
                             check.check_handle).encode('utf-8')
                resolving_user = cache.get(
                    cache_key) if cache is not None else None
                if resolving_user and resolving_user != cherrypy.session[
                        'user'].login:
                    check_link += '&nbsp;%s resolving' % resolving_user
                else:
                    check_link += '''&nbsp;<a href="{0}detail/{1}/resolve/">{2}</a>'''
            check_link = check_link.format(f_urls[self.classname],
                                           check.check_handle, _('Resolve'),
                                           _('Show'))
            row = [
                check_link,
                '<a href="{}detail/?id={}">{}</a>'.format(
                    f_urls['contact'], check.contact_id, check.contact_handle),
                ContactCheckEnums.SUITE_NAMES.get(check.test_suite_handle,
                                                  _('!Unknown error!')),
                to_resolve,
                check.created.isoformat(),
                '<span title="%s">%s</span>' %
                (ContactCheckEnums.CHECK_STATUS_DESCS.get(
                    check.current_status, _('!Unknown error!')),
                 ContactCheckEnums.CHECK_STATUS_NAMES.get(
                     check.current_status, _('!Unknown error!'))),
            ]
            yield row
Exemplo n.º 3
0
def get_status_action(test_suite_handle, current_status):
    status_action = None
    if test_suite_handle == 'automatic':
        if current_status.startswith('auto_'):
            status_action = OrderedDict((('fail:add_manual', _('Resolve as failed')),
                                         ('invalidated:', _('Invalidate')),
                                         ('ok:', _('Resolve as OK'))))
    elif test_suite_handle == 'manual':
        if current_status == 'enqueue_req':
            status_action = OrderedDict((('confirm_enqueue:', _('Confirm enqueue')),
                                         ('invalidated:', _('Invalidate')),
                                         ('ok:', _('Resolve as OK'))))
        elif current_status == 'auto_to_be_decided':
            status_action = OrderedDict((('fail_req:', _('Request failed')),
                                         ('invalidated:', _('Invalidate')),
                                         ('invalidated:add_thank_you', _('Inv. + thank letter')),
                                         ('ok:', _('Resolve as OK'))))
        elif current_status == 'fail_req':
            status_action = OrderedDict((('fail:delete_domains', _('Resolve as failed')),
                                         ('invalidated:', _('Invalidate')),
                                         ('invalidated:add_thank_you', _('Inv. + thank letter')),
                                         ('ok:', _('Resolve as OK'))))
    elif test_suite_handle == 'thank_you':
        if current_status == 'auto_to_be_decided':
            status_action = OrderedDict((('fail:add_manual', _('Resolve as failed')),
                                         ('invalidated:', _('Invalidate')),
                                         ('ok:', _('Resolve as OK'))))
    if status_action is not None:
        # filter out action that are not allowed by permission:
        from fred_webadmin.controller.perms import check_nperm_func
        for key in status_action:
            action = key.split(':')[1]
            if (action.startswith('add_') and not check_nperm_func('add.contactcheck_%s' % action[4:])
                    or action == 'delete_domains' and not  check_nperm_func('delete.domain')):
                del status_action[key]

    if status_action is None:
        raise RuntimeError('Unknown current_status "%s" of contact check with suite "%s".' % (current_status, test_suite_handle))
    return status_action
 def filter(self, contact_id=None):
     context = DictLookup({
         'heading':
         _('Contact checks'),
         'ajax_json_filter_url':
         f_urls['contactcheck'] + 'json_filter/' +
         ('%s/' % contact_id if contact_id else ''),
         'table_tag':
         self._get_checks_table_tag(),
     })
     if contact_id is None:  # don't set filter when user is wating check of particular contact:
         context['default_js_type_filter'] = 'filter-manual' if check_nperm_func('change.contactcheck_manual') \
                                                             else 'filter-automatic'
     return self._render('filter', ctx=context)
    def detail(self, *args, **kwd):
        # path can be 'detail/ID/' or 'detail/ID/resolve/'
        if (not 1 <= len(args) <= 2) or (len(args) > 1
                                         and args[1] != 'resolve'):
            return self._render('404_not_found')

        check_handle = args[0]
        if len(args) > 1:
            # cache lock is just helping users so they don't work on the same Check, but it's optional:
            if cache:
                cache_key = RESOLVE_LOCK_CACHE_KEY % check_handle
                stored = cache.add(
                    cache_key, cherrypy.session['user'].login,
                    config.verification_check_lock_default_duration)
                current_resolving_user = cache.get(cache_key)
                # resolve only if memcache is not running (return value 0) or lock was acquired (return value True) or
                # the current user is the user who has the lock:
                if (stored == 0 and type(stored) == type(0)) or stored is True \
                    or current_resolving_user == cherrypy.session['user'].login:
                    resolve = True
                else:
                    messages.warning(
                        'This check is currently being resolved by the user "%s"'
                        % current_resolving_user)
                    raise cherrypy.HTTPRedirect(f_urls['contactcheck'] +
                                                'detail/%s/' % check_handle)
            else:
                resolve = True
        else:  # read only mode
            resolve = False

        post_data = kwd if cherrypy.request.method == 'POST' else None

        if resolve and post_data:
            req_type = 'ContactCheckUpdateTestStatuses'
        else:
            req_type = 'ContactCheckDetail'

        log_req = create_log_request(
            req_type, properties=[['check_handle', check_handle]])
        out_props = []

        check = None
        try:
            check = c2u(cherrypy.session['Verification'].getContactCheckDetail(
                check_handle))
            if resolve:
                check_nperm_func('change.contactcheck_%s' %
                                 check.test_suite_handle,
                                 raise_err=True)
            else:
                check_nperm_func('read.contactcheck_%s' %
                                 check.test_suite_handle,
                                 raise_err=True)

            if resolve:
                if self._is_check_post_closed(check):
                    messages.warning(
                        _('This contact check was already resolved.'))
                    raise cherrypy.HTTPRedirect(f_urls['contactcheck'] +
                                                'detail/%s/' %
                                                check.check_handle)
                elif self._is_check_pre_run(check) and check.status_history[
                        -1].status != 'enqueue_req':
                    messages.warning(_('This contact check was not yet run.'))
                    raise cherrypy.HTTPRedirect(f_urls['contactcheck'] +
                                                'detail/%s/' %
                                                check.check_handle)

                initial = {
                    test_data.test_handle: test_data.status_history[-1].status
                    for test_data in check.test_list
                }
                form = self._generate_update_tests_form_class(check)(
                    post_data, initial=initial)
                if form.is_valid():
                    changed_statuses = {}
                    for test_data in check.test_list:
                        status_in_form = form.cleaned_data[
                            test_data.test_handle]
                        if status_in_form != test_data.status_history[
                                -1].status:
                            changed_statuses[
                                test_data.test_handle] = status_in_form
                    if changed_statuses:
                        cherrypy.session[
                            'Verification'].updateContactCheckTests(
                                u2c(check.check_handle),
                                u2c([
                                    Registry.AdminContactVerification.
                                    ContactTestUpdate(test_handle, status)
                                    for test_handle, status in
                                    changed_statuses.items()
                                ]), u2c(log_req.request_id))
                    log_req.result = 'Success'
                    out_props += [['changed_statuses', '']] + [[
                        key, val, True
                    ] for key, val in changed_statuses.items()]
                    self._update_check(check, post_data)
                else:
                    log_req.result = 'Fail'
            else:
                form = None

            log_req.result = 'Success'

            detail = VerificationCheckDetail(check=check,
                                             resolve=resolve,
                                             form=form)

            try:
                contact_detail = get_detail('contact', check.contact_id)
            except ccReg.Admin.ObjectNotFound:
                contact_detail = None

            context = DictLookup({
                'test_suit_name':
                ContactCheckEnums.SUITE_NAMES.get(check.test_suite_handle),
                'check':
                check,
                'contact_url':
                f_urls['contact'] + 'detail/?id=%s' % check.contact_id,
                'detail':
                detail,
                'contact_detail':
                contact_detail,
                'ajax_json_filter_url':
                f_urls['contactcheck'] + 'json_filter/%s/' % check.contact_id,
            })
            if cherrypy.session.get('history', False):
                context.update({
                    'table_tag':
                    self._get_checks_table_tag(),
                    'messages_list':
                    self._get_check_messages_list(check)
                })
            return self._render('detail', ctx=context)
        except Registry.AdminContactVerification.INVALID_CHECK_HANDLE:
            log_req.result = 'Fail'
            return self._render('404_not_found')
        finally:
            log_req.close(properties=out_props,
                          references=[('contact',
                                       check.contact_id)] if check else None)