Reputation: 886
I have an app that stores users and their posts. To view the page of a user, I want it to require authentication for a given user. I'm not quite sure how to implement this because before without DRF, I'd just check if the current user was the same as the id requested in the url like page/users/10. DRF generates tokens for each user which I have specified when they register with this:
class RegisterView(generics.GenericAPIView):
serializer_class = RegisterSerializer
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.save()
return Response({
"user": UserSerializer(user, context=self.get_serializer_context()).data,
"token": Token.objects.get(user=user).key
})
Each token keys to a user like here:
What I am wondering is how can I get each of these tokens to be used to authenticate the user. If the user logs in with his account, how will I be able to get the token and then pass it to the restricted views?
Here is one of the views that restricts access to only logged in users:
class CreateGroupView(APIView):
permission_classes = [IsAuthenticated]
serializer_class = GroupSerializer
# name = models.CharField(max_length=50)
# description = models.CharField(max_length=300)
# meeting_link = models.CharField(max_length=100)
def post(self, request, format=None):
self.request.session.create()
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
owner = User.objects.get(id=serializer.data.get('owner'))
name = serializer.data.get('name')
description = serializer.data.get('description')
meeting_link = serializer.data.get('meeting_link')
group = Group(owner=owner, description=description, meeting_link=meeting_link, name=name)
group.save()
return Response(GroupSerializer(course).data, status=status.HTTP_201_CREATED)
Here are some of my url patterns to show what I am working with
urlpatterns = [
path('viewgroup', views.GroupView.as_view()),
path('creategroup', views.CreateGroupView.as_view()),
path('register', views.RegisterView.as_view()),
]
Upvotes: 3
Views: 2909
Reputation: 1684
You will have to return the token to the user when they successfully login to their account and save that token in the localstorage
of that user.
Now that the user has access to the token
pass it as Authorization HTTP header
like this:
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
Now when you request the url
fetch(YOUR_URL, {
method: 'GET',
headers: {Accept: 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b'}
});
And now in your view you can simply access the user as request.user
.
You can read more at https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication
Upvotes: 1