I'm new to Django Rest and JWT token based authentication.
I'm using a package called djangorestframework_simplejwt
I have my frontend UI created and successfully authenticating users.
I am having one issue, when I create a new user, I am sending the user back in the response data and then in a promise hitting the authentication endpoint to retrieve my tokens.
This doesn't feel right and feels like something that the backend can take care of entirely.
On the front end -
return APIUtil.signup(user).then((user) => {
return APIUtil.authenticate(user.data)
}).then((user) => dispatch(authenticateUser(user)))
export const authenticate = (user) => {
return axios({
method: 'post',
url: 'http://localhost:8000/api/token/',
data: {
username: user.username,
password: user.password
}
});
}
export const signup = (user) => {
return axios({
method: 'post',
url: 'http://localhost:8000/signup/',
data: {
username: user.username,
password: user.password,
email: user.email
}
});
}
In my backend, I have a user viewset and serializer and with the django rest framework simple JWT package, I have the end point api/token/ which takes a user and returns their auth tokens.
I want to create the user and after creation, hit that endpoint on the backend, but I am not entirely sure the best way of doing this. I tried inheriting from the auth viewset in my user viewset, but wasn't successfully able to pass a post request to it.
Here is my user viewset
class UserViewSet(ModelViewSet):
model = User
queryset = model.objects.all()
serializer_class = serializers.UserSerializer
permission_classes = ([])
authentication_classes = ([])
def create(self, request, format=None):
user = serializers.UserSerializer(data=request.data,context={'request': request})
if user.is_valid():
new_user = user.save()
new_user.password = request.data['password']
return Response({'username': new_user.username, 'password': new_user.password}, status=status.HTTP_201_CREATED)
else:
return Response(user.errors, status=status.HTTP_400_BAD_REQUEST)
Thanks in advance for any help/direction.