Reputation: 31
I would like to ask how I can do authentication and query tags limited to a specific user (owner) using Graphen Relay and Django JWT. Here is my Model:
class Tag(models.Model):
"""Tag to be used for a objective"""
name = models.CharField(max_length=255)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
related_name='tag',
on_delete=models.CASCADE,
)
Here is my Schema code:
class TagNode(DjangoObjectType):
class Meta:
model = Tag
filter_fields = ['name']
interfaces = (relay.Node,)
Here is my Query:
class Query(graphene.ObjectType):
tag = relay.Node.Field(TagNode)
all_tags = DjangoFilterConnectionField(TagNode)
def resolve_all_tags(self, info):
# context will reference to the Django request
print(info.context.user)
if not info.context.user.is_authenticated:
return Tag.objects.none()
else:
return Tag.objects.filter(user=info.context.user)
Here is the document for Django JWT: https://github.com/flavors/django-graphql-jwt but I do not know how to get the user (already use info.context.user) but it does not work, when I tried to add Authorization (JWT token) in the header or as an argument. It also does not work.
Upvotes: 3
Views: 2671
Reputation: 6019
Basically you are doing everything correctly and your user should be fetched successfully. I've just checked and it works in my case, I use JWT like a cookie but it doesn't matter.
Had you authorized your user when tried to get tags?
Because regarding JWT you need to authorize your user and receive the JWT token. Only after that the real user will be presented in the request when you call the tags query. Otherwise the user will be anonymous.
Upvotes: 3