def custom_exception_handler(exc, context):

    error_response = exception_handler(exc, context)
    if error_response is not None:
        error = error_response.data
        if isinstance(error, list) and error:
            if isinstance(error[0], dict):
                error_response.data = helper.getNegativeResponse(
                        helper.getErrorMessage(error), 
                        error_response.status_code
                    )

            elif isinstance(error[0], str):
                error_response.data = helper.getNegativeResponse(
                        error[0],
                        error_response.status_code
                    )

        if isinstance(error, dict):
            error_message = helper.getFirstErrorMessage(error)
            if error_message in constants.EXCEPTION_HANDLER:
                if error_message in constants.EXCEPTION_RESPONSE_CODE:
                    error_response.data = helper.getNegativeResponse(constants.EXCEPTION_HANDLER[error_message], constants.EXCEPTION_RESPONSE_CODE[error_message])
                    error_response.status_code = constants.EXCEPTION_RESPONSE_CODE[error_message]
                else:
                    error_response.data = helper.getNegativeResponse(constants.EXCEPTION_HANDLER[error_message], error_response.status_code)
            else:
                error_response.data = helper.getNegativeResponse(
                        helper.getErrorMessage(error), 
                        error_response.status_code
                    )

    return error_response
Example #2
0
    def post(self, request):
        user_signin_ser = UserSignInSerializer(data=request.data)
        user_signin_ser.is_valid(raise_exception=True)
        validated_data = user_signin_ser.validated_data
        try:
            user = User.objects.get(phone=validated_data['mobile_number'])
        except:
            response = helper.getNegativeResponse(
                'Mobile number or password is incorrect')
            return Response(response, status=response['statusCode'])
            # raise ValidationError('Mobile number or password is incorrect', code="002")

        if not user.check_password(validated_data['password']):
            response = helper.getNegativeResponse(
                'Mobile number or password is incorrect')
            return Response(response, status=response['statusCode'])
            # raise ValidationError('Mobile number or password is incorrect')

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        response = helper.getPositiveResponse("Valid user.", token)
        # response = get_response('Valid user.',BaseAPIView.PASS_RESPONSE_STATUS,BaseAPIView.SUCCESS_CODE,token)
        return Response(response)
Example #3
0
    def getValidationErrorMessage(self, error, status_code, is_message=False):
        if isinstance(error, list):
            if isinstance(error[0], dict):
                error_message = helper.getFirstErrorMessage(error[0])
                if error_message in constants.EXCEPTION_HANDLER:
                    response = helper.getNegativeResponse(constants.EXCEPTION_HANDLER[error_message], status_code)
                else:
                    if is_message == False:
                        response = helper.getNegativeResponse(helper.getErrorMessage(error[0]), status_code)
                    if is_message == True:
                        response = helper.getNegativeResponse(error_message, status_code)

            if isinstance(error[0], str):
                if error[0] in constants.EXCEPTION_HANDLER:
                    response = helper.getNegativeResponse(constants.EXCEPTION_HANDLER[error[0]], status_code)
                else:
                    response = helper.getNegativeResponse(error[0], status_code)

        elif isinstance(error, dict):
            error_message = helper.getFirstErrorMessage(error)
            if error_message in constants.EXCEPTION_HANDLER:
                response = helper.getNegativeResponse(constants.EXCEPTION_HANDLER[error_message], status_code)
            else:
                if is_message == False:                    
                    response = helper.getNegativeResponse(helper.getErrorMessage(error), status_code)
                if is_message == True:
                    response = helper.getNegativeResponse(error_message, status_code)

        return response
Example #4
0
def sendNotification(title, body, data, token):
    print(token)
    """
    @desc: Send notification
    @param: data (dictionary)
        1) title (string)
        2) body (string)
        3) data (dict with any format)
        4) token (string)
    @return:
        Dictionary: {'status' : SUCCESS|FAIL, 'msg' : (string), 'status_code' : (int), data : (dict)}
    """
  
    try:
        notification = messaging.Notification(title=title, body=body)
        web_notification = messaging.WebpushNotification(icon=constants.NOTIFICATION_ICON)
        web_push_config = messaging.WebpushConfig(notification=web_notification)
        message = messaging.Message(
            notification=notification,
            data=data,
            token=token,
            webpush=web_push_config
        )
        message_id = firebase_admin.messaging.send(message)
        print(message_id)
        return helper.getPositiveResponse("Message send successfully",message_id)
    except Exception as e:
        return helper.getNegativeResponse("Message send failed")
Example #5
0
    def post(self, request):
        forgot_password_serializer = ForgotpasswordSerializer(
            data=request.data)
        forgot_password_serializer.is_valid(raise_exception=True)

        validated_data = forgot_password_serializer.validated_data
        verification_token = helper.randomGeneratorCode()

        try:
            user = User.objects.get(phone=validated_data['mobile_number'])

            try:
                user_verification = UserVerification.objects.get(user=user)
                user_verification.verification_token = verification_token
                user_verification.save()
            except UserVerification.DoesNotExist:
                user_verification = UserVerification(
                    verification_token=verification_token, user=user)
                user_verification.save()

            token = {
                'set_password_token': user_verification.verification_token
            }

            response = helper.getPositiveResponse('', token)
        except User.DoesNotExist:
            response = helper.getNegativeResponse("User does not exist")
        return Response(response)
Example #6
0
    def post(self, request):
        if 'business_photo' not in request.data:
            response = helper.getNegativeResponse('business photo is require')
            return Response(response, status=response['statusCode'])
            # raise ParseError("Empty content")

        f = request.data['business_photo']

        try:
            img = Image.open(f)
            img.verify()
        except:
            response = helper.getNegativeResponse('Unsupported image type')
            return Response(response, status=response['statusCode'])
            # raise ParseError("Unsupported image type")

        request.user.profile_photo = f
        request.user.save()
        data = {'business_photo': request.user.profile_photo.url}
        response = helper.getPositiveResponse("Profile updated successfully",
                                              data)
        return Response(response, status=200)
Example #7
0
    def delete(self, request):
        try:
            user_remove_serializer = UserRemoveSerializer(data=request.data)
            print(user_remove_serializer)
            user_remove_serializer.is_valid(raise_exception=True)
            validated_data = user_remove_serializer.validated_data

            user = User.objects.get(id=validated_data['user_id'])
            user.delete()
            response = helper.getPositiveResponse("User Deleted")
        except User.DoesNotExist:
            response = helper.getNegativeResponse("User does not exist")
        return Response(response)
Example #8
0
    def put(self, request):
        response = {}
        user = request.user
        passward_serializer = UserPasswordUpdateSerializer(data=request.data)
        passward_serializer.is_valid(raise_exception=True)

        password_data = passward_serializer.validated_data
        if user.check_password(password_data['oldPassword']) == True:
            if password_data['password'] != password_data[
                    'passwordConfirmation']:
                response = helper.getNegativeResponse(
                    'Password and confirmpassword did not match')
                return Response(response, status=response['statusCode'])
                # raise ValidationError('Password and confirmpassword did not match')
            else:
                user.set_password(password_data['password'])
                user.save()
        else:
            response = helper.getNegativeResponse('Old password is not valid.')
            return Response(response, status=response['statusCode'])
            # raise ValidationError('Old password is not valid.')

        response = helper.getPositiveResponse("Password updated!")
        return Response(response)
Example #9
0
    def post(self, request):
        set_password_serializer = SetPasswordSerializer(data=request.data)
        set_password_serializer.is_valid(raise_exception=True)

        validated_data = set_password_serializer.validated_data

        try:
            user_verification = UserVerification.objects.get(
                verification_token=validated_data['set_password_token'])
        except UserVerification.DoesNotExist:
            response = helper.getNegativeResponse("Invalid verification token")
            return Response(response, status=response['statusCode'])

        user_verification.user.set_password(validated_data['password'])
        user_verification.user.save()
        response = helper.getPositiveResponse('Set password successfully')
        return Response(response)
Example #10
0
    def put(self, request):
        # old_email = request.user.email
        user_profile_serializer = UserProfileSerializer(request.user,
                                                        data=request.data)
        user_profile_serializer.is_valid(raise_exception=True)
        validated_data = user_profile_serializer.validated_data

        if user_profile_serializer.is_valid() == False:
            response = helper.getNegativeResponse(user_profile_serializer)
            # response = self.getErrorResponse(user_profile_serializer, status.HTTP_400_BAD_REQUEST)
            return Response(response, status=response['statusCode'])
        # validated_data['email'] = validated_data['email'].lower()
        user_profile_serializer.save()
        # if validated_data['email'] != old_email:
        #     jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        #     jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        #     payload = jwt_payload_handler(request.user)
        #     payload['user_id'] = str(payload['user_id'])
        #     token = jwt_encode_handler(payload)
        # else:
        #     token = request.META['HTTP_AUTHORIZATION'][4:]

        response = helper.getPositiveResponse("Profile updated!")
        return Response(response)