def doSet(target, value): assert isinstance(processing, Processing), 'Invalid processing %s' % processing assert isinstance(relation, Invoker), 'Invalid invoker %s' % relation assert isinstance(target, Target), 'Invalid target %s' % target assert isinstance( target.arg.request, RequestTarget), 'Invalid request %s' % target.arg.request arg = dict(target.arg.__dict__) request = processing.ctx.request() assert isinstance(request, Request) request.node = relation.node request.converterPath = target.arg.request.converterPath request.method = HTTP_GET if target.arg.request.nodesValues: request.nodesValues = dict(target.arg.request.nodesValues) else: request.nodesValues = {} assert isinstance(request.converterPath, Converter) request.nodesValues[ relation.node.parent] = request.converterPath.asString( value, prop) arg['request'] = request arg['response'] = processing.ctx.response() arg = processing.execute(**arg) assert isinstance(arg.response, Response), 'Invalid response %s' % arg.response if arg.response.errorInput or arg.response.obj is None: raise IdError(prop) wrapped(target, value)
def getById(self, id): ''' Provides the component based on the provided id. @see: IComponentService.getById ''' assert isinstance(id, str), 'Invalid id %s' % id module = self.modules().get(id) if module is None: raise IdError(self.Component) c = self.Component() assert isinstance(c, Component), 'Invalid component %s' % c c.Id = id m = sys.modules.get(module) if m: c.Loaded = True c.Name = getattr(m, 'NAME', None) c.Group = getattr(m, 'GROUP', None) c.Version = getattr(m, 'VERSION', None) c.Description = getattr(m, 'DESCRIPTION', None) c.Path = path.relpath(path.dirname(path.dirname(path.dirname(m.__file__)))) c.InEgg = not path.isfile(m.__file__) else: c.Loaded = False return c
def addPropertyFilter(self, identifier, accessId, propertyName, filterName): ''' @see: IACLPrototype.addPropertyFilter ''' assert isinstance(accessId, int), 'Invalid access id %s' % accessId assert isinstance(propertyName, str), 'Invalid property name %s' % propertyName assert isinstance(filterName, str), 'Invalid filter name %s' % filterName filtre = self.filterObtain(filterName) assert isinstance(filtre, FilterMapped), 'Invalid filter %s' % filtre sql = self.session().query(PropertyMapped.Signature) sql = sql.filter(PropertyMapped.accessId == accessId).filter( PropertyMapped.Name == propertyName) try: psignature, = sql.one() except NoResultFound: raise IdError(Property) if not isCompatible(filtre.Signature, psignature): raise InputError(_('Invalid filter for property name')) self.assignPropertyFilter(identifier, accessId, propertyName, filtre.id)
def getPerform(self, performId): ''' @see: IIndexingService.getPerform ''' assert isinstance(performId, int), 'Invalid perform id %s' % performId self._process() perform = self._performsById.get(performId) if perform is None: raise IdError() return perform
def getBlock(self, blockId): ''' @see: IIndexingService.getAction ''' assert isinstance(blockId, int), 'Invalid block id %s' % blockId self._process() block = self._blocksById.get(blockId) if block is None: raise IdError() return block
def getAction(self, actionId): ''' @see: IIndexingService.getAction ''' assert isinstance(actionId, int), 'Invalid action id %s' % actionId self._process() action = self._actionsById.get(actionId) if action is None: raise IdError() return action
def update(self, gateway): ''' @see: IGatewayService.update ''' assert isinstance(gateway, Custom), 'Invalid gateway %s' % gateway data = self.session().query(GatewayData).get(gateway.Name) if data is None: raise IdError() assert isinstance(data, GatewayData), 'Invalid data %s' % data data.navigate = self.dataFor(gateway, onlyNavigate=True).encode()
def getProperty(self, api): ''' @see: IModelService.getProperty ''' intr = self.processing.execute(Introspect=self.processing.ctx.introspect).introspect assert isinstance(intr, Introspect), 'Invalid introspect %s' % intr prop = intr.properties.get(api) if prop is None: raise IdError() return prop
def getModel(self, api): ''' @see: IIntrospectService.getModel ''' intr = self.processing.execute(Introspect=self.processing.ctx.introspect).introspect assert isinstance(intr, Introspect), 'Invalid introspect %s' % intr model = intr.models.get(api) if model is None: raise IdError() return model
def getById(self, name): ''' @see: IGatewayService.getById ''' assert isinstance(name, str), 'Invalid gateway name %s' % name data = self.session().query(GatewayData).get(name) if data is None: raise IdError() assert isinstance(data, GatewayData), 'Invalid data %s' % data gatewayData = json.loads(str(data.identifier, 'utf8')) gatewayData.update(json.loads(str(data.navigate, 'utf8'))) gateway = copyContainer(gatewayData, Custom()) gateway.Name = name return gateway
def addAcl(self, identifier, accessId): ''' @see: IACLPrototype.addAcl ''' assert isinstance(accessId, int), 'Invalid access id %s' % accessId try: access = self.session().query(AccessMapped).filter( AccessMapped.Id == accessId).one() except: raise IdError(Access) assert isinstance(access, AccessMapped), 'Invalid access %s' % access sql = self.session().query(self.AclId) sql = sql.filter(self.AclIdentifier == identifier) try: aclId, = sql.one() except: raise IdError(typeFor(self.Acl)) ids = [accessId] if access.Shadowing: ids.append(access.Shadowing) for id, in self.session().query(AccessMapped.Id).filter( AccessMapped.Shadowing == accessId).all(): ids.append(id) for accessId in ids: sql = self.session().query(self.AclAccess) sql = sql.filter(self.AclAccess.accessId == accessId).filter( self.AclAccess.aclId == aclId) if sql.count() > 0: continue aclAccess = self.AclAccess() aclAccess.accessId = accessId aclAccess.aclId = aclId self.session().add(aclAccess)
def addRole(self, identifier, roleName): ''' @see: IRbacPrototype.addRole ''' assert isinstance(roleName, str), 'Invalid role name %s' % roleName try: roleId, = self.session().query( RoleMapped.id).filter(RoleMapped.Name == roleName).one() except NoResultFound: raise IdError(Role) rbacId = self.obtainRbacId(identifier) sql = self.session().query(RbacRole).filter( RbacRole.rbacId == rbacId).filter(RbacRole.roleId == roleId) if sql.count() > 0: return # The role is already mapped to Rbac self.session().add(RbacRole(rbacId=rbacId, roleId=roleId))
def filterObtain(self, filterName): ''' Obtains the filter data. @param filterName: string The filter name to obtain data for, @return: FilterMapped Provides the filter mapped. ''' assert isinstance(filterName, str), 'Invalid filter name %s' % filterName sql = self.session().query(FilterMapped) sql = sql.filter(FilterMapped.Name == filterName) try: return sql.one() except NoResultFound: raise IdError(Filter)
def handle(self, execution): ''' @see: IProxyHandler.handle ''' assert isinstance(execution, Execution), 'Invalid execution %s' % execution assert isinstance(execution.proxyCall, ProxyCall), 'Invalid proxy call %s' % execution.proxyCall assert isinstance(execution.proxyCall.proxyMethod, ProxyMethod), \ 'Invalid proxy method %s' % execution.proxyCall.proxyMethod invoker = self.invokers.get(execution.proxyCall.proxyMethod.name) if not invoker: return execution.invoke() assert isinstance(invoker, Invoker), 'Invalid invoker %s' % invoker try: return execution.invoke() except SQLAlchemyError as exc: iexc = None if isinstance(exc, NoResultFound): iexc = IdError() elif isinstance(exc, IntegrityError): iexc = InputError(_('There is already an entity having this unique properties')) elif isinstance(exc, OperationalError): if invoker.method == DELETE: iexc = InputError(_('Cannot delete because is used')) elif invoker.method != GET: iexc = InputError(_('An entity relation identifier is not valid')) if iexc is not None: if invoker.target: iexc.update(invoker.target) log.info('SQL Alchemy handled exception occurred', exc_info=(type(exc), exc, exc.__traceback__)) iexc.with_traceback(exc.__traceback__) exc = iexc else: log.warn('Unknown SQL Alchemy error', exc_info=(type(exc), exc, exc.__traceback__)) raise exc
def assignPropertyFilter(self, identifier, accessId, propertyName, filterId): ''' Register the filter at the provided property name. @param identifier: object The ACL object identifier. @param accessId: integer The access id to register the filter with. @param propertyName: string The property name to register the filter at. @param filterId: integer The filter id to register @param data: key arguments The data used to identify the category, by default a 'categoryId' is expected. ''' assert isinstance(accessId, int), 'Invalid access id %s' % accessId assert isinstance(propertyName, str), 'Invalid property name %s' % propertyName assert isinstance(filterId, int), 'Invalid filter id %s' % filterId sql = self.session().query(PropertyMapped.id).join(AccessMapped) sql = sql.filter(AccessMapped.Id == accessId).filter( PropertyMapped.Name == propertyName) try: propertyId, = sql.one() except NoResultFound: raise IdError(Property.Name) aclAccessId = self.aclAccessId(identifier, accessId) sql = self.session().query(self.PropertyFilter) sql = sql.filter(self.PropertyFilter.aclAccessId == aclAccessId) sql = sql.filter(self.PropertyFilter.propertyId == propertyId).filter( self.PropertyFilter.filterId == filterId) if sql.count() > 0: return # Already assigned. propertyFilter = self.PropertyFilter() propertyFilter.aclAccessId = aclAccessId propertyFilter.propertyId = propertyId propertyFilter.filterId = filterId self.session().add(propertyFilter)
def assignEntryFilter(self, identifier, accessId, entryPosition, filterId): ''' Register the filter at the provided entry position. @param identifier: object The ACL object identifier. @param accessId: integer The access id to register the filter with. @param entryPosition: integer The entry position to register the filter at. @param filterId: integer The filter id to register @param data: key arguments The data used to identify the category, by default a 'categoryId' is expected. ''' assert isinstance(accessId, int), 'Invalid access id %s' % accessId assert isinstance(entryPosition, int), 'Invalid position %s' % entryPosition assert isinstance(filterId, int), 'Invalid filter id %s' % filterId sql = self.session().query(EntryMapped.id).join(AccessMapped) sql = sql.filter(AccessMapped.Id == accessId).filter( EntryMapped.Position == entryPosition) try: entryId, = sql.one() except NoResultFound: raise IdError(Entry.Position) aclAccessId = self.aclAccessId(identifier, accessId) sql = self.session().query(self.EntryFilter) sql = sql.filter(self.EntryFilter.aclAccessId == aclAccessId) sql = sql.filter(self.EntryFilter.entryId == entryId).filter( self.EntryFilter.filterId == filterId) if sql.count() > 0: return # Already assigned. entryFilter = self.EntryFilter() entryFilter.aclAccessId = aclAccessId entryFilter.entryId = entryId entryFilter.filterId = filterId self.session().add(entryFilter)
def updateModel(Mapped, model, **data): ''' Updates the provided model entity using the current session. @param Mapped: class The mapped class to update the model for, the model type is required to have a property id. @param model: object The model to be updated. @param data: key arguments Additional data to place on the updated model. @return: object The database model that has been updated. ''' assert isclass(Mapped), 'Invalid class %s' % Mapped assert isinstance(Mapped, MappedSupport), 'Invalid mapped class %s' % Mapped if isinstance(model, Mapped): dbModel = model openSession().merge(dbModel) else: typ = typeFor(Mapped) assert isinstance(typ, TypeModel), 'Invalid model class %s' % Mapped assert typ.isValid(model), 'Invalid model %s for %s' % (model, typ) assert isinstance(typ.propertyId, TypeProperty), 'Invalid property id of %s' % typ dbModel = openSession().query(Mapped).get( getattr(model, typ.propertyId.name)) if not dbModel: raise IdError(typ.propertyId) for name, prop in typ.properties.items(): if name in data or not isinstance(getattr(Mapped, name), InstrumentedAttribute): continue if prop in model: setattr(dbModel, name, getattr(model, name)) for name, value in data.items(): setattr(dbModel, name, value) openSession().flush((dbModel, )) return dbModel
def addEntryFilter(self, identifier, accessId, entryPosition, filterName): ''' @see: IACLPrototype.addEntryFilter ''' assert isinstance(accessId, int), 'Invalid access id %s' % accessId assert isinstance(entryPosition, int), 'Invalid entry position %s' % entryPosition assert isinstance(filterName, str), 'Invalid filter name %s' % filterName filtre = self.filterObtain(filterName) assert isinstance(filtre, FilterMapped), 'Invalid filter %s' % filtre sql = self.session().query(EntryMapped.Signature) sql = sql.filter(EntryMapped.accessId == accessId).filter( EntryMapped.Position == entryPosition) try: esignature, = sql.one() except NoResultFound: raise IdError(Entry) if not isCompatible(filtre.Signature, esignature): raise InputError(_('Invalid filter for entry position')) self.assignEntryFilter(identifier, accessId, entryPosition, filtre.id)
def obtainRbacId(self, identifier): ''' Find or create the Rbac id for the provided identifier. @param identifier: object The RBAC object identifier to get the Rbac id. @return: integer The found or created Rbac id. ''' sql = self.session().query(self.Rbac) sql = sql.filter(self.RbacIdentifier == identifier) try: withRbac = sql.one() except NoResultFound: raise IdError(self.Rbac) assert isinstance( withRbac, WithRbac), 'Invalid with Rbac container %s' % withRbac if withRbac.rbacId is None: rbac = Rbac() self.session().add(rbac) self.session().flush((rbac, )) withRbac.rbacId = rbac.id return withRbac.rbacId
def addCompensate(self, identifier, accessId, compensatedId): ''' @see: ICompensatePrototype.addCompensate ''' assert isinstance(accessId, int), 'Invalid access id %s' % accessId assert isinstance( compensatedId, int), 'Invalid compensated access id %s' % compensatedId sql = self.session().query(AccessMapped, self.AclAccess.id).join( self.AclAccess).join(self.Acl) sql = sql.filter(self.AclAccess.accessId == accessId).filter( self.AclIdentifier == identifier) try: access, aclAccessId = sql.one() except NoResultFound: raise InputError(_('Access not allowed')) compensated = self.session().query(AccessMapped).get(compensatedId) if compensated is None: raise IdError(Access) assert isinstance(access, AccessMapped), 'Invalid access %s' % access assert isinstance(compensated, AccessMapped), 'Invalid access %s' % compensated if compensated.Method != access.Method: raise InputError(_('The compensated method is not compatible'), Access.Method) if compensated.Output != access.Output: raise InputError(_('The compensated output is not compatible'), Access.Output) sql = self.session().query(EntryMapped.Signature) sql = sql.filter(EntryMapped.accessId == accessId) sql = sql.order_by(EntryMapped.Position.desc()) saccesses = [signature for signature, in sql.all()] sql = self.session().query(EntryMapped.Signature).filter( EntryMapped.accessId == compensatedId) sql = sql.order_by(EntryMapped.Position.desc()) scompensateds = [signature for signature, in sql.all()] if len(saccesses) < len(scompensateds): raise InputError( _('To many compensated entries versus the access entries')) fixed = iter(reversed(access.Path.split('*'))) items, mapping = [next(fixed)], {} for k, (saccess, scompensated) in enumerate(zip(saccesses, scompensateds)): if isCompatible(saccess, scompensated): items.append(COMPENSATE_CREATE_MARKER % (len(scompensateds) - k)) items.append(next(fixed)) mapping[len(saccesses) - k] = len(scompensateds) - k else: raise InputError(_( 'The compensated entry is not compatible with the access entry for position %(position)i' ), position=len(scompensateds) - k) if len(saccesses) > len(scompensateds): if not self.signatures: raise InputError( _('Cannot provide a values for access prefix entries')) for k, saccess in enumerate(saccesses[len(scompensateds):]): for signature, marker in self.signatures.items(): if isCompatible(signature, saccess): if isinstance(marker, str): items.append(marker) else: value = marker(identifier) assert isinstance( value, str ), 'Invalid maker %s return value \'%s\'' % ( marker, value) items.append(value) items.append(next(fixed)) break else: raise InputError(_( 'Cannot provide a value for access position %(position)i' ), position=len(saccesses) - k) items.reverse() path = ''.join(items) sql = self.session().query(self.Compensate) sql = sql.filter(self.Compensate.aclAccessId == aclAccessId).filter( self.Compensate.Access == compensatedId) try: compensate = sql.one() except NoResultFound: compensate = self.Compensate() assert isinstance( compensate, WithCompensate), 'Invalid compensate %s' % compensate compensate.Access = compensatedId compensate.Path = path compensate.Mapping = mapping compensate.aclAccessId = aclAccessId self.session().add(compensate) else: compensate.Path = path compensate.Mapping = mapping
def registerFilter(self, identifier, accessId, filterName, place=None): ''' @see: IACLPrototype.registerFilter ''' assert isinstance(accessId, int), 'Invalid access id %s' % accessId assert isinstance(filterName, str), 'Invalid filter name %s' % filterName try: access = self.session().query(AccessMapped).filter( AccessMapped.Id == accessId).one() except NoResultFound: raise IdError(Access) assert isinstance(access, AccessMapped), 'Invalid access %s' % access filtre = self.filterObtain(filterName) assert isinstance(filtre, FilterMapped), 'Invalid filter %s' % filtre sql = self.session().query(EntryMapped) sql = sql.filter(EntryMapped.accessId == accessId) entries = {entry.Position: entry for entry in sql.all()} filterEntries = [] # The compatible entries with the filter. for entry in entries.values(): assert isinstance(entry, EntryMapped), 'Invalid entry %s' % entry if isCompatible(filtre.Signature, entry.Signature): filterEntries.append(entry) sql = self.session().query(PropertyMapped) sql = sql.filter(PropertyMapped.accessId == accessId) properties = {prop.Name: prop for prop in sql.all()} filterProperties = [] # The compatible properties with the filter. for prop in properties.values(): assert isinstance(prop, PropertyMapped), 'Invalid property %s' % prop if isCompatible(filtre.Signature, prop.Signature): filterProperties.append(prop) if not filterEntries and not filterProperties: return False if len(filterEntries) + len(filterProperties) > 1: if place is None: raise InputError( _('Filter matches multiple entries and/or properties, a place is required to be specified' )) filterEntries, filterProperties = self.determineFilterPlace( access, filtre.Signature, place, entries, properties) for entry in filterEntries: self.assignEntryFilter(identifier, accessId, entry.Position, filtre.id) if entry.Shadowing is not None: # Registering the filter also for the shadowing entry. self.assignEntryFilter(identifier, access.Shadowing, entry.Shadowing, filtre.id) for prop in filterProperties: self.assignPropertyFilter(identifier, accessId, prop.Name, filtre.id) if access.Shadowing is not None: # Registering the filter also for the shadowing property. self.assignPropertyFilter(identifier, access.Shadowing, prop.Name, filtre.id) if access.Shadowing is None: # Registering the filter also for the shadows, if any, of this access. sql = self.session().query(EntryMapped).select_from( AccessMapped).join(EntryMapped) sql = sql.filter(AccessMapped.Shadowing == accessId) shadows = {} for sentry in sql.all(): assert isinstance(sentry, EntryMapped), 'Invalid entry %s' % sentry sentries = shadows.get(sentry.accessId) if sentries is None: sentries = shadows[sentry.accessId] = {} sentries[sentry.Shadowing] = sentry.Position for shadowId, sentries in shadows.items(): for entry in filterEntries: self.assignEntryFilter(identifier, shadowId, sentries[entry.Position], filtre.id) for prop in filterProperties: self.assignPropertyFilter(identifier, shadowId, prop.Name, filtre.id) return True