def validate(self, attrs): if 'resource' in attrs: if 'project' not in attrs: raise ValidationError( '"project" is required when specifying "resource"') if 'secret_tokens' in attrs and len(attrs['secret_tokens']): if 'resource' not in attrs: raise ValidationError( '"resource" is required when specifying "secret_tokens"') names = attrs['secret_tokens'].split(',') instances = {} request = self.context.get('request') token_prefix = 'Token ' authorization = request.headers.get('AUTHORIZATION', '') user_token = authorization[len(token_prefix ):] if authorization.startswith( token_prefix) else None for item in get_secret_tokens(attrs['project'], attrs['resource'], settings.TOKEN, user_token): instances[item['name']] = item['value'] for name in names: if name not in instances: instances[name] = '' attrs['secret_tokens'] = instances if isinstance(attrs['headers'], dict): attrs['headers'] = dict( [[key, str(value)] for key, value in attrs['headers'].items()]) return attrs
def validation_error_from_database_error(e, model): if hasattr(e, 'orig'): if hasattr(e.orig, 'args') and hasattr(e.orig.args, '__getitem__'): if len(e.orig.args) == 1: message = e.orig.args[0] elif len(e.orig.args) == 2: message = e.orig.args[1] else: message = e.orig.args message = six.text_type(message) regex = [ [r'Key\s\((.+)\)=\((.+)\)\salready\sexists', 1, 2], # PostgreSQL [r'Duplicate\sentry\s\'(.+)\'\sfor key\s\'(.+)\'', 2, 1], # MySQL [r'UNIQUE\sconstraint\sfailed\:\s(.+)\.(.+)', 2, None] # SQLite ] for (r, field_index, value_index) in regex: match = re.search(r, message, re.IGNORECASE | re.MULTILINE) if match: mapper = inspect(model) columns = dict(map(lambda x: (x.key, x), mapper.columns)) column_name = match.group(field_index) if column_name in columns: error = dict() error[column_name] = ValidationError('record with the same value already exists') return ValidationError(error) return ValidationError(message) return ValidationError('Query failed')
def before_dispatch(self, request): super(APIView, self).before_dispatch(request) try: request.session = create_session(request) except Exception as e: raise ValidationError(str(e))
def to_internal_value_item(self, value): result = OrderedDict() errors = OrderedDict() for field in self.writable_fields: field_value = field.get_value(value) if field_value is empty: if self.partial or not field.required: continue validate_method = getattr(self, 'validate_' + field.field_name, None) try: validated_value = field.run_validation(field_value) if validate_method is not None: validated_value = validate_method(validated_value) result[field.field_name] = validated_value except ValidationError as e: errors[field.field_name] = e if errors: raise ValidationError(errors) return result
def submit(self): method = self.validated_data['method'] url = self.validated_data['url'] headers = self.validated_data['headers'] or [] query_params = self.validated_data['query_params'] or [] body = self.validated_data.get('body') if isinstance(headers, dict): headers = self.params_dict_to_list(headers) if isinstance(query_params, dict): query_params = self.params_dict_to_list(query_params) if 'secret_tokens' in self.validated_data: url, headers, query_params, body = self.interpolate( url, headers, query_params, body, '{-%s-}', self.validated_data['secret_tokens']) if 'context' in self.validated_data: url, headers, query_params, body = self.interpolate( url, headers, query_params, body, '{{%s}}', self.validated_data['context']) if body: body = body.encode('utf-8') headers = dict(map(lambda x: (x['name'], x['value']), headers)) query_params = list( map(lambda x: (x['name'], x['value']), query_params)) try: r = requests.request(method, url, headers=headers, params=query_params, data=body) response_headers = r.headers remove_headers = [ 'Access-Control-Allow-Origin', 'Access-Control-Allow-Methods', 'Access-Control-Allow-Headers', 'Access-Control-Expose-Headers', 'Access-Control-Allow-Credentials', 'Connection', 'Content-Encoding', 'Content-Length', 'Keep-Alive', 'Proxy-Authenticate', 'Proxy-Authorization', 'TE', 'Trailers', 'Transfer-Encoding', 'Upgrade' ] for header in remove_headers: if header in response_headers: del response_headers[header] response = Response(data=r.content, status=r.status_code, headers=response_headers) return response except Exception as e: raise ValidationError(e)
def error(self, key, **kwargs): """ A helper method that simply raises a validation error. """ try: msg = self.error_messages[key] except KeyError: class_name = self.__class__.__name__ raise AssertionError('Error with key={} is not found for class={}'.format(key, class_name)) message_string = msg.format(**kwargs) raise ValidationError(message_string, code=key)
def validate(self, attrs): if 'resource' in attrs: if 'project' not in attrs: raise ValidationError( '"project" is required when specifying "resource"') if 'secret_tokens' in attrs and len(attrs['secret_tokens']): if 'resource' not in attrs: raise ValidationError( '"resource" is required when specifying "secret_tokens"') names = attrs['secret_tokens'].split(',') attrs['secret_tokens'] = self.resolve_secret_tokens( names, attrs['project'], attrs['resource']) if isinstance(attrs['headers'], dict): attrs['headers'] = dict( [[key, str(value)] for key, value in attrs['headers'].items()]) return attrs
def is_valid(self, raise_exception=False): try: self.validated_data = self.run_validation(self.data) self.errors = None except ValidationError as e: self.validated_data = None self.errors = e.detail if self.errors and raise_exception: raise ValidationError(self.errors) return not bool(self.errors)
def validate_query(self, value): forbidden = ['insert', 'update', 'delete', 'grant', 'show'] for i in range(len(forbidden)): forbidden.append('({}'.format(forbidden[i])) if any(map(lambda x: ' {} '.format(value.lower()).find(' {} '.format(x)) != -1, forbidden)): raise ValidationError('forbidden query') i = 0 while value.find('%s') != -1: value = value.replace('%s', ':param_{}'.format(i), 1) i += 1 return value
def validate(self, attrs): forbidden = ['insert', 'update', 'delete', 'grant', 'show'] for i in range(len(forbidden)): forbidden.append('({}'.format(forbidden[i])) if any(map(lambda x: ' {} '.format(attrs['query'].lower()).find(' {} '.format(x)) != -1, forbidden)): raise ValidationError({'query': 'forbidden query'}) if attrs['v'] < 2: i = 0 while attrs['query'].find('%s') != -1: attrs['query'] = attrs['query'].replace('%s', ':param_{}'.format(i), 1) i += 1 return attrs