Example #1
0
 def check_question_author(user, content):
     """ Check if the given user is the author of the original question for both threads and comments. """
     if not content:
         return False
     try:
         request_cache_dict = RequestCache.get_request_cache().data
         if content["type"] == "thread":
             cache_key = "django_comment_client.permissions._check_condition.check_question_author.{}.{}".format(
                 user.id, content['id']
             )
             if cache_key in request_cache_dict:
                 return request_cache_dict[cache_key]
             else:
                 result = content["thread_type"] == "question" and content["user_id"] == str(user.id)
                 request_cache_dict[cache_key] = result
                 return result
         else:
             cache_key = "django_comment_client.permissions._check_condition.check_question_author.{}.{}".format(
                 user.id, content['thread_id']
             )
             if cache_key in request_cache_dict:
                 return request_cache_dict[cache_key]
             else:
                 # make the now-unavoidable comments service query
                 thread = Thread(id=content['thread_id']).to_dict()
                 return check_question_author(user, thread)
     except KeyError:
         return False
Example #2
0
 def check_team_member(user, content):
     """
     If the content has a commentable_id, verifies that either it is not associated with a team,
     or if it is, that the user is a member of that team.
     """
     if not content:
         return False
     try:
         commentable_id = content['commentable_id']
         request_cache_dict = RequestCache.get_request_cache().data
         cache_key = u"django_comment_client.check_team_member.{}.{}".format(
             user.id, commentable_id)
         if cache_key in request_cache_dict:
             return request_cache_dict[cache_key]
         team = get_team(commentable_id)
         if team is None:
             passes_condition = True
         else:
             passes_condition = team.users.filter(id=user.id).exists()
         request_cache_dict[cache_key] = passes_condition
     except KeyError:
         # We do not expect KeyError in production-- it usually indicates an improper test mock.
         logging.warning("Did not find key commentable_id in content.")
         passes_condition = False
     return passes_condition
Example #3
0
 def check_question_author(user, content):
     """ Check if the given user is the author of the original question for both threads and comments. """
     if not content:
         return False
     try:
         request_cache_dict = RequestCache.get_request_cache().data
         if content["type"] == "thread":
             cache_key = "django_comment_client.permissions._check_condition.check_question_author.{}.{}".format(
                 user.id, content['id'])
             if cache_key in request_cache_dict:
                 return request_cache_dict[cache_key]
             else:
                 result = content["thread_type"] == "question" and content[
                     "user_id"] == str(user.id)
                 request_cache_dict[cache_key] = result
                 return result
         else:
             cache_key = "django_comment_client.permissions._check_condition.check_question_author.{}.{}".format(
                 user.id, content['thread_id'])
             if cache_key in request_cache_dict:
                 return request_cache_dict[cache_key]
             else:
                 # make the now-unavoidable comments service query
                 thread = Thread(id=content['thread_id']).to_dict()
                 return check_question_author(user, thread)
     except KeyError:
         return False
Example #4
0
def has_permission(user, permission, course_id=None):
    assert isinstance(course_id, (NoneType, CourseKey))
    request_cache_dict = RequestCache.get_request_cache().data
    cache_key = "django_comment_client.permissions.has_permission.all_permissions.{}.{}".format(
        user.id, course_id)
    if cache_key in request_cache_dict:
        all_permissions = request_cache_dict[cache_key]
    else:
        all_permissions = all_permissions_for_user_in_course(user, course_id)
        request_cache_dict[cache_key] = all_permissions

    return permission in all_permissions
Example #5
0
def has_permission(user, permission, course_id=None):
    assert isinstance(course_id, (NoneType, CourseKey))
    request_cache_dict = RequestCache.get_request_cache().data
    cache_key = "django_comment_client.permissions.has_permission.all_permissions.{}.{}".format(
        user.id, course_id
    )
    if cache_key in request_cache_dict:
        all_permissions = request_cache_dict[cache_key]
    else:
        all_permissions = all_permissions_for_user_in_course(user, course_id)
        request_cache_dict[cache_key] = all_permissions

    return permission in all_permissions
Example #6
0
    def _bookmarks_cache(self, course_key, fetch=False):
        """
        Return the user's bookmarks cache for a particular course.

        Arguments:
            course_key (CourseKey): course_key of the course whose bookmarks cache should be returned.
            fetch (Bool): if the bookmarks should be fetched and cached if they already aren't.
        """
        store = modulestore()
        course_key = store.fill_in_run(course_key)
        if course_key.run is None:
            return []
        cache_key = CACHE_KEY_TEMPLATE.format(self._user.id, course_key)

        bookmarks_cache = RequestCache.get_request_cache().data.get(cache_key, None)
        if bookmarks_cache is None and fetch is True:
            bookmarks_cache = api.get_bookmarks(
                self._user, course_key=course_key, fields=DEFAULT_FIELDS
            )
            RequestCache.get_request_cache().data[cache_key] = bookmarks_cache

        return bookmarks_cache
Example #7
0
    def _bookmarks_cache(self, course_key, fetch=False):
        """
        Return the user's bookmarks cache for a particular course.

        Arguments:
            course_key (CourseKey): course_key of the course whose bookmarks cache should be returned.
            fetch (Bool): if the bookmarks should be fetched and cached if they already aren't.
        """
        store = modulestore()
        course_key = store.fill_in_run(course_key)
        if course_key.run is None:
            return []
        cache_key = CACHE_KEY_TEMPLATE.format(self._user.id, course_key)

        bookmarks_cache = RequestCache.get_request_cache().data.get(
            cache_key, None)
        if bookmarks_cache is None and fetch is True:
            bookmarks_cache = api.get_bookmarks(self._user,
                                                course_key=course_key,
                                                fields=DEFAULT_FIELDS)
            RequestCache.get_request_cache().data[cache_key] = bookmarks_cache

        return bookmarks_cache
Example #8
0
    def __init__(self, **kwargs):
        request_cache_dict = RequestCache.get_request_cache().data
        store = modulestore()

        services = kwargs.setdefault('services', {})
        services['completion'] = CompletionService(
            user=kwargs.get('user'), course_key=kwargs.get('course_id'))
        services['fs'] = xblock.reference.plugins.FSService()
        services['i18n'] = ModuleI18nService
        services['library_tools'] = LibraryToolsService(store)
        services['partitions'] = PartitionService(
            course_id=kwargs.get('course_id'), cache=request_cache_dict)
        services['settings'] = SettingsService()
        services['user_tags'] = UserTagsService(self)
        if badges_enabled():
            services['badging'] = BadgingService(
                course_id=kwargs.get('course_id'), modulestore=store)
        self.request_token = kwargs.pop('request_token', None)
        super(LmsModuleSystem, self).__init__(**kwargs)
Example #9
0
    def __init__(self, **kwargs):
        request_cache_dict = RequestCache.get_request_cache().data
        store = modulestore()

        services = kwargs.setdefault('services', {})
        services['completion'] = CompletionService(user=kwargs.get('user'), course_key=kwargs.get('course_id'))
        services['fs'] = xblock.reference.plugins.FSService()
        services['i18n'] = ModuleI18nService
        services['library_tools'] = LibraryToolsService(store)
        services['partitions'] = PartitionService(
            course_id=kwargs.get('course_id'),
            cache=request_cache_dict
        )
        services['settings'] = SettingsService()
        services['user_tags'] = UserTagsService(self)
        if badges_enabled():
            services['badging'] = BadgingService(course_id=kwargs.get('course_id'), modulestore=store)
        self.request_token = kwargs.pop('request_token', None)
        super(LmsModuleSystem, self).__init__(**kwargs)
    def _providers_for_block(cls, block):
        """
        Computes a list of enabled providers based on the given XBlock.
        The result is cached per request to avoid the overhead incurred
        by filtering override providers hundreds of times.

        Arguments:
            block: An XBlock
        """
        course_id = unicode(block.location.course_key)
        cache_key = ENABLED_MODULESTORE_OVERRIDE_PROVIDERS_KEY.format(course_id=course_id)

        request_cache = RequestCache.get_request_cache()
        enabled_providers = request_cache.data.get(cache_key)

        if enabled_providers is None:
            enabled_providers = [
                provider_class for provider_class in cls.provider_classes if provider_class.enabled_for(block)
            ]
            request_cache.data[cache_key] = enabled_providers

        return enabled_providers
    def _providers_for_course(cls, course):
        """
        Return a filtered list of enabled providers based
        on the course passed in. Cache this result per request to avoid
        needing to call the provider filter api hundreds of times.

        Arguments:
            course: The course XBlock
        """
        request_cache = RequestCache.get_request_cache()
        if course is None:
            cache_key = ENABLED_OVERRIDE_PROVIDERS_KEY.format(course_id='None')
        else:
            cache_key = ENABLED_OVERRIDE_PROVIDERS_KEY.format(course_id=unicode(course.id))
        enabled_providers = request_cache.data.get(cache_key, NOTSET)
        if enabled_providers == NOTSET:
            enabled_providers = tuple(
                (provider_class for provider_class in cls.provider_classes if provider_class.enabled_for(course))
            )
            request_cache.data[cache_key] = enabled_providers

        return enabled_providers
Example #12
0
 def check_team_member(user, content):
     """
     If the content has a commentable_id, verifies that either it is not associated with a team,
     or if it is, that the user is a member of that team.
     """
     if not content:
         return False
     try:
         commentable_id = content['commentable_id']
         request_cache_dict = RequestCache.get_request_cache().data
         cache_key = u"django_comment_client.check_team_member.{}.{}".format(user.id, commentable_id)
         if cache_key in request_cache_dict:
             return request_cache_dict[cache_key]
         team = get_team(commentable_id)
         if team is None:
             passes_condition = True
         else:
             passes_condition = team.users.filter(id=user.id).exists()
         request_cache_dict[cache_key] = passes_condition
     except KeyError:
         # We do not expect KeyError in production-- it usually indicates an improper test mock.
         logging.warning("Did not find key commentable_id in content.")
         passes_condition = False
     return passes_condition
Example #13
0
def create_modulestore_instance(
    engine,
    content_store,
    doc_store_config,
    options,
    i18n_service=None,
    fs_service=None,
    user_service=None,
    signal_handler=None,
):
    """
    This will return a new instance of a modulestore given an engine and options
    """
    # Import is placed here to avoid model import at project startup.
    import xblock.reference.plugins

    class_ = load_function(engine)

    _options = {}
    _options.update(options)

    FUNCTION_KEYS = ['render_template']
    for key in FUNCTION_KEYS:
        if key in _options and isinstance(_options[key], basestring):
            _options[key] = load_function(_options[key])

    request_cache = RequestCache.get_request_cache()

    try:
        metadata_inheritance_cache = caches['mongo_metadata_inheritance']
    except InvalidCacheBackendError:
        metadata_inheritance_cache = caches['default']

    if issubclass(class_, MixedModuleStore):
        _options['create_modulestore_instance'] = create_modulestore_instance

    if issubclass(class_, BranchSettingMixin):
        _options['branch_setting_func'] = _get_modulestore_branch_setting

    if HAS_USER_SERVICE and not user_service:
        xb_user_service = DjangoXBlockUserService(get_current_user())
    else:
        xb_user_service = None

    xblock_field_data_wrappers = [
        load_function(path) for path in settings.XBLOCK_FIELD_DATA_WRAPPERS
    ]

    def fetch_disabled_xblock_types():
        """
        Get the disabled xblock names, using the request_cache if possible to avoid hitting
        a database every time the list is needed.
        """
        # If the import could not be loaded, return an empty list.
        if disabled_xblocks is None:
            return []

        if request_cache:
            if 'disabled_xblock_types' not in request_cache.data:
                request_cache.data['disabled_xblock_types'] = [
                    block.name for block in disabled_xblocks()
                ]
            return request_cache.data['disabled_xblock_types']
        else:
            disabled_xblock_types = [
                block.name for block in disabled_xblocks()
            ]

        return disabled_xblock_types

    return class_(
        contentstore=content_store,
        metadata_inheritance_cache_subsystem=metadata_inheritance_cache,
        request_cache=request_cache,
        xblock_mixins=getattr(settings, 'XBLOCK_MIXINS', ()),
        xblock_select=getattr(settings, 'XBLOCK_SELECT_FUNCTION', None),
        xblock_field_data_wrappers=xblock_field_data_wrappers,
        disabled_xblock_types=fetch_disabled_xblock_types,
        doc_store_config=doc_store_config,
        i18n_service=i18n_service or ModuleI18nService,
        fs_service=fs_service or xblock.reference.plugins.FSService(),
        user_service=user_service or xb_user_service,
        signal_handler=signal_handler or SignalHandler(class_),
        **_options)
Example #14
0
def create_modulestore_instance(
        engine,
        content_store,
        doc_store_config,
        options,
        i18n_service=None,
        fs_service=None,
        user_service=None,
        signal_handler=None,
):
    """
    This will return a new instance of a modulestore given an engine and options
    """
    # Import is placed here to avoid model import at project startup.
    import xblock.reference.plugins

    class_ = load_function(engine)

    _options = {}
    _options.update(options)

    FUNCTION_KEYS = ['render_template']
    for key in FUNCTION_KEYS:
        if key in _options and isinstance(_options[key], basestring):
            _options[key] = load_function(_options[key])

    request_cache = RequestCache.get_request_cache()

    try:
        metadata_inheritance_cache = caches['mongo_metadata_inheritance']
    except InvalidCacheBackendError:
        metadata_inheritance_cache = caches['default']

    if issubclass(class_, MixedModuleStore):
        _options['create_modulestore_instance'] = create_modulestore_instance

    if issubclass(class_, BranchSettingMixin):
        _options['branch_setting_func'] = _get_modulestore_branch_setting

    if HAS_USER_SERVICE and not user_service:
        xb_user_service = DjangoXBlockUserService(get_current_user())
    else:
        xb_user_service = None

    xblock_field_data_wrappers = [load_function(path) for path in settings.XBLOCK_FIELD_DATA_WRAPPERS]

    def fetch_disabled_xblock_types():
        """
        Get the disabled xblock names, using the request_cache if possible to avoid hitting
        a database every time the list is needed.
        """
        # If the import could not be loaded, return an empty list.
        if disabled_xblocks is None:
            return []

        if request_cache:
            if 'disabled_xblock_types' not in request_cache.data:
                request_cache.data['disabled_xblock_types'] = [block.name for block in disabled_xblocks()]
            return request_cache.data['disabled_xblock_types']
        else:
            disabled_xblock_types = [block.name for block in disabled_xblocks()]

        return disabled_xblock_types

    return class_(
        contentstore=content_store,
        metadata_inheritance_cache_subsystem=metadata_inheritance_cache,
        request_cache=request_cache,
        xblock_mixins=getattr(settings, 'XBLOCK_MIXINS', ()),
        xblock_select=getattr(settings, 'XBLOCK_SELECT_FUNCTION', None),
        xblock_field_data_wrappers=xblock_field_data_wrappers,
        disabled_xblock_types=fetch_disabled_xblock_types,
        doc_store_config=doc_store_config,
        i18n_service=i18n_service or ModuleI18nService,
        fs_service=fs_service or xblock.reference.plugins.FSService(),
        user_service=user_service or xb_user_service,
        signal_handler=signal_handler or SignalHandler(class_),
        **_options
    )