api.py 1.28 KB
from django.contrib.auth.tokens import default_token_generator
from rest_framework import mixins, viewsets, status
from rest_framework.decorators import action
from rest_framework.exceptions import ValidationError
from rest_framework.parsers import JSONParser
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.response import Response

from usuario.models import Usuario
from usuario.serializers import UsuarioSerializer, CambiarClaveSecretaSerializer


class UsuarioViewSet(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet):
    queryset = Usuario.objects.all()
    permission_classes = (IsAuthenticated,)
    serializer_class = UsuarioSerializer

    def get_object(self, base_method=False):
        user = self.request.user
        if base_method:
            user = super().get_object()

        return user

    @action(
        methods=('patch',),
        detail=False,
        url_path='cambiar-clave-secreta',
        parser_classes=(JSONParser,),
        serializer_class=CambiarClaveSecretaSerializer
    )
    def cambiar_clave_secreta(self, request):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(status=status.HTTP_200_OK)