Beispiel #1
0
    def get(self, request, **kwargs):
        """[displays specific label and all labels depends on user input]
        args: kwargs[userid]: user id of the user decoded from token
        Returns:
            Response: status , message and data
            @type: status: Boolean, message:str, data: list
        """
        try:
            current_user = kwargs['userid']

            if kwargs.get('pk'):
                label = Label.objects.get(Q(id=kwargs.get('pk')),
                                          Q(is_deleted=False),
                                          Q(user=current_user))
                serializer = LabelSerializer(label)

            else:
                labels = Label.objects.filter(
                    Q(user=current_user)).exclude(is_deleted=True)
                serializer = LabelSerializer(labels, many=True)

            result = utils.manage_response(status=True,
                                           message='retrieved successfully',
                                           data=serializer.data,
                                           log='retrieved labels',
                                           logger_obj=logger)
            return Response(result, status.HTTP_200_OK)

        except Exception as e:
            result = utils.manage_response(
                status=False,
                message='Something label went wrong.Please try again.',
                log=str(e),
                logger_obj=logger)
            return Response(result, status.HTTP_404_NOT_FOUND)
Beispiel #2
0
    def delete(self, request, pk, **kwargs):
        """[soft deletes existing label]
        Returns:
            [Response]: [confirmation message and status]
        """
        try:
            label = Label.objects.get(Q(id=pk), Q(is_deleted=False),
                                      Q(user=kwargs['userid']))

            label.soft_delete()
            result = utils.manage_response(
                status=True,
                message='label deleted successfully',
                log=('deleted label with id: {}'.format(pk)),
                logger_obj=logger)
            return Response(result, status.HTTP_204_NO_CONTENT)

        except Label.DoesNotExist as e:

            result = utils.manage_response(status=False,
                                           message='label not found',
                                           log=str(e),
                                           logger_obj=logger)
            return Response(result, status.HTTP_404_NOT_FOUND)
        except Exception as e:

            result = utils.manage_response(
                status=False,
                message='Something went wrong.Please try again.',
                log=str(e),
                logger_obj=logger)
            return Response(result, status.HTTP_400_BAD_REQUEST)
Beispiel #3
0
    def post(self, request):
        """
        Created method to send base64 encoded token along with user details to email
            for password reset

        Returns:
            Response message along with status code
        """
        email = request.data.get('email', '')
        try:
            if User.objects.filter(email=email).exists():
                user = User.objects.get(email=email)
                uidb64 = urlsafe_base64_encode(smart_bytes(user.id))
                token = PasswordResetTokenGenerator().make_token(user)
                current_site = get_current_site(request=request).domain
                relativeLink = reverse('password-reset-confirm',
                                       kwargs={
                                           'uidb64': uidb64,
                                           'token': token
                                       })
                redirect_url = request.data.get('redirect_url', '')
                absurl = 'http://' + current_site + relativeLink
                email_body = 'Hello, \n Use link below to reset your password  \n' + absurl + "?redirect_url=" + redirect_url
                data = {
                    'email_body': email_body,
                    'to_email': user.email,
                    'email_subject': 'Reset your passsword'
                }
                send_email.delay(data)
            result = utils.manage_response(
                status=True,
                message='A reset password link has been sent successfully',
                data=user.email,
                log='Password reset link has been sent ',
                logger_obj=logger)
            return Response(result, status=status.HTTP_200_OK)
        except ValidationError as e:
            result = utils.manage_response(
                status=False,
                message='Please enter proper details for each field',
                log=str(e),
                logger_obj=logger)
            return Response(result, status.HTTP_400_BAD_REQUEST)
        except EmptyFieldError as e:
            result = utils.manage_response(
                status=False,
                message='Please dont leave the field empty',
                log=str(e),
                logger_obj=logger)
            return Response(result, status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            result = utils.manage_response(status=False,
                                           message='Something went wrong',
                                           log=str(e),
                                           logger_obj=logger)
            return Response(result, status.HTTP_400_BAD_REQUEST)
Beispiel #4
0
    def put(self, request, pk, **kwargs):
        """
        A method to update labels
        @param request: name: name of label
                        @type:str

        @param kwargs[userid]: user id of the user decoded from token
        @type kwargs[userid]: int

        @return: status, message,data and status code
        @rtype: status: boolean, message: str, data:list
        """
        try:

            label = Label.objects.get(Q(id=pk), Q(is_deleted=False),
                                      Q(user=kwargs['userid']))

            serializer = LabelSerializer(label,
                                         data=request.data,
                                         partial=True)

            if serializer.is_valid(raise_exception=True):
                serializer.save()
            else:
                result = utils.manage_response(status=False,
                                               message=serializer.errors,
                                               log=serializer.errors,
                                               logger_obj=logger)
                return Response(result, status.HTTP_400_BAD_REQUEST)

            result = utils.manage_response(status=True,
                                           message='updated successfully',
                                           data=serializer.data,
                                           log='updated label',
                                           logger_obj=logger)
            return Response(result, status.HTTP_200_OK)

        except Label.DoesNotExist as e:

            result = utils.manage_response(status=False,
                                           message='label not found',
                                           log=str(e),
                                           logger_obj=logger)
            return Response(result, status.HTTP_404_NOT_FOUND)
        except Exception as e:

            result = utils.manage_response(
                status=False,
                message='Something went wrong.Please try again.',
                log=str(e),
                logger_obj=logger)
            return Response(result, status.HTTP_400_BAD_REQUEST)
Beispiel #5
0
    def post(self, request):
        """
        Defined post method which register users with valid email and oher inputs.
        It checks the authenticity of the email by sending a token to the respective email

       Returns: The serialized user details in JSON format
        """
        try:
            user = request.data
            serializer = self.serializer_class(data=user)
            serializer.is_valid(raise_exception=True)
            serializer.save()
            user_data = serializer.data
            user = User.objects.get(email=user_data['email'])
            token = RefreshToken.for_user(user).access_token
            current_site = get_current_site(request).domain
            relativeLink = reverse('email-verify')
            absurl = 'http://' + current_site + relativeLink + "?token=" + str(
                token)
            email_body = 'Hi ' + user.user_name + \
                         ' Use the link below to verify your email \n' + absurl
            data = {
                'email_body': email_body,
                'to_email': user.email,
                'email_subject': 'Verify your email'
            }
            send_email.delay(data)
            result = utils.manage_response(
                status=True,
                message='An email has been sent for verification',
                data=serializer.data,
                log='User registration request has been recieved',
                logger_obj=logger)
            return Response(result, status=status.HTTP_201_CREATED)
        except ValidationError as e:
            result = utils.manage_response(
                status=False,
                message='Please enter proper details for each field',
                log=str(e),
                logger_obj=logger)
            return Response(result, status.HTTP_400_BAD_REQUEST)
        except EmptyFieldError as e:
            result = utils.manage_response(
                status=False,
                message='Please dont leave the field empty',
                log=str(e),
                logger_obj=logger)
            return Response(result, status.HTTP_400_BAD_REQUEST)
        except Exception:
            return Response(default_error_message,
                            status=status.HTTP_400_BAD_REQUEST)
Beispiel #6
0
 def get(self, request):
     """
     Created method for verifying email and successfully registering the user
     Returns:
        response message with status code
     """
     token = request.GET.get('token')  # retrieving query params token
     try:
         payload = jwt.decode(token, settings.SECRET_KEY)
         user = User.objects.get(id=payload['user_id'])
         if not user.is_verified:
             user.is_verified = True
             user.is_active = True
             user.save()
         result = utils.manage_response(
             status=True,
             message='Email has been successfully activated',
             data=user.email,
             log='Email verification has been sucessful',
             logger_obj=logger)
         return Response(result, status=status.HTTP_200_OK)
     except jwt.ExpiredSignatureError as identifier:
         logging.exception('Exception due to expired signature')
         return Response({'error': 'Activation Expired'},
                         status=status.HTTP_400_BAD_REQUEST)
     except jwt.exceptions.DecodeError as identifier:
         logging.exception('Exception due to error in decoding')
         return Response({'error': 'Invalid token'},
                         status=status.HTTP_400_BAD_REQUEST)
     except Exception:
         logging.exception('Exception due to other reasons')
         return Response(default_error_message,
                         status=status.HTTP_400_BAD_REQUEST)
Beispiel #7
0
    def post(self, request, **kwargs):
        """
        A method to post labels of the user
        @param request: name: name for the label
                        @type:str

        @param kwargs[userid]: user id of the user decoded from token
        @type kwargs[userid]: int

        @return: status, message and status code
        @rtype: status: boolean, message: str
        """
        try:
            utils.set_user(request, kwargs['userid'])
            serializer = LabelSerializer(data=request.data)
            if serializer.is_valid(
                    raise_exception=True
            ):  # Return a 400 response if the data was invalid.
                serializer.save()
                result = utils.manage_response(status=True,
                                               message='created successfully',
                                               data=serializer.data,
                                               log='created new label',
                                               logger_obj=logger)
                return Response(result, status.HTTP_201_CREATED)
            else:

                result = utils.manage_response(status=False,
                                               message=serializer.errors,
                                               log=serializer.errors,
                                               logger_obj=logger)
                return Response(result, status.HTTP_400_BAD_REQUEST)
        except Label.DoesNotExist as e:

            result = utils.manage_response(status=False,
                                           message='label not found',
                                           log=str(e),
                                           logger_obj=logger)
            return Response(result, status.HTTP_404_NOT_FOUND)
        except Exception as e:
            result = utils.manage_response(status=False,
                                           message=str(e),
                                           log=str(e),
                                           logger_obj=logger)
            return Response(result, status.HTTP_400_BAD_REQUEST)
Beispiel #8
0
    def patch(self, request):
        """
        Created a method to set a new password for existing user

        Args:
            request : The request given by user to set the new password

        Returns:
            Response message with status code
        """
        try:
            serializer = self.serializer_class(data=request.data)
            serializer.is_valid(raise_exception=True)
            result = utils.manage_response(
                status=True,
                message='Password reset successfully',
                data=serializer.data,
                log='Password reset has been done ',
                logger_obj=logger)
            return Response(result, status=status.HTTP_200_OK)
        except ValidationError as e:
            result = utils.manage_response(
                status=False,
                message='Please enter proper details for each field',
                log=str(e),
                logger_obj=logger)
            return Response(result, status.HTTP_400_BAD_REQUEST)
        except EmptyFieldError as e:
            result = utils.manage_response(
                status=False,
                message='Please dont leave the field empty',
                log=str(e),
                logger_obj=logger)
            return Response(result, status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            result = utils.manage_response(
                status=False,
                message='Something went wrong. Please try again later',
                log=str(e),
                logger_obj=logger)
            return Response(result, status.HTTP_400_BAD_REQUEST)
Beispiel #9
0
 def post(self, request):
     """[validates user email and password, sets user id in cache]
     Returns:
         [dictionary]: [token]
     """
     try:
         serializer = self.serializer_class(data=request.data)
         serializer.is_valid(raise_exception=True)
         user = User.objects.get(email=serializer.data['email'])
         token = Encrypt.encode(user.id)
         cache = Cache()
         cache.set_cache("TOKEN_" + str(user.id) + "_AUTH", token)
         result = utils.manage_response(status=True,
                                        message='Token generated',
                                        data=token,
                                        log=serializer.data,
                                        logger_obj=logger)
         return Response(result, status=status.HTTP_200_OK)
     except User.DoesNotExist as e:
         result = utils.manage_response(status=False,
                                        message='Account does not exist',
                                        log=str(e),
                                        logger_obj=logger)
         return Response(result, status.HTTP_400_BAD_REQUEST)
     except AuthenticationFailed as e:
         result = utils.manage_response(
             status=False,
             message='Please enter a valid token',
             log=str(e),
             logger_obj=logger)
         return Response(result, status.HTTP_400_BAD_REQUEST)
     except Exception as e:
         result = utils.manage_response(
             status=False,
             message='some other issue.Please try again',
             log=str(e),
             logger_obj=logger)
         return Response(result, status.HTTP_400_BAD_REQUEST)