def check_required_params(self): """ Check if all required parameters are set""" for param in self.REQUIRED_FIELDS: if param not in self.params: raise ValidationError("Missing parameter: {} for {}".format( param, self.__class__.path)) for child in self.TASKS: for param in child.REQUIRED_FIELDS: if param not in self.params: raise ValidationError( "Missing parameter: {} for {}".format( param, child.path))
def search_value(self, xpath: str, default: Optional[Any] = None, fail_if_no_match: Optional[bool] = False) -> Optional[Any]: """ Try to find a value in the result. see https://github.com/kennknowles/python-jsonpath-rw#jsonpath-syntax :param str xpath: a xpath filter :param any default: default value if not found :param bool fail_if_no_match: Raise a ValidationError if no matches :return: the value found or None """ matches = [ match.value for match in jsonpath_rw_ext.parse(xpath).find(self.retval) ] if len(matches) == 0: if fail_if_no_match is True: raise ValidationError("No value found for xpath: '{}'".format( xpath )) else: return default elif len(matches) == 1: return matches[0] else: return matches
def list_user(self): """docstring for list_user""" conn = self.bind try: query_filter = "(objectclass=inetOrgPerson)" records = conn.search_s(current_app.config['LDAP_BASE_DN'], ldap.SCOPE_SUBTREE, "(&%s)" % query_filter, ['*']) conn.unbind_s() if records: return [LDAPUser(x[0], **x[1]) for x in dict(records).items()] else: return list() except ldap.LDAPError as err: raise ValidationError(message=str(getattr(err, 'message', err))) except Exception as err: raise ValidationError(message=str(err))
def get_user(self, **kwargs): """docstring for get_user""" conn = self.bind try: query_filter = "(objectclass=inetOrgPerson)" for item in kwargs.items(): query_filter += "(%s=%s)" % item records = conn.search_s(current_app.config['LDAP_BASE_DN'], ldap.SCOPE_SUBTREE, "(&%s)" % query_filter, ['*']) conn.unbind_s() if records: return LDAPUser(records[0][0], **records[0][1]) except ldap.LDAPError as err: raise ValidationError(message=str(getattr(err, 'message', err))) except Exception as err: raise ValidationError(message=str(err))
def add_user(self, username, mail=None, password=None, lastname=None, firstname=None, description=None): """docstring for add_user""" conn = self.bind try: if not password: password = create_random_string() if not mail: mail = current_app.config['LDAP_USER_MAIL'] dn = 'uid=%s,%s' % (username, current_app.config['LDAP_BASE_DN']) uid, gid = self.get_random_ids() data = dict( uid=username, objectclass=current_app.config['LDAP_USER_OBJECT_CLASSES'], loginShell='/bin/bash', userPassword=to_hash(password), uidNumber=uid, gidNumber=gid, mail=mail, homeDirectory="/home/%s" % username, shadowExpire="-1", sn=unidecode(lastname) if lastname else mail, givenName=unidecode(firstname) if firstname else username, cn=mail) if description: data['description'] = description conn.add_s(dn, LDAPManager.to_ldap(data)) conn.unbind_s() return {"email": mail, "password": password, "username": username} except (ldap.INVALID_SYNTAX, ldap.OBJECT_CLASS_VIOLATION) as exc: raise ValidationError(extra=exc.args[0]) except Exception as err: raise ValidationError(message=str(err))
def delete_user(self, username): """docstring for delete_user""" user = self.get_user(uid=username) if user is None: raise NotFound( message=MESSAGE_MAP["UserDoesNotExists"], extra=dict(factory="openldap", msgid="UserDoesNotExists", long_message="User '{}' doesn't exists !".format( username))) conn = self.bind try: dn = "uid=%s,%s" % (username, current_app.config['LDAP_BASE_DN']) conn.delete_s(dn) conn.unbind_s() return user except ldap.LDAPError as err: raise ValidationError(message=str(getattr(err, 'message', err))) except Exception as err: raise ValidationError(message=str(err))
def update_attribute(self, username, attr, old, new): """docstring for update_status""" conn = self.bind try: dn = "uid=%s,%s" % (username, current_app.config['LDAP_BASE_DN']) if old in ("", None, list()): mod_attrs = [(ldap.MOD_ADD, attr, LDAPManager.value_to_ldap(new))] elif new in ("", None, list()): mod_attrs = [(ldap.MOD_DELETE, attr, LDAPManager.value_to_ldap(old))] else: mod_attrs = [(ldap.MOD_REPLACE, attr, LDAPManager.value_to_ldap(new))] conn.modify_s(str(dn), mod_attrs) conn.unbind_s() return {"old": old, "new": new} except ldap.LDAPError as err: raise ValidationError(message=str(getattr(err, 'message', err))) except Exception as err: raise ValidationError(message=str(err))
def run(cls, raw_data): """description of run""" logger.debug("{}.ReceivedFromKafka: {}".format( cls.__name__, raw_data )) try: kmsg = cls._onmessage(cls.TRANSPORT.loads(raw_data)) except Exception as exc: error = from_exc(exc) logger.error( "{}.ImportError: Failed to load data from kafka: {} " "<- {}".format(cls.__name__, exc, raw_data), extra=dict(kafka_raw_data=raw_data, error=error.to_dict()) ) return Result.from_error(error) try: cls.start_processing(kmsg) if kmsg.entrypoint not in cls.ENTRYPOINTS: raise ValidationError( "Entrypoint '{}' not registred".format(kmsg.entrypoint), extra=dict( uuid=kmsg.uuid, entrypoint=kmsg.entrypoint, allowed=list(cls.ENTRYPOINTS.keys()) ) ) result = cls.ENTRYPOINTS[kmsg.entrypoint].from_Message( kmsg ).execute() except Exception as exc: result = Result.from_exception(exc, kmsg.uuid) finally: cls.stop_processing() # noinspection PyUnboundLocalVariable if result and result.retcode < 300: return cls._onsuccess(kmsg=kmsg, result=result) else: return cls._onerror(kmsg=kmsg, result=result)
def loads(cls, json_data): """description of load""" try: return cls(**vars(cls.MARSHMALLOW_SCHEMA.decode(json_data))) except marshmallow.exceptions.ValidationError as exc: raise ValidationError("Failed to load message", extra=exc.args[0])
def loads(cls, json_data): """Load message from a string""" try: return cls(**cls.MARSHMALLOW_SCHEMA.loads(json_data)) except marshmallow.exceptions.ValidationError as exc: raise ValidationError("Failed to load message", extra=exc.args[0])
def check_required_params(self): """ Check if all required parameters are set""" for param in self.REQUIRED_FIELDS: if param not in self.params: raise ValidationError("Missing parameter: {}".format(param))