Ejemplo n.º 1
0
    def post(self, request):
        """
        it verifies the credentials, if credentials were matched then returns data in json format, else throws exception
        :return: return json data if credentials are matched
        """
        try:
            data = request.data
            if Validation.validate_data(data):
                serializer = self.serializer_class(data=data)
                serializer.is_valid(raise_exception=True)
                user = Account.objects.get(email=serializer.data['email'])
                token = Encrypt.encode(user.id)
                cache = Cache.get_instance()
                cache.set_cache("TOKEN_" + str(user.id) + "_AUTH", token)

                response = utils.manage_response(status=True, message="login successful",
                                                 status_code=status.HTTP_200_OK)
                response.__setitem__(header="HTTP_AUTHORIZATION", value=token)
                return response
        except MyCustomError as e:
            return utils.manage_response(status=False, message=e.message, exception=str(e),
                                         status_code=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return utils.manage_response(status=False, message='some other issue please try after some time',
                                         exception=str(e),
                                         status_code=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 2
0
 def post(self, request):
     """
     it takes user details and it will create account for user
     :rtype: user data and its status if credentials are valid
     """
     try:
         data = request.data
         if Validation.validate_data(data) and Validation.validate_register(data):
             serializer = self.serializer_class(data=data)
             serializer.is_valid(raise_exception=True)
             serializer.save()
             user_data = serializer.data
             user = Account.objects.get(email=user_data['email'])
             token = RefreshToken.for_user(user).access_token
             absolute_url = request.build_absolute_uri(reverse('email-verify')) + "?token=" + str(token)
             email_body = 'Hi ' + user.user_name + \
                          ', \n Use the link below to verify your email \n' + absolute_url
             data = {'email_body': email_body, 'to_email': user.email,
                     'email_subject': 'Verify your email'}
             send_email.delay(data)
             response = utils.manage_response(status=True, message="Account created successfully", data=user_data,
                                              status_code=status.HTTP_201_CREATED)
             response.__setitem__(header="HTTP_AUTHORIZATION", value=token)
             return response
     except MyCustomError as e:
         return utils.manage_response(status=False, message=e.message, exception=str(e),
                                      status_code=status.HTTP_400_BAD_REQUEST)
     except Exception as e:
         return utils.manage_response(status=False, message='some other issue please try after some time',
                                      exception=str(e),
                                      status_code=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 3
0
    def put(self, request, *args, **kwargs):
        """
        takes label data as input and if the data is valid then it replaces the data in database
        :rtype:Response returns success or failure message along with status
        """

        try:
            item = Label.objects.filter(Q(pk=kwargs.get('pk')) &
                                            (Q(user=kwargs.get('user').id))).exclude(is_deleted=True).first()
            if item is None:
                raise MyCustomError(ExceptionType.UnAuthorized, "No such note exist")
            serializer = LabelSerializer(item, data=request.data, partial=True)

            if serializer.is_valid():
                serializer.save()
                return utils.manage_response(status=True, message="Label Update Successfully", data=serializer.data,
                                             status_code=status.HTTP_201_CREATED)
            raise MyCustomError(ExceptionType.LengthError, "title should be less than 50 characters")

        except MyCustomError as e:
            return utils.manage_response(status=False, message=e.message, exception=str(e),
                                         status_code=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return utils.manage_response(status=False, message='some other issue please try after some time',
                                         exception=str(e),
                                         status_code=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 4
0
    def get(self, *args, **kwargs):
        """
        takes key as input and if data exists for that key then it returns the data from database
        :rtype:Response returns data along if it is success else returns failure message along with status
        """

        try:

            if kwargs.get('pk'):
                item = Label.objects.filter(Q(pk=kwargs.get('pk')) &
                                            (Q(user=kwargs.get('user').id))).exclude(is_deleted=True).first()
                if item is None:
                    raise MyCustomError(ExceptionType.UnAuthorized, "No such note exist")
                serializer = LabelSerializer(item)
                return utils.manage_response(status=True, message="Label retrieved successfully",
                                             data=serializer.data,
                                             status_code=status.HTTP_200_OK)

            else:
                labels = Label.objects.filter(Q(user=kwargs.get('user').id))
                serializer = LabelSerializer(labels, many=True)
                return utils.manage_response(status=True, message="Labels retrieved successfully",
                                             data=serializer.data,
                                             status_code=status.HTTP_200_OK)
        except MyCustomError as e:
            return utils.manage_response(status=False, message=e.message, exception=str(e),
                                         status_code=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return utils.manage_response(status=False, message='some other issue please try after some time',
                                         exception=str(e),
                                         status_code=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 5
0
 def patch(self, request):
     """
     it take new password and confirm password and if the password matches all criteria then it will set new password
     :rtype: data of the user and its success status
     """
     try:
         serializer = self.serializer_class(data=request.data)
         serializer.is_valid(raise_exception=True)
         return utils.manage_response(status=True, message='Password reset success',
                                      status_code=status.HTTP_200_OK)
     except MyCustomError as e:
         return utils.manage_response(status=False, message=e.message, exception=str(e),
                                      status_code=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 6
0
    def get(self, request):

        """
        it verifies for credentials, if credentials are in correct format then after email verification user will have access to login
        :rtype: user data and its status if credentials are valid
        """
        token = request.GET.get('token')
        result = {'message': 'some other issue',
                  'status': False}
        try:
            payload = jwt.decode(token, settings.SECRET_KEY)
            user = Account.objects.get(id=payload['user_id'])
            if not user.is_verified:
                user.is_verified = True
                user.is_active = True
                user.save()
                result['message'] = 'Successfully activated'
                result['status'] = True
                return utils.manage_response(status=result['status'], message=result['message'],
                                             status_code=status.HTTP_200_OK)
            else:
                result['message'] = 'email is already verified'
                return utils.manage_response(status=result['status'], message=result['message'],
                                             status_code=status.HTTP_400_BAD_REQUEST)

        except jwt.ExpiredSignatureError as e:
            result['message'] = 'Activation Expired'
            return utils.manage_response(status=result['status'], message=result['message'],
                                         exception=str(e),
                                         status_code=status.HTTP_400_BAD_REQUEST)
        except jwt.exceptions.DecodeError as e:
            result['message'] = 'Invalid Token'
            return utils.manage_response(status=result['status'], message=result['message'],
                                         exception=str(e),
                                         status_code=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return utils.manage_response(status=result['status'], message=result['message'],
                                         exception=str(e),
                                         status_code=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 7
0
    def delete(self, *args, **kwargs):
        """
        takes key as input inside kwargs and if data exists for that key then it returns the delete that data from database
        :rtype:Response returns success or failure message along with status
        """

        try:
            item = Label.objects.filter(Q(pk=kwargs.get('pk')) &
                                            (Q(user=kwargs.get('user').id))).exclude(is_deleted=True).first()
            if item is None:
                raise MyCustomError(ExceptionType.UnAuthorized, "No such note exist")

            item.soft_delete()
            return utils.manage_response(status=True, message="Label Deleted Successfully",
                                             status_code=status.HTTP_202_ACCEPTED)
        except MyCustomError as e:
            return utils.manage_response(status=False, message=e.message, exception=str(e),
                                         status_code=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return utils.manage_response(status=False, message='some other issue please try after some time',
                                         exception=str(e),
                                         status_code=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 8
0
    def post(self, request):
        """
        it takes email id as input and sends verification email link
        :rtype: it returns a response message saying verification link is sent to mail
        """
        result = {'message': 'some other issue',
                  'status': False}
        try:
            email = request.data.get('email', '')

            if Account.objects.filter(email=email).exists():
                user = Account.objects.get(email=email)
                uidb64 = urlsafe_base64_encode(smart_bytes(user.id))
                token = PasswordResetTokenGenerator().make_token(user)
                redirect_url = request.build_absolute_uri(reverse('password-reset-complete'))
                email_body = 'Hello, \n Your token number is : ' + token + ' \n your uidb64 code is ' + uidb64 + ' \n Use link below to reset your password  \n' + "?redirect_url=" + redirect_url
                data = {'email_body': email_body, 'to_email': user.email,
                        'email_subject': 'Reset your passsword'}
                send_email.delay(data)
                result['message'] = 'We have sent you a link to reset your password'
                result['status'] = True
                response = Response(data=result, status=status.HTTP_200_OK)

                response.__setitem__(header="HTTP_AUTHORIZATION", value=data)
                logging.debug('{}, status_code = {}, token = {}'.format(result, status.HTTP_200_OK, token))
                return response
                # return utils.manage_response(status=result['status'], message=result['message'],
                #                              status_code=status.HTTP_200_OK)
            else:
                result['message'] = "Email id you have entered doesn't exist"
                logging.debug('{}'.format(result))
                return utils.manage_response(status=result['status'], message=result['message'],
                                             status_code=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return utils.manage_response(status=result['status'], message=result['message'],
                                         exception=str(e),
                                         status_code=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 9
0
    def post(self, request, *args, **kwargs):
        """
        takes label data as input and if the data is valid then it stores the data in database
        :rtype:Response returns success or failure message along with status
        """

        try:
            _mutable = request.data._mutable
            request.data._mutable = True
            request.data['user'] = str(kwargs.get('user').id)
            request.data._mutable = _mutable
            serializer = LabelSerializer(data=request.data)
            if serializer.is_valid():
                serializer.save()
                return utils.manage_response(status=True, message='Label Added Successfully', data=serializer.data,
                                             status_code=status.HTTP_201_CREATED)
            raise MyCustomError(ExceptionType.LengthError, "maximum length of label name should be 50 characters")
        except MyCustomError as e:
            return utils.manage_response(status=False, message=e.message, exception=str(e),
                                         status_code=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return utils.manage_response(status=False, message='some other issue please try after some time',
                                         exception=str(e),
                                         status_code=status.HTTP_400_BAD_REQUEST)