def test_role_set_operations(): protected = whitelist("email", "password") all_fields = whitelist("id", "name") + protected def count(n): while True: yield n n += 1 class User(Model): id = IntType(default=count(42).next) name = StringType() email = StringType() password = StringType() class Options: roles = { "create": all_fields - ["id"], "public": all_fields - ["password"], "nospam": blacklist("password") + blacklist("email"), } data = {"id": "NaN", "name": "Arthur", "email": "*****@*****.**", "password": "******"} user = User( dict((k, v) for k, v in data.iteritems() if k in User._options.roles["create"]) # filter by 'create' role ) d = user.serialize(role="public") assert d == {"id": 42, "name": "Arthur", "email": "*****@*****.**"} d = user.serialize(role="nospam") assert d == {"id": 42, "name": "Arthur"} def test_md5_type(self): class M(Model): md5 = MD5Type() import hashlib myhash = hashlib.md5("hashthis").hexdigest() m = M() m.md5 = myhash self.assertEqual(m.md5, myhash) d = m.serialize() self.assertEqual(d, {"md5": myhash}) m2 = M(d) self.assertEqual(m2.md5, myhash)
class Options: _base_roles = BaseComplaint.Options.roles roles = { "create": _base_roles["create"], # TODO inherit the rest of the roles "draft": whitelist("author", "title", "description", "status"), "cancellation": whitelist("cancellationReason", "status"), "satisfy": whitelist("satisfied", "status"), "escalate": whitelist("status"), "resolve": whitelist("status", "tendererAction"), "answer": whitelist("resolution", "resolutionType", "status", "tendererAction"), "action": whitelist("tendererAction"), "review": whitelist("decision", "status", "rejectReason", "rejectReasonDescription", "reviewDate", "reviewPlace"), "embedded": (blacklist("owner_token", "owner", "transfer_token", "bid_id") + schematics_embedded_role), "view": (blacklist("owner_token", "owner", "transfer_token", "bid_id") + schematics_default_role), }
class Options: _edit_role = whitelist( "procuringEntity", "tender", "budget", "classification", "additionalClassifications", "documents", "items", "buyers", "status", "cancellation", "procurementMethodType", ) _create_role = _edit_role + whitelist("mode") _common_view = _create_role + whitelist( "doc_id", "tender_id", "planID", "datePublished", "owner", "milestones", "switch_status", ) roles = { "plain": _common_view + whitelist("owner_token", "transfer_token"), "revision": whitelist("revisions"), "create": _create_role, "edit": _edit_role, "view": _common_view + whitelist("dateModified"), "listing": whitelist("dateModified", "doc_id"), "Administrator": whitelist("status", "mode", "procuringEntity"), "default": schematics_default_role, }
def test_role_set_operations(self): protected = whitelist('email', 'password') all_fields = whitelist('id', 'name') + protected def count(n): while True: yield n n += 1 class User(Model): id = IntType(default=count(42).next) name = StringType() email = StringType() password = StringType() class Options: roles = { 'create': all_fields - ['id'], 'public': all_fields - ['password'], 'nospam': blacklist('password') + blacklist('email'), } data = { 'id': 'NaN', 'name': 'Arthur', 'email': '*****@*****.**', 'password': '******', } user = User({ k: v for k, v in data.iteritems() if k in User._options.roles['create'] # filter by 'create' role }) d = user.serialize(role='public') self.assertEqual(d, { 'id': 42, 'name': 'Arthur', 'email': '*****@*****.**', }) d = user.serialize(role='nospam') self.assertEqual(d, { 'id': 42, 'name': 'Arthur', })
class Options: roles = { 'create': whitelist('title', 'description', 'documents', 'relatedParty', 'relatedPost'), 'edit': whitelist(), 'view': schematics_default_role, 'default': schematics_default_role, 'embedded': schematics_embedded_role, }
class Options: roles = { 'plain': plain_role, 'create': create_role_eu, 'edit': edit_role_eu, 'edit_active.tendering': edit_role_eu, 'edit_active.pre-qualification': whitelist('status'), 'edit_active.pre-qualification.stand-still': whitelist(), 'edit_active.auction': whitelist(), 'edit_active.qualification': whitelist(), 'edit_active.awarded': whitelist(), 'edit_complete': whitelist(), 'edit_unsuccessful': whitelist(), 'edit_cancelled': whitelist(), 'view': view_role, 'listing': listing_role, 'auction_view': auction_view_role, 'auction_post': auction_post_role, 'auction_patch': auction_patch_role, 'active.tendering': qualifications_role, 'active.pre-qualification': pre_qualifications_role, 'active.pre-qualification.stand-still': pre_qualifications_role, 'active.auction': pre_qualifications_role, 'active.qualification': view_role, 'active.awarded': view_role, 'complete': view_role, 'unsuccessful': view_role, 'cancelled': view_role, 'chronograph': chronograph_role, 'chronograph_view': chronograph_view_role, 'Administrator': Administrator_role, 'default': schematics_default_role, }
class Options: _common = whitelist('eligible', 'qualified', 'title', 'title_en', 'title_ru', 'description', 'description_en', 'description_ru') _all = _common + whitelist('status', 'lotID', 'id', 'date', 'bidID', 'complaints', 'documents', 'milestones') roles = { "edit": _common + whitelist('status', ), "default": _all, "create": _common + whitelist( 'lotID', 'bidID'), # csv also had: 'complaints', '__parent__' "embedded": _all, "view": _all }
class Options: roles = { 'plain': plain_role, 'create': create_role, 'edit': edit_role, 'edit_draft': draft_role, 'edit_active.enquiries': edit_role, 'edit_active.tendering': whitelist(), 'edit_active.auction': whitelist(), 'edit_active.qualification': whitelist(), 'edit_active.awarded': whitelist(), 'edit_complete': whitelist(), 'edit_unsuccessful': whitelist(), 'edit_cancelled': whitelist(), 'view': view_role, 'listing': listing_role, 'auction_view': auction_view_role, 'auction_post': auction_post_role, 'auction_patch': auction_patch_role, 'draft': enquiries_role, 'active.enquiries': enquiries_role, 'active.tendering': enquiries_role, 'active.auction': auction_role, 'active.qualification': view_role, 'active.awarded': view_role, 'complete': view_role, 'unsuccessful': view_role, 'cancelled': view_role, 'chronograph': chronograph_role, 'chronograph_view': chronograph_view_role, 'Administrator': Administrator_role, 'default': schematics_default_role, 'contracting': whitelist('doc_id', 'owner'), }
class Options: namespace = "Tender" _parent_roles = BaseTender.Options.roles _all_forbidden = whitelist() _edit_fields = whitelist( "procuringEntity", "items", "value", "cause", "causeDescription", "causeDescription_en", "causeDescription_ru", ) _edit_role = _parent_roles["edit"] + _edit_fields _read_only_fields = whitelist( "lots", "contracts", # fields below are not covered by the tests "awards", "cancellations", ) _view_role = _parent_roles["view"] + _edit_fields + _read_only_fields roles = { "create": _parent_roles["create"] + _edit_fields + whitelist("lots"), "edit_draft": _edit_role + whitelist("status"), "edit": _edit_role, "edit_active": _edit_role, "edit_active.awarded": _all_forbidden, "edit_complete": _all_forbidden, "edit_unsuccessful": _all_forbidden, "edit_cancelled": _all_forbidden, "view": _view_role, "draft": _view_role, "active": _view_role, "active.awarded": _view_role, "complete": _view_role, "unsuccessful": _view_role, "cancelled": _view_role, "Administrator": _parent_roles["Administrator"], "chronograph": _parent_roles["chronograph"], "chronograph_view": _parent_roles["chronograph_view"], "plain": _parent_roles["plain"], "listing": _parent_roles["listing"], "contracting": _parent_roles["contracting"], "default": _parent_roles["default"], }
class Options(object): roles = { 'create': whitelist('value', 'relatedLot', 'subcontractingDetails'), 'edit': whitelist('value', 'relatedLot', 'subcontractingDetails'), 'auction_view': whitelist( 'value', 'date', 'relatedLot', 'participationUrl', 'status', ), }
class Options: serialize_when_none = False roles = { 'embedded': schematics_embedded_role, 'view': schematics_default_role, 'auction_view': whitelist('value', 'id', 'date'), 'active.enquiries': whitelist(), 'active.tendering': whitelist(), 'active.auction': whitelist('value'), 'active.qualification': schematics_default_role, 'active.awarded': schematics_default_role, 'complete': schematics_default_role, 'unsuccessful': schematics_default_role, 'paused': whitelist(), }
class Options: roles = { 'create': whitelist('author', 'title', 'description', 'questionOf', 'relatedItem'), 'edit': whitelist('answer'), 'embedded': schematics_embedded_role, 'view': schematics_default_role, 'active.enquiries': (blacklist('author') + schematics_embedded_role), 'active.tendering': (blacklist('author') + schematics_embedded_role), 'active.auction': (blacklist('author') + schematics_embedded_role), 'active.qualification': schematics_default_role, 'active.awarded': schematics_default_role, 'complete': schematics_default_role, 'unsuccessful': schematics_default_role, 'cancelled': schematics_default_role, }
class Options: roles = { # 'edit': blacklist('id', 'date'), "create": whitelist("rationale", "rationale_ru", "rationale_en", "rationaleTypes", "contractNumber", "dateSigned"), "edit": whitelist("rationale", "rationale_ru", "rationale_en", "rationaleTypes", "contractNumber", "status", "dateSigned"), "view": schematics_default_role, "embedded": schematics_embedded_role, }
class Options: roles = { 'create': blacklist('id', 'status', 'date', 'documents', 'complaints', 'complaintPeriod'), 'edit': whitelist('status', 'title', 'title_en', 'title_ru', 'description', 'description_en', 'description_ru'), 'embedded': schematics_embedded_role, 'view': schematics_default_role, 'Administrator': whitelist('complaintPeriod'), }
class Options: roles = { 'create': whitelist('value', 'relatedLot'), 'edit': whitelist('value', 'relatedLot'), 'auction_view': whitelist( 'value', 'date', 'relatedLot', 'participationUrl', 'status', ), }
class Options: roles = { # 'edit': blacklist('id', 'date'), 'create': whitelist('rationale', 'rationale_ru', 'rationale_en', 'rationaleTypes', 'contractNumber', 'dateSigned'), 'edit': whitelist('rationale', 'rationale_ru', 'rationale_en', 'rationaleTypes', 'contractNumber', 'status', 'dateSigned'), 'view': schematics_default_role, 'embedded': schematics_embedded_role, }
class Options: namespace = "post" roles = { "create": whitelist("title", "description", "documents", "relatedParty", "relatedPost", "recipient"), "edit": whitelist(), "view": schematics_default_role, "default": schematics_default_role, "embedded": schematics_embedded_role, }
def model_fields(model, only=None, exclude=None, hidden=None, field_args=None, converter=None): """ Generate a dictionary of fields for a given Django model. See `model_form` docstring for description of parameters. """ from schematics.models import Model if not isinstance(model, Model): raise TypeError('model must be a schematics.Model schema') converter = converter or ModelConverter() field_args = field_args or {} gottago = wholelist() field_dict = { } if only: gottago = whitelist(*only) elif exclude: gottago = blacklist(*exclude) for field_name, field in model._fields.items(): if gottago(field_name, None): continue ishidden = False if hidden: if field_name in hidden: ishidden=True form_field = converter.convert(model, field, field_name, field_args.get(field_name), hidden=ishidden) if form_field is not None: field_dict[field_name] = form_field from pprint import pprint #pprint(field_dict) return field_dict
def __init__(self, path, relative_to=__file__): super(RolesFromCsv, self).__init__(()) self.base_dir = os.path.dirname(os.path.abspath(relative_to)) with open(os.path.join(self.base_dir, path)) as csvfile: reader = csv.DictReader(csvfile) for row in reader: self[row["rolename"]] = whitelist(*[k for k in row if k != "rolename" and row[k]])
class Options: serialize_when_none = False roles = { 'embedded': schematics_embedded_role, 'view': (blacklist('revisions') + schematics_default_role), 'revisions': whitelist('uri', 'dateModified'), }
class Options: roles = { 'edit': whitelist('status', 'qualified', 'eligible', 'title', 'title_en', 'title_ru', 'description', 'description_en', 'description_ru'), }
class Options: roles = { "embedded": schematics_embedded_role, "view": schematics_default_role, "edit_draft": schematics_default_role, "edit_active": whitelist("contactPoint"), }
class Options: roles = { "create": award_create_reporting_role, "edit": award_edit_reporting_role, "embedded": schematics_embedded_role, "view": schematics_default_role, "Administrator": whitelist("complaintPeriod"), }
class Options: roles = { "embedded": schematics_embedded_role, "view": schematics_default_role, "create": whitelist("value", "relatedLot", "subcontractingDetails"), "edit": whitelist("value", "relatedLot", "subcontractingDetails"), "auction_view": whitelist("value", "date", "relatedLot", "participationUrl"), "auction_post": whitelist("value", "date", "relatedLot"), "auction_patch": whitelist("participationUrl", "relatedLot"), }
class Options: roles = { 'embedded': schematics_embedded_role, 'view': schematics_default_role, 'create': whitelist('value', 'relatedLot'), 'edit': whitelist('value', 'relatedLot'), 'auction_view': whitelist('value', 'date', 'relatedLot', 'participationUrl'), 'auction_post': whitelist('value', 'date', 'relatedLot'), 'auction_patch': whitelist('participationUrl', 'relatedLot'), }
class Options: roles = { 'edit': whitelist(), 'edit_contract': blacklist('id', 'documents', 'date', 'awardID', 'suppliers', 'contractID'), }
class Options: roles = { 'create': award_create_reporting_role, 'edit': award_edit_reporting_role, 'embedded': schematics_embedded_role, 'view': schematics_default_role, 'Administrator': whitelist('complaintPeriod'), }
class Options: roles = { "edit": whitelist(), "edit_contract": blacklist("id", "documents", "date", "awardID", "suppliers", "contractID"), }
class Options: roles = { 'edit': blacklist('id', 'url', 'datePublished', 'dateModified', 'author', 'md5', 'download_url'), 'embedded': schematics_embedded_role, 'view': (blacklist('revisions') + schematics_default_role), 'restricted_view': (blacklist('revisions', 'url', 'download_url') + schematics_default_role), 'revisions': whitelist('url', 'dateModified'), }
class Options: roles = { 'create': blacklist('id', 'status', 'documents', 'date'), 'edit': whitelist('status', 'qualified', 'eligible', 'title', 'title_en', 'title_ru', 'description', 'description_en', 'description_ru'), 'embedded': schematics_embedded_role, 'view': schematics_default_role, }
class Options: roles = { 'create': all_fields - ['id'], 'public': all_fields - ['password'], 'nospam': blacklist('password') + blacklist('email'), 'empty': whitelist(), 'everything': blacklist(), }
class Options: _edit_role = whitelist("reason", "reason_en", "status") roles = { "create": _edit_role, "edit": _edit_role, "embedded": schematics_embedded_role, "view": schematics_default_role, }
def test_callable_role(): acl_fields = { 'user_id_1': ['name'], 'user_id_2': ['name', 'password'], } class User(Model): name = StringType() password = StringType() u = User({'name': 'A', 'password': '******'}) user_1_acl = whitelist(*acl_fields['user_id_1']) d = u.serialize(role=user_1_acl) assert d == {'name': 'A'} user_2_acl = whitelist(*acl_fields['user_id_2']) d = u.serialize(role=user_2_acl) assert d == {'name': 'A', 'password': '******'}
def test_subclassing_overides_roles(self): class Parent(Model): id = StringType() gender = StringType() name = StringType() class Options: roles = { 'public': blacklist("id", "gender"), 'gender': blacklist("gender") } class GrandParent(Parent): age = IntType() family_secret = StringType() class Options: roles = { 'grandchildren': whitelist("age"), 'public': blacklist("id", "family_secret") } gramps = GrandParent({ "id": "1", "name": "Edward", "gender": "Male", "age": 87, "family_secret": "Secretly Canadian" }) options = gramps._options self.assertEqual(options.roles, { "grandchildren": whitelist("age"), "public": blacklist("id", "family_secret"), "gender": blacklist("gender") })
name = StringType(required=True) name_en = StringType() name_ru = StringType() identifier = ModelType(Identifier, required=True) class PlanTender(Model): procurementMethod = StringType(choices=['open'], default='open', required=True) tenderPeriod = ModelType(Period, required=True) plain_role = (blacklist('revisions', 'dateModified') + schematics_embedded_role) create_role = (blacklist('owner_token', 'owner', 'revisions') + schematics_embedded_role) edit_role = (blacklist('owner_token', 'owner', 'revisions', 'dateModified', 'doc_id', 'planID') + schematics_embedded_role) cancel_role = whitelist('status') view_role = (blacklist('owner', 'owner_token', '_attachments', 'revisions') + schematics_embedded_role) listing_role = whitelist('dateModified', 'doc_id') Administrator_role = whitelist('status', 'mode', 'procuringEntity') class Plan(SchematicsDocument, Model): """Plan""" class Options: roles = { 'plain': plain_role, 'create': create_role, 'edit': edit_role, 'view': view_role, 'listing': listing_role,
) from openprocurement.tender.openua.utils import ( calculate_business_date, BLOCK_COMPLAINT_STATUS, ) from openprocurement.tender.openua.models import ( Complaint as BaseComplaint, Award as BaseAward, Item as BaseItem, PeriodStartEndRequired, SifterListType, COMPLAINT_SUBMIT_TIME, EnquiryPeriod, ENQUIRY_STAND_STILL_TIME, ) eu_role = blacklist('enquiryPeriod', 'qualifications') edit_role_eu = edit_role + eu_role create_role_eu = create_role + eu_role tendering_role = enquiries_role pre_qualifications_role = (blacklist('owner_token', '_attachments', 'revisions') + schematics_embedded_role) qualifications_role = enquiries_role + whitelist('bids') eu_auction_role = auction_role TENDERING_DAYS = 30 TENDERING_DURATION = timedelta(days=TENDERING_DAYS) TENDERING_AUCTION = timedelta(days=35) QUESTIONS_STAND_STILL = timedelta(days=10) PREQUALIFICATION_COMPLAINT_STAND_STILL = timedelta(days=5) COMPLAINT_STAND_STILL = timedelta(days=10) def bids_validation_wrapper(validation_func): def validator(klass, data, value): if data['status'] in ('deleted', 'invalid'): # skip not valid bids
def test_role_set_operations(): protected = whitelist('email', 'password') all_fields = whitelist('id', 'name') + protected def count(n): while True: yield n n += 1 class User(Model): id = IntType(default=six.next(count(42))) name = StringType() email = StringType() password = StringType() class Options: roles = { 'create': all_fields - ['id'], 'public': all_fields - ['password'], 'nospam': blacklist('password') + blacklist('email'), 'empty': whitelist(), 'everything': blacklist(), } roles = User.Options.roles assert len(roles['create']) == 3 assert len(roles['public']) == 3 assert len(roles['nospam']) == 2 assert len(roles['empty']) == 0 assert len(roles['everything']) == 0 # Sets sort different with different Python versions. We should be getting something back # like: "whitelist('password', 'email', 'name')" s = str(roles['create']) assert s.startswith('whitelist(') and s.endswith(')') assert sorted(s[10:-1].split(', ')) == ["'email'", "'name'", "'password'"] # Similar, but now looking for: <Role whitelist('password', 'email', 'name')> r = repr(roles['create']) assert r.startswith('<Role whitelist(') and r.endswith(')>') assert sorted(r[16:-2].split(', ')) == ["'email'", "'name'", "'password'"] data = { 'id': 'NaN', 'name': 'Arthur', 'email': '*****@*****.**', 'password': '******', } user = User( dict( (k, v) for k, v in iteritems(data) if k in User._options.roles['create'] # filter by 'create' role ) ) d = user.serialize(role='public') assert d == { 'id': 42, 'name': 'Arthur', 'email': '*****@*****.**', } d = user.serialize(role='nospam') assert d == { 'id': 42, 'name': 'Arthur', } d = user.serialize(role='empty') assert d is None d = user.serialize(role='everything') assert d == { 'email': '*****@*****.**', 'id': 42, 'name': 'Arthur', 'password': '******' } def test_md5_type(self): class M(Model): md5 = MD5Type() import hashlib myhash = hashlib.md5("hashthis").hexdigest() m = M() m.md5 = myhash self.assertEqual(m.md5, myhash) d = m.serialize() self.assertEqual(d, { 'md5': myhash }) m2 = M(d) self.assertEqual(m2.md5, myhash)
from schematics.types import (StringType, FloatType, URLType, IntType, BooleanType, BaseType, EmailType, MD5Type, DecimalType as BaseDecimalType) from schematics.types.compound import (ModelType, DictType, ListType as BaseListType) from schematics.types.serializable import serializable from openprocurement.api.utils import get_now, set_parent, get_schematics_document from openprocurement.api.constants import ( CPV_CODES, ORA_CODES, TZ, DK_CODES, CPV_BLOCK_FROM, ATC_CODES, INN_CODES, ATC_INN_CLASSIFICATIONS_FROM, ) schematics_default_role = SchematicsDocument.Options.roles['default'] + blacklist("__parent__") schematics_embedded_role = SchematicsDocument.Options.roles['embedded'] + blacklist("__parent__") plain_role = (blacklist('_attachments', 'revisions', 'dateModified') + schematics_embedded_role) listing_role = whitelist('dateModified', 'doc_id') draft_role = whitelist('status') class DecimalType(BaseDecimalType): def __init__(self, precision=-3, min_value=None, max_value=None, **kwargs): super(DecimalType, self).__init__(**kwargs) self.min_value, self.max_value = min_value, max_value self.precision = Decimal("1E{:d}".format(precision)) def _apply_precision(self, value): try: value = Decimal(value).quantize(self.precision, rounding=ROUND_HALF_UP).normalize() except (TypeError, InvalidOperation): raise ConversionError(self.messages['number_coerce'].format(value))
) from openprocurement.tender.openeu.constants import ( TENDERING_DURATION as TENDERING_DURATION_EU, ) from openprocurement.tender.competitivedialogue.utils import ( validate_features_custom_weight ) from openprocurement.tender.competitivedialogue.constants import ( CD_UA_TYPE, CD_EU_TYPE, STAGE_2_EU_TYPE, STAGE_2_UA_TYPE, STAGE2_STATUS, FEATURES_MAX_SUM ) edit_role_ua = edit_role + blacklist('enquiryPeriod', 'status') edit_stage2_pending = whitelist('status') edit_stage2_waiting = whitelist('status', 'stage2TenderID') view_role_stage1 = (view_role + blacklist('auctionPeriod')) pre_qualifications_role_stage1 = (pre_qualifications_role + blacklist('auctionPeriod')) roles = { 'plain': plain_role, 'create': create_role, 'view': view_role_stage1, 'listing': listing_role, 'active.pre-qualification': pre_qualifications_role_stage1, 'active.pre-qualification.stand-still': pre_qualifications_role_stage1, 'active.stage2.pending': pre_qualifications_role_stage1, 'active.stage2.waiting': pre_qualifications_role_stage1, 'edit_active.stage2.pending': whitelist('status'),
plain_role, listing_role, ) from openregistry.api.interfaces import IORContent create_role = (blacklist('owner_token', 'owner', '_attachments', 'revisions', 'date', 'dateModified', 'lotID', 'status', 'doc_id') + schematics_embedded_role) edit_role = (blacklist('owner_token', 'owner', 'status', '_attachments', 'revisions', 'date', 'dateModified', 'lotID', 'mode', 'doc_id') + schematics_embedded_role) view_role = (blacklist('owner_token', '_attachments', 'revisions') + schematics_embedded_role) Administrator_role = whitelist('status', 'mode') class ILot(IORContent): """ Base lot marker interface """ def get_lot(model): while not ILot.providedBy(model): model = model.__parent__ return model @implementer(ILot) class BaseLot(SchematicsDocument, Model): class Options:
items = ListType(ModelType(Item)) documents = ListType(ModelType(Document), default=list()) complaints = ListType(ModelType(Complaint), default=list()) contracts = ListType(ModelType(Contract), default=list()) complaintPeriod = ModelType(Period) def validate_cpv_group(items, *args): if items and len(set([i.classification.id[:3] for i in items])) != 1: raise ValidationError(u"CPV group of items be identical") plain_role = (blacklist('_attachments', 'revisions', 'dateModified') + schematics_embedded_role) create_role = (blacklist('owner_token', 'owner', '_attachments', 'revisions', 'dateModified', 'doc_id', 'tenderID', 'bids', 'documents', 'awards', 'questions', 'complaints', 'auctionUrl', 'status', 'auctionPeriod', 'awardPeriod', 'procurementMethod', 'awardCriteria', 'submissionMethod') + schematics_embedded_role) edit_role = (blacklist('owner_token', 'owner', '_attachments', 'revisions', 'dateModified', 'doc_id', 'tenderID', 'bids', 'documents', 'awards', 'questions', 'complaints', 'auctionUrl', 'auctionPeriod', 'awardPeriod', 'procurementMethod', 'awardCriteria', 'submissionMethod', 'mode') + schematics_embedded_role) cancel_role = whitelist('status') view_role = (blacklist('owner', 'owner_token', '_attachments', 'revisions') + schematics_embedded_role) listing_role = whitelist('dateModified', 'doc_id') auction_view_role = whitelist('tenderID', 'dateModified', 'bids', 'auctionPeriod', 'minimalStep', 'auctionUrl') auction_post_role = whitelist('bids') auction_patch_role = whitelist('auctionUrl', 'bids') enquiries_role = (blacklist('owner', 'owner_token', '_attachments', 'revisions', 'bids', 'numberOfBids') + schematics_embedded_role) auction_role = (blacklist('owner', 'owner_token', '_attachments', 'revisions', 'bids') + schematics_embedded_role) chronograph_role = whitelist('status', 'enquiryPeriod', 'tenderPeriod', 'auctionPeriod', 'awardPeriod') Administrator_role = whitelist('status', 'mode') class Tender(SchematicsDocument, Model): """Data regarding tender process - publicly inviting prospective contractors to submit bids for evaluation and selecting a winner or winners.""" class Options: roles = {
return lot = lots[0] if lot.value.amount > value.amount: raise ValidationError(u"value of bid should be greater than value of lot") if lot.get('value').currency != value.currency: raise ValidationError(u"currency of bid should be identical to currency of value of lot") if lot.get('value').valueAddedTaxIncluded != value.valueAddedTaxIncluded: raise ValidationError(u"valueAddedTaxIncluded of bid should be identical to valueAddedTaxIncluded of value of lot") def validate_relatedLot(self, data, relatedLot): if isinstance(data['__parent__'], Model) and relatedLot not in [i.id for i in get_auction(data['__parent__']).lots]: raise ValidationError(u"relatedLot should be one of lots") view_bid_role = (blacklist('owner_token') + schematics_default_role) Administrator_bid_role = whitelist('tenderers') class Bid(Bid): class Options: roles = { 'embedded': view_bid_role, 'view': view_bid_role, 'auction_view': whitelist('value', 'lotValues', 'id', 'date', 'parameters', 'participationUrl', 'owner'), 'active.qualification': view_bid_role, 'active.awarded': view_bid_role, 'complete': view_bid_role, 'unsuccessful': view_bid_role, 'cancelled': view_bid_role, }
title_ru = StringType() description = StringType() # Award description description_en = StringType() description_ru = StringType() status = StringType(required=True, choices=['pending', 'unsuccessful', 'active', 'cancelled']) date = IsoDateTimeType(default=get_now) value = ModelType(Value) suppliers = ListType(ModelType(Organization), default=list()) items = ListType(ModelType(Item)) documents = ListType(ModelType(Document), default=list()) complaints = ListType(ModelType(Complaint), default=list()) plain_role = (blacklist('owner_token', '_attachments', 'revisions', 'dateModified') + schematics_embedded_role) view_role = (blacklist('owner_token', '_attachments', 'revisions') + schematics_embedded_role) listing_role = whitelist('dateModified', 'doc_id') auction_view_role = whitelist('tenderID', 'dateModified', 'bids', 'auctionPeriod', 'minimalStep') enquiries_role = (blacklist('owner_token', '_attachments', 'revisions', 'bids') + schematics_embedded_role) class Tender(SchematicsDocument, Model): """Data regarding tender process - publicly inviting prospective contractors to submit bids for evaluation and selecting a winner or winners.""" class Options: roles = { 'plain': plain_role, 'view': view_role, 'listing': listing_role, 'auction_view': auction_view_role, 'active.enquiries': enquiries_role, 'active.tendering': enquiries_role, 'active.auction': view_role,
from openprocurement.api.models import get_now from openprocurement.api.models import Contract as BaseContract from openprocurement.api.models import Document as BaseDocument from openprocurement.api.models import Organization as BaseOrganization from openprocurement.api.models import ContactPoint as BaseContactPoint from openprocurement.api.models import Item as BaseItem from openprocurement.api.models import (Model, ListType, Revision, Value, IsoDateTimeType) from openprocurement.api.models import validate_cpv_group, validate_items_uniq from openprocurement.api.models import (plain_role, Administrator_role, schematics_default_role, schematics_embedded_role) contract_create_role = (whitelist( 'id', 'awardID', 'contractID', 'contractNumber', 'title', 'title_en', 'title_ru', 'description', 'description_en', 'description_ru', 'status', 'period', 'value', 'dateSigned', 'documents', 'items', 'suppliers', 'procuringEntity', 'owner', 'tender_token', 'tender_id', 'mode' )) contract_edit_role = (whitelist( 'title', 'title_en', 'title_ru', 'description', 'description_en', 'description_ru', 'status', 'period', 'value' , 'items', 'amountPaid', 'terminationDetails', 'contract_amountPaid', )) contract_view_role = (whitelist( 'id', 'awardID', 'contractID', 'dateModified', 'contractNumber', 'title', 'title_en', 'title_ru', 'description', 'description_en', 'description_ru', 'status', 'period', 'value', 'dateSigned', 'documents', 'items', 'suppliers', 'procuringEntity', 'owner', 'mode', 'tender_id', 'changes', 'amountPaid', 'terminationDetails', 'contract_amountPaid',
from schematics.types import StringType, BaseType from schematics.types.compound import ModelType, DictType from schematics.types.serializable import serializable from schematics.exceptions import ValidationError from schematics.transforms import whitelist from openprocurement.api.models import Contract as BaseContract from openprocurement.api.models import Document as BaseDocument from openprocurement.api.models import Item as BaseItem from openprocurement.api.models import (ListType, Revision, IsoDateTimeType, ProcuringEntity) from openprocurement.api.models import (plain_role, Administrator_role, schematics_default_role) contract_create_role = (whitelist( 'id', 'awardID', 'contractID', 'contractNumber', 'title', 'title_en', 'title_ru', 'description', 'description_en', 'description_ru', 'status', 'period', 'value', 'dateSigned', 'documents', 'items', 'suppliers', 'procuringEntity', 'owner', 'tender_token', 'tender_id', 'mode' )) contract_edit_role = (whitelist( 'title', 'title_en', 'title_ru', 'description', 'description_en', 'description_ru', 'status', 'period', 'value' , 'mode' )) contract_view_role = (whitelist( 'id', 'awardID', 'contractID', 'dateModified', 'contractNumber', 'title', 'title_en', 'title_ru', 'description', 'description_en', 'description_ru', 'status', 'period', 'value', 'dateSigned', 'documents', 'items', 'suppliers', 'procuringEntity', 'owner', 'mode', 'tender_id' ))
def test_role_set_operations(): protected = whitelist('email', 'password') all_fields = whitelist('id', 'name') + protected def count(n): while True: yield n n += 1 class User(Model): id = IntType(default=count(42).next) name = StringType() email = StringType() password = StringType() class Options: roles = { 'create': all_fields - ['id'], 'public': all_fields - ['password'], 'nospam': blacklist('password') + blacklist('email'), } data = { 'id': 'NaN', 'name': 'Arthur', 'email': '*****@*****.**', 'password': '******', } user = User( dict( (k, v) for k, v in data.iteritems() if k in User._options.roles['create'] # filter by 'create' role ) ) d = user.serialize(role='public') assert d == { 'id': 42, 'name': 'Arthur', 'email': '*****@*****.**', } d = user.serialize(role='nospam') assert d == { 'id': 42, 'name': 'Arthur', } def test_md5_type(self): class M(Model): md5 = MD5Type() import hashlib myhash = hashlib.md5("hashthis").hexdigest() m = M() m.md5 = myhash self.assertEqual(m.md5, myhash) d = m.serialize() self.assertEqual(d, { 'md5': myhash }) m2 = M(d) self.assertEqual(m2.md5, myhash)