예제 #1
0
파일: adifwidgets.py 프로젝트: LANJr4D/FRED
 def __init__(self, filters, filter_name=None, *content, **kwd):
     ''' Filters is list of triplets [id, type, name] 
         If filter_name is specified, general filter for that object is added (e.g. /domains/filter/)
     '''
     ul.__init__(self, *content, **kwd)
     self.tag = 'ul'
     debug('LIST OF FILTERS(unpacked): %s' % filters)
     
     custom_presented = False
     for filter in filters:
         url_filter = f_urls[f_id_name[int(filter['Type'])]] + 'filter/?filter_id=' + filter['Id']
         url_filter_with_form =  url_filter + '&show_form=1'
         if filter['Name'].lower() == 'custom':
             form = self.get_form(filter)
             custom_presented = True
         else:
             form = None
         self.add(li(
                     a(attr(href=url_filter), filter['Name']),
                     ' (', a(attr(href=url_filter_with_form), _('form')),  ')',
                     form))
     if not custom_presented and filter_name:
         self.add(li(a(attr(href=f_urls[filter_name] + 'filter/'), _('Custom filter')),
                     self.get_default_form(filter_name)
                    ))
         
     self.add(script(attr(type='text/javascript'), 'Ext.onReady(function () {addFieldsButtons()})')) 
예제 #2
0
class LoggerFilterForm(FilterForm):
    def __init__(self, *args, **kwargs):
        super(LoggerFilterForm, self).__init__(*args, **kwargs)

    def _get_header_title(self):
        return _("Logged Actions")

    def get_key_time_field(self):
        return self.base_fields['TimeBegin']

    default_fields_names = ['ServiceType', 'TimeBegin', 'IsMonitoring']

    ServiceType = IntegerChoiceField(id="logger_service_type_id",
                                     label=_('Service type'),
                                     choices=CorbaLazyRequestIterStruct(
                                         'Logger', None, 'getServices',
                                         ['id', 'name'], None, 'name'),
                                     onchange="filter_action_types();")
    SourceIp = CharField(label=_('Source IP'))
    UserName = CharField(label=_('Username'))
    RequestType = IntegerChoiceField(id="logger_action_type_id",
                                     label=_('Request type'),
                                     choices=[],
                                     validate=False,
                                     onfocus="filter_action_types();")
    TimeBegin = DateTimeIntervalField(label=_('Begin time'))
    TimeEnd = DateTimeIntervalField(label=_('End time'))
    RequestPropertyValue = CompoundFilterField(label=_('Property'),
                                               form_class=PropertyFilterForm)
    ResultCode = CompoundFilterField(label=_('Result code'),
                                     form_class=ResultCodeFilterForm)
    RequestObjectRef = CompoundFilterField(
        label=_('Object reference'), form_class=RequestObjectRefFilterForm)
    IsMonitoring = BooleanField(label=_("Monitoring"))
예제 #3
0
파일: adif.py 프로젝트: LANJr4D/FRED
    def unblock(self, id):
        context = DictLookup()
        try:
            reg_id = int(id)
        except (TypeError, ValueError):
            context.message = _("Required_integer_as_parameter")
            raise CustomView(self._render('error', ctx=context))

        return_message = [
            _(u'You can return back to '),
            a(attr(href=f_urls[self.classname] + 'detail/?id=%s' % reg_id),
              _('registrar.'))
        ]

        admin = cherrypy.session.get('Admin')
        if not admin.isRegistrarBlocked(reg_id):
            context.message = [_("This registrar is not blocked.")] + return_message
            return self._render('error', ctx=context)
        else:
            log_req = utils.create_log_request('RegistrarUpdate', [['blocked', 'False']], [[self.classname, reg_id]])
            try:
                admin.unblockRegistrar(reg_id, log_req.request_id)
                log_req.result = 'Success'
            finally:
                log_req.close()

            context.main = [_("Registrar successfully unblocked.")] + return_message
            return self._render('base', ctx=context)
예제 #4
0
파일: editforms.py 프로젝트: LANJr4D/FRED
 def fire_actions(self, *args, **kwargs):
     mgr = cherrypy.session['Admin'].getGroupManager()
     group_id = self.fields['id'].value
     group_name = recoder.u2c(self.fields['name'].value)
     if not group_id:
         if ('name' in self.changed_data):
             props = [('group_name', group_name)]
             log_req = utils.create_log_request('CreateRegistrarGroup', properties = props)
             out_props = []
             try:
                 gid = mgr.createGroup(group_name)
                 out_props.append(('group_id', gid))
                 log_req.result = 'Success'
             except Registry.Registrar.InvalidValue:
                 log_req.result = 'Fail'
                 raise UpdateFailedError(
                     _(u"Could not create group. Perhaps you've entered "
                        "a name of an already existing group (or name of "
                        "a deleted one, which is currently invalid too)?"))
             finally:
                 log_req.close(properties=out_props)
     else:
         group_id = int(group_id)
         if 'DELETE' in self.changed_data:
             props = [('group_name', group_name), ('group_id', group_id)]
             log_req = utils.create_log_request('DeleteRegistrarGroup', properties = props)
             try:
                 mgr.deleteGroup(group_id)
                 log_req.result = 'Success'
             except Registry.Registrar.InvalidValue, e:
                 log_req.result = 'Fail'
                 error(e)
                 raise UpdateFailedError(_(u'Group %s is not empty.') % group_name)
             finally:
                 log_req.close()
예제 #5
0
class ZoneEditForm(EditForm):
    def __init__(self, *args, **kwargs):
        super(ZoneEditForm, self).__init__(layout_class=TableFormLayout,
                                           *args,
                                           **kwargs)

    id = HiddenIntegerField(initial=0)
    #credit = HiddenIntegerField(initial=0)

    name = CharField(label=_('Name'))
    fromDate = DateField(label=_('From'))
    toDate = DateField(label=_('To'), required=False)

    def clean(self):
        """ Check that 'To' date is bigger than 'From' date.
        """
        to_date = self.fields['toDate'].value
        from_date = self.fields['fromDate'].value
        if from_date and to_date:
            if to_date < from_date:
                raise ValidationError(
                    "'To' date must be bigger than 'From' date.")
        if 'fromDate' in self.changed_data:
            if from_date < datetime.date.today().isoformat():
                raise ValidationError("'From' date must be in future.")
        return self.cleaned_data
    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()
예제 #7
0
    def make_content(self):
        self.content = []

        self.inner_field.owner_detail = self.owner_detail
        if self.value:
            for i, history_rec in enumerate(self.value):
                val = from_any(history_rec.value, True)
                inner_field_copy = copy(self.inner_field)
                inner_field_copy.value = val
                date_from = history_rec._from  #recoder.corba_to_datetime(history_rec._from)
                date_to = history_rec.to  #recoder.corba_to_datetime(history_rec.to)
                logger_url = f_urls[
                    'logger'] + 'detail/?id=%s' % history_rec.requestId

                history_tr = tr()
                if i > 0:
                    history_tr.cssc = 'history_row'
                log_req_link = a(attr(
                    href=logger_url), img(attr(src='/img/icons/open.png'))
                                 ) if history_rec.requestId else ''
                history_tr.add(
                    td(inner_field_copy),
                    td(attr(cssc='history_dates_field'), _('from'), date_from),
                    td(attr(cssc='history_dates_field'), date_to and _('to')
                       or '', date_to),
                    td(attr(cssc='history_dates_field'), log_req_link))
                self.add(history_tr)
        else:
            self.add(div(attr(cssc='field_empty')))
예제 #8
0
    def resolve(self, **kwd):
        '''Accept and send'''
        log_req = self._create_log_req_for_object_view('PublicRequestAccept', **kwd)
        try:
            cherrypy.session['Admin'].processPublicRequest(int(kwd['id']), False)
            log_req.result = 'Success'
        except ccReg.Admin.REQUEST_BLOCKED:
            log_req.result = 'Fail'
            raise CustomView(self._render(
                'error', {'message': [
                    _(u'This object is blocked, request cannot be accepted.'
                      u'You can return back to '),
                    a(attr(href=f_urls[self.classname] + 'detail/?id=%s' % kwd['id']),
                      _('public request.'))
                ]}))
        except ccReg.Admin.OBJECT_NOT_FOUND:
            log_req.result = 'Fail'
            raise CustomView(self._render(
                'error', {'message': [
                    _(u'No such public request. Maybe it has already been resolved '
                      u'or this type of public request cannot be resolved. '
                      u'You can return back to '),
                    a(attr(href=f_urls[self.classname] + 'detail/?id=%s' % kwd['id']),
                      _('public request.'))
                ]}))
        finally:
            log_req.close()

        raise cherrypy.HTTPRedirect(f_urls[self.classname] + 'filter/?reload=1&load=1')
예제 #9
0
class DomainUnblockForm(DomainBlockingBase):
    new_holder = CharField(label=_('New holder'), required=False)
    remove_admin_contacts = BooleanField(label=_('Remove admin. contacts'))
    restore_prev_state = BooleanField(
        label=_('Restore prev. state'),
        title=_('Restores previous user blocking and the previous holder,'
                ' if the field "New holder" is empty.'))

    def clean(self):
        cleaned_data = super(DomainUnblockForm, self).clean()
        if cleaned_data.get('restore_prev_state') and cleaned_data.get(
                'remove_admin_contacts'):
            self.add_error(
                'remove_admin_contacts',
                _('You cannot use "Remove admin. contacts" and "Restore prev. state"'
                  ' at the same time.'))

        if not cleaned_data.get('restore_prev_state') and not cleaned_data.get(
                'new_holder'):
            self.add_error(
                'new_holder',
                _('New holder is required when you don\'t use "Restore prev. state"'
                  ))

        return cleaned_data
예제 #10
0
    def make_content(self):
        self.content = []
        self.create_inner_details()

        if self.inner_details:
            # Header:
            thead_row = tr()
            for field in self.inner_details[0].fields.values():
                thead_row.add(th(field.label))
            thead_row.add(th(_('From')), th(_('To')), th(_('L.')))
            self.add(thead(thead_row))

            # rows (each row is made from one detail of object in object list
            self.add(tbody(tagid('tbody')))
            for i, detail in enumerate(self.inner_details):
                history_rec = self.value[i]
                date_from = history_rec._from  #recoder.corba_to_datetime(history_rec._from)
                date_to = history_rec.to  #recoder.corba_to_datetime(history_rec.to)
                logger_url = f_urls[
                    'logger'] + 'detail/?id=%s' % history_rec.requestId

                history_tr = tr()
                if i > 0:
                    history_tr.cssc = 'history_row'
                log_req_link = a(attr(
                    href=logger_url), img(attr(src='/img/icons/open.png'))
                                 ) if history_rec.requestId else ''
                history_tr.add(
                    detail, td(attr(cssc='history_dates_field'), date_from),
                    td(attr(cssc='history_dates_field'), date_to),
                    td(attr(cssc='history_dates_field'), log_req_link))
                self.add(history_tr)
        else:
            self.add(div(attr(cssc='field_empty')))
예제 #11
0
 def clean(self):
     # If no URL scheme given, assume http://
     value = self.value
     if value and '://' not in value:
         value = u'http://%s' % value
     value = super(URLField, self).clean()
     if value == u'':
         return value
     if self.verify_exists:
         import urllib2
         headers = {
             "Accept":
             "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5",
             "Accept-Language": "en-us,en;q=0.5",
             "Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.7",
             "Connection": "close",
             "User-Agent": self.user_agent,
         }
         try:
             req = urllib2.Request(value, None, headers)
             urllib2.urlopen(req)
         except ValueError:
             raise ValidationError(_(u'Enter a valid URL.'))
         except:  # urllib2.URLError, httplib.InvalidURL, etc.
             raise ValidationError(
                 _(u'This URL appears to be a broken link.'))
     return value
예제 #12
0
    def __init__(self, filters, filter_name=None, *content, **kwd):
        ''' Filters is list of triplets [id, type, name]
            If filter_name is specified, general filter for that object is added (e.g. /domains/filter/)
        '''
        ul.__init__(self, *content, **kwd)
        self.tag = 'ul'
        debug('LIST OF FILTERS(unpacked): %s' % filters)
        for obj_filter in filters:
            url_filter = f_urls[f_id_name[int(
                obj_filter['Type'])]] + 'filter/?filter_id=' + obj_filter['Id']
            url_filter_with_form = url_filter + '&show_form=1'
            filter_form = self.get_form(obj_filter)
            self.add(
                li(a(attr(href=url_filter), obj_filter['Name']), ' (',
                   a(attr(href=url_filter_with_form), _('form')), ')',
                   filter_form))
        if filter_name:
            self.add(
                li(
                    a(attr(href=f_urls[filter_name] + 'filter/'),
                      _('Custom filter'))))

        self.add(
            script(attr(type='text/javascript'),
                   'Ext.onReady(function () {addFieldsButtons()})'))
예제 #13
0
파일: adifdetails.py 프로젝트: saimir/FRED
class CertificationDetail(Detail):
    score = CharDField(label=_("Score"))
    fromDate = DateDField(label=_('From'))
    toDate = DateDField(label=_('To'))
    evaluation_file_id = FileHandleDField(
        handle="pdf", label=_('Evaluation'))
    pass
예제 #14
0
    def clean(self):
        super(FileField, self).clean()  # data)
        #        if not self.required and data in EMPTY_VALUES:
        if self.value is None:
            return fredtypes.NullFile()
        if not self.required and self.value.filename in EMPTY_VALUES:
            return fredtypes.NullFile()
        if self.required and self.value.filename in EMPTY_VALUES:
            raise ValidationError(_(u"No file specified."))
        try:
            #            f = UploadedFile(data['filename'], data['content'])
            #            f = fredtypes.NullFile() #UploadedFile(self.value, None)
            #            data = self.value
            #            f = UploadedFile(data.filename, data.file.read(-1))
            f = UploadedFile(self.value.filename, self.value)
        except TypeError:
            raise ValidationError(
                _(u"No file was submitted. Check the encoding type on the form."
                  ))
        except KeyError:
            raise ValidationError(_(u"No file was submitted."))


#        if not f.content:
#            raise ValidationError(_(u"The submitted file is empty."))
        return f
예제 #15
0
파일: dfields.py 프로젝트: LANJr4D/FRED
    def make_content(self):
        self.content = []

        self.inner_field.owner_detail = self.owner_detail
        if self.value:
            for i, history_rec in enumerate(self.value):
                val = from_any(history_rec.value, True)
                inner_field_copy = copy(self.inner_field)
                inner_field_copy.value = val
                date_from = history_rec._from #recoder.corba_to_datetime(history_rec._from)
                date_to = history_rec.to #recoder.corba_to_datetime(history_rec.to)
                logger_url = f_urls['logger'] + 'detail/?id=%s' % history_rec.requestId

                history_tr = tr()
                if i > 0:
                    history_tr.cssc = 'history_row'
                log_req_link = a(attr(href=logger_url), img(attr(src='/img/icons/open.png'))) if history_rec.requestId else ''
                history_tr.add(
                    td(inner_field_copy),
                    td(attr(cssc='history_dates_field'), _('from'), date_from),
                    td(attr(cssc='history_dates_field'), date_to and _('to') or '', date_to),
                    td(attr(cssc='history_dates_field'), log_req_link)
                )
                self.add(history_tr)
        else:
            self.add(div(attr(cssc='field_empty')))
예제 #16
0
파일: fields.py 프로젝트: LANJr4D/FRED
 def clean(self):
     # If no URL scheme given, assume http://
     value = self.value
     if value and '://' not in value:
         value = u'http://%s' % value
     value = super(URLField, self).clean()
     if value == u'':
         return value
     if self.verify_exists:
         import urllib2
         from django.conf import settings
         headers = {
             "Accept": "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5",
             "Accept-Language": "en-us,en;q=0.5",
             "Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.7",
             "Connection": "close",
             "User-Agent": self.user_agent,
         }
         try:
             req = urllib2.Request(value, None, headers)
             u = urllib2.urlopen(req)
         except ValueError:
             raise ValidationError(_(u'Enter a valid URL.'))
         except: # urllib2.URLError, httplib.InvalidURL, etc.
             raise ValidationError(_(u'This URL appears to be a broken link.'))
     return value
예제 #17
0
파일: dfields.py 프로젝트: LANJr4D/FRED
    def make_content(self):
        self.content = []
        self.create_inner_details()

        if self.inner_details:
            # Header:
            thead_row = tr()
            for field in self.inner_details[0].fields.values():
                thead_row.add(th(field.label))
            thead_row.add(th(_('From')), th(_('To')), th(_('L.')))
            self.add(thead(thead_row))

            # rows (each row is made from one detail of object in object list
            self.add(tbody(tagid('tbody')))
            for i, detail in enumerate(self.inner_details):
                history_rec = self.value[i]
                date_from = history_rec._from #recoder.corba_to_datetime(history_rec._from)
                date_to = history_rec.to #recoder.corba_to_datetime(history_rec.to)
                logger_url = f_urls['logger'] + 'detail/?id=%s' % history_rec.requestId

                history_tr = tr()
                if i > 0:
                    history_tr.cssc = 'history_row'
                log_req_link = a(attr(href=logger_url), img(attr(src='/img/icons/open.png'))) if history_rec.requestId else ''
                history_tr.add(
                    detail,
                    td(attr(cssc='history_dates_field'), date_from),
                    td(attr(cssc='history_dates_field'), date_to),
                    td(attr(cssc='history_dates_field'), log_req_link)
                )
                self.add(history_tr)
        else:
            self.add(div(attr(cssc='field_empty')))
예제 #18
0
    def unblock(self, id):
        context = DictLookup()
        try:
            reg_id = int(id)
        except (TypeError, ValueError):
            context.message = _("Required_integer_as_parameter")
            raise CustomView(self._render('error', ctx=context))

        return_message = [
            _(u'You can return back to '),
            a(attr(href=f_urls[self.classname] + 'detail/?id=%s' % reg_id),
              _('registrar.'))
        ]

        admin = cherrypy.session.get('Admin')
        if not admin.isRegistrarBlocked(reg_id):
            context.message = [_("This registrar is not blocked.")
                               ] + return_message
            return self._render('error', ctx=context)
        else:
            log_req = utils.create_log_request('RegistrarUpdate',
                                               [['blocked', 'False']],
                                               [[self.classname, reg_id]])
            try:
                admin.unblockRegistrar(reg_id, log_req.request_id)
                log_req.result = 'Success'
            finally:
                log_req.close()

            context.main = [_("Registrar successfully unblocked.")
                            ] + return_message
            return self._render('base', ctx=context)
예제 #19
0
    def close(self, **kwd):
        '''Close and invalidate'''
        log_req = self._create_log_req_for_object_view(
            'PublicRequestInvalidate', **kwd)
        try:
            cherrypy.session['Admin'].processPublicRequest(
                int(kwd['id']), True)
            log_req.result = 'Success'
        except ccReg.Admin.REQUEST_BLOCKED:
            log_req.result = 'Fail'
            raise CustomView(
                self._render(
                    'error', {
                        'message': [
                            _(u'Request cannot be accepted.'
                              u'You can return back to '),
                            a(
                                attr(href=f_urls[self.classname] +
                                     'detail/?id=%s' % kwd['id']),
                                _('public request.'))
                        ]
                    }))
        finally:
            log_req.close()

        raise cherrypy.HTTPRedirect(f_urls[self.classname] +
                                    'filter/?reload=1&load=1')
예제 #20
0
    def resend(self, pr_type, **kwd):
        '''Resend associated message with public request, works only with serveral public request types'''
        backend = cherrypy.session['Admin']
        backend_call_switch = {
            Registry.PublicRequest.PRT_MOJEID_CONTACT_IDENTIFICATION._n: backend.resendPin3Letter,
            Registry.PublicRequest.PRT_CONTACT_IDENTIFICATION._n: backend.resendPin3Letter,
            Registry.PublicRequest.PRT_MOJEID_CONTACT_CONDITIONAL_IDENTIFICATION._n: backend.resendPin2SMS,
            Registry.PublicRequest.PRT_CONTACT_CONDITIONAL_IDENTIFICATION._n: backend.resendPin2SMS,
        }
        log_req = self._create_log_req_for_object_view('PublicRequestResendMessage', **kwd)
        try:
            method = backend_call_switch.get(pr_type)
            if method:
                method(int(kwd['id']))
                log_req.result = 'Success'
                messages.success(_('Message was succesfully enqueued for re-send.'))
            else:
                log_req.result = 'Fail'
                messages.error(_('Invalid public request type.'))

        except ccReg.Admin.ObjectNotFound:
            log_req.result = 'Fail'
            messages.error(_(u'Associated message cannot be resend because request was already processed or has not valid type.'))
        except ccReg.Admin.MessageCopyProhibited:
            log_req.result = 'Fail'
            messages.error(_(u'Message cannot be re-send because it is still in queue.'))
        finally:
            log_req.close()

        raise cherrypy.HTTPRedirect(f_urls[self.classname] + 'detail/?id=%s' % kwd['id'])
예제 #21
0
    def _render_keyset(self, keyset_detail):
        registrar_detail = keyset_detail.fields.get("registrar").current_field.inner_detail  # registrar of keyset

        handle_field = keyset_detail.fields["handle_url"]
        registrar_field = registrar_detail.fields["handle_url"]
        admins_field = keyset_detail.fields["admins"]
        dsrecords_field = keyset_detail.fields["dsrecords"]
        dnskeys_field = keyset_detail.fields["dnskeys"]

        handle_label = self.get_label_name(handle_field)
        registrar_label = self.get_label_name(_("Registrar"))
        admins_label = self.get_label_name(_("Tech. contacts"))
        dsrecords_label = self.get_label_name(_("DS records"))
        dnskeys_label = self.get_label_name(_("DNSKeys"))

        self.add(tr(td(attr(cssc="left_label"), handle_label), td(handle_field)))
        self.add(tr(td(attr(cssc="left_label"), registrar_label), td(registrar_field)))

        for i, admin_detail in enumerate(admins_field.current_field.inner_details):
            row = tr()
            if i == 0:
                row.add(
                    td(attr(cssc="left_label", rowspan=len(admins_field.current_field.inner_details)), admins_label)
                )
            email_part = ""
            if admin_detail.fields["email"].value:
                email_part = [", ", admin_detail.fields["email"]]
            row.add(td(attr(enclose_content=True), admin_detail.fields["handle_url"], email_part))
            self.add(row)

        for i, dsrecord_detail in enumerate(dsrecords_field.current_field.inner_details):
            row = tr()
            if i == 0:
                row.add(
                    td(
                        attr(cssc="left_label", rowspan=len(dsrecords_field.current_field.inner_details)),
                        dsrecords_label,
                    )
                )

            cell = td(attr(enclose_content=True))
            cell.add(dsrecord_detail.fields["keyTag"])

            cell.add(dsrecord_detail.fields["digest"], " (", dsrecord_detail.fields["digestType"], ")")

            row.add(cell)
            self.add(row)

        for i, dnskey_detail in enumerate(dnskeys_field.current_field.inner_details):
            row = tr()
            if i == 0:
                row.add(
                    td(attr(cssc="left_label", rowspan=len(dnskeys_field.current_field.inner_details)), dnskeys_label)
                )

            cell = td(attr(enclose_content=True))
            cell.add(dnskey_detail.fields["key"])

            row.add(cell)
            self.add(row)
예제 #22
0
    def printout(self, handle, **kwd):
        lang_code = config.lang[:2]
        if lang_code == 'cs':  # conversion between cs and cz identifier of lagnguage
            lang_code = 'cz'
        context = {'main': div()}
        context['main'].add(
            script(
                attr(type='text/javascript'),
                'scwLanguage = "%s"; //sets language of js_calendar' %
                lang_code,
                'scwDateOutputFormat = "%s"; // set output format for js_calendar'
                % config.js_calendar_date_format))

        if cherrypy.request.method == 'POST':
            form = ObjectPrintoutForm(data=kwd)
            if form.is_valid():
                for_time = form.cleaned_data['for_time']
                props = [('handle', handle), ('for_time', for_time)]
                log_req = create_log_request('RecordStatement',
                                             properties=props)
                try:
                    return self._get_printout_pdf(handle, for_time)
                except Registry.RecordStatement.OBJECT_NOT_FOUND:
                    form.add_error(
                        'for_time',
                        _('Object "{}" was not found for the given date.'.
                          format(handle)))
                finally:
                    log_req.close()
        else:
            form = ObjectPrintoutForm()

        context['heading'] = _('Download printout')
        context['form'] = form
        return self._render('printout', context)
예제 #23
0
    def make_content(self):
        state_table = self.compute_state_data()
        if self.owner_detail.history and len(
                state_table
        ):  # dont display history if state_table have no row
            self.content = []

            display_state_list = self.state_list[1:]
            self.tag = 'table'
            self.tattr_list = table.tattr_list
            self.cssc = 'state_table section_table'

            # header
            self.add(
                tr(th(_('Date')), [
                    th(
                        attr(cssc='state_header_cell',
                             title=self.transform_title(
                                 _('Status'), self.get_state_title(state_id))),
                        self.states_abbrev[state_id])
                    for state_id in display_state_list
                ]))
            if state_table:
                # date rows
                for row in state_table:
                    tr_row = tr(
                        th(
                            attr(cssc='date_cell',
                                 title=self.transform_title(
                                     _('Statuses'),
                                     self.get_states_title_for_row(row))),
                            row['row_date']))
                    for state_id in display_state_list:
                        state_on = row[state_id]
                        if state_on == True:
                            tr_row.add(
                                td(
                                    attr(cssc='state_on',
                                         title=self.transform_title(
                                             _('Status'),
                                             self.get_state_title(state_id))),
                                    'X'))
                        else:
                            tr_row.add(
                                td(
                                    attr(title=self.transform_title(
                                        _('Status'),
                                        self.get_state_title(state_id)))))
                    self.add(tr_row)
        else:
            self.tag = 'table'
            self.tattr_list = table.tattr_list
            self.cssc = 'section_table'
            if len(state_table):
                self.add(
                    tr(td(noesc(self.get_states_title_for_row(
                        state_table[0])))))
            else:
                self.add(tr(td(self.get_state_title(0))))
예제 #24
0
    def make_content(self):
        def _add_row(i, j, detail):
            history_tr = tr()
            history_tr.cssc = ''
            if i > 0:
                history_tr.cssc += ' history_row'
            if detail:
                history_tr.add(detail)
            else:
                history_tr.add(
                    td(attr(colspan=len(thead_row.content) - 3),
                       div(attr(cssc='field_empty'))))
            if j == 0:
                history_tr.cssc += ' history_division_row'
                rowspan_attr = attr(rowspan=len(self.inner_details[i]) or 1,
                                    cssc='history_dates_field')
                log_req_link = a(attr(
                    href=logger_url), img(src='/img/icons/open.png')
                                 ) if history_rec.requestId else ''
                history_tr.add(td(rowspan_attr, date_from),
                               td(rowspan_attr, date_to),
                               td(rowspan_attr, log_req_link))
            self.add(history_tr)

        self.content = []
        self.create_inner_details()

        if self.inner_details:
            # Header:
            thead_row = tr()
            #  Find one (any of them) innter detail for obtaining field labels (cannot take first one, becouse firt can be empty list):
            some_detail = None
            for details in self.inner_details:
                if details:
                    some_detail = details[0]
                    break

            for field in some_detail.fields.values():
                thead_row.add(th(field.label))
            thead_row.add(th(_('From')), th(_('To')), th(_('L.')))
            self.add(thead(thead_row))

            # rows (each row is made from one detail of object in object list
            self.add(tbody(tagid('tbody')))
            for i in range(len(self.inner_details)):
                history_rec = self.value[i]
                date_from = history_rec._from  #recoder.corba_to_datetime(history_rec._from)
                date_to = history_rec.to  #recoder.corba_to_datetime(history_rec.to)
                logger_url = f_urls[
                    'logger'] + 'detail/?id=%s' % history_rec.requestId

                if self.inner_details[i]:
                    for j, detail in enumerate(self.inner_details[i]):
                        _add_row(i, j, detail)
                else:
                    _add_row(i, 0, None)

        else:
            self.add(div(attr(cssc='field_empty')))
예제 #25
0
 def __init__(self, context = None):
     super(DigPage, self).__init__(context)
     c = self.context
     self.main.add(h2(_('dig_query')))
     if c.get('handle'):
         self.main.add(h3(_('Domain'), c.handle))
     if c.get('dig'):
         self.main.add(pre(c.dig))
예제 #26
0
파일: adifforms.py 프로젝트: saimir/FRED
class LoginForm(Form):
    corba_server = ChoiceField(choices=[(str(i), ior[0])
                                        for i, ior in enumerate(config.iors)],
                               label=_("Server"))
    login = CharField(max_length=30, label=_('Username'))
    password = PasswordField(max_length=30)
    next = HiddenField(initial='/')
    media_files = 'form_files.js'
예제 #27
0
class FilterFilterForm(FilterForm):
    default_fields_names = ['Type']

    UserID = CharField(label=_('User name'))
    GroupID = CharField(label=_('Group name'))
    Type = ChoiceField(label=_('Result'),
                       choices=[(1, u'Poraněn'), (2, u'Preživší'),
                                (3, u'Mrtev'), (4, u'Nemrtvý')])
예제 #28
0
파일: adiffields.py 프로젝트: LANJr4D/FRED
 def clean(self):
     if self.form:
         if self.form.is_valid():
             return self.form.cleaned_data
         else:
             raise ValidationError(_(u'Correct errors below.'))
     elif self.required and not self.value:
         raise ValidationError(_(u'This field is required.'))
예제 #29
0
class PropertyFilterForm(FilterForm):
    default_fields_names = ['Name']
    try:
        Name = ChoiceField(label=_('Name'), choices=get_property_list())
    except Exception:
        Name = CharField(label=_('Name'))
    Value = CharField(label=_('Value'))
    OutputFlag = BooleanField(label=_('Output Flag'))
예제 #30
0
파일: adiffields.py 프로젝트: saimir/FRED
 def clean(self):
     if self.form:
         if self.form.is_valid():
             return self.form.cleaned_data
         else:
             raise ValidationError(_(u'Correct errors below.'))
     elif self.required and not self.value:
         raise ValidationError(_(u'This field is required.'))
예제 #31
0
 def _check_for_malformed_perm(self, perm):
     perm_len = len(perm.split("."))
     if not 2 <= perm_len <= 4:
         raise MalformedAuthorizationError(
             _("Malformed authorization record in csv file: '%s'!" % perm))
     if perm_len == 3 and not perm.startswith('!'):
         raise MalformedAuthorizationError(
             _("Malformed authorization record in csv file: '%s'! Field negative permission must start with '!'"
               % perm))
예제 #32
0
파일: adiffields.py 프로젝트: LANJr4D/FRED
 def clean(self):
     self.create_formset_once()
     if self.formset:
         if self.formset.is_valid():
             return self.formset.cleaned_data
         else:
             raise ValidationError(_(u'Correct errors below.'))
     elif self.required and not self.value:
         raise ValidationError(_(u'This field is required.'))
예제 #33
0
    def _render_nsset(self, nsset_detail):
        registrar_detail = nsset_detail.fields[
            'registrar'].current_field.inner_detail  # registrar of nsset

        handle_field = nsset_detail.fields['handle_url']
        registrar_field = registrar_detail.fields['handle_url']
        admins_field = nsset_detail.fields['admins']
        hosts_field = nsset_detail.fields['hosts']

        handle_label = self.get_label_name(handle_field)
        registrar_label = self.get_label_name(_('Registrar'))
        admins_label = self.get_label_name(_('Tech. contacts'))
        hosts_label = self.get_label_name(_('DNSs'))

        self.add(
            tr(td(attr(cssc='left_label'), handle_label), td(handle_field)))
        self.add(
            tr(td(attr(cssc='left_label'), registrar_label),
               td(registrar_field)))

        for i, admin_detail in enumerate(
                admins_field.current_field.inner_details):
            row = tr()
            if i == 0:
                row.add(
                    td(
                        attr(cssc='left_label',
                             rowspan=len(
                                 admins_field.current_field.inner_details)),
                        admins_label))
            email_part = ''
            if admin_detail.fields['email'].value:
                email_part = [', ', admin_detail.fields['email']]
            row.add(
                td(attr(enclose_content=True),
                   admin_detail.fields['handle_url'], email_part))
            self.add(row)

        for i, host_detail in enumerate(
                hosts_field.current_field.inner_details):
            row = tr()
            if i == 0:
                row.add(
                    td(
                        attr(cssc='left_label',
                             rowspan=len(
                                 hosts_field.current_field.inner_details)),
                        hosts_label))

            cell = td(attr(enclose_content=True))
            cell.add(host_detail.fields['fqdn'])

            if host_detail.fields['inet'].value:
                cell.add(' (', host_detail.fields['inet'], ')')

            row.add(cell)
            self.add(row)
예제 #34
0
class NSSetFilterForm(ObjectFilterForm):
    TechContact = CompoundFilterField(label=_('Technical contact'),
                                      form_class=ContactFilterForm)
    HostIP = CharField(label=_('IP address'))
    HostFQDN = CharField(label=_('Nameserver name'))

    def clean(self):
        cleaned_data = super(NSSetFilterForm, self).clean()
        return cleaned_data
예제 #35
0
파일: adiffields.py 프로젝트: saimir/FRED
 def clean(self):
     self.create_formset_once()
     if self.formset:
         if self.formset.is_valid():
             return self.formset.cleaned_data
         else:
             raise ValidationError(_(u'Correct errors below.'))
     elif self.required and not self.value:
         raise ValidationError(_(u'This field is required.'))
예제 #36
0
class DomainBlockForm(DomainBlockBase):
    owner_block_mode = CorbaEnumChoiceField(
        label=_('Holder blocking'),
        corba_enum=Registry.Administrative.OwnerBlockMode,
        enum_translation_mapping={
            'KEEP_OWNER': _('Do not block the holder'),
            'BLOCK_OWNER': _('Block the holder'),
            'BLOCK_OWNER_COPY': _('Create copy of the holder'),
        })
예제 #37
0
class OpenIDLoginForm(Form):
    corba_server = ChoiceField(choices=[(str(i), ior[0])
                                        for i, ior in enumerate(config.iors)],
                               label=_("Server"))
    login = CharField(max_length=30, label=_('Username'))
    # Hide password (OpenID prompts for password at a different place).
    password = HiddenField(max_length=30)
    next = HiddenField(initial='/')
    media_files = 'form_files.js'
예제 #38
0
파일: dfields.py 프로젝트: LANJr4D/FRED
    def make_content(self):
        def _add_row(i, j, detail):
            history_tr = tr()
            history_tr.cssc = ''
            if i > 0:
                history_tr.cssc += ' history_row'
            if detail:
                history_tr.add(detail)
            else:
                history_tr.add(td(attr(colspan=len(thead_row.content) - 3), div(attr(cssc='field_empty'))))
            if j == 0:
                history_tr.cssc += ' history_division_row'
                rowspan_attr = attr(rowspan=len(self.inner_details[i]) or 1, cssc='history_dates_field')
                log_req_link = a(attr(href=logger_url), img(src='/img/icons/open.png')) if history_rec.requestId else ''
                history_tr.add(
                    td(rowspan_attr, date_from),
                    td(rowspan_attr, date_to),
                    td(rowspan_attr, log_req_link)
                )
            self.add(history_tr)


        self.content = []
        self.create_inner_details()

        if self.inner_details:
            # Header:
            thead_row = tr()
            #  Find one (any of them) innter detail for obtaining field labels (cannot take first one, becouse firt can be empty list):
            some_detail = None
            for details in self.inner_details:
                if details:
                    some_detail = details[0]
                    break

            for field in some_detail.fields.values():
                thead_row.add(th(field.label))
            thead_row.add(th(_('From')), th(_('To')), th(_('L.')))
            self.add(thead(thead_row))

            # rows (each row is made from one detail of object in object list
            self.add(tbody(tagid('tbody')))
            for i in range(len(self.inner_details)):
                history_rec = self.value[i]
                date_from = history_rec._from #recoder.corba_to_datetime(history_rec._from)
                date_to = history_rec.to #recoder.corba_to_datetime(history_rec.to)
                logger_url = f_urls['logger'] + 'detail/?id=%s' % history_rec.requestId

                if self.inner_details[i]:
                    for j, detail in enumerate(self.inner_details[i]):
                        _add_row(i, j, detail)
                else:
                    _add_row(i, 0, None)

        else:
            self.add(div(attr(cssc='field_empty')))
예제 #39
0
파일: ldap_auth.py 프로젝트: LANJr4D/FRED
def authenticate_user(admin, username=None, password=None):
    """ Authenticate user using LDAP server.
    """
    try:
        l = ldap.open(config.LDAP_server)
        l.simple_bind_s(config.LDAP_scope % username, password)
    except ldap.SERVER_DOWN:
        raise fred_webadmin.controller.adiferrors.AuthenticationError(_('LDAP server is unavailable!'))
    except ldap.INVALID_CREDENTIALS:
        raise fred_webadmin.controller.adiferrors.AuthenticationError(_('Invalid username and/or password!'))
예제 #40
0
class ObjectStateFilterForm(FilterForm):
    default_field_names = ['StateId']

    StateId = ChoiceField(label=_('State Type'),
                          choices=CorbaLazyRequestIterStruct(
                              'Admin', None, 'getObjectStatusDescList',
                              ['id', 'shortName'], None, config.lang[:2]))

    ValidFrom = DateTimeIntervalField(label=_('Valid from'))
    ValidTo = DateTimeIntervalField(label=_('Valid to'))
예제 #41
0
파일: adifdetails.py 프로젝트: saimir/FRED
class PublicRequestDetail(Detail):
    id = CharDField(label=_('ID'))
    objects = ListObjectHandleDField(label=_('Objects'))
    type = CorbaEnumDField(label=_('Type'))
    status = CorbaEnumDField(label=_('Status'))
    registrar = ObjectHandleDField(label=_('Registrar'))
    email = CharDField(label=_('Email'))
    answerEmail = ObjectHandleDField(label=_('Answer email'))
    createTime = CharDField(label=_('Create time'))
    resolveTime = CharDField(label=_('Close time'))
    
    def add_to_bottom(self):
        if self.data and \
            self.data.get('status') == Registry.PublicRequest.PRS_NEW:
                self.media_files.append('/js/publicrequests.js')
                self.add(FilterPanel([[
                    [_('Accept_and_send'), 
                        "javascript:processPublicRequest('%s')" % \
                        (f_urls['publicrequest'] + 'resolve/?id=%s' % \
                            self.data.get('id'))],
                    [_('Invalidate_and_close'), 
                        "javascript:closePublicRequest('%s')" % \
                            (f_urls['publicrequest'] + 'close/?id=%s' % \
                                self.data.get('id'))],
                ]]))
        super(PublicRequestDetail, self).add_to_bottom()
예제 #42
0
파일: fields.py 프로젝트: LANJr4D/FRED
 def compress(self, data_list):
     if data_list and data_list[0]:
         # Raise a validation error if time or date is empty
         # (possible if SplitDateTimeField has required=False).
         if data_list[0] in EMPTY_VALUES:
             raise ValidationError(_(u'Enter a valid date.'))
         if data_list[1] in EMPTY_VALUES:
             raise ValidationError(_(u'Enter a valid time.'))
         return datetime.datetime.combine(*data_list)
     #TODO(tom): Should we return a Null type here?
     return None
예제 #43
0
파일: pages.py 프로젝트: LANJr4D/FRED
 def __init__(self, context = None):
     super(SetInZoneStatusPage, self).__init__(context)
     c = self.context
     self.main.add(h2(_('Set InZone Status')))
     if c.get('handle'):
         self.main.add(h3(_('Domain'), c.handle))
     if c.get('success') and c.success:
         self.main.add(pre(attr(style='color:green;'), 
                           _("Function returns True.")))
     if c.get('error'):
         self.main.add(pre(attr(style='color:red;'), c.error))
예제 #44
0
파일: listtable.py 프로젝트: LANJr4D/FRED
    def _get_detail(self, obj_id):
        context = {}
        try:
            obj_id = int(obj_id)
        except (TypeError, ValueError):
            context['main'] = _("Required_integer_as_parameter")
            raise CustomView(self._render('base', ctx=context))

        try:
            return get_detail(self.classname, obj_id)
        except (ccReg.Admin.ObjectNotFound,):
            context['main'] = _("Object_not_found")
            raise CustomView(self._render('base', ctx=context))
예제 #45
0
파일: fields.py 프로젝트: LANJr4D/FRED
 def clean(self):
     "Validates max_length and min_length. Returns a Unicode object."
     if self.strip_spaces and isinstance(self.value, types.StringTypes):
         self.value = self.value.strip()
     super(CharField, self).clean()
     if self.is_empty():
         return u''
     value_length = len(self.value)
     if self.max_length is not None and value_length > self.max_length:
         raise ValidationError(_(u'Ensure this value has at most %(max)d characters (it has %(length)d).') % {'max': self.max_length, 'length': value_length})
     if self.min_length is not None and value_length < self.min_length:
         raise ValidationError(_(u'Ensure this value has at least %(min)d characters (it has %(length)d).') % {'min': self.min_length, 'length': value_length})
     return self.value
예제 #46
0
파일: adifdetails.py 프로젝트: LANJr4D/FRED
 def add_to_bottom(self):
     if self.data and \
         self.data.get('status') == Registry.PublicRequest.PRS_NEW:
             self.media_files.append('/js/publicrequests.js')
             self.add(FilterPanel([[
                 [_('Accept_and_send'), 
                     "javascript:processPublicRequest('%s')" % \
                     (f_urls['publicrequest'] + 'resolve/?id=%s' % \
                         self.data.get('id'))],
                 [_('Invalidate_and_close'), 
                     "javascript:closePublicRequest('%s')" % \
                         (f_urls['publicrequest'] + 'close/?id=%s' % \
                             self.data.get('id'))],
             ]]))
     super(PublicRequestDetail, self).add_to_bottom()
예제 #47
0
파일: adif.py 프로젝트: LANJr4D/FRED
 def detail(self, **kwd):
     log_req = self._create_log_req_for_object_view(**kwd)
     context = {}
     try:
         file_id = int(kwd['id'])
         response = cherrypy.response
         filemanager = cherrypy.session.get('FileManager')
         info = filemanager.info(recoder.u2c(file_id))
         try:
             f = filemanager.load(recoder.u2c(file_id))
             body = ''
             while 1:
                 part = f.download(102400) # 100kBytes
                 if part:
                     body = '%s%s' % (body, part)
                 else:
                     break
             response.body = body
             response.headers['Content-Type'] = info.mimetype
             cd = '%s; filename=%s' % ('attachment', info.name)
             response.headers["Content-Disposition"] = cd
             response.headers['Content-Length'] = info.size
             log_req.result = 'Success'
         except ccReg.FileManager.FileNotFound:
             log_req.result = 'Fail'
             context['main'] = _("Object_not_found")
             return self._render('file', ctx=context)
     finally:
         log_req.close()
     return response.body
예제 #48
0
파일: itertable.py 프로젝트: LANJr4D/FRED
    def __init__(self, request_object, session_key, pagesize=50, timeout=10000):
        super(IterTable, self).__init__()

        self.iterable = True
        self.request_object = request_object

        table, header_id = self._map_request(session_key)
        self._table = table
        self._table._set_pageSize(pagesize)
        self._table.setTimeout(timeout)

        columnHeaders = table.getColumnHeaders()
        self.rawheader = [x.name for x in columnHeaders]
        self.rawheader.insert(0, 'Id')

        self.header = [ _(x) for x in self.rawheader ]
        self.header_type = [x.type._n for x in columnHeaders]
        self.header_type.insert(0, header_id)

        self.page_index = None
        self.page_size = None
        self.page_start = None
        # Number of rows in table.
        self.num_rows = None
        self.num_rows_over_limit = None
        self.num_pages = None
        self.page_rows = None
        self.current_page = None
        self.first_page = None
        self.last_page = None
        self.prev_page = None
        self.next_page = None
        self._row_index = None

        self._update()
예제 #49
0
파일: adif.py 프로젝트: LANJr4D/FRED
    def _create_log_req_for_object_view(self, request_type=None, properties=None, references=None, **kwd):
        '''
            To avoid code duplication - this is common for all views (like detail) which 
            are taking id of an object.
            request_type - default is view detail
            It checks if ID is integer, returns errorpage if not otherwise creates new
            log request with references and object_id in properties.
            (note: object_id in properties will be obsolete when references will be everywhere)  
        '''

        context = {}
        try:
            object_id = int(kwd.get('id'))
        except (TypeError, ValueError):
            context['message'] = _("Required_integer_as_parameter")
            raise CustomView(self._render('error', ctx=context))

        if request_type is None:
            request_type = f_name_actiondetailname[self.classname]

        if properties is None:
            properties = []
        if references is None:
            references = []

        properties.append(('object_id', object_id))
        object_type = f_name_req_object_type.get(self.classname)
        if object_type:
            references.append((object_type, object_id))

        log_req = utils.create_log_request(request_type, properties=properties, references=references)
        return log_req
예제 #50
0
파일: formlayouts.py 프로젝트: LANJr4D/FRED
    def create_layout(self):
        form = self.form
        self.add(tbody(tagid('tbody')))
        
        if form.non_field_errors():
            self.tbody.add(tr(td(attr(colspan=self.columns_count), _('Errors:'), form.non_field_errors())))
        hidden_fields = []
        for field in form.fields.values():
            if field.is_hidden:
                hidden_fields.append(field)
                continue
            
            label_str = self.get_label_name(field)
            
            if field.required:
                cell_tag = th
            else:
                cell_tag = td
            
            errors = form.errors.get(field.name_orig, None)
                
            self.tbody.add(tr(
                cell_tag(label(label_str)),
                td(errors, field)))
        self.add(hidden_fields)

        if not form.is_nested:
            self.tbody.add(self.get_submit_row())
예제 #51
0
파일: fields.py 프로젝트: LANJr4D/FRED
 def clean(self):
     """Validates that float() can be called on the input. Returns a float.
         Returns None for empty values.
     """
     super(FloatField, self).clean()
     if self.is_empty():
         return fredtypes.NullFloat()
     try:
         value = float(self.value)
     except (ValueError, TypeError):
         raise ValidationError(_(u'Enter a number.'))
     if self.max_value is not None and value > self.max_value:
         raise ValidationError(_(u'Ensure this value is less than or equal to %s.') % self.max_value)
     if self.min_value is not None and value < self.min_value:
         raise ValidationError(_(u'Ensure this value is greater than or equal to %s.') % self.min_value)
     return value
예제 #52
0
파일: adifwidgets.py 프로젝트: LANJr4D/FRED
 def __init__(self, filters, filter_name=None, *content, **kwd):
     ''' Filters is list of triplets [id, type, name] 
         If filter_name is specified, general filter for that object is added (e.g. /domains/filter/)
     '''
     super(FilterList, self).__init__(*content, **kwd)
     self.tag = 'ul'
     debug('LIST OF FILTERS: %s' % filters)
     for filter in filters:
         url_filter = f_urls[f_id_name[int(filter['Type'])]] + 'filter/?filter_id=' + filter['Id']
         url_filter_with_form =  url_filter + '&show_form=1'
         self.add(li(
                     a(attr(href=url_filter), filter['Name']),
                     ' (', a(attr(href=url_filter_with_form), _('form')),  ')',
                    ))
     if filter_name:
         self.add(li(a(attr(href=f_urls[filter_name] + 'filter/'), _('Custom filter'))))
예제 #53
0
파일: perms.py 프로젝트: LANJr4D/FRED
        def _wrapper(*args, **kwd):
            self = args[0]
            user = cherrypy.session.get('user', None)
            if user:
                utils.details_cache = {} # invalidate details cache
                nperms = []
                if isinstance(objects_nperms, types.StringTypes):
                    onperms = [objects_nperms]
                else:
                    onperms = objects_nperms
                for objects_nperm in onperms:
                    nperms.append('%s.%s' % (objects_nperm, self.classname))
                if user.check_nperms(nperms, check_type):
                    context = {'message': div()}
                    context['message'].add(
                        p(_("You don't have permissions for this page!")))
                    if fred.config.debug:
                        context['message'].add(
                            p(
                                'usernperm = %s,' % user.nperms, br(),
                                'nperms=%s,' % nperms, br(),
                                'nperm_type=%s' % check_type, br()))
                        context['message'].add(p(
                            "a tohle to je udelano nejsofistikovanejsim "
                            "decoratorem"))
                    return self._render('error', context)
                return view_func(*args, **kwd)

            redir_addr = '/login/?next=%s' % get_current_url(cherrypy.request)
            raise cherrypy.HTTPRedirect(redir_addr)
예제 #54
0
파일: adifwidgets.py 프로젝트: LANJr4D/FRED
    def __init__(self, filters, max_row_size=5, *content, **kwd):
        ''' filters is list of tripplet [button_label, object_name, filters] where filters in linear form. written
            (e.g. [{'domain.registrar.handle'='ahoj', 'handle'=[True, 'ahoj']}] (True is for negation))
            (so if there is negation, then value is list [value, negation], otherwise it is just value)
            Alternatively, instead of filter (which is a triplet), can be used direct link (couple):
            [button_label, url]
        '''
        super(FilterPanel, self).__init__(*content, **kwd)
        self.tag = 'div'

#        chunks = grouper(max_row_size, filters)
        first = True
#        import ipdb; ipdb.set_trace()
        filter_count = max([len(l) for l in filters])

        for chunk in filters:
            filter_count = len(chunk)
            tbl = table()
            tbl.add(attr(cssc='filter_panel'),
                 tr(th(
                    attr(colspan=filter_count), 
                    b(_('Options')) if first else b())),
                 tr(save(self, 'filter_buttons')))
            self._create_links(chunk)
            self.add(tbl)
            first = False

        """for button_data in filters:
예제 #55
0
파일: corba_auth.py 프로젝트: LANJr4D/FRED
def authenticate_user(admin, username=None, password=None):
    """ Authenticate user using CORBA backend.
    """
    try:
        admin.authenticateUser(recoder.u2c(username), recoder.u2c(password)) 
    except ccReg.Admin.AuthFailed:
        raise fred_webadmin.controller.adiferrors.AuthenticationError(
            _('Invalid username and/or password!'))
예제 #56
0
파일: nicauth.py 프로젝트: LANJr4D/FRED
 def __init__(self, username):
     try:
         self._auth_user = auth_user.User.objects.get(username=username)
         self.perms = self._auth_user.get_all_permissions()
     except auth_user.User.DoesNotExist:
         raise AuthorizationError(
                 _("Authorization record does not exist for user ") + \
                     str(username))
예제 #57
0
파일: pages.py 프로젝트: LANJr4D/FRED
 def __init__(self, context = None):
     super(MessageDetail, self).__init__(context)
     c = self.context
     if c.get('result'):
         self.main.add(h1(_('Detail_of_%s' % self.get_object_name())))
         self.main.add(adifdetails.MessageDetail(c.result, c.history))
         if config.debug:
             self.main.add('MessageDETAIL:', pre(unicode(c.result).replace(u', ', u',\n')))
예제 #58
0
파일: fields.py 프로젝트: LANJr4D/FRED
 def clean(self):
     """
     Validates that the input is a list or tuple.
     """
     value = self.value
     if self.required and not value:
         raise ValidationError(_(u'This field is required.'))
     elif not self.required and not value:
         return []
     if not isinstance(value, (list, tuple)):
         value = list(value)
     # Validate that each value in the value list is in self.choices.
     valid_values = set([unicode(k) for k, v in self.choices])
     for val in value:
         if val not in valid_values:
             raise ValidationError(_(u'Select a valid choice. %s is not one of the available choices.') % val)
     return value
예제 #59
0
파일: pages.py 프로젝트: LANJr4D/FRED
 def __init__(self, context = None):
     super(BankStatementDetailWithPaymentPairing, self).__init__(context)
     c = self.context
     if c.get('detail'):
         self.main.add(h1(_('Detail of payment')))
         self.main.add(adifdetails.BankStatementDetail(c.detail, c.history))
     if c.get('form'):
         self.main.add(c.form)