Django restful API - get user id with token - django

How to obtain User ID from Django API having authentication token?
Basically, I want to send authentication token and get back User id.
I have tried this solution: How can I return user ID with token in Django?
but it is returning token with provided username and password, which is not what I want.

#myapp/views.py
class UserIdViewSet(viewsets.ModelViewSet):
serializer_class = UserSerializer
def get_queryset(self):
return User.objects.filter(id=self.request.user.id)
#myapp/urls.py
router.register(r'api/user-id', userviews.UserIdViewSet, base_name="UserId")
sort out the problem. Basically created View set and sort this out against current user.

What type of authentication you use ?
If for example, you use TokenAuthentication from rest_framework, you can have a look how this class implements request authentication.
You can find there methods authenticate and authenticate_credentials and I believe that there - you will find your answer how to get the user.

In the perform_create method you can assign the user to your model
class EmailViewSet(viewsets.ModelViewSet):
authentication_classes = (TokenAuthentication)
permission_classes = (IsAuthenticated,)
queryset = Email.objects.all()
serializer_class = EmailSerializer
def perform_create(self, serializer):
serializer.save(user=self.request.user)

Related

Why i'm unable to autherize in my django app?

i'm testing my api. if the user is authenticated then he can able to see the projects otherwise return not authorizated response. I'm passing my jwt token in header but still unable to autherize...?
class ListProjectAPIView(generics.ListAPIView):
"""This endpoint list all of the available Projects from the database"""
permission_classes = [IsAuthenticated,]
queryset = Project.objects.get_all()
serializer_class = serializers.ProjectSerializer

Django Rest-framework, JWT authentication

I'm newbie in Django Restframework. I use JWT to make login, register API, everythings worked well, I want to GET a user information with authenticated (tokens). This is my code for UserViewSet
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
authentication_classes = [IsAuthenticated,]
I've tested on Postman but i received: "'IsAuthenticated' object has no attributes 'authenticate'"
REST_FRAMEWORK = {
'NONE_FIELD_ERRORS_KEY':'error',
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
}
Could you please to help me to solve this promblem? Thank you very much.
IsAuthenticated is not an authentication class. It's a permission class.
You would put it in permission_classes to allow any authenticated user access to that view set, while authentication (the mechanism of figuring out who the user for that request is) would be handled by that default JWT authentication:
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = [IsAuthenticated,]

django_rest_framework, how to update user profile by token?

I have models user and profile(foreight key to user).
Can someone show me(or explain) example how in viewset, update user profile by token.
I send token in HTTP header that name is: "Authorization", and value: "Token " + (token_string).
class ProfileViewSet(viewsets.ModelViewSet):
queryset = Profile.objects.all()
serializer_class = Profileerializer
def update(self, request, pk=None):
# Get user by token and update profile
Based on what you said, I'll asume that you are using Django Rest Framework Token Authentication
If so,
The request.user property will typically be set to an instance of the contrib.auth package's User class.
The request.auth property is used for any additional authentication information, for example, it may be used to represent an authentication token that the request was signed with.
That way, you should be able to do something like:
def update(self, request, pk=None):
user = request.user
profile = user.profile
# Update with user here

Using different authentication for different operations in ModelViewSet in Django REST framework

I have the following ModelViewSet
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all()
serializer_class = UserSerializer
authentication_classes = (TokenAuthentication,)
permission_classes = (permissions.IsAuthenticated, MyUserPermissions)
I want the create method (POST on /users/) to not ask for any authentication. How can I override the authentication_classes in this case? I'm talking about ModelViewSet not generic API views.
I want the create method (POST on /users/) to not ask for any authentication.
Actually that's not quite what you want. You want POST on users to not require any permissions, which will have the effect that either authenticated or unauthenticated requests will succeed.
I'd suggest overriding your permission classes so that they always allow POST requests. Follow the custom permissions documentation for more info on that.
Essentially you'll have something like:
class IsAuthenticatedOrCreate(permissions.IsAuthenticated):
def has_permission(self, request, view):
if request.method == 'POST':
return True
return super(IsAuthenticatedOrCreate, self).has_permission(request, view)
And probably something similar for your other permission class too.

Build tastypie resource in view?

I already know how to create ModelResource in tastypie. For example, I have UserResource in resources.py and User in models.py. However in views.py, I have a view called match_user where it takes the list of all user and match to request.user. It return a render_to_response html called mymatch.html. Everything works on the browser but I want to create an API for this particular match_user. How can I do that?
Thank you
I think the following answers your question:
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
resource_name = "user"
authentication = SessionAuthentication()
# User is only authorized to view his own details
def apply_authorization_limits(self, request, object_list):
return object_list.filter(pk=request.user.pk)
Session authentication would work if the user has an active session and is already logged in. For more authentication options, see https://django-tastypie.readthedocs.org/en/latest/authentication_authorization.html?highlight=authentication#authentication-options