Bearle / django_private_chat2

Chat app for Django, powered by Django Channels, Websockets & Asyncio
MIT License
295 stars 80 forks source link

Django Rest Framework Simple JWT getting anonymous user #30

Open devhusnain opened 2 years ago

devhusnain commented 2 years ago

Description

I want to use Rest Framework simpleJWT as authentication earlier I was using Django default authentication. Here are views currently I am getting AnonymousUser error, what changes do I need to get a user request from JWT Authenticated user. I want to get a request.user from a jWT Authenticated user. Please help me out.

Here are views

class MessagesModelList(ListView):
http_method_names = ['get', ]
paginate_by = getattr(settings, 'MESSAGES_PAGINATION', 500)

def get_queryset(self):
    if self.kwargs.get('dialog_with'):
        qs = MessageModel.objects \
            .filter(Q(recipient=self.request.user, sender=self.kwargs['dialog_with']) |
                    Q(sender=self.request.user, recipient=self.kwargs['dialog_with'])) \
            .select_related('sender', 'recipient')
    else:
        qs = MessageModel.objects.filter(Q(recipient=self.request.user) |
                                         Q(sender=self.request.user)).prefetch_related('sender', 'recipient', 'file')

    return qs.order_by('-created')

def render_to_response(self, context, **response_kwargs):
    user_pk = self.request.user.pk
    data = [serialize_message_model(i, user_pk)
            for i in context['object_list']]
    page: Page = context.pop('page_obj')
    paginator: Paginator = context.pop('paginator')
    return_data = {
        'page': page.number,
        'pages': paginator.num_pages,
        'data': data
    }
    return JsonResponse(return_data, **response_kwargs)

class DialogsModelList(ListView):

http_method_names = ['get', ]
paginate_by = getattr(settings, 'DIALOGS_PAGINATION', 20)

def get_queryset(self):
    qs = DialogsModel.objects.filter(Q(user1_id=self.request.user.pk) | Q(user2_id=self.request.user.pk)) \
        .select_related('user1', 'user2')
    return qs.order_by('-created')

def render_to_response(self, context, **response_kwargs):
    # TODO: add online status
    user_pk = self.request.user.pk
    data = [serialize_dialog_model(i, user_pk)
            for i in context['object_list']]
    page: Page = context.pop('page_obj')
    paginator: Paginator = context.pop('paginator')
    return_data = {
        'page': page.number,
        'pages': paginator.num_pages,
        'data': data
    }
    return JsonResponse(return_data, **response_kwargs)

class SelfInfoView(DetailView):

def get_object(self, queryset=None):
    return self.request.user

def render_to_response(self, context, **response_kwargs):
    user: AbstractBaseUser = context['object']
    data = {
        "username": user.get_username(),
        "pk": str(user.pk)
    }
    return JsonResponse(data, **response_kwargs)

class UploadView(CreateView):
http_method_names = ['post', ]
model = UploadedFile
form_class = UploadForm

def form_valid(self, form: UploadForm):
    self.object = UploadedFile.objects.create(
        uploaded_by=self.request.user, file=form.cleaned_data['file'])
    return JsonResponse(serialize_file_model(self.object))

def form_invalid(self, form: UploadForm):
    context = self.get_context_data(form=form)
    errors_json: str = context['form'].errors.get_json_data()
    return HttpResponseBadRequest(content=json.dumps({'errors': errors_json}))
acfuns commented 2 years ago

I meet this problem, My solution is (: add APIView and inherit it

from rest_framework.views import APIView
...

class DialogsModelList(ListView, APIView):
    http_method_names = ['get', ]
    paginate_by = getattr(settings, 'DIALOGS_PAGINATION', 20)

    def get_queryset(self):
        qs = DialogsModel.objects.filter(Q(user1_id=self.request.user.pk) | Q(user2_id=self.request.user.pk)) \
            .select_related('user1', 'user2')
        return qs.order_by('-created')

    def render_to_response(self, context, **response_kwargs):
        # TODO: add online status
        user_pk = self.request.user.pk
        print(self.request.user)
        data = [serialize_dialog_model(i, user_pk) for i in context['object_list']]
        page: Page = context.pop('page_obj')
        paginator: Paginator = context.pop('paginator')
        return_data = {
            'page': page.number,
            'pages': paginator.num_pages,
            'data': data
        }
        return JsonResponse(return_data, **response_kwargs)