def create(self, validated_data):
        """
        Create BOOKMARK entry

        Required Fields:
            * Type
            * `listing id` if type is LISTING
            * `title` if type is folder
        """
        username = self.context['request'].user.username
        request_profile = self.context['request'].user.profile
        bookmark_parent_object = validated_data.get('bookmark_parent_object')
        type = validated_data.get('type')
        bookmark_children = validated_data.get('bookmark_children')
        listing_id = validated_data.get('listing', {}).get('id')

        if type == model_access.LISTING_TYPE:
            if not listing_id:
                raise errors.ValidationException('Listing id entry not found')

            listing = listing_model_access.get_listing_by_id(username, listing_id)

            if not listing:
                raise errors.ValidationException('Listing id entry not found')

            return model_access.create_listing_bookmark_for_profile(
                request_profile,
                listing,
                bookmark_parent_object)

        elif type == model_access.FOLDER_TYPE:
            if 'title' not in validated_data:
                raise errors.ValidationException('No title provided')

            listing = None
            if listing_id:
                listing = listing_model_access.get_listing_by_id(username, listing_id)

                if not listing:
                    raise errors.ValidationException('Listing id entry not found')

            return model_access.create_folder_bookmark_for_profile(
                request_profile,
                validated_data['title'],
                bookmark_parent_object,
                bookmark_children,
                listing)
        else:
            raise errors.ValidationException('No valid type provided')
Example #2
0
    def validate(self, data):
        """
        Check for listing id
        - folder is optional
        - position is optional
        """
        if 'listing' not in data:
            raise serializers.ValidationError('No listing provided')

        username = self.context['request'].user.username
        listing = listing_model_access.get_listing_by_id(
            username, data['listing']['id'])

        if listing:
            if not listing.is_enabled:
                raise serializers.ValidationError(
                    'Can not bookmark apps that are disabled')
        else:
            raise serializers.ValidationError('Listing id entry not found')

        if 'id' not in data['listing']:
            raise serializers.ValidationError('No listing id provided')

        if 'folder' in data:
            if not data.get('folder'):
                data['folder'] = None

        if 'position' in data:
            try:
                position_value = int(data['position'])
                data['position'] = position_value
            except ValueError:
                raise serializers.ValidationError('Position is not a integer')

        return data
Example #3
0
    def create(self, request, listing_pk=None):
        """
        Create a new review
        """
        try:
            listing = model_access.get_listing_by_id(request.user.username,
                listing_pk)
            if listing is None:
                raise Exception
        except Exception:
            return Response('Invalid listing',
                status=status.HTTP_400_BAD_REQUEST)

        try:
            rate = int(request.data['rate'])
            text = request.data.get('text', None)
        except Exception:
            return Response('Invalid input data',
                status=status.HTTP_400_BAD_REQUEST)

        try:
            resp = model_access.create_listing_review(request.user.username,
                listing, rate, text)
            return Response(resp, status=status.HTTP_201_CREATED)
        except Exception as e:
            raise e
            return Response('Bad request to create new review',
                status=status.HTTP_400_BAD_REQUEST)
Example #4
0
    def update(self, request, pk=None, profile_pk=None):
        """
        Update an existing listing visit count
        """
        if profile_pk == 'self':
            profile = model_access.get_self(request.user.username)
        else:
            profile = model_access.get_profile_by_id(profile_pk)
        if 'listing' in request.data and 'id' in request.data['listing']:
            listing = listing_model_access.get_listing_by_id(
                request.user.username, request.data['listing']['id'], True)
        else:
            listing = None

        visit_count = model_access.get_visit_count_by_id(pk)

        serializer = listing_serializers.ListingVisitCountSerializer(
            visit_count,
            data=request.data,
            context={
                'request': request,
                'profile': profile,
                'listing': listing
            },
            partial=True)
        if not serializer.is_valid():
            logger.error('{0!s}'.format(serializer.errors),
                         extra={'request': request})
            raise errors.ValidationException('{0}'.format(serializer.errors))

        serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)
Example #5
0
    def validate(self, data):
        """
        Check for listing id (folder is optional)
        """
        if 'listing' not in data:
            raise serializers.ValidationError('No listing provided')

        username = self.context['request'].user.username
        listing = listing_model_access.get_listing_by_id(
            username, data['listing']['id'])

        if listing:
            if not listing.is_enabled:
                raise serializers.ValidationError(
                    'Can not bookmark apps that are disabled')
        else:
            raise serializers.ValidationError('Listing id entry not found')

        if 'id' not in data['listing']:
            raise serializers.ValidationError('No listing id provided')
        if 'folder' in data:
            if not data.get('folder'):
                data['folder'] = None

        return data
Example #6
0
def ApplicationView(request, id='0'):
    """
    Single application
    """
    if not hal.validate_version(request.META.get('HTTP_ACCEPT')):
        return Response('Invalid version requested',
            status=status.HTTP_406_NOT_ACCEPTABLE)

    listing_root_url = hal.get_abs_url_for_iwc(request)
    profile = model_access.get_profile(request.user.username)

    # TODO: only include the fields that are necessary for IWC. This will also
    # allow us to sever ties with ozpcenter.api.listing.serializers

    # This minimal definition of what a Listing object must have should be
    # advertised so that others can use IWC with their own systems
    queryset = listing_model_access.get_listing_by_id(profile.user.username, id)
    if not queryset:
        return Response(status=status.HTTP_404_NOT_FOUND)
    serializer = listing_serializers.ListingSerializer(queryset,
            context={'request': request})
    data = serializer.data
    data = hal.add_hal_structure(data, request, hal.generate_content_type(
        request.accepted_media_type))

    return Response(data)
Example #7
0
def create_self_user_library_entry(username, listing_id, folder_name=None):
    """
    Create ApplicationLibrary Entry

    Args:
        username (str): the username to create a library entry for (Bookmark)
        listing_id (str): the id of the listing
        folder_name (str) optional: the name of the folder

    Return:
        ApplicationLibrary: New Entry of ApplicationLibrary

    Raise:
        Exception: if profile was not found based on username or
            or listing was not found based on listing_id
    """
    listing = listing_model_access.get_listing_by_id(username, listing_id)
    owner = generic_model_access.get_profile(username)

    if not listing or not owner:
        raise Exception('Listing or user not found')

    logger.debug('Adding bookmark for listing[{0!s}], user[{1!s}]'.format(listing.title, username), extra={'user': username})

    entry = models.ApplicationLibraryEntry(listing=listing, owner=owner, folder=folder_name)
    entry.save()
    return entry
    def update(self, request, pk=None, listing_pk=None):
        """
        Update an existing review
        """
        listing = model_access.get_listing_by_id(request.user.username,
                                                 listing_pk, True)
        custom_field = model_access.get_custom_field_value_by_id(pk)
        if model_access.is_listing_owner_or_admin(request.user.username,
                                                  listing):
            serializer = serializers.CustomFieldValueSerializer(
                custom_field,
                data=request.data,
                context={
                    'request': request,
                    'listing': listing
                },
                partial=True)

            if not serializer.is_valid():
                logger.error('{0!s}'.format(serializer.errors),
                             extra={'request': request})
                raise errors.ValidationException('{0}'.format(
                    serializer.errors))

            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)

        else:
            return Response(status=status.HTTP_403_FORBIDDEN)
    def validate(self, validated_data):
        """ Responsible of cleaning and validating user input data """
        initial_data = self.initial_data
        username = self.context['request'].user.username

        if 'message' not in validated_data and self.context['request'].method == 'POST':
            raise serializers.ValidationError('Messsage field is required for POST Request')

        if 'listing' in initial_data and 'agency' in initial_data:
            raise serializers.ValidationError('Notification can only be listing or agency')

        # TODO: Figure how to get listing data using validated data
        listing = initial_data.get('listing')
        if listing and listing.get('id'):
            try:
                validated_data['listing'] = listing_model_access.get_listing_by_id(
                    username, initial_data['listing']['id'], True)
            except ObjectDoesNotExist:
                raise serializers.ValidationError('Valid Listing ID is required, Could not find listing')
        else:
            validated_data['listing'] = None

        agency = initial_data.get('agency')
        if agency and agency.get('id'):
            try:
                validated_data['agency'] = agency_model_access.get_agency_by_id(
                    initial_data['agency']['id'], True)
            except ObjectDoesNotExist:
                raise serializers.ValidationError('Valid agency ID is required, Could not find listing')
        else:
            validated_data['agency'] = None

        return validated_data
Example #10
0
def ApplicationView(request, id='0'):
    """
    Single application
    """
    if not hal.validate_version(request.META.get('HTTP_ACCEPT')):
        return Response('Invalid version requested',
                        status=status.HTTP_406_NOT_ACCEPTABLE)

    listing_root_url = hal.get_abs_url_for_iwc(
        request
    )  # flake8: noqa TODO: Is Necessary? - Variable not being used in method
    profile = model_access.get_profile(request.user.username)

    # TODO: only include the fields that are necessary for IWC. This will also
    # allow us to sever ties with ozpcenter.api.listing.serializers

    # This minimal definition of what a Listing object must have should be
    # advertised so that others can use IWC with their own systems
    queryset = listing_model_access.get_listing_by_id(profile.user.username,
                                                      id)
    if not queryset:
        return Response(status=status.HTTP_404_NOT_FOUND)
    serializer = listing_serializers.ListingSerializer(
        queryset, context={'request': request})
    data = serializer.data
    data = hal.add_hal_structure(
        data, request, hal.generate_content_type(request.accepted_media_type))

    return Response(data)
Example #11
0
def create_self_user_library_entry(username, listing_id, folder_name=None):
    """
    Create ApplicationLibrary Entry

    Args:
        username (str): the username to create a library entry for (Bookmark)
        listing_id (str): the id of the listing
        folder_name (str) optional: the name of the folder

    Return:
        ApplicationLibrary: New Entry of ApplicationLibrary

    Raise:
        Exception: if profile was not found based on username or
            or listing was not found based on listing_id
    """
    listing = listing_model_access.get_listing_by_id(username, listing_id)
    owner = generic_model_access.get_profile(username)

    if not listing or not owner:
        raise Exception('Listing or user not found')

    logger.debug('Adding bookmark for listing[{0!s}], user[{1!s}]'.format(listing.title, username), extra={'user': username})

    entry = models.ApplicationLibraryEntry(listing=listing, owner=owner, folder=folder_name)
    entry.save()
    return entry
    def validate(self, data):
        """
        Check for listing id
        - folder is optional
        - position is optional
        """
        if 'listing' not in data:
            raise serializers.ValidationError('No listing provided')

        username = self.context['request'].user.username
        listing = listing_model_access.get_listing_by_id(username,
            data['listing']['id'])

        if listing:
            if not listing.is_enabled:
                raise serializers.ValidationError('Can not bookmark apps that are disabled')
        else:
            raise serializers.ValidationError('Listing id entry not found')

        if 'id' not in data['listing']:
            raise serializers.ValidationError('No listing id provided')

        if 'folder' in data:
            if not data.get('folder'):
                data['folder'] = None

        if 'position' in data:
            try:
                position_value = int(data['position'])
                data['position'] = position_value
            except ValueError:
                raise serializers.ValidationError('Position is not a integer')

        return data
Example #13
0
    def create(self, validated_data):
        """
        Create BOOKMARK entry

        Required Fields:
            * Type
            * `listing id` if type is LISTING
            * `title` if type is folder
        """
        username = self.context['request'].user.username
        request_profile = self.context['request'].user.profile
        bookmark_parent_object = validated_data.get('bookmark_parent_object')
        type = validated_data.get('type')
        bookmark_children = validated_data.get('bookmark_children')
        listing_id = validated_data.get('listing', {}).get('id')

        if type == model_access.LISTING_TYPE:
            if not listing_id:
                raise errors.ValidationException('Listing id entry not found')

            listing = listing_model_access.get_listing_by_id(
                username, listing_id)

            if not listing:
                raise errors.ValidationException('Listing id entry not found')

            return model_access.create_listing_bookmark_for_profile(
                request_profile, listing, bookmark_parent_object)

        elif type == model_access.FOLDER_TYPE:
            if 'title' not in validated_data:
                raise errors.ValidationException('No title provided')

            listing = None
            if listing_id:
                listing = listing_model_access.get_listing_by_id(
                    username, listing_id)

                if not listing:
                    raise errors.ValidationException(
                        'Listing id entry not found')

            return model_access.create_folder_bookmark_for_profile(
                request_profile, validated_data['title'],
                bookmark_parent_object, bookmark_children, listing)
        else:
            raise errors.ValidationException('No valid type provided')
Example #14
0
    def destroy(self, request, listing_pk=None, pk=None):
        listing = model_access.get_listing_by_id(request.user.username, listing_pk, True)
        feedback = model_access.get_recommendation_feedback(request.user.username, listing)

        if feedback is None:
            return Response(status=status.HTTP_404_NOT_FOUND)

        model_access.delete_recommendation_feedback(listing, feedback)
        return Response(status=status.HTTP_204_NO_CONTENT)
Example #15
0
    def update_all(self, request):
        """
        Update ALL of the user's library entries

        Used to move library entries into different folders for HUD

        [
            {
                "listing": {
                    "id": 1
                },
                "folder": "folderName" (or null),
                "id": 2
            },
            {
                "listing": {
                    "id": 2
                },
                "folder": "folderName" (or null),
                "id": 1
            }
        ]
        ---
        parameters:
            - name: body
              required: true
              paramType: body
        parameters_strategy:
            form: replace
            query: replace
        omit_serializer: true
        """
        username = request.user.username
        # This method is different than most. The ViewSet update method only
        # works on a single instance, hence the use of a special update_all
        # method. Serializers must be customized to support nested writable
        # representations, and even after doing so, the input data validation
        # didn't seem acceptable. Hence this customized method
        #
        # validate input
        for i in request.data:
            if 'listing' not in i or 'id' not in i:
                return Response('Missing listing and/or id from request data',
                    status=status.HTTP_400_BAD_REQUEST)

        # update each instance
        for i in request.data:
            instance = model_access.get_library_entry_by_id(i['id'])
            instance.folder = i['folder']
            instance.listing = listing_model_access.get_listing_by_id(username,
                i['listing']['id'])
            instance.save()

        # return original data
        return Response(request.data, status=status.HTTP_200_OK)
Example #16
0
    def list(self, request, listing_pk=None):
        listing = model_access.get_listing_by_id(request.user.username, listing_pk, True)

        queryset = self.get_queryset(listing)

        if not queryset:
            return Response({'feedback': 0}, status=status.HTTP_404_NOT_FOUND)

        serializer = serializers.RecommendationFeedbackSerializer(queryset, context={'request': request, 'listing': listing})
        data = serializer.data
        return Response(data)
Example #17
0
 def create(self, validated_data):
     username = self.context['request'].user.username
     folder = validated_data.get('folder', '')
     listing = listing_model_access.get_listing_by_id(username,
         validated_data['listing']['id'])
     logger.debug('adding bookmark for %s' % listing.title)
     owner = generic_model_access.get_profile(username)
     entry = models.ApplicationLibraryEntry(listing=listing, owner=owner,
         folder=folder)
     entry.save()
     return entry
Example #18
0
    def destroy(self, request, listing_pk=None, pk=None):
        listing = model_access.get_listing_by_id(request.user.username,
                                                 listing_pk, True)
        feedback = model_access.get_recommendation_feedback(
            request.user.username, listing)

        if feedback is None:
            return Response(status=status.HTTP_404_NOT_FOUND)

        model_access.delete_recommendation_feedback(listing, feedback)
        return Response(status=status.HTTP_204_NO_CONTENT)
    def destroy(self, request, listing_pk=None, pk=None):
        listing = model_access.get_listing_by_id(request.user.username,
                                                 listing_pk, True)
        custom_field = model_access.get_custom_field_value_by_id(pk)

        if custom_field is None:
            return Response(status=status.HTTP_404_NOT_FOUND)

        if model_access.is_listing_owner_or_admin(request.user.username,
                                                  listing):
            custom_field.delete()
            return Response(status=status.HTTP_204_NO_CONTENT)
Example #20
0
 def get_queryset(self):
     queryset = model_access.get_all_pending_notifications()
     profile = self.request.user.profile
     listing_id = self.request.query_params.get('listing', None)
     if listing_id is not None:
         listing = model_access_listing.get_listing_by_id(username=self.request.user.username, id=self.request.query_params.get('listing', None))
         if (profile in listing.owners.all()) or (profile.highest_role() in ['ORG_STEWARD', 'APPS_MALL_STEWARD']):
             queryset = queryset.filter(notification_type='listing', entity_id=listing_id)
             return queryset
     if profile.highest_role() in ['ORG_STEWARD', 'APPS_MALL_STEWARD']:
         return queryset
     return None
Example #21
0
    def create(self, request, listing_pk=None):
        listing = model_access.get_listing_by_id(request.user.username, listing_pk, True)

        serializer = serializers.RecommendationFeedbackSerializer(data=request.data, context={'request': request, 'listing': listing})

        if not serializer.is_valid():
            logger.error('{0!s}'.format(serializer.errors), extra={'request': request})
            raise errors.ValidationException('{0}'.format(serializer.errors))

        serializer.save()

        return Response(serializer.data, status=status.HTTP_201_CREATED)
Example #22
0
 def create(self, request, listing_pk=None):
     try:
         user = generic_model_access.get_profile(request.user.username)
         listing = model_access.get_listing_by_id(request.user.username,
             listing_pk)
         rejection_description = request.data['description']
         listing = model_access.reject_listing(user, listing,
             rejection_description)
         return Response(data={"listing": {"id": listing.id}},
             status=status.HTTP_201_CREATED)
     except Exception as e:
         logger.error('Exception: {}'.format(e), extra={'request': request})
         raise errors.RequestException('Error rejecting listing')
 def create(self, request, listing_pk=None):
     try:
         user = generic_model_access.get_profile(request.user.username)
         listing = model_access.get_listing_by_id(request.user.username,
                                                  listing_pk)
         rejection_description = request.data['description']
         listing = model_access.reject_listing(user, listing,
                                               rejection_description)
         return Response(data={"listing": {"id": listing.id}},
                         status=status.HTTP_201_CREATED)
     except Exception as e:
         logger.error('Exception: {}'.format(e), extra={'request': request})
         raise errors.RequestException('Error rejecting listing')
    def test_create_delete_detailed_listing_as_aml_steward_with_confirmation(
            self):
        self.authenticate_as(self.aml_steward_profile)

        request = self._basic_listing_with_listing_type_request()

        response = self._create_listing(request)

        new_listing_id = response.data['id']

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        data = {'delete_associated_listings': True}
        response = self._delete_listing_type(self.listing_type1.id, data)

        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

        with self.assertRaises(ListingType.DoesNotExist):
            get_listing_type_by_id(self.listing_type1.id, True)

        with self.assertRaises(Listing.DoesNotExist):
            get_listing_by_id('bigbrother', new_listing_id, True)
Example #25
0
 def create(self, request, listing_pk=None):
     try:
         user = generic_model_access.get_profile(request.user.username)
         listing = model_access.get_listing_by_id(request.user.username,
             listing_pk)
         rejection_description = request.data['description']
         listing = model_access.reject_listing(user, listing,
             rejection_description)
         return Response(data={"listing": {"id": listing.id}},
             status=status.HTTP_201_CREATED)
     except Exception as e:
         return Response("Error rejecting listing",
                 status=status.HTTP_400_BAD_REQUEST)
Example #26
0
    def create(self, request, listing_pk=None):
        """
        Create a new review
        """
        request_current_username = request.user.username
        listing = model_access.get_listing_by_id(request_current_username,
            listing_pk, True)

        rate = int(request.data.get('rate', None))
        text = request.data.get('text', None)

        resp = model_access.create_listing_review(request_current_username,
            listing, rate, text)
        return Response(resp, status=status.HTTP_201_CREATED)
Example #27
0
    def update(self, request, pk=None, listing_pk=None):
        """
        Update an existing review
        """
        listing = model_access.get_listing_by_id(request.user.username, listing_pk, True)
        review = model_access.get_review_by_id(pk)

        serializer = serializers.ReviewSerializer(review, data=request.data, context={'request': request, 'listing': listing}, partial=True)
        if not serializer.is_valid():
            logger.error('{0!s}'.format(serializer.errors), extra={'request': request})
            raise errors.ValidationException('{0}'.format(serializer.errors))

        serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)
Example #28
0
    def create(self, request, listing_pk=None):
        """
        Create a new review
        """
        request_current_username = request.user.username
        listing = model_access.get_listing_by_id(request_current_username,
            listing_pk, True)

        rate = int(request.data.get('rate', None))
        text = request.data.get('text', None)

        resp = model_access.create_listing_review(request_current_username,
            listing, rate, text)
        return Response(resp, status=status.HTTP_201_CREATED)
Example #29
0
    def create(self, request, listing_pk=None):
        try:
            user = generic_model_access.get_profile(request.user.username)
            listing = model_access.get_listing_by_id(request.user.username,
                listing_pk)
            description = request.data['description'] if 'description' in request.data else None
            if not description:
                raise errors.InvalidInput('Description is required when pending a listing for deletion')

            listing = model_access.pending_delete_listing(user, listing, description)
            return Response(data={"listing": {"id": listing.id}},
                status=status.HTTP_201_CREATED)
        except Exception as e:
            logger.error('Exception: {}'.format(e), extra={'request': request})
            raise errors.RequestException('Error pending listing for deletion')
Example #30
0
    def list(self, request, listing_pk=None):
        listing = model_access.get_listing_by_id(request.user.username,
                                                 listing_pk, True)

        queryset = self.get_queryset(listing)

        if not queryset:
            return Response({'feedback': 0}, status=status.HTTP_404_NOT_FOUND)

        serializer = serializers.RecommendationFeedbackSerializer(
            queryset, context={
                'request': request,
                'listing': listing
            })
        data = serializer.data
        return Response(data)
Example #31
0
    def create(self, request, listing_pk=None):
        listing = model_access.get_listing_by_id(request.user.username,
                                                 listing_pk, True)

        serializer = serializers.RecommendationFeedbackSerializer(
            data=request.data,
            context={
                'request': request,
                'listing': listing
            })

        if not serializer.is_valid():
            logger.error('{0!s}'.format(serializer.errors),
                         extra={'request': request})
            raise errors.ValidationException('{0}'.format(serializer.errors))

        serializer.save()

        return Response(serializer.data, status=status.HTTP_201_CREATED)
Example #32
0
    def create(self, request, listing_pk=None):
        """
        Create a new review
        """
        listing = model_access.get_listing_by_id(request.user.username,
                                                 listing_pk, True)

        serializer = serializers.ReviewSerializer(data=request.data,
                                                  context={
                                                      'request': request,
                                                      'listing': listing
                                                  },
                                                  partial=True)
        if not serializer.is_valid():
            logger.error('{0!s}'.format(serializer.errors),
                         extra={'request': request})
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
Example #33
0
    def create(self, request, profile_pk=None):
        """
        Create a listing visit count
        """
        if profile_pk == 'self':
            profile = model_access.get_self(request.user.username)
        else:
            profile = model_access.get_profile_by_id(profile_pk)
        if 'listing' in request.data and 'id' in request.data['listing']:
            listing = listing_model_access.get_listing_by_id(request.user.username, request.data['listing']['id'], True)
        else:
            listing = None

        serializer = listing_serializers.ListingVisitCountSerializer(data=request.data,
            context={'request': request, 'profile': profile, 'listing': listing}, partial=True)
        if not serializer.is_valid():
            logger.error('{0!s}'.format(serializer.errors), extra={'request': request})
            raise errors.ValidationException('{0}'.format(serializer.errors))

        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
Example #34
0
    def create(self, request, listing_pk=None):
        try:
            user = generic_model_access.get_profile(request.user.username)
            listing = model_access.get_listing_by_id(request.user.username,
                                                     listing_pk)
            description = request.data[
                'description'] if 'description' in request.data else None
            if not description:
                raise errors.InvalidInput(
                    'Description is required when pending a listing for deletion'
                )

            listing = model_access.pending_delete_listing(
                user, listing, description)
            return Response(data={"listing": {
                "id": listing.id
            }},
                            status=status.HTTP_201_CREATED)
        except Exception as e:
            logger.error('Exception: {}'.format(e), extra={'request': request})
            raise errors.RequestException('Error pending listing for deletion')
Example #35
0
    def update(self, request, pk=None, listing_pk=None):
        """
        Update an existing review
        """
        listing = model_access.get_listing_by_id(request.user.username,
                                                 listing_pk, True)
        review = model_access.get_review_by_id(pk)

        serializer = serializers.ReviewSerializer(review,
                                                  data=request.data,
                                                  context={
                                                      'request': request,
                                                      'listing': listing
                                                  },
                                                  partial=True)
        if not serializer.is_valid():
            logger.error('{0!s}'.format(serializer.errors),
                         extra={'request': request})
            raise errors.ValidationException('{0}'.format(serializer.errors))

        serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)
    def create(self, request, listing_pk=None):
        listing = model_access.get_listing_by_id(request.user.username,
                                                 listing_pk, True)
        if model_access.is_listing_owner_or_admin(request.user.username,
                                                  listing):
            serializer = serializers.CustomFieldValueSerializer(
                data=request.data,
                context={
                    'request': request,
                    'listing': listing
                })

            if not serializer.is_valid():
                logger.error('{0!s}'.format(serializer.errors),
                             extra={'request': request})
                raise errors.ValidationException('{0}'.format(
                    serializer.errors))

            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(status=status.HTTP_403_FORBIDDEN)
    def validate(self, data):
        """
        Check for listing id (folder is optional)
        """
        if 'listing' not in data:
            raise serializers.ValidationError('No listing provided')

        username = self.context['request'].user.username
        listing = listing_model_access.get_listing_by_id(username,
            data['listing']['id'])

        if listing:
            if not listing.is_enabled:
                raise serializers.ValidationError('Can not bookmark apps that are disabled')
        else:
            raise serializers.ValidationError('Listing id entry not found')

        if 'id' not in data['listing']:
            raise serializers.ValidationError('No listing id provided')
        if 'folder' in data:
            if not data.get('folder'):
                data['folder'] = None

        return data
Example #38
0
def batch_update_user_library_entry(username, data):
    """
    Update ALL of the user's library entries

    Used to move library entries into different folders for HUD

    Args:
        username (str): username
        data (List<Dict>): Payload
            [
                {
                    "listing": {
                        "id": 1
                    },
                    "folder": "folderName" (or null),
                    "id": 2,
                    "position": 2
                },
                {
                    "listing": {
                        "id": 2
                    },
                    "folder": "folderName" (or null),
                    "id": 1,
                    "position": 1
                }
            ]

        Return:
            List<Dict>: payload data  # TODO: Pass list of instances (rivera 2017-01-23)

        Raise:
            Exception: if validation fails
    """
    validated_data = []
    errors = []
    # validate input
    for data_entry in data:
        error = False
        # Validates Listing

        new_data_entry = {}

        if 'listing' not in data_entry:
            errors.append('Missing listing from data entry')
            error = True
        else:
            listing_id = data_entry.get('listing', {}).get('id')
            listing_obj = listing_model_access.get_listing_by_id(
                username, listing_id)
            if not listing_obj:
                errors.append('Listing obj not found')
                error = True
            else:
                new_data_entry['listing'] = listing_obj

        if 'id' not in data_entry:
            errors.append('Missing id from data entry')
            error = True
        else:
            new_data_entry['id'] = data_entry['id']

        if 'folder' not in data_entry:
            new_data_entry['folder'] = None
        else:
            new_data_entry['folder'] = data_entry['folder']

        if 'position' not in data_entry:
            new_data_entry['position'] = None
        else:
            try:
                position_value = int(data_entry['position'])
                new_data_entry['position'] = position_value
            except ValueError:
                errors.append('Position is not an integer')
                error = True
                new_data_entry['position'] = None

        if not error:
            validated_data.append(new_data_entry)

    if errors:
        return errors, None

    for data_entry in validated_data:
        instance = get_library_entry_by_id(data_entry['id'])
        instance.folder = data_entry['folder']
        instance.listing = data_entry['listing']

        if data_entry['position'] is not None:
            instance.position = data_entry['position']

        instance.save()

    return None, data
Example #39
0
def create_batch_library_entries(username, data):
    """
    Create Batch

    Args:
        username (str): username
        data (List<Dict>): Payload
            [
                {
                    "listing": {
                        "id": 1
                    },
                    "folder": "folderName" (or null),
                    "id": 2,
                    "position": 2
                },
                {
                    "listing": {
                        "id": 2
                    },
                    "folder": "folderName" (or null),
                    "id": 1,
                    "position": 1
                }
            ]

        Return:
            List<Dict>: payload data
    """
    owner = generic_model_access.get_profile(username)
    if not owner:
        return []

    validated_data = []
    # validate input
    for data_entry in data:
        error = False
        # Validates Listing
        new_data_entry = {}

        if 'listing' not in data_entry:
            error = True
        else:
            listing_id = data_entry.get('listing', {}).get('id')
            listing_obj = listing_model_access.get_listing_by_id(
                username, listing_id)
            if not listing_obj:
                error = True
            else:
                new_data_entry['listing'] = listing_obj

        if 'folder' not in data_entry:
            new_data_entry['folder'] = None
        else:
            new_data_entry['folder'] = data_entry['folder']

        if 'position' not in data_entry:
            new_data_entry['position'] = None
        else:
            try:
                position_value = int(data_entry['position'])
                new_data_entry['position'] = position_value
            except:
                new_data_entry['position'] = None

        if not error:
            validated_data.append(new_data_entry)

    output_entries = []
    for data_entry in validated_data:
        listing = data_entry.get('listing')
        folder_name = data_entry.get('folder')
        position = data_entry.get('position')

        if not listing:
            raise Exception('Listing not found')

        logger.debug('Adding bookmark for listing[{0!s}], user[{1!s}]'.format(
            listing.title, username),
                     extra={'user': username})

        entry = models.ApplicationLibraryEntry(listing=listing,
                                               owner=owner,
                                               folder=folder_name)
        if position:
            entry.position = position

        entry.save()

        output_entries.append(entry)

    return output_entries
Example #40
0
def batch_update_user_library_entry(username, data):
    """
    Update ALL of the user's library entries

    Used to move library entries into different folders for HUD

    Args:
        username (str): username
        data (List<Dict>): Payload
            [
                {
                    "listing": {
                        "id": 1
                    },
                    "folder": "folderName" (or null),
                    "id": 2
                },
                {
                    "listing": {
                        "id": 2
                    },
                    "folder": "folderName" (or null),
                    "id": 1
                }
            ]

        Return:
            List<Dict>: payload data

        Raise:
            Exception: if validation fails
    """
    validated_data = []
    errors = []
    # validate input
    for data_entry in data:
        error = False
        # Validates Listing

        new_data_entry = {}

        if 'listing' not in data_entry:
            errors.append('Missing listing from data entry')
            error = True
        else:
            listing_id = data_entry.get('listing', {}).get('id')
            listing_obj = listing_model_access.get_listing_by_id(username, listing_id)
            if not listing_obj:
                errors.append('Listing obj not found')
                error = True
            else:
                new_data_entry['listing'] = listing_obj

        if 'id' not in data_entry:
            errors.append('Missing id from data entry')
            error = True
        else:
            new_data_entry['id'] = data_entry['id']

        if 'folder' not in data_entry:
            new_data_entry['folder'] = None
        else:
            new_data_entry['folder'] = data_entry['folder']

        if not error:
            validated_data.append(new_data_entry)

    if errors:
        return errors, None

    for data_entry in validated_data:
        instance = get_library_entry_by_id(data_entry['id'])
        instance.folder = data_entry['folder']
        instance.listing = data_entry['listing']
        instance.save()

    return None, data
def create_batch_library_entries(username, data):
    """
    Create Batch

    Args:
        username (str): username
        data (List<Dict>): Payload
            [
                {
                    "listing": {
                        "id": 1
                    },
                    "folder": "folderName" (or null),
                    "id": 2,
                    "position": 2
                },
                {
                    "listing": {
                        "id": 2
                    },
                    "folder": "folderName" (or null),
                    "id": 1,
                    "position": 1
                }
            ]

        Return:
            List<Dict>: payload data
    """
    owner = generic_model_access.get_profile(username)
    if not owner:
        return []

    validated_data = []
    # validate input
    for data_entry in data:
        error = False
        # Validates Listing
        new_data_entry = {}

        if 'listing' not in data_entry:
            error = True
        else:
            listing_id = data_entry.get('listing', {}).get('id')
            listing_obj = listing_model_access.get_listing_by_id(username, listing_id)
            if not listing_obj:
                error = True
            else:
                new_data_entry['listing'] = listing_obj

        if 'folder' not in data_entry:
            new_data_entry['folder'] = None
        else:
            new_data_entry['folder'] = str(data_entry['folder'])

        if 'position' not in data_entry:
            new_data_entry['position'] = None
        else:
            try:
                position_value = int(data_entry['position'])
                new_data_entry['position'] = position_value
            except:
                new_data_entry['position'] = None

        if not error:
            validated_data.append(new_data_entry)

    output_entries = []
    for data_entry in validated_data:
        listing = data_entry.get('listing')
        folder_name = data_entry.get('folder')
        position = data_entry.get('position')

        logger.debug('Adding bookmark for listing[{0!s}], user[{1!s}]'.format(listing.title, username), extra={'user': username})

        entry = models.ApplicationLibraryEntry(listing=listing,
                                               owner=owner,
                                               folder=folder_name)
        if position:
            entry.position = position

        entry.save()

        output_entries.append(entry)

    return output_entries
Example #42
0
    def validate(self, validated_data):
        """ Responsible of cleaning and validating user input data """
        validated_data['error'] = None
        initial_data = self.initial_data
        username = self.context['request'].user.username

        # Check for notification types
        key_type_list = []

        if 'listing' in initial_data:
            key_type_list.append('listing')

        if 'agency' in initial_data:
            key_type_list.append('agency')

        if 'peer' in initial_data:
            key_type_list.append('peer')

        if len(key_type_list) >= 2:
            raise serializers.ValidationError('Notifications can only be one type. Input: {0}'.format(key_type_list))

        if 'message' not in validated_data and self.context['request'].method == 'POST':
            raise serializers.ValidationError('Messsage field is required for POST Request')

        # TODO: Figure how to get listing data using validated data
        listing = initial_data.get('listing')
        if listing:
            if listing.get('id'):
                try:
                    validated_data['listing'] = listing_model_access.get_listing_by_id(
                        username, initial_data['listing']['id'], True)
                except ObjectDoesNotExist:
                    raise serializers.ValidationError('Could not find listing')
            else:
                raise serializers.ValidationError('Valid Listing ID is required')
        else:
            validated_data['listing'] = None

        # Agency Validation
        agency = initial_data.get('agency')
        if agency:
            if agency.get('id'):
                try:
                    validated_data['agency'] = agency_model_access.get_agency_by_id(
                        initial_data['agency']['id'], True)
                except ObjectDoesNotExist:
                    raise serializers.ValidationError('Could not find agency')
            else:
                raise serializers.ValidationError('Valid Agency ID is required')
        else:
            validated_data['agency'] = None

        # Peer Validation
        peer = initial_data.get('peer')
        if peer:
            temp_peer = {}

            if peer.get('user'):
                temp_peer['user'] = peer.get('user')

            if peer.get('folder_name'):
                temp_peer['folder_name'] = peer.get('folder_name')

            target_username = temp_peer.get('user', {}).get('username')

            if not target_username:
                raise serializers.ValidationError('Valid Username is Required')

            target_username_profile = generic_model_access.get_profile(target_username)

            if not target_username_profile:
                raise serializers.ValidationError('Valid User is Required')

            # Folder Validation - Optional Field
            temp_folder_name = temp_peer.get('folder_name')
            if temp_folder_name:
                library_query = library_model_access.get_self_application_library(username, folder_name=temp_folder_name)
                temp_peer['_bookmark_listing_ids'] = [library_query_entry.listing.id for library_query_entry in library_query]

                # temp_peer['_user_folders'] = library_serializers.UserLibrarySerializer(library_query,
                #      many=True, context={'request': self.context['request']}).data

                if len(temp_peer['_bookmark_listing_ids']) == 0:
                    raise serializers.ValidationError('No entries in target folder')

            validated_data['peer'] = temp_peer
        else:
            validated_data['peer'] = None

        return validated_data
Example #43
0
    def validate(self, validated_data):
        """ Responsible of cleaning and validating user input data """
        validated_data['error'] = None
        initial_data = self.initial_data
        username = self.context['request'].user.username

        # Check for notification types
        key_type_list = []

        if 'listing' in initial_data:
            key_type_list.append('listing')

        if 'agency' in initial_data:
            key_type_list.append('agency')

        if 'peer' in initial_data:
            key_type_list.append('peer')

        if len(key_type_list) >= 2:
            raise serializers.ValidationError(
                'Notifications can only be one type. Input: {0}'.format(
                    key_type_list))

        if 'message' not in validated_data and self.context[
                'request'].method == 'POST':
            raise serializers.ValidationError(
                'Messsage field is required for POST Request')

        # TODO: Figure how to get listing data using validated data
        listing = initial_data.get('listing')
        if listing:
            if listing.get('id'):
                try:
                    validated_data[
                        'listing'] = listing_model_access.get_listing_by_id(
                            username, initial_data['listing']['id'], True)
                except ObjectDoesNotExist:
                    raise serializers.ValidationError('Could not find listing')
            else:
                raise serializers.ValidationError(
                    'Valid Listing ID is required')
        else:
            validated_data['listing'] = None

        # Agency Validation
        agency = initial_data.get('agency')
        if agency:
            if agency.get('id'):
                try:
                    validated_data[
                        'agency'] = agency_model_access.get_agency_by_id(
                            initial_data['agency']['id'], True)
                except ObjectDoesNotExist:
                    raise serializers.ValidationError('Could not find agency')
            else:
                raise serializers.ValidationError(
                    'Valid Agency ID is required')
        else:
            validated_data['agency'] = None

        # Peer Validation
        peer = initial_data.get('peer')
        if peer:
            temp_peer = {}

            if peer.get('user'):
                temp_peer['user'] = peer.get('user')

            if peer.get('folder_name'):
                temp_peer['folder_name'] = peer.get('folder_name')

            target_username = temp_peer.get('user', {}).get('username')

            if not target_username:
                raise serializers.ValidationError('Valid Username is Required')

            target_username_profile = generic_model_access.get_profile(
                target_username)

            if not target_username_profile:
                raise serializers.ValidationError('Valid User is Required')

            validated_data['entity_target'] = target_username_profile
            validated_data['entity_id'] = target_username_profile.pk
            # Folder Validation - Optional Field
            temp_folder_name = temp_peer.get('folder_name')
            if temp_folder_name:
                library_query = library_model_access.get_self_application_library(
                    username, folder_name=temp_folder_name)
                temp_peer['_bookmark_listing_ids'] = [
                    library_query_entry.listing.id
                    for library_query_entry in library_query
                ]

                # temp_peer['_user_folders'] = library_serializers.UserLibrarySerializer(library_query,
                #      many=True, context={'request': self.context['request']}).data

                if len(temp_peer['_bookmark_listing_ids']) == 0:
                    raise serializers.ValidationError(
                        'No entries in target folder')

            validated_data['peer'] = temp_peer
        else:
            validated_data['peer'] = None

        return validated_data