Custom GraphQL String Field Parameter
I'm required to sanitize all my inputs coming in via the GraphQL endpoint and remove potential malicious stuff (No the Django build-in mechanism are not enough, it shall be actively removed).
As I do not want to add the sanitization for every mutation manually, I thought about creating a custom graphene.String()
class called clean_string.String()
including nh3.clean()
for the sanitization so I must only exchange singe lines:
import graphene
import nh3
from graphql import StringValueNode, Undefined
class String(graphene.String):
@classmethod
def parse_value(cls, value):
if isinstance(value, str):
cleaned_value = nh3.clean(value)
else:
cleaned_value = value
return super(String, cls).parse_value(cleaned_value)
@staticmethod
def parse_literal(ast, _variables=None):
if isinstance(ast, StringValueNode):
return nh3.clean(ast.value)
return Undefined
In my schema.py I have then
import clean_string
class CreateUser(graphene.Mutation):
user = graphene.Field(UserType)
class Arguments:
email = clean_string.String(required=True)
password = clean_string.String(required=True)
@staticmethod
def mutate(_, info, email, password)
# sanitized email & password
But this does not get called at all.
When I have inputs like <img>password</img>
and do the sanitation manually the result will be <img>password
but with my custom class nothing happens.
Does anyone have a clue how to resolve this? Thanks in advance!