Esempio n. 1
0
def get_user_preferences(requesting_user, username=None):
    """Returns all user preferences as a JSON response.

    Args:
        requesting_user (User): The user requesting the user preferences. Only the user with username
            `username` or users with "is_staff" privileges can access the preferences.
        username (str): Optional username for which to look up the preferences. If not specified,
            `requesting_user.username` is assumed.

    Returns:
         A dict containing account fields.

    Raises:
         UserNotFound: no user with username `username` exists (or `requesting_user.username` if
            `username` is not specified)
         UserNotAuthorized: the requesting_user does not have access to the user preference.
         UserAPIInternalError: the operation failed due to an unexpected error.
    """
    existing_user = _get_authorized_user(requesting_user,
                                         username,
                                         allow_staff=True)

    # Django Rest Framework V3 uses the current request to version
    # hyperlinked URLS, so we need to retrieve the request and pass
    # it in the serializer's context (otherwise we get an AssertionError).
    # We're retrieving the request from the cache rather than passing it in
    # as an argument because this is an implementation detail of how we're
    # serializing data, which we want to encapsulate in the API call.
    context = {"request": get_request_or_stub()}
    user_serializer = UserSerializer(existing_user, context=context)
    return user_serializer.data["preferences"]
    def data(self):
        """
        Uses the CourseTeamSerializer to create a serialized course_team object.
        Adds in additional text and pk fields.
        Removes membership relation.

        Returns serialized object with additional search fields.
        """
        # Django Rest Framework v3.1 requires that we pass the request to the serializer
        # so it can construct hyperlinks.  To avoid changing the interface of this object,
        # we retrieve the request from the request cache.
        context = {
            "request": get_request_or_stub()
        }

        serialized_course_team = CourseTeamSerializer(self.course_team, context=context).data

        # Save the primary key so we can load the full objects easily after we search
        serialized_course_team['pk'] = self.course_team.pk
        # Don't save the membership relations in elasticsearch
        serialized_course_team.pop('membership', None)

        # add generally searchable content
        serialized_course_team['content'] = {
            'text': self.content_text()
        }

        return serialized_course_team
Esempio n. 3
0
    def data(self):
        """
        Uses the CourseTeamSerializer to create a serialized course_team object.
        Adds in additional text and pk fields.
        Removes membership relation.

        Returns serialized object with additional search fields.
        """
        # Django Rest Framework v3.1 requires that we pass the request to the serializer
        # so it can construct hyperlinks.  To avoid changing the interface of this object,
        # we retrieve the request from the request cache.
        context = {"request": get_request_or_stub()}

        serialized_course_team = CourseTeamSerializer(self.course_team,
                                                      context=context).data

        # Save the primary key so we can load the full objects easily after we search
        serialized_course_team['pk'] = self.course_team.pk
        # Don't save the membership relations in elasticsearch
        serialized_course_team.pop('membership', None)

        # add generally searchable content
        serialized_course_team['content'] = {'text': self.content_text()}

        return serialized_course_team
Esempio n. 4
0
def get_user_preferences(requesting_user, username=None):
    """Returns all user preferences as a JSON response.

    Args:
        requesting_user (User): The user requesting the user preferences. Only the user with username
            `username` or users with "is_staff" privileges can access the preferences.
        username (str): Optional username for which to look up the preferences. If not specified,
            `requesting_user.username` is assumed.

    Returns:
         A dict containing account fields.

    Raises:
         UserNotFound: no user with username `username` exists (or `requesting_user.username` if
            `username` is not specified)
         UserNotAuthorized: the requesting_user does not have access to the user preference.
         UserAPIInternalError: the operation failed due to an unexpected error.
    """
    existing_user = _get_authorized_user(requesting_user, username, allow_staff=True)

    # Django Rest Framework V3 uses the current request to version
    # hyperlinked URLS, so we need to retrieve the request and pass
    # it in the serializer's context (otherwise we get an AssertionError).
    # We're retrieving the request from the cache rather than passing it in
    # as an argument because this is an implementation detail of how we're
    # serializing data, which we want to encapsulate in the API call.
    context = {
        "request": get_request_or_stub()
    }
    user_serializer = UserSerializer(existing_user, context=context)
    return user_serializer.data["preferences"]
Esempio n. 5
0
 def test_get_request_or_stub(self):
     # Outside the context of the request, we should still get a request
     # that allows us to build an absolute URI.
     stub = get_request_or_stub()
     expected_url = "http://{site_name}/foobar".format(
         site_name=settings.SITE_NAME)
     self.assertEqual(stub.build_absolute_uri("foobar"), expected_url)
Esempio n. 6
0
 def test_get_request_or_stub(self):
     """
     Outside the context of the request, we should still get a request
     that allows us to build an absolute URI.
     """
     stub = get_request_or_stub()
     expected_url = "http://{site_name}/foobar".format(site_name=settings.SITE_NAME)
     self.assertEqual(stub.build_absolute_uri("foobar"), expected_url)
def _get_course_module(course_descriptor, user):
    # Fake a request to fool parts of the courseware that want to inspect it.
    request = get_request_or_stub()
    request.user = user

    # Now evil modulestore magic to inflate our descriptor with user state and
    # permissions checks.
    field_data_cache = FieldDataCache.cache_for_descriptor_descendents(
        course_descriptor.id, user, course_descriptor, depth=1, read_only=True,
    )
    return get_module_for_descriptor(
        user, request, course_descriptor, field_data_cache, course_descriptor.id, course=course_descriptor,
    )
def _get_course_module(course_descriptor, user):
    # Fake a request to fool parts of the courseware that want to inspect it.
    request = get_request_or_stub()
    request.user = user

    # Now evil modulestore magic to inflate our descriptor with user state and
    # permissions checks.
    field_data_cache = FieldDataCache.cache_for_descriptor_descendents(
        course_descriptor.id, user, course_descriptor, depth=1, read_only=True,
    )
    return get_module_for_descriptor(
        user, request, course_descriptor, field_data_cache, course_descriptor.id, course=course_descriptor,
    )
Esempio n. 9
0
def emulate_http_request(site=None, user=None, middleware_classes=None):
    """
    Generate a fake HTTP request and run selected middleware on it.

    This is used to enable features that assume they are running as part of an HTTP request handler. Many of these
    features retrieve the "current" request from a thread local managed by crum. They will make a call like
    crum.get_current_request() or something similar.

    Since some tasks are kicked off by a management commands (which does not have an HTTP request) and then executed
    in celery workers there is no "current HTTP request". Instead we just populate the global state that is most
    commonly used on request objects.

    Arguments:
        site (Site): The site that this request should emulate. Defaults to None.
        user (User): The user that initiated this fake request. Defaults to None
        middleware_classes (list): A list of classes that implement Django's middleware interface.
            Defaults to [CurrentRequestUserMiddleware, CurrentSiteThemeMiddleware] if None.
    """
    request = get_request_or_stub()
    request.site = site
    request.user = user

    # TODO: define the default middleware_classes in settings.py
    middleware_classes = middleware_classes or [
        CurrentRequestUserMiddleware,
        CurrentSiteThemeMiddleware,
    ]
    middleware_instances = [klass() for klass in middleware_classes]
    response = HttpResponse()

    for middleware in middleware_instances:
        _run_method_if_implemented(middleware, 'process_request', request)

    try:
        yield
    except Exception as exc:
        for middleware in reversed(middleware_instances):
            _run_method_if_implemented(middleware, 'process_exception',
                                       request, exc)
    else:
        for middleware in reversed(middleware_instances):
            _run_method_if_implemented(middleware, 'process_response', request,
                                       response)
Esempio n. 10
0
def emulate_http_request(site=None, user=None, middleware_classes=None):
    """
    Generate a fake HTTP request and run selected middleware on it.

    This is used to enable features that assume they are running as part of an HTTP request handler. Many of these
    features retrieve the "current" request from a thread local managed by crum. They will make a call like
    crum.get_current_request() or something similar.

    Since some tasks are kicked off by a management commands (which does not have an HTTP request) and then executed
    in celery workers there is no "current HTTP request". Instead we just populate the global state that is most
    commonly used on request objects.

    Arguments:
        site (Site): The site that this request should emulate. Defaults to None.
        user (User): The user that initiated this fake request. Defaults to None
        middleware_classes (list): A list of classes that implement Django's middleware interface.
            Defaults to [CurrentRequestUserMiddleware, CurrentSiteThemeMiddleware] if None.
    """
    request = get_request_or_stub()
    request.site = site
    request.user = user

    # TODO: define the default middleware_classes in settings.py
    middleware_classes = middleware_classes or [
        CurrentRequestUserMiddleware,
        CurrentSiteThemeMiddleware,
    ]
    middleware_instances = [klass() for klass in middleware_classes]
    response = HttpResponse()

    for middleware in middleware_instances:
        _run_method_if_implemented(middleware, 'process_request', request)

    try:
        yield
    except Exception as exc:
        for middleware in reversed(middleware_instances):
            _run_method_if_implemented(middleware, 'process_exception', request, exc)
    else:
        for middleware in reversed(middleware_instances):
            _run_method_if_implemented(middleware, 'process_response', request, response)