def get_named_logkey_group(name): """ Get named log-key group from the config file. :param name: name of the group """ section = 'LogGroups' try: groups = dict(CONFIG.items(section)) name = name.lower() if name in groups: logkeys = [ line for line in str(groups[name]).splitlines() if line is not None ] for logkey in logkeys: if not validators.uuid(logkey): print_config_error_and_exit( section, 'Named Logkey Group(%s)' % name, logkey) return logkeys else: print_config_error_and_exit(section, 'Named Logkey Group(%s)' % name) except ConfigParser.NoSectionError: print_config_error_and_exit(section)
def get_queryset(self): ids = self.request.GET.getlist('uid', []) validate_uuid = [i for i in ids if validators.uuid(i)] usernames = self.request.GET.getlist('username') querysets = User.objects.filter(Q(id__in=validate_uuid) | Q(username__in=usernames)).order_by('date_joined') [setattr(item, 'uid', item.id) for item in querysets] return querysets
def search_managed_devices(self, device): if validators.uuid(device): return list( filter( lambda iter_device: iter_device['userId'] == device or iter_device['id'] == device, self._call_api( "GET", "deviceManagement/managedDevices")["value"])) elif validators.email(device): param = 'emailAddress' else: param = 'deviceName' value = self._call_api( "GET", f"deviceManagement/managedDevices?$filter={param} eq '{device}'" )["value"] if value: return value device = device.strip().lower() return list( filter( lambda iter_device: iter_device['emailAddress'].lower() == device or iter_device['userPrincipalName'].lower() == device, self._call_api("GET", "deviceManagement/managedDevices")["value"]))
def run(self, params={}): scan_identifier = params.get(Input.SCAN_IDENTIFIER) template_identifier = params.get(Input.TEMPLATE_IDENTIFIER) if not uuid(scan_identifier): scan_identifier = self.get_scan_id(scan_identifier) if not uuid(template_identifier): template_identifier = self.get_template_id(template_identifier) if params.get(Input.DOWNLOAD_PATCHES): self.connection.ivanti_api.start_patch_download(scan_identifier) payload = {"scanId": scan_identifier, "templateId": template_identifier} self.connection.ivanti_api.create_session_credential() success = False if self.connection.ivanti_api.start_patch_deployment(payload): success = True return {Output.SUCCESS: success}
def search_agents(self, agent: str, device_list: list) -> list: agents = [] if validators.ipv4(agent): agents.extend(self.get_device_by_ip(agent, device_list)) elif match('[0-9a-f]{2}([-:]?)[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$', agent.lower()): agents.extend(self.get_device_by_mac(agent, device_list)) elif validators.uuid(agent): agents.extend(self.get_device_by_id(agent, device_list)) else: agents.extend(self.get_device_by_name(agent, device_list)) return agents
def user(userid): ''' Use the UUID as a unique identifier, somehow, add checks for validity of the uuid, send uuid relevant data back to the requested url ''' boolTry = validators.uuid(str(userid)) if boolTry == True: message = {'status': 'A valid UUID was provided'} return jsonify(message) else: message = {'status': 'An invalid UUID was provided'} return jsonify(message)
def run(self, params={}): app = params.get(Input.APP) if validators.uuid(app): return { Output.MANAGED_APPS: insightconnect_plugin_runtime.helper.clean( self.connection.api.get_managed_app(app)) } return { Output.MANAGED_APPS: self.connection.api.get_managed_apps_all_pages(app) }
def get_rw_apikey(): """ Get read-write api key from the config file. """ config_key = 'rw_api_key' try: rw_api_key = CONFIG.get(AUTH_SECTION, config_key) if not validators.uuid(rw_api_key): print_config_error_and_exit(AUTH_SECTION, 'Read/Write API key(%s)' % config_key, rw_api_key) else: return rw_api_key except ConfigParser.NoOptionError: print_config_error_and_exit(AUTH_SECTION, 'Read/Write API key(%s)' % config_key)
def get_ro_apikey(): """ Get read-only api key from the config file. """ config_key = 'ro_api_key' try: ro_api_key = CONFIG.get(AUTH_SECTION, config_key) if not validators.uuid(ro_api_key): return get_rw_apikey() else: return ro_api_key except ConfigParser.NoOptionError: # because read-write api key is a superset of read-only api key return get_rw_apikey()
def get_account_resource_id(): """ Get account resource id from the config file. """ config_key = 'account_resource_id' try: account_resource_id = CONFIG.get(AUTH_SECTION, config_key) if not validators.uuid(account_resource_id): print_config_error_and_exit(AUTH_SECTION, 'Account Resource ID(%s)' % config_key, account_resource_id) return else: return account_resource_id except ConfigParser.NoOptionError: print_config_error_and_exit(AUTH_SECTION, 'Account Resource ID(%s)' % config_key)
def get_owner_apikey_id(): """ Get owner api key id from the config file. """ config_key = 'owner_api_key_id' try: owner_apikey_id = CONFIG.get(AUTH_SECTION, config_key) if not validators.uuid(owner_apikey_id): print_config_error_and_exit(AUTH_SECTION, 'Owner API key ID(%s)' % config_key, owner_apikey_id) return else: return owner_apikey_id except ConfigParser.NoOptionError: print_config_error_and_exit(AUTH_SECTION, 'Owner API key ID(%s)' % config_key)
def get_record_id(record_id): out = {} if validators.uuid(record_id): record_uuid = UUID(record_id) rec = query.get_single_record(db, record_uuid.bytes) if rec: out = { 'Record_ID': str(rec.id), 'Start': rec.start, 'End': rec.end, 'Size': rec.size, 'Path': rec.path, 'Status': rec.status, 'Removed': rec.removed } return render_template('singlerecord.html', record=out)
def search_managed_devices(self, device): if validators.uuid(device): return list( filter( lambda iter_device: iter_device['userId'] == device or iter_device['id'] == device, self._call_api( "GET", f"deviceManagement/managedDevices")["value"])) elif validators.email(device): filtering_params = ['emailAddress'] else: filtering_params = ['deviceName'] filtering_params = " or ".join( map(lambda param: f"{param} eq '{device}'", filtering_params)) return self._call_api( "GET", f"deviceManagement/managedDevices?$filter={filtering_params}" )["value"]
def decorated_function(*args, **kwargs): # get the auth token auth_header = request.headers.get('Authorization') auth_token = auth_token = auth_header.split( " ")[1] if auth_header else '' if auth_token: resp = User.decode_auth_token(auth_token) if bool(validators.uuid(resp)): g.auth_token = auth_token g.user = User.query.filter_by(id=resp).first() return f(*args, **kwargs) response_object = {'status': 'fail', 'message': resp} return make_response(jsonify(response_object)), 401 else: response_object = { 'status': 'fail', 'message': 'Provide a valid auth token.' } return make_response(jsonify(response_object)), 401
def get_archive_id(archive_id): out = {} if validators.uuid(archive_id): archive_uuid = UUID(archive_id) arc = query.get_single_archive(db, archive_uuid.bytes) if arc: records_out = dict() for rec in arc.records: records_out[str(rec.id)] = {'Start': rec.start, 'End': rec.end} out = { 'Archive_ID': arc.id, 'Creation': arc.creation, 'Size': arc.size, 'RemotePath': arc.remote_path, 'Removed': arc.removed, 'RecordsArchived': records_out } return render_template('singlearchive.html', archive=out)
def read_cell(self, cell): if not isinstance(cell, str): return None if self.field.format == "default": return cell elif self.field.format == "uri": if not validators.url(cell): return None elif self.field.format == "email": if not validators.email(cell): return None elif self.field.format == "uuid": if not validators.uuid(cell): return None elif self.field.format == "binary": try: base64.b64decode(cell) except Exception: return None return cell
def retrieve(self, request, pk=None): if not uuid(pk): return Response({_('detail'): _('not a valid UUID')}, status=400) device = Devices.objects.filter(device_id=pk, device_state=0).first() response_data = {} if not request.user.is_active: return Response({_("detail"): _("User inactive or deleted.")}, status=403) if device is not None: device_data = DeviceSerializer( device, fields=('device_id', 'device_push_token', 'device_os', 'device_type', 'device_state', 'device_heartbeat_date')) response_data = device_data.data response_data['user_id'] = device.device_user.user_id return Response(response_data, status=200) else: return Response({_("detail"): _("Device does not exists")}, status=400)
def read_cell(self, cell): if not isinstance(cell, str): return None if self.field.format == "default": return cell elif self.field.format == "uri": uri = rfc3986.uri_reference(cell) try: uri_validator.validate(uri) except rfc3986.exceptions.ValidationError: return None elif self.field.format == "email": if not validators.email(cell): return None elif self.field.format == "uuid": if not validators.uuid(cell): return None elif self.field.format == "binary": try: base64.b64decode(cell) except Exception: return None return cell
def get_named_logkey(name): """ Get named log-key from the config file. :param name: name of the log key """ section = 'LogNicknames' try: named_logkeys = dict(CONFIG.items(section)) name = name.lower() if name in named_logkeys: logkey = (named_logkeys[name], ) if not validators.uuid(logkey[0]): print_config_error_and_exit(section, 'Named Logkey(%s)' % name, logkey) else: return logkey else: print_config_error_and_exit(section, 'Named Logkey(%s)' % name) except ConfigParser.NoSectionError: print_config_error_and_exit(section)
def run(self, params={}): data = { "asset_name": params.get(Input.ASSET_NAME), "assetid": params.get(Input.ASSET_ID), "assettag": params.get(Input.ASSET_TAG), "ci_asset_tag": params.get(Input.CI_ASSET_TAG), "ci_id": params.get(Input.CI_ID), "ci_name": params.get(Input.CI_NAME), "department_code": params.get(Input.DEPARTMENT_CODE), "department_id": params.get(Input.DEPARTMENT_ID), "description": params.get(Input.DESCRIPTION), "external_reference": params.get(Input.EXTERNAL_REFERENCE), "impact_id": params.get(Input.IMPACT_ID), "location_code": params.get(Input.LOCATION_CODE), "location_id": params.get(Input.LOCATION_ID), "origin": params.get(Input.ORIGIN), "parentrequest": params.get(Input.PARENTREQUEST), "phone": params.get(Input.PHONE), "recipient_id": params.get(Input.RECIPIENT_ID), "recipient_identification": params.get(Input.RECIPIENT_IDENTIFICATION), "recipient_mail": params.get(Input.RECIPIENT_MAIL), "recipient_name": params.get(Input.RECIPIENT_NAME), "requestor_identification": params.get(Input.REQUESTOR_IDENTIFICATION), "requestor_mail": params.get(Input.REQUESTOR_MAIL), "requestor_name": params.get(Input.REQUESTOR_NAME), "severity_id": params.get(Input.SEVERITY_ID), "submit_date": params.get(Input.SUBMIT_DATE), "title": params.get(Input.TITLE), "urgency_id": params.get(Input.URGENCY_ID), } catalog = params.get(Input.CATALOG) if validators.uuid(catalog): data.update({"catalog_guid": catalog}) else: data.update({"catalog_code": catalog}) return {Output.RESULT: self.connection.client.ticket_action("POST", {"requests": [data]})}
def test_returns_true_on_valid_mac_address(value): assert uuid(value)
def test_returns_failed_validation_on_invalid_mac_address(value): assert isinstance(uuid(value), ValidationFailure)
def validate_request_id(req_id): if not validators.uuid(req_id): abort(400)
def _validate_type_uuid(self, field, value): if not validators.uuid(value): self._error(field, errors.ERROR_BAD_TYPE.format('uuid'))
def is_valid_uuid(value): """Validates if a value is a string representation of a UUID. :param value: string to validate :return: a boolean """ return isinstance(value, UUID) or validators.uuid(value)
def v_uuid(self, key): return validators.uuid(self.__dict__[key])
def _ensure_is_valid_uuid(self, value): if value is None or not validators.uuid(value): raise InvalidUuidError(value)
async def validate_uuid(uuid): return validators.uuid(uuid)
def arg_validator(arg, vlist=None): """ 检查数据,可对同一个数据进行多种检查 arg : 字符串,要验证的参数 vlist : 列表,验证列表,每个元素包含两项. 第一个项是检查类型(字符串),第二项是可选参数字典,类似: [ ("检查类型",{"可选参数1":参数值,"可选参数2":参数值...}), ("检查类型",{"可选参数1":参数值,"可选参数2":参数值...}), ... ] 返回: 双元组,第一项为True 或 False,第二项为验证失败的类型(第一项为True的话第二项就留空) 注意: vlist 列表的第一项可以是字符串 "required",用于表示是必填项: 如果第一项不是,而且要验证的 arg 为空,会直接返回 True,不是的继续验证。 如果第一项是,就完全按照 vlist[1:] 的要求验证 vlist 的元素如果是验证整数/小数/email等不需要附加参数的可以直接传入验证类型字符串即可 用例(使用args_validator函数的,看这里vdict每个键值对的形式): vdict = { "token": ["required", "uuid"], "username": ["required", ("length", {"min": 4, "max": 30}), "safe_str"], "password": ["required", ("length", {"min": 4, "max": 20}), "safe_str"], "captcha": ["required", ("length", {"min": 4, "max": 8}), "safe_str"], } form = args_validator(self.request.arguments, vdict) """ if not any((isinstance(vlist, list), isinstance(vlist, tuple))): einfo = "不支持的数据类型!应使用列表或元组,但输入的是{}".format(type(vlist)) raise ValueError(einfo) if vlist[0] == "required": # 第一项不是 required 的,把第一项的 "required" 去掉 vlist = vlist[1:] else: # 第一项不是 required 的,如果 arg 是空的,直接返回 True,不是的继续验证 if not arg: return True, None # 待返回的验证结果 verification = None failed_type = None # 验证失败的类型 # 开始检查,有一个不通过就返回 False for i in vlist: local_verification = None if isinstance(i, str): # 如果是字符串的话就改为元组 i = (i, {}) if len(i) == 1: # 只有一个元素的,添加一个空字典 i = (i[0], {}) vtype = i[0] # 检查类型是第一项 vdict = i[1] # 检查类型所需的可选参数字典 # 在 validators 之外添加的 # 没有空白 if vtype == "no_space": if not re.search(r"\s", arg): local_verification = True # 安全字符串,只包含 0-9a-zA-Z-空格和下划线 elif vtype == "safe_str": if re.match(r"^[0-9a-zA-Z-_ ]+$", arg, flags=re.U): local_verification = True # 是否包含 elif vtype == "in": # 迭代 vdict 的键值(所以键名无所谓) for v in vdict.values(): if arg not in v: local_verification = False break elif vtype == "not_in": # 迭代 vdict 的键值(所以键名无所谓) for v in vdict.values(): if arg in v: local_verification = False break # 字符串形式的数字 elif vtype == "str_number": if re.match(r"[+-]?\d+$", arg, flags=re.U) or \ re.match(r"[+-]?\d+\.\d+$", arg, flags=re.U): local_verification = True elif vtype == "str_int": if re.match(r"[+-]?\d+$", arg, flags=re.U): local_verification = True elif vtype == "str_float": if re.match(r"[+-]?\d+\.\d+$", arg, flags=re.U): local_verification = True # 数字 elif vtype == "number": # 整数或浮点数都可以 local_verification = isinstance(arg, int) or isinstance(arg, float) elif vtype == "int": local_verification = isinstance(arg, int) elif vtype == "float": local_verification = isinstance(arg, float) # 直接调用 validators的 elif vtype == "length": local_verification = validators.length(arg, **vdict) elif vtype == "url": local_verification = validators.url(arg, **vdict) elif vtype == "email": local_verification = validators.email(arg, **vdict) elif vtype == "ip": # ipv4 或 ipv6都可以 local_verification = any((validators.ipv4(arg, **vdict), validators.ipv6(arg, **vdict))) elif vtype == "between": local_verification = validators.between(arg, **vdict) elif vtype == "uuid": local_verification = validators.uuid(arg, **vdict) elif vtype == "ipv4": local_verification = validators.ipv4(arg, **vdict) elif vtype == "ipv6": local_verification = validators.ipv6(arg, **vdict) elif vtype == "mac_address": local_verification = validators.mac_address(arg, **vdict) elif vtype == "iban": local_verification = validators.iban(arg, **vdict) elif vtype == "slug": local_verification = validators.slug(arg, **vdict) elif vtype == "truthy": local_verification = validators.truthy(arg, **vdict) # 对于验证不为真或没有验证的 # 不为真的时候返回的是: ValidationFailure(......) if not local_verification: verification = False failed_type = vtype break # 有一条不为 True, 直接返回 False else: verification = True # 处理返回值 if verification not in(False, True): verification = False if not verification: return verification, failed_type else: return True, None
def test_returns_true_on_valid_uuid_object(value): assert uuid(value)
def test_import_with_non_uuids(self, user_id): assume(not validators.uuid(user_id)) with self.assertRaises(TypeError): pic_importer.picture_for(user_id)