def _set_one_compound_filter(cls, compound, filter_data): debug('filter_data in set_one_compound_filter: %s' % filter_data) for key, [neg, val] in filter_data.items(): func = getattr(compound, "add%s" % key) sub_filter = func() # add # Follows ugly code full of 'isinstance' calls. However, it seems # to be necessary because we're using Corba. if isinstance(sub_filter, ccReg.Filters._objref_Compound): # Compound: cls._set_one_compound_filter(sub_filter, val) else: sub_filter._set_neg(recoder.u2c(neg)) # Only set active filters (those that have a value). if not isinstance(val, fred_webadmin.webwidgets.forms.emptyvalue.FilterFormEmptyValue): if isinstance(sub_filter, ccReg.Filters._objref_Date): value = recoder.date_time_interval_to_corba( val, recoder.date_to_corba) elif isinstance(sub_filter, ccReg.Filters._objref_DateTime): value = recoder.date_time_interval_to_corba( val, recoder.datetime_to_corba) elif isinstance( sub_filter, (ccReg.Filters._objref_Int, ccReg.Filters._objref_Id)): value = int(val) else: value = val sub_filter._set_value(recoder.u2c(value))
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
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!'))
def __init__(self, object_name, mgr_getter_name, function_name, selector=None, *args, **kwargs): self.object_name = object_name self.function_name = function_name self.mgr_getter_name = mgr_getter_name self.c_args = recoder.u2c(args) or [] self.c_kwargs = recoder.u2c(kwargs) or {} self.selector_func = selector self.data = None
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()
def _authorize(self, form, admin): login = form.cleaned_data.get('login', '') corbaSessionString = admin.createSession(recoder.u2c(login)) try: session = admin.getSession(corbaSessionString) # User gets authorized for login when User object is created. user = User(session.getUser()) except AuthorizationError, e: admin.destroySession(corbaSessionString) cherrypy.response.status = 403 raise
def fire_actions(self, reg_id, *args, **kwargs): if not self.cleaned_data or not self.changed_data: return file_mgr = cherrypy.session['FileManager'] file_obj = self.cleaned_data['evaluation_file'] if "evaluation_file" in self.changed_data: # User wants to upload a new file. file_upload_obj = file_mgr.save(file_obj.filename, file_obj.content.type, 6) chunk = file_obj.content.file.read(2**14) while chunk: file_upload_obj.upload(chunk) chunk = file_obj.content.file.read(2**14) file_id = file_upload_obj.finalize_upload() else: file_id = self.cleaned_data['evaluation_file_id'] if not file_id: # This can happen when user changes something in the edit form, # but specifies no file to upload. # TODO(tom): This is wrong. Specifying file upload should be # mandatory. However making it mandatory breaks FormSetField # validation... raise UpdateFailedError( "You have not specified the upload file " "for a certification!") certs_mgr = cherrypy.session['Admin'].getCertificationManager() if not self.cleaned_data['id']: # Create a new certification. try: certs_mgr.createCertification( reg_id,recoder.u2c(self.cleaned_data['fromDate']), recoder.u2c(self.cleaned_data['toDate']), self.cleaned_data['score'], file_id) except Registry.Registrar.InvalidValue, e: error(e) raise UpdateFailedError( _("Failed to create a certification. Perhaps you have " "tried to create overlapping certifications?"))
def _pair_payment_with_registrar(self, payment_id, payment_type, registrar_handle): """ Links the payment with registrar. """ props = [("registrar_handle", registrar_handle)] log_req = self._create_log_req_for_object_view('PaymentPair', properties=props, **{'id': str(payment_id)}) try: invoicing = utils.get_corba_session().getBankingInvoicing() success = True if payment_type == editforms.PAYMENT_REGISTRAR: success = invoicing.pairPaymentRegistrarHandle(payment_id, recoder.u2c(registrar_handle)) success = success and invoicing.setPaymentType(payment_id, payment_type) if success: log_req.result = 'Success' else: log_req.result = 'Fail' finally: log_req.close() return success
def get_detail(obj_type_name, obj_id, use_cache=True): """ If use_cache == False, we always get the object from server. """ if use_cache: result_from_cache = details_cache.get((obj_type_name, obj_id)) if result_from_cache is not None: debug('Cache hit (%s, %s)' % (obj_type_name, obj_id)) return result_from_cache debug('Getting detail %s id %s' % (obj_type_name, obj_id)) corba_session = get_corba_session() c_any = corba_session.getDetail( f_name_enum[obj_type_name], recoder.u2c(obj_id)) corba_obj = from_any(c_any, True) result = recoder.c2u(corba_obj) details_cache[(obj_type_name, obj_id)] = result return result
def _pair_payment_with_registrar(self, payment_id, payment_type, registrar_handle): """ Links the payment with registrar. """ props = [("registrar_handle", registrar_handle)] log_req = self._create_log_req_for_object_view( 'PaymentPair', properties=props, **{'id': str(payment_id)}) try: invoicing = utils.get_corba_session().getBankingInvoicing() success = True if payment_type == editforms.PAYMENT_REGISTRAR: success = invoicing.pairPaymentRegistrarHandle( payment_id, recoder.u2c(registrar_handle)) success = success and invoicing.setPaymentType( payment_id, payment_type) if success: log_req.result = 'Success' else: log_req.result = 'Fail' finally: log_req.close() return success
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()
def _process_valid_form(self, form, reg, reg_id, context, log_request_name): props = self._construct_changed_fields(form) in_refs = [] if reg_id: in_refs = [('registrar', int(reg_id))] log_req = utils.create_log_request(log_request_name, properties=props, references=in_refs) out_refs = [] try: registrar = self._fill_registrar_struct_from_form(reg, form.cleaned_data) corba_reg = recoder.u2c(registrar) result = {'reg_id': None} form.fire_actions(updated_registrar=corba_reg, result=result) if result['reg_id'] != reg_id: # new registrar created, add him to out_refs out_refs.append(('registrar', result['reg_id'])) reg_id = result['reg_id'] log_req.result = 'Success' except editforms.UpdateFailedError, e: form.non_field_errors().append(str(e)) context['form'] = form log_req.result = 'Fail' return context
try: certs_mgr.createCertification( reg_id, recoder.u2c(self.cleaned_data['fromDate']), recoder.u2c(self.cleaned_data['toDate']), self.cleaned_data['score'], file_id) except Registry.Registrar.InvalidValue, e: error(e) raise UpdateFailedError( _("Failed to create a certification. Perhaps you have " "tried to create overlapping certifications?")) else: # Update an existing certifications. try: certs_mgr.updateCertification( self.cleaned_data['id'], recoder.u2c(self.cleaned_data['score']), file_id) except Registry.Registrar.InvalidValue: raise UpdateFailedError("Unable to update certification.") if "toDate" in self.changed_data: cert_id = int(self.fields['id'].value) try: certs_mgr.shortenCertification( cert_id, recoder.u2c(self.cleaned_data['toDate'])) except Registry.Registrar.InvalidValue: raise UpdateFailedError("Unable to shorten certification.") class RegistrarEditForm(EditForm): def __init__(self, *args, **kwargs): super(RegistrarEditForm, self).__init__(layout_class=RegistrarEditFormLayout,
def save_filter(self, name): self._table.saveFilter(recoder.u2c(name))
try: certs_mgr.createCertification( reg_id,recoder.u2c(self.cleaned_data['fromDate']), recoder.u2c(self.cleaned_data['toDate']), self.cleaned_data['score'], file_id) except Registry.Registrar.InvalidValue, e: error(e) raise UpdateFailedError( _("Failed to create a certification. Perhaps you have " "tried to create overlapping certifications?")) else: # Update an existing certifications. try: certs_mgr.updateCertification( self.cleaned_data['id'], recoder.u2c(self.cleaned_data['score']), file_id) except Registry.Registrar.InvalidValue: raise UpdateFailedError( "Unable to update certification.") if "toDate" in self.changed_data: cert_id = int(self.fields['id'].value) try: certs_mgr.shortenCertification( cert_id, recoder.u2c(self.cleaned_data['toDate'])) except Registry.Registrar.InvalidValue: raise UpdateFailedError( "Unable to shorten certification.") class RegistrarEditForm(EditForm): def __init__(self, *args, **kwargs):
def convert_corba_arguments(self, arguments): return [recoder.u2c(argument) for argument in arguments]
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)