Пример #1
0
 def get(self, request, format=None):
     if request.query_params.get('raise', ''):
         raise RuntimeError()
     if request.query_params.get('impersonate', ''):
         with impersonate(None):
             current_user = six.text_type(get_current_user())
     else:
         current_user = six.text_type(get_current_user())
     return Response(current_user)
Пример #2
0
def index(request):
    if request.GET.get('raise', ''):
        raise RuntimeError()
    if request.GET.get('impersonate', ''):
        with impersonate(None):
            current_user = smart_text(get_current_user())
    else:
        current_user = smart_text(get_current_user())
    return HttpResponse(current_user, content_type='text/plain')
Пример #3
0
 def filter(self, record):
     user = get_current_user()
     if user and user.pk:
         record.userid = user.pk
     else:
         record.userid = None
     return True
Пример #4
0
 def save(self, force_insert=False, force_update=False, using=None,
          update_fields=None):
     user = get_current_user()
     self.create_by = user
     if self.customer_name is None:
         self.customer_name = '客户' + self.customer_id
     super(BaseInfo, self).save(force_insert, force_update, using, update_fields)
Пример #5
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
    """
    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])

    if HAS_REQUEST_CACHE:
        request_cache = RequestCache.get_request_cache()
    else:
        request_cache = None

    try:
        metadata_inheritance_cache = get_cache("mongo_metadata_inheritance")
    except InvalidCacheBackendError:
        metadata_inheritance_cache = get_cache("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

    if "read_preference" in doc_store_config:
        doc_store_config["read_preference"] = getattr(ReadPreference, doc_store_config["read_preference"])

    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),
        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
    )
Пример #6
0
def update_masters_access_course(sender, instance, **kwargs):  # pylint: disable=unused-argument
    """
    Update all blocks in the verified content group to include the master's content group
    """
    if instance.mode_slug != CourseMode.MASTERS:
        return
    masters_id = getattr(settings, 'COURSE_ENROLLMENT_MODES', {}).get('masters', {}).get('id', None)
    verified_id = getattr(settings, 'COURSE_ENROLLMENT_MODES', {}).get('verified', {}).get('id', None)
    if not (masters_id and verified_id):
        log.error("Missing settings.COURSE_ENROLLMENT_MODES -> verified:%s masters:%s", verified, masters)
        return

    course_id = instance.course_id
    user = get_current_user()
    user_id = user.id if user else None
    store = modulestore()

    with store.bulk_operations(course_id):
        try:
            items = store.get_items(course_id, settings={'group_access': {'$exists': True}}, include_orphans=False)
        except ItemNotFoundError:
            return
        for item in items:
            group_access = item.group_access
            enrollment_groups = group_access.get(ENROLLMENT_TRACK_PARTITION_ID, None)
            if enrollment_groups is not None:
                if verified_id in enrollment_groups and masters_id not in enrollment_groups:
                    enrollment_groups.append(masters_id)
                    item.group_access = group_access
                    log.info("Publishing %s with Master's group access", item.location)
                    store.update_item(item, user_id)
                    store.publish(item.location, user_id)
Пример #7
0
def grade_updated(**kwargs):
    """
    Emits the appropriate grade-related event after checking for which
    event-transaction is active.

    Emits a problem.submitted event only if there is no current event
    transaction type, i.e. we have not reached this point in the code via
    an outer event type (such as problem.rescored or score_overridden).
    """
    root_type = get_event_transaction_type()

    if not root_type:
        root_id = get_event_transaction_id()
        if not root_id:
            root_id = create_new_event_transaction_id()
        set_event_transaction_type(PROBLEM_SUBMITTED_EVENT_TYPE)
        tracker.emit(
            unicode(PROBLEM_SUBMITTED_EVENT_TYPE),
            {
                'user_id': unicode(kwargs['user_id']),
                'course_id': unicode(kwargs['course_id']),
                'problem_id': unicode(kwargs['usage_id']),
                'event_transaction_id': unicode(root_id),
                'event_transaction_type': unicode(PROBLEM_SUBMITTED_EVENT_TYPE),
                'weighted_earned': kwargs.get('weighted_earned'),
                'weighted_possible': kwargs.get('weighted_possible'),
            }
        )

    elif root_type in [GRADES_RESCORE_EVENT_TYPE, GRADES_OVERRIDE_EVENT_TYPE]:
        current_user = get_current_user()
        instructor_id = getattr(current_user, 'id', None)
        tracker.emit(
            unicode(root_type),
            {
                'course_id': unicode(kwargs['course_id']),
                'user_id': unicode(kwargs['user_id']),
                'problem_id': unicode(kwargs['usage_id']),
                'new_weighted_earned': kwargs.get('weighted_earned'),
                'new_weighted_possible': kwargs.get('weighted_possible'),
                'only_if_higher': kwargs.get('only_if_higher'),
                'instructor_id': unicode(instructor_id),
                'event_transaction_id': unicode(get_event_transaction_id()),
                'event_transaction_type': unicode(root_type),
            }
        )

    elif root_type in [SUBSECTION_OVERRIDE_EVENT_TYPE]:
        tracker.emit(
            unicode(root_type),
            {
                'course_id': unicode(kwargs['course_id']),
                'user_id': unicode(kwargs['user_id']),
                'problem_id': unicode(kwargs['usage_id']),
                'only_if_higher': kwargs.get('only_if_higher'),
                'override_deleted': kwargs.get('score_deleted', False),
                'event_transaction_id': unicode(get_event_transaction_id()),
                'event_transaction_type': unicode(root_type),
            }
        )
Пример #8
0
 def test_middleware(self):
     self.create_test_users_and_groups()
     self.assertEqual(get_current_user(), None)
     url = reverse("test_app:index")
     # Test anonymous user.
     response = self.client.get(url)
     self.assertEqual(response.status_code, 200)
     self.assertEqual(response.content, "AnonymousUser")
     self.assertEqual(get_current_user(), None)
     # Test logged in user.
     self.client.login(username=self.users[0].username, password=self.user_passwords[0])
     response = self.client.get(url)
     self.assertEqual(response.status_code, 200)
     self.assertEqual(response.content, unicode(self.users[0]))
     self.assertEqual(get_current_user(), None)
     # Test impersonate context manager.
     with impersonate(self.users[0]):
         self.assertEqual(get_current_user(), self.users[0])
     self.assertEqual(get_current_user(), None)
     # Test impersonate(None) within view requested by logged in user.
     self.client.login(username=self.users[0].username, password=self.user_passwords[0])
     response = self.client.get(url + "?impersonate=1")
     self.assertEqual(response.status_code, 200)
     self.assertEqual(response.content, unicode(None))
     self.assertEqual(get_current_user(), None)
     # Test when request raises exception.
     try:
         response = self.client.get(url + "?raise=1")
     except RuntimeError:
         response = None
     self.assertEqual(response, None)
     self.assertEqual(get_current_user(), None)
Пример #9
0
 def save(self, *args, **kwargs):
     ### vengono aggiunti l'ip l'utente e la data di modifica/creazione in automatico
     request = get_current_request()
     if request:
         remote_addr = request.META['REMOTE_ADDR']
     
     user = get_current_user()
     if user and not user.pk:
         user = None
     if not self.pk:
         self.created_by = user.get_username() + '[' + remote_addr + ']'
         self.created = datetime.now()
     self.modified_by = user.get_username() + '[' + remote_addr + ']'
     self.modified = datetime.now()        
     super(Base, self).save(*args, **kwargs)        
Пример #10
0
def _emit_event(kwargs):
    """
    Emits a problem submitted event only if there is no current event
    transaction type, i.e. we have not reached this point in the code via a
    rescore or student state deletion.

    If the event transaction type has already been set and the transacation is
    a rescore, emits a problem rescored event.
    """
    root_type = get_event_transaction_type()

    if not root_type:
        root_id = get_event_transaction_id()
        if not root_id:
            root_id = create_new_event_transaction_id()
        set_event_transaction_type(PROBLEM_SUBMITTED_EVENT_TYPE)
        tracker.emit(
            unicode(PROBLEM_SUBMITTED_EVENT_TYPE),
            {
                'user_id': unicode(kwargs['user_id']),
                'course_id': unicode(kwargs['course_id']),
                'problem_id': unicode(kwargs['usage_id']),
                'event_transaction_id': unicode(root_id),
                'event_transaction_type': unicode(PROBLEM_SUBMITTED_EVENT_TYPE),
                'weighted_earned': kwargs.get('weighted_earned'),
                'weighted_possible': kwargs.get('weighted_possible'),
            }
        )

    if root_type in [GRADES_RESCORE_EVENT_TYPE, GRADES_OVERRIDE_EVENT_TYPE]:
        current_user = get_current_user()
        instructor_id = getattr(current_user, 'id', None)
        tracker.emit(
            unicode(GRADES_RESCORE_EVENT_TYPE),
            {
                'course_id': unicode(kwargs['course_id']),
                'user_id': unicode(kwargs['user_id']),
                'problem_id': unicode(kwargs['usage_id']),
                'new_weighted_earned': kwargs.get('weighted_earned'),
                'new_weighted_possible': kwargs.get('weighted_possible'),
                'only_if_higher': kwargs.get('only_if_higher'),
                'instructor_id': unicode(instructor_id),
                'event_transaction_id': unicode(get_event_transaction_id()),
                'event_transaction_type': unicode(root_type),
            }
        )
Пример #11
0
    def save(self, *args, **kwargs):

        global content_role_type
        global main_role
        global content_city_type

        user = get_current_user()

        if main_role=="is_Enumerator" or main_role=="is_admin":
            self.roles_type=content_role_type
            self.city_type=content_city_type
            if self.Send=="Do not send":
                self.Send=main_role
            else:
                pass

        elif main_role=="is_AreaSupervisor" or main_role=="is_admin":
            self.roles_type==content_role_type
            self.city_type=content_city_type
            if self.Send=="Do not send":
                self.Send=main_role
            else:
                pass

        elif main_role=="is_Verification" or main_role=="is_admin":
            self.roles_type==content_role_type
            self.city_type=content_city_type
            if self.Send=="Do not send":
                self.Send=main_role
            else:
                pass

        if user and not user.pk:
            user = None
        if not self.pk:
            self.enumerator_name = user
        super(Organization, self).save(*args, **kwargs)
Пример #12
0
 def test_middleware(self):
     # For test coverage.
     import crum
     imp.reload(crum)
     # Test anonymous user.
     self.assertEqual(get_current_user(), None)
     url = reverse('test_app:index')
     response = self.client.get(url)
     response_content = response.content.decode('utf-8')
     self.assertEqual(response.status_code, 200)
     self.assertEqual(response_content, 'AnonymousUser')
     self.assertEqual(get_current_user(), None)
     # Test logged in user.
     self.client.login(username=self.user.username,
                       password=self.user_password)
     response = self.client.get(url)
     response_content = response.content.decode('utf-8')
     self.assertEqual(response.status_code, 200)
     self.assertEqual(response_content, six.text_type(self.user))
     self.assertEqual(get_current_user(), None)
     # Test impersonate context manager.
     with impersonate(self.user):
         self.assertEqual(get_current_user(), self.user)
     self.assertEqual(get_current_user(), None)
     # Test impersonate(None) within view requested by logged in user.
     self.client.login(username=self.user.username,
                       password=self.user_password)
     response = self.client.get(url + '?impersonate=1')
     response_content = response.content.decode('utf-8')
     self.assertEqual(response.status_code, 200)
     self.assertEqual(response_content, six.text_type(None))
     self.assertEqual(get_current_user(), None)
     # Test when request raises exception.
     try:
         response = self.client.get(url + '?raise=1')
     except RuntimeError:
         response = None
     self.assertEqual(response, None)
     self.assertEqual(get_current_user(), None)
Пример #13
0
 def test_middleware_with_rest_framework(self):
     # Test anonymous user.
     self.assertEqual(get_current_user(), None)
     url = reverse('test_app:api_index')
     response = self.client.get(url)
     response_content = json.loads(response.content.decode('utf-8'))
     self.assertEqual(response.status_code, 200)
     self.assertEqual(response_content, six.text_type('AnonymousUser'))
     self.assertEqual(get_current_user(), None)
     # Test logged in user (session auth).
     self.client.login(username=self.user.username,
                       password=self.user_password)
     response = self.client.get(url)
     response_content = json.loads(response.content.decode('utf-8'))
     self.assertEqual(response.status_code, 200)
     self.assertEqual(response_content, six.text_type(self.user))
     self.assertEqual(get_current_user(), None)
     # Test logged in user (basic auth).
     basic_auth = '{0}:{1}'.format(self.user.username, self.user_password)
     basic_auth = six.binary_type(basic_auth.encode('utf-8'))
     basic_auth = base64.b64encode(basic_auth).decode('ascii')
     client_kwargs = {'HTTP_AUTHORIZATION': 'Basic %s' % basic_auth}
     client = Client(**client_kwargs)
     response = client.get(url)
     response_content = json.loads(response.content.decode('utf-8'))
     self.assertEqual(response.status_code, 200)
     self.assertEqual(response_content, six.text_type(self.user))
     self.assertEqual(get_current_user(), None)
     # Test impersonate(None) within view requested by logged in user.
     self.client.login(username=self.user.username,
                       password=self.user_password)
     response = self.client.get(url + '?impersonate=1')
     response_content = json.loads(response.content.decode('utf-8'))
     self.assertEqual(response.status_code, 200)
     self.assertEqual(response_content, six.text_type(None))
     self.assertEqual(get_current_user(), None)
     # Test when request raises exception.
     try:
         response = self.client.get(url + '?raise=1')
     except RuntimeError:
         response = None
     self.assertEqual(response, None)
     self.assertEqual(get_current_user(), None)
Пример #14
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        friends_ids = get_current_user().friends.values('id')
        self.helper = FormHelper()
        self.helper.form_id = 'BudgetedEventForm'
        self.fields['cat1'].queryset = Cat1.admin_objects.filter(is_deleted=False)
        if 'cat1' in self.initial:
            try:
                cat1 = int(self.initial.get('cat1'))
                self.fields['cat2'].queryset = Cat2.admin_objects.filter(cat1=cat1, is_deleted=False)
            except (ValueError, TypeError):
                self.fields['cat2'].queryset = Cat2.objects.none()
        else:
            self.fields['cat2'].queryset = Cat2.objects.none()

        self.fields['cat1'].queryset = Cat1.admin_objects.filter(is_deleted=False)
        self.fields['account_source'].queryset = Account.admin_objects.filter(is_deleted=False)
        self.fields['account_destination'].queryset = Account.admin_objects.filter(is_deleted=False)
        self.fields['vendor'].queryset = Vendor.admin_objects.filter(is_deleted=False)
        self.fields["users_admin"].widget = forms.widgets.CheckboxSelectMultiple()
        self.fields["users_admin"].queryset = User.objects.filter(id__in=friends_ids,)
        self.fields["users_view"].widget = forms.widgets.CheckboxSelectMultiple()
        self.fields["users_view"].queryset = User.objects.filter(id__in=friends_ids,)
        self.helper.layout = Layout(
            Div(
                Div('description', css_class='form-group col-md-6 mb-0'),
                Div('vendor', css_class='form-group col-md-4 mb-0'),
                css_class='form-row'
            ),
            Div(
                Div('cat1', css_class='form-group col-md-4 mb-0'),
                Div('cat2', css_class='form-group col-md-4 mb-0'),
                css_class='form-row'
            ),
            Div(
                # Div('amount_planned', css_class='form-group col-md-4 mb-0'),
                Div(PrependedText('amount_planned', '$', css_class='form-group col-sm-6 mb-0 ml-0')),
                Div('account_source', css_class='form-group col-md-4 mb-0'),
                Div('account_destination', css_class='form-group col-md-4 mb-0'),
                css_class='form-row'
            ),
            Div(
                Div('budget_only', css_class='form-group col-md-4 mb-0'),
                Div('ismanual', css_class='form-group col-md-4 mb-0'),
                Div('isrecurring', css_class='form-group col-md-4 mb-0'),
                css_class='form-row'
            ),
            Div(
                Div('repeat_start', css_class='form-group col-md-4 mb-0'),
                Div('repeat_stop', css_class='form-group col-md-4 mb-0'),
                css_class='form-row'
            ),
            Div(
                Div('repeat_interval_days', css_class='form-group col-md-2 mb-0'),
                Div('repeat_interval_weeks', css_class='form-group col-md-2 mb-0'),
                Div('repeat_interval_months', css_class='form-group col-md-2 mb-0'),
                Div('repeat_interval_years', css_class='form-group col-md-2 mb-0'),
                css_class='form-row'
            ),
            Div(
                Div('users_admin', css_class='form-group col-md-4 mb-0'),
                Div('users_view', css_class='form-group col-md-4 mb-0'),
                css_class='form-row'
            ),
        )
Пример #15
0
 def unmark(self):
     x = self.validated_data.get('x')
     y = self.validated_data.get('y')
     self.instance.unmark_cell(get_current_user(), x, y)
Пример #16
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], six.string_types):
            _options[key] = load_function(_options[key])

    request_cache = DEFAULT_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 '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']

    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)
Пример #17
0
 def join(self):
     self.instance.join(get_current_user())
Пример #18
0
    def get_blacklist_of_fields(cls, course_key):
        """
        Returns a list of fields to not include in Studio Advanced settings based on a
        feature flag (i.e. enabled or disabled).
        """
        # Copy the filtered list to avoid permanently changing the class attribute.
        black_list = list(cls.FIELDS_BLACK_LIST)

        # Do not show giturl if feature is not enabled.
        if not settings.FEATURES.get('ENABLE_EXPORT_GIT'):
            black_list.append('giturl')

        # Do not show edxnotes if the feature is disabled.
        if not settings.FEATURES.get('ENABLE_EDXNOTES'):
            black_list.append('edxnotes')

        # Do not show video auto advance if the feature is disabled
        if not settings.FEATURES.get('ENABLE_OTHER_COURSE_SETTINGS'):
            black_list.append('other_course_settings')

        # Do not show video_upload_pipeline if the feature is disabled.
        if not settings.FEATURES.get('ENABLE_VIDEO_UPLOAD_PIPELINE'):
            black_list.append('video_upload_pipeline')

        # Do not show video auto advance if the feature is disabled
        if not settings.FEATURES.get('ENABLE_AUTOADVANCE_VIDEOS'):
            black_list.append('video_auto_advance')

        # Do not show social sharing url field if the feature is disabled.
        if (not hasattr(settings, 'SOCIAL_SHARING_SETTINGS') or
                not getattr(settings, 'SOCIAL_SHARING_SETTINGS', {}).get("CUSTOM_COURSE_URLS")):
            black_list.append('social_sharing_url')

        # Do not show teams configuration if feature is disabled.
        if not settings.FEATURES.get('ENABLE_TEAMS'):
            black_list.append('teams_configuration')

        if not settings.FEATURES.get('ENABLE_VIDEO_BUMPER'):
            black_list.append('video_bumper')

        # Do not show enable_ccx if feature is not enabled.
        if not settings.FEATURES.get('CUSTOM_COURSES_EDX'):
            black_list.append('enable_ccx')
            black_list.append('ccx_connector')

        # Do not show "Issue Open Badges" in Studio Advanced Settings
        # if the feature is disabled.
        if not settings.FEATURES.get('ENABLE_OPENBADGES'):
            black_list.append('issue_badges')

        # If the XBlockStudioConfiguration table is not being used, there is no need to
        # display the "Allow Unsupported XBlocks" setting.
        if not XBlockStudioConfigurationFlag.is_enabled():
            black_list.append('allow_unsupported_xblocks')

        # If the ENABLE_PROCTORING_PROVIDER_OVERRIDES waffle flag is not enabled,
        # do not show "Proctoring Configuration" in Studio Advanced Settings.
        if not ENABLE_PROCTORING_PROVIDER_OVERRIDES.is_enabled(course_key):
            black_list.append('proctoring_provider')

        # Do not show "Course Visibility For Unenrolled Learners" in Studio Advanced Settings
        # if the enable_anonymous_access flag is not enabled
        if not COURSE_ENABLE_UNENROLLED_ACCESS_FLAG.is_enabled(course_key=course_key):
            black_list.append('course_visibility')

        # Do not show "Create Zendesk Tickets For Suspicious Proctored Exam Attempts" in
        # Studio Advanced Settings if the user is not edX staff.
        if not GlobalStaff().has_user(get_current_user()):
            black_list.append('create_zendesk_tickets')

        return black_list
Пример #19
0
def save_to_git(sender, instance, **kwargs):
    current_user = get_current_user()
    if current_user:
        committer = "{} <{}>".format(current_user, current_user.email).encode('utf8')
        repo_dir = os.path.join(settings.STATIC_ROOT, 'circle_history')
        git.commit_circles_to_git(repo_dir, committer)
Пример #20
0
 def save(self, *args, **kwargs):
     user = get_current_user()
     if user:
         self.owner = user
     super().save(*args, **kwargs)
Пример #21
0
 def get_others(self, obj):
     user = get_current_user()
     qs = Game.objects.exclude(players__pk=user.pk)
     return GameSerializer(qs, many=True).data
Пример #22
0
def get_authorized_dojo_meta(permission):
    user = get_current_user()

    if user is None:
        return DojoMeta.objects.none()

    if user.is_superuser:
        return DojoMeta.objects.all().order_by('name')

    if settings.FEATURE_AUTHORIZATION_V2:
        if user.is_staff and settings.AUTHORIZATION_STAFF_OVERRIDE:
            return DojoMeta.objects.all().order_by('name')

        if hasattr(
                user, 'global_role'
        ) and user.global_role.role is not None and role_has_permission(
                user.global_role.role.id, permission):
            return DojoMeta.objects.all().order_by('name')

        for group in get_groups(user):
            if hasattr(
                    group, 'global_role'
            ) and group.global_role.role is not None and role_has_permission(
                    group.global_role.role.id, permission):
                return DojoMeta.objects.all().order_by('name')

        roles = get_roles_for_permission(permission)
        product_authorized_product_type_roles = Product_Type_Member.objects.filter(
            product_type=OuterRef('product__prod_type_id'),
            user=user,
            role__in=roles)
        product_authorized_product_roles = Product_Member.objects.filter(
            product=OuterRef('product_id'), user=user, role__in=roles)
        product_authorized_product_type_groups = Product_Type_Group.objects.filter(
            product_type=OuterRef('product__prod_type_id'),
            group__users=user,
            role__in=roles)
        product_authorized_product_groups = Product_Group.objects.filter(
            product=OuterRef('product_id'), group__users=user, role__in=roles)
        endpoint_authorized_product_type_roles = Product_Type_Member.objects.filter(
            product_type=OuterRef('endpoint__product__prod_type_id'),
            user=user,
            role__in=roles)
        endpoint_authorized_product_roles = Product_Member.objects.filter(
            product=OuterRef('endpoint__product_id'),
            user=user,
            role__in=roles)
        endpoint_authorized_product_type_groups = Product_Type_Group.objects.filter(
            product_type=OuterRef('endpoint__product__prod_type_id'),
            group__users=user,
            role__in=roles)
        endpoint_authorized_product_groups = Product_Group.objects.filter(
            product=OuterRef('endpoint__product_id'),
            group__users=user,
            role__in=roles)
        finding_authorized_product_type_roles = Product_Type_Member.objects.filter(
            product_type=OuterRef(
                'finding__test__engagement__product__prod_type_id'),
            user=user,
            role__in=roles)
        finding_authorized_product_roles = Product_Member.objects.filter(
            product=OuterRef('finding__test__engagement__product_id'),
            user=user,
            role__in=roles)
        finding_authorized_product_type_groups = Product_Type_Group.objects.filter(
            product_type=OuterRef(
                'finding__test__engagement__product__prod_type_id'),
            group__users=user,
            role__in=roles)
        finding_authorized_product_groups = Product_Group.objects.filter(
            product=OuterRef('finding__test__engagement__product_id'),
            group__users=user,
            role__in=roles)
        dojo_meta = DojoMeta.objects.annotate(
            product__prod_type__member=Exists(
                product_authorized_product_type_roles),
            product__member=Exists(product_authorized_product_roles),
            product__prod_type__authorized_group=Exists(
                product_authorized_product_type_groups),
            product__authorized_group=Exists(
                product_authorized_product_groups),
            endpoint__product__prod_type__member=Exists(
                endpoint_authorized_product_type_roles),
            endpoint__product__member=Exists(
                endpoint_authorized_product_roles),
            endpoint__product__prod_type__authorized_group=Exists(
                endpoint_authorized_product_type_groups),
            endpoint__product__authorized_group=Exists(
                endpoint_authorized_product_groups),
            finding__test__engagement__product__prod_type__member=Exists(
                finding_authorized_product_type_roles),
            finding__test__engagement__product__member=Exists(
                finding_authorized_product_roles),
            finding__test__engagement__product__prod_type__authorized_group=
            Exists(finding_authorized_product_type_groups),
            finding__test__engagement__product__authorized_group=Exists(
                finding_authorized_product_groups)).order_by('name')
        dojo_meta = dojo_meta.filter(
            Q(product__prod_type__member=True) | Q(product__member=True)
            | Q(product__prod_type__authorized_group=True)
            | Q(product__authorized_group=True)
            | Q(endpoint__product__prod_type__member=True)
            | Q(endpoint__product__member=True)
            | Q(endpoint__product__prod_type__authorized_group=True)
            | Q(endpoint__product__authorized_group=True)
            | Q(finding__test__engagement__product__prod_type__member=True)
            | Q(finding__test__engagement__product__member=True)
            | Q(finding__test__engagement__product__prod_type__authorized_group
                =True)
            | Q(finding__test__engagement__product__authorized_group=True))
    else:
        if user.is_staff:
            dojo_meta = DojoMeta.objects.all().order_by('name')
        else:
            dojo_meta = DojoMeta.objects.filter(
                Q(product__authorized_users__in=[user])
                | Q(product__prod_type__authorized_users__in=[user])
                | Q(endpoint__product__authorized_users__in=[user])
                | Q(endpoint__product__prod_type__authorized_users__in=[user])
                | Q(finding__test__engagement__product__authorized_users__in=[
                    user
                ]) |
                Q(finding__test__engagement__product__prod_type__authorized_users__in
                  =[user])).order_by('name')
    return dojo_meta
Пример #23
0
 def clean(self):
     try:
         self.created_by
     except Exception as e:
         self.created_by = get_current_user()
     self.updated_by = get_current_user()
Пример #24
0
def get_authorized_tests(permission, product=None):
    user = get_current_user()

    if user is None:
        return Test.objects.none()

    tests = Test.objects.all()
    if product:
        tests = tests.filter(engagement__product=product)

    if user.is_superuser:
        return tests

    if settings.FEATURE_AUTHORIZATION_V2:
        if user.is_staff and settings.AUTHORIZATION_STAFF_OVERRIDE:
            return Test.objects.all()

        if hasattr(
                user, 'global_role'
        ) and user.global_role.role is not None and role_has_permission(
                user.global_role.role.id, permission):
            return Test.objects.all()

        for group in get_groups(user):
            if hasattr(
                    group, 'global_role'
            ) and group.global_role.role is not None and role_has_permission(
                    group.global_role.role.id, permission):
                return Test.objects.all()

        roles = get_roles_for_permission(permission)
        authorized_product_type_roles = Product_Type_Member.objects.filter(
            product_type=OuterRef('engagement__product__prod_type_id'),
            user=user,
            role__in=roles)
        authorized_product_roles = Product_Member.objects.filter(
            product=OuterRef('engagement__product_id'),
            user=user,
            role__in=roles)

        authorized_product_type_groups = Product_Type_Group.objects.filter(
            product_type=OuterRef('engagement__product__prod_type_id'),
            group__users=user,
            role__in=roles)
        authorized_product_groups = Product_Group.objects.filter(
            product=OuterRef('engagement__product_id'),
            group__users=user,
            role__in=roles)

        tests = tests.annotate(
            engagement__product__prod_type__member=Exists(
                authorized_product_type_roles),
            engagement__product__member=Exists(authorized_product_roles),
            engagement__product__prod_type__authorized_group=Exists(
                authorized_product_type_groups),
            engagement__product__authorized_group=Exists(
                authorized_product_groups))

        tests = tests.filter(
            Q(engagement__product__prod_type__member=True)
            | Q(engagement__product__member=True)
            | Q(engagement__product__prod_type__authorized_group=True)
            | Q(engagement__product__authorized_group=True))
    else:
        if not user.is_staff:
            tests = tests.filter(
                Q(engagement__product__authorized_users__in=[user]) |
                Q(engagement__product__prod_type__authorized_users__in=[user]))
    return tests
Пример #25
0
def session(request):
    context = {}
    user_id = get_current_user().id
    # print('USER ID', user_id)
    parent = Parent.objects.get(user_id=user_id)

    # option for select to choose which child correspondent should appear
    option = Child.objects.filter(parent_id=parent.id)
    context['select_child'] = option

    my_child = request.GET.get('option')
    print("LLLLLL", my_child)

    if my_child:
        get_child_from_clicked = Child.objects.get(id=my_child)
        context['clicked_child'] = get_child_from_clicked

    # get a list of all kids belonging to the current parent except 1st child since its a dummy account
    if my_child:
        parent_children = Child.objects.filter(id=my_child)
    else:
        parent_children = Child.objects.filter(parent_id=parent.id)

    # print("exclude", parent_children)

    # test = Languagetolearn.objects.all().values('child', 'child_correspondent')
    previous_sessions = []
    for child in parent_children:
        # stores the foreign child id when my child is the host
        meetings_with_my_child_as_host = Languagetolearn.objects.filter(child_id=child.id). \
            values(
            'child_correspondent').exclude(child_correspondent_id=1).filter(date_slot__lte=datetime.today()).filter(end_time_slot__lte=datetime.today().now())

        for kiddy_talk in meetings_with_my_child_as_host:
            current_id = kiddy_talk['child_correspondent']
            # checks if the current id to append is already known or not
            if current_id not in previous_sessions:
                # then add it to the final list
                previous_sessions.append(current_id)

        # stores the foreign child id when my child is the correspondent
        meetings_with_my_child_as_corr = Languagetolearn.objects.filter(child_correspondent_id=child.id)\
            .values('child').filter(date_slot__lte=datetime.today()).filter(end_time_slot__lte=datetime.today().now())
        print("TIME", meetings_with_my_child_as_corr)
        for kiddy_talk in meetings_with_my_child_as_corr:
            current_id = kiddy_talk['child']
            # check if the current id to append is already known
            if current_id not in previous_sessions:
                # then add it to the final list
                previous_sessions.append(current_id)

    print("TO DISPLAY: ", previous_sessions)

    children_to_display = []
    for index, child_id in enumerate(previous_sessions):
        children_to_display.append(Child.objects.filter(id=child_id))

    context["content"] = children_to_display
    print('CONTEXT DATA', context["content"])

    return render(request, 'previous_session.html', context)
Пример #26
0
def grade_updated(**kwargs):
    """
    Emits the appropriate grade-related event after checking for which
    event-transaction is active.

    Emits a problem.submitted event only if there is no current event
    transaction type, i.e. we have not reached this point in the code via
    an outer event type (such as problem.rescored or score_overridden).
    """
    root_type = get_event_transaction_type()

    if not root_type:
        root_id = get_event_transaction_id()
        if not root_id:
            root_id = create_new_event_transaction_id()
        set_event_transaction_type(PROBLEM_SUBMITTED_EVENT_TYPE)
        tracker.emit(
            six.text_type(PROBLEM_SUBMITTED_EVENT_TYPE), {
                'user_id':
                six.text_type(kwargs['user_id']),
                'course_id':
                six.text_type(kwargs['course_id']),
                'problem_id':
                six.text_type(kwargs['usage_id']),
                'event_transaction_id':
                six.text_type(root_id),
                'event_transaction_type':
                six.text_type(PROBLEM_SUBMITTED_EVENT_TYPE),
                'weighted_earned':
                kwargs.get('weighted_earned'),
                'weighted_possible':
                kwargs.get('weighted_possible'),
            })

    elif root_type in [GRADES_RESCORE_EVENT_TYPE, GRADES_OVERRIDE_EVENT_TYPE]:
        current_user = get_current_user()
        instructor_id = getattr(current_user, 'id', None)
        tracker.emit(
            six.text_type(root_type), {
                'course_id': six.text_type(kwargs['course_id']),
                'user_id': six.text_type(kwargs['user_id']),
                'problem_id': six.text_type(kwargs['usage_id']),
                'new_weighted_earned': kwargs.get('weighted_earned'),
                'new_weighted_possible': kwargs.get('weighted_possible'),
                'only_if_higher': kwargs.get('only_if_higher'),
                'instructor_id': six.text_type(instructor_id),
                'event_transaction_id': six.text_type(
                    get_event_transaction_id()),
                'event_transaction_type': six.text_type(root_type),
            })

    elif root_type in [SUBSECTION_OVERRIDE_EVENT_TYPE]:
        tracker.emit(
            six.text_type(root_type), {
                'course_id': six.text_type(kwargs['course_id']),
                'user_id': six.text_type(kwargs['user_id']),
                'problem_id': six.text_type(kwargs['usage_id']),
                'only_if_higher': kwargs.get('only_if_higher'),
                'override_deleted': kwargs.get('score_deleted', False),
                'event_transaction_id': six.text_type(
                    get_event_transaction_id()),
                'event_transaction_type': six.text_type(root_type),
            })
def add_default_owners(instance, **kwargs):
    user = get_current_user()
    if instance and not instance.owners.count() and user:
        instance.owners.add(user)
Пример #28
0
def auto_save_current_user(obj):
    user = get_current_user()
    if user and not user.pk:
        user = None
    if not obj.pk:
        obj.added_by = user
Пример #29
0
 def save(self, *args, **kwargs):
     if self.forum_type == ForumType.CST.value:
         current_profile = get_current_user().profile
         if self.pk is None:
             self.creator = current_profile
     super(Forum, self).save(*args, **kwargs)
Пример #30
0
 def get_queryset(self):
     user = get_current_user()
     qs = super().get_queryset()
     owned = qs.filter(owner=user)
     admins = qs.filter(users_admin=user)
     return owned | admins
Пример #31
0
 def save(self, *args, **kwargs):
     user = get_current_user()
     if not Employee.objects.filter(id=self.id).exists():
         self.create_user = user.id if user else None
     self.update_user = user.id if user else None
     super(Employee, self).save(*args, **kwargs)
Пример #32
0
 def save(self, *args, **kwargs):
     is_new = self.pk is None
     if is_new:
         self.initiator = get_current_user().profile
     super(MessagingThread, self).save(*args, **kwargs)
Пример #33
0
def user_cafeterias_only():
    user = get_current_user()
    if is_admin(user):
        return Q()
    else:
        return Q(owner=user)
Пример #34
0
def get_current_user_or_none():
    u = get_current_user()
    if not isinstance(u, User):
        return None
    return u
Пример #35
0
    def get_blacklist_of_fields(cls, course_key):
        """
        Returns a list of fields to not include in Studio Advanced settings based on a
        feature flag (i.e. enabled or disabled).
        """
        # Copy the filtered list to avoid permanently changing the class attribute.
        black_list = list(cls.FIELDS_BLACK_LIST)

        # Do not show giturl if feature is not enabled.
        if not settings.FEATURES.get('ENABLE_EXPORT_GIT'):
            black_list.append('giturl')

        # Do not show edxnotes if the feature is disabled.
        if not settings.FEATURES.get('ENABLE_EDXNOTES'):
            black_list.append('edxnotes')

        # Do not show video auto advance if the feature is disabled
        if not settings.FEATURES.get('ENABLE_OTHER_COURSE_SETTINGS'):
            black_list.append('other_course_settings')

        # Do not show video_upload_pipeline if the feature is disabled.
        if not settings.FEATURES.get('ENABLE_VIDEO_UPLOAD_PIPELINE'):
            black_list.append('video_upload_pipeline')

        # Do not show video auto advance if the feature is disabled
        if not settings.FEATURES.get('ENABLE_AUTOADVANCE_VIDEOS'):
            black_list.append('video_auto_advance')

        # Do not show social sharing url field if the feature is disabled.
        if (not hasattr(settings, 'SOCIAL_SHARING_SETTINGS') or
                not getattr(settings, 'SOCIAL_SHARING_SETTINGS', {}).get("CUSTOM_COURSE_URLS")):
            black_list.append('social_sharing_url')

        # Do not show teams configuration if feature is disabled.
        if not settings.FEATURES.get('ENABLE_TEAMS'):
            black_list.append('teams_configuration')

        if not settings.FEATURES.get('ENABLE_VIDEO_BUMPER'):
            black_list.append('video_bumper')

        # Do not show enable_ccx if feature is not enabled.
        if not settings.FEATURES.get('CUSTOM_COURSES_EDX'):
            black_list.append('enable_ccx')
            black_list.append('ccx_connector')

        # Do not show "Issue Open Badges" in Studio Advanced Settings
        # if the feature is disabled.
        if not settings.FEATURES.get('ENABLE_OPENBADGES'):
            black_list.append('issue_badges')

        # If the XBlockStudioConfiguration table is not being used, there is no need to
        # display the "Allow Unsupported XBlocks" setting.
        if not XBlockStudioConfigurationFlag.is_enabled():
            black_list.append('allow_unsupported_xblocks')

        # If the ENABLE_PROCTORING_PROVIDER_OVERRIDES waffle flag is not enabled,
        # do not show "Proctoring Configuration" in Studio Advanced Settings.
        if not ENABLE_PROCTORING_PROVIDER_OVERRIDES.is_enabled(course_key):
            black_list.append('proctoring_provider')

        # Do not show "Course Visibility For Unenrolled Learners" in Studio Advanced Settings
        # if the enable_anonymous_access flag is not enabled
        if not COURSE_ENABLE_UNENROLLED_ACCESS_FLAG.is_enabled(course_key=course_key):
            black_list.append('course_visibility')

        # Do not show "Create Zendesk Tickets For Suspicious Proctored Exam Attempts" in
        # Studio Advanced Settings if the user is not edX staff.
        if not GlobalStaff().has_user(get_current_user()):
            black_list.append('create_zendesk_tickets')

        return black_list
Пример #36
0
 def get_thanked(self, obj):
     current_user_profile = get_current_user().profile
     return current_user_profile in obj.thanked_by.all()
Пример #37
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
    """
    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])

    if HAS_REQUEST_CACHE:
        request_cache = RequestCache.get_request_cache()
    else:
        request_cache = None

    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

    if 'read_preference' in doc_store_config:
        doc_store_config['read_preference'] = getattr(ReadPreference, doc_store_config['read_preference'])

    if XBlockDisableConfig and settings.FEATURES.get('ENABLE_DISABLING_XBLOCK_TYPES', False):
        disabled_xblock_types = XBlockDisableConfig.disabled_block_types()
    else:
        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),
        disabled_xblock_types=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
    )
Пример #38
0
def objects_authorized(objects):
    authorized_objects = []
    for check_object in objects:
        if user_is_authorized(get_current_user(), "view", check_object):
            authorized_objects.append(check_object)
    return authorized_objects
Пример #39
0
 def get_is_your_turn(self, obj):
     player = get_current_user()
     return obj.is_your_turn(player)
Пример #40
0
def record_trail(action, instance, data=None, user=None):
    """Record an action taken against a model instance."""
    user = user or get_current_user()
    #logger.debug('%s on %r by %r (%r)', action, instance, user, data)
    #print '%s %r by %r (%r)' % (action, instance, user, data)

    # Based on setting, skip recording anything not done by a user account.
    if not get_setting('TRAILS_LOG_USER_NONE') and user is None:
        return
    # Based on setting, skip recording anything done by the anonymous user.
    if not get_setting('TRAILS_LOG_USER_ANONYMOUS') and user and \
            user.is_anonymous():
        return
    # Skip recording changes for the Trail model itself.
    if isinstance(instance, Trail):
        return
    # Skip excluded apps and models.
    app_label = instance._meta.app_label
    model_name = getattr(instance._meta, 'model_name',
                         getattr(instance._meta, 'module_name'))
    excludes = get_setting('TRAILS_EXCLUDE')
    if app_label in excludes:
        return
    if '%s.%s' % (app_label, model_name) in excludes:
        return

    # FIXME: model_to_dict isn't JSON serializable if there's a file field.
    #if action == 'add' and data is None:
    #    data = model_to_dict(instance)
    # FIXME: Store data on delete?

    # Get user instance and unicode string from user.
    if user is None:
        user_unicode = get_setting('TRAILS_USER_NONE')
    elif user.is_anonymous():
        user_unicode = get_setting('TRAILS_USER_ANONYMOUS')
    else:
        user_unicode = unicode(user)
    if not getattr(user, 'pk', 0):
        user = None
    # Get content type for the given instance.
    try:
        content_type = ContentType.objects.get_for_model(instance)
    except ContentType.DoesNotExist:
        return
    # Get primary key for the given instance.
    try:
        object_id = int(instance.pk)
    except (AttributeError, ValueError):
        return  # FIXME: Handle non-integer primary keys.
    # Based on setting, recording action to the Python logging module.
    if get_setting('TRAILS_USE_LOGGING'):
        pass  # FIXME: Log to logging module.
    # Based on setting, recording action to the database.
    if get_setting('TRAILS_USE_DATABASE'):
        kwargs = {
            'user': user,
            'user_unicode': user_unicode,
            'content_type': content_type,
            'object_id': object_id,
            'action': action,
            'data': data or {},
        }
        Trail.objects.create(**kwargs)
Пример #41
0
 def leave(self):
     self.instance.leave(get_current_user())
Пример #42
0
 def save(self, *args, **kwargs):
     self.user = get_current_user()
     models.Model.save(self, *args, **kwargs)
Пример #43
0
def get_authorized_dojo_meta(permission):
    user = get_current_user()

    if user is None:
        return DojoMeta.objects.none()

    if user.is_superuser:
        return DojoMeta.objects.all().order_by('name')

    if user_has_global_permission(user, permission):
        return DojoMeta.objects.all().order_by('name')

    roles = get_roles_for_permission(permission)
    product_authorized_product_type_roles = Product_Type_Member.objects.filter(
        product_type=OuterRef('product__prod_type_id'),
        user=user,
        role__in=roles)
    product_authorized_product_roles = Product_Member.objects.filter(
        product=OuterRef('product_id'),
        user=user,
        role__in=roles)
    product_authorized_product_type_groups = Product_Type_Group.objects.filter(
        product_type=OuterRef('product__prod_type_id'),
        group__users=user,
        role__in=roles)
    product_authorized_product_groups = Product_Group.objects.filter(
        product=OuterRef('product_id'),
        group__users=user,
        role__in=roles)
    endpoint_authorized_product_type_roles = Product_Type_Member.objects.filter(
        product_type=OuterRef('endpoint__product__prod_type_id'),
        user=user,
        role__in=roles)
    endpoint_authorized_product_roles = Product_Member.objects.filter(
        product=OuterRef('endpoint__product_id'),
        user=user,
        role__in=roles)
    endpoint_authorized_product_type_groups = Product_Type_Group.objects.filter(
        product_type=OuterRef('endpoint__product__prod_type_id'),
        group__users=user,
        role__in=roles)
    endpoint_authorized_product_groups = Product_Group.objects.filter(
        product=OuterRef('endpoint__product_id'),
        group__users=user,
        role__in=roles)
    finding_authorized_product_type_roles = Product_Type_Member.objects.filter(
        product_type=OuterRef('finding__test__engagement__product__prod_type_id'),
        user=user,
        role__in=roles)
    finding_authorized_product_roles = Product_Member.objects.filter(
        product=OuterRef('finding__test__engagement__product_id'),
        user=user,
        role__in=roles)
    finding_authorized_product_type_groups = Product_Type_Group.objects.filter(
        product_type=OuterRef('finding__test__engagement__product__prod_type_id'),
        group__users=user,
        role__in=roles)
    finding_authorized_product_groups = Product_Group.objects.filter(
        product=OuterRef('finding__test__engagement__product_id'),
        group__users=user,
        role__in=roles)
    dojo_meta = DojoMeta.objects.annotate(
        product__prod_type__member=Exists(product_authorized_product_type_roles),
        product__member=Exists(product_authorized_product_roles),
        product__prod_type__authorized_group=Exists(product_authorized_product_type_groups),
        product__authorized_group=Exists(product_authorized_product_groups),
        endpoint__product__prod_type__member=Exists(endpoint_authorized_product_type_roles),
        endpoint__product__member=Exists(endpoint_authorized_product_roles),
        endpoint__product__prod_type__authorized_group=Exists(endpoint_authorized_product_type_groups),
        endpoint__product__authorized_group=Exists(endpoint_authorized_product_groups),
        finding__test__engagement__product__prod_type__member=Exists(finding_authorized_product_type_roles),
        finding__test__engagement__product__member=Exists(finding_authorized_product_roles),
        finding__test__engagement__product__prod_type__authorized_group=Exists(finding_authorized_product_type_groups),
        finding__test__engagement__product__authorized_group=Exists(finding_authorized_product_groups)
    ).order_by('name')
    dojo_meta = dojo_meta.filter(
        Q(product__prod_type__member=True) |
        Q(product__member=True) |
        Q(product__prod_type__authorized_group=True) |
        Q(product__authorized_group=True) |
        Q(endpoint__product__prod_type__member=True) |
        Q(endpoint__product__member=True) |
        Q(endpoint__product__prod_type__authorized_group=True) |
        Q(endpoint__product__authorized_group=True) |
        Q(finding__test__engagement__product__prod_type__member=True) |
        Q(finding__test__engagement__product__member=True) |
        Q(finding__test__engagement__product__prod_type__authorized_group=True) |
        Q(finding__test__engagement__product__authorized_group=True))

    return dojo_meta
Пример #44
0
 def clean_create_by(self):
     create_by = get_current_user()
     return create_by
Пример #45
0
 def get_yours(self, obj):
     user = get_current_user()
     qs = Game.objects.filter(players__pk=user.pk)
     return GameSerializer(qs, many=True).data
Пример #46
0
 def get_read(self, obj):
     user = get_current_user()
     if obj.user.id == user.id:
         return f"Yes {user.first_name} - {obj.user.first_name}"
     else:
         return f"No {user.first_name}  - {obj.user.first_name}"
Пример #47
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
    """
    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])

    if HAS_REQUEST_CACHE:
        request_cache = RequestCache.get_request_cache()
    else:
        request_cache = None

    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

    if 'read_preference' in doc_store_config:
        doc_store_config['read_preference'] = getattr(ReadPreference, doc_store_config['read_preference'])

    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
    )
Пример #48
0
 def save(self, *args, **kwargs):
     self.create_by = get_current_user()
     super(RoutineTask, self).save(*args, **kwargs)
Пример #49
0
def new_connection(sender, connection, **kwargs):
    user = get_current_user()
    # set current user for the session
    if user:
        connection.cursor().execute("SET @current_user = %s", [user.id])
Пример #50
0
 def save(self, *args, **kwargs):
     is_new = self.pk is None
     if is_new:
         self.author = get_current_user().profile
     super(EventThread, self).save(*args, **kwargs)
Пример #51
0
def add_user(**kwargs):
    '''
    Add the current user to the pipeline.
    '''
    user = kwargs.get('user') or get_current_user()
    return dict(user=user)