Ejemplo n.º 1
0
 def filter_func(self):
     qs = Category.objects.filter(pk__in=applicable_categories(self.user))
     lookup_var = self.get_lookup_kwarg()
     for cat in user_category_filter(qs, self.user):
         link = ( cat, {lookup_var: cat.pk})
         self.links.append(link)
     return True
Ejemplo n.º 2
0
 def filter_func(self):
     qs = Category.objects.filter(pk__in=applicable_categories(self.user))
     lookup_var = self.get_lookup_kwarg()
     for cat in user_category_filter(qs, self.user):
         link = (cat, {lookup_var: cat.pk})
         self.links.append(link)
     return True
Ejemplo n.º 3
0
def category_field_filter(fspec):
    qs = Category.objects.filter(pk__in=applicable_categories(fspec.user))
    for cat in user_category_filter(qs, fspec.user):
        lookup_var = '%s__%s__exact' % (fspec.f.name, fspec.f.rel.to._meta.pk.name)
        link = ( cat, {lookup_var: cat.pk})
        fspec.links.append(link)
    return True
Ejemplo n.º 4
0
    def test_denormalized_applicable_categories_same_as_computed_ones_using_permissions(self):
        computed_categories = compute_applicable_categories(self.user, 'articles.view_article')
        computed_categories.sort()

        denormalized_categories = applicable_categories(self.user, 'articles.view_article')
        denormalized_categories.sort()

        self.assert_equals(computed_categories, denormalized_categories)
Ejemplo n.º 5
0
    def test_applicable_categories_for_user(self):
        categories = applicable_categories(self.user)
        categories.sort()
        # we expect category from roles + nested ones
        expected_categories = [self.nested_first_level_two.pk, self.nested_second_level_two.pk]
        expected_categories.sort()

        self.assert_equals(expected_categories, categories)
Ejemplo n.º 6
0
    def login(self, request):
        """
        Displays the login form for the given HttpRequest.
        """
        from django.contrib.auth.models import User

        ERROR_MESSAGE = _("Please enter a correct username and password. Note that both fields are case-sensitive.")
        LOGIN_FORM_KEY = 'this_is_the_login_form'

        # If this isn't already the login page, display it.
        if not request.POST.has_key(LOGIN_FORM_KEY):
            if request.POST:
                message = _("Please log in again, because your session has expired.")
            else:
                message = ""
            return self.display_login_form(request, message)

        # Check that the user accepts cookies.
        if not request.session.test_cookie_worked():
            message = _("Looks like your browser isn't configured to accept cookies. Please enable cookies, reload this page, and try again.")
            return self.display_login_form(request, message)
        else:
            request.session.delete_test_cookie()

        # Check the password.
        username = request.POST.get('username', None)
        password = request.POST.get('password', None)
        user = authenticate(username=username, password=password)
        if user is None:
            message = ERROR_MESSAGE
            if u'@' in username:
                # Mistakenly entered e-mail address instead of username? Look it up.
                try:
                    user = User.objects.get(email=username)
                except (User.DoesNotExist, User.MultipleObjectsReturned):
                    message = _("Usernames cannot contain the '@' character.")
                else:
                    if user.check_password(password):
                        message = _("Your e-mail address is not your username."
                                    " Try '%s' instead.") % user.username
                    else:
                        message = _("Usernames cannot contain the '@' character.")
            return self.display_login_form(request, message)

        # The user data is correct; log in the user in and continue.
        else:
            if user.is_active and user.is_staff:
                login(request, user)
                # user has no applicable categories, probably his role is undefined
                if not applicable_categories(user):
                    return self.norole(request, user)
                # load all user's specific settings into session
                for c in AdminSetting.objects.filter(user=user):
                    uc = get_user_config(user, c.var)
                    set_user_config_session(request.session, c.var, uc)
                return HttpResponseRedirect(request.get_full_path())
            else:
                return self.display_login_form(request, ERROR_MESSAGE)
Ejemplo n.º 7
0
    def test_denormalized_applicable_categories_same_as_computed_ones(self):
        # test applicable_categories() compare results of  compute_applicable_categories
        computed_categories = compute_applicable_categories(self.user)
        computed_categories.sort()

        denormalized_categories = applicable_categories(self.user)
        denormalized_categories.sort()

        self.assert_equals(computed_categories, denormalized_categories)
Ejemplo n.º 8
0
    def test_denormalized_applicable_categories_same_as_computed_ones(self):
        # test applicable_categories() compare results of  compute_applicable_categories
        computed_categories = compute_applicable_categories(self.user)
        computed_categories.sort()

        denormalized_categories = applicable_categories(self.user)
        denormalized_categories.sort()

        self.assert_equals(computed_categories, denormalized_categories)
Ejemplo n.º 9
0
    def test_applicable_categories_for_user_permission_view(self):
        categories = applicable_categories(self.user, 'articles.view_article')
        categories.sort()

        # we expect category from roles + nested ones
        expected_categories = [self.nested_first_level_two.pk, self.nested_second_level_two.pk]
        expected_categories.sort()

        self.assert_equals(expected_categories, categories)
Ejemplo n.º 10
0
    def test_applicable_categories_for_user(self):
        categories = applicable_categories(self.user)
        categories.sort()
        # we expect category from roles + nested ones
        expected_categories = [
            self.nested_first_level_two.pk, self.nested_second_level_two.pk
        ]
        expected_categories.sort()

        self.assert_equals(expected_categories, categories)
Ejemplo n.º 11
0
    def test_applicable_categories_for_user_permission_view(self):
        categories = applicable_categories(self.user, 'articles.view_article')
        categories.sort()

        # we expect category from roles + nested ones
        expected_categories = [
            self.nested_first_level_two.pk, self.nested_second_level_two.pk
        ]
        expected_categories.sort()

        self.assert_equals(expected_categories, categories)
Ejemplo n.º 12
0
    def test_denormalized_applicable_categories_same_as_computed_ones_using_permissions(
            self):
        computed_categories = compute_applicable_categories(
            self.user, 'articles.view_article')
        computed_categories.sort()

        denormalized_categories = applicable_categories(
            self.user, 'articles.view_article')
        denormalized_categories.sort()

        self.assert_equals(computed_categories, denormalized_categories)
Ejemplo n.º 13
0
def category_field_filter(fspec):
    #qs = Category.objects.filter(pk__in=applicable_categories(fspec.user))
    print 'Categories %d' % fspec.model_admin.queryset(fspec.request).count()
    #print 'self.params %s' % fspec.params
    #print 'self.result_list %s' % fspec.result_list
    qs = Category.objects.filter(pk__in=applicable_categories(fspec.user))
    for cat in user_category_filter(qs, fspec.user):
        lookup_var = '%s__%s__exact' % (fspec.field_path, fspec.f.rel.to._meta.pk.name)
        link = ( cat, {lookup_var: cat.pk})
        fspec.links.append(link)
    return True
Ejemplo n.º 14
0
    def suggest_view(self, request, extra_context=None):
        self.register_newman_variables(request)

        SUGGEST_VIEW_LIMIT = getattr(settings, 'SUGGEST_VIEW_LIMIT', 20)
        SUGGEST_VIEW_MIN_LENGTH = getattr(settings, 'SUGGEST_VIEW_MIN_LENGTH', 2)

        if not ('f' in request.GET.keys() and 'q' in request.GET.keys()):
            raise AttributeError, 'Invalid query attributes. Example: ".../?f=field_a&f=field_b&q=search_term&o=offset"'
        elif len(request.GET.get('q')) < SUGGEST_VIEW_MIN_LENGTH:
            return HttpResponse( '', mimetype='text/plain;charset=utf-8' )

        offset = 0
        if 'o' in request.GET.keys() and request.GET.get('o'):
            offset = int(request.GET.get('o'))
        limit = offset + SUGGEST_VIEW_LIMIT

        model_fields = [mf.name for mf in self.model._meta.fields]
        lookup_fields = []
        lookup_value = request.GET.get('q')
        lookup = None
        has_non_lookup_attr = False
        all_fields = [u'id'] + request.GET.getlist('f')

        for lf in all_fields:
            if lf in model_fields or lf.split('__')[0] in model_fields:
                lookup_fields.append(lf)
            elif hasattr(self.model, lf):
                has_non_lookup_attr = True
            else:
                raise AttributeError, 'Model "%s" has not field "%s". Possible fields are "%s".' \
                                    % (self.model._meta.object_name, lf, ', '.join(model_fields))

        for f in lookup_fields:
            lookup_key = str('%s__icontains' % f)
            if not lookup:
                lookup = models.Q(**{lookup_key: lookup_value})
            else:
                lookup = lookup | models.Q(**{lookup_key: lookup_value})
        # user role based category filtering
        if not is_category_model(self.model):
            category_field = model_category_fk(self.model)
            if category_field and request.user:
                applicable = applicable_categories(request.user)
                args_lookup = { '%s__in' % category_field.name: applicable}
                lookup = lookup & models.Q(**args_lookup)
        else:
            applicable = applicable_categories(request.user)
            lookup = lookup & models.Q(pk__in=applicable)
        # user category filter
        qs = utils.user_category_filter(self.model.objects.filter(lookup), request.user)

        if not has_non_lookup_attr:
            data = qs.values(*lookup_fields)
        else:
            data = qs.only(*lookup_fields)

        def construct_row(inst, fields):
            row = {}
            for f in fields:
                attr = getattr(inst, f)
                if callable(attr):
                    row[f] = attr()
                else:
                    row[f] = attr
                row[f] = truncatewords(striptags(unicode(row[f])), 5)
            return row

        if has_non_lookup_attr:
            outdata = []
            for i in data:
                outdata.append(construct_row(i, all_fields))
            data = outdata

        # sort the suggested items so that those starting with the sought term come first
        def compare(a,b):
            def _cmp(a,b,sought):
                a_starts = unicode(a).lower().startswith(sought)
                b_starts = unicode(b).lower().startswith(sought)
                # if exactly one of (a,b) starts with sought, the one starting with it comes first
                if a_starts ^ b_starts:
                    if a_starts: return -1
                    if b_starts: return +1
                # else compare lexicographically
                return cmp(a,b)
            return _cmp(a,b,unicode(lookup_value).lower())
        cnt = len(data)
        data = list(data)
        if offset >= len(data): return HttpResponse('SPECIAL: OFFSET OUT OF RANGE', mimetype='text/plain')
        data.sort(cmp=compare, key=lambda x: x[lookup_fields[1]])
        data = data[offset:limit]

        ft = []
        ft.append('{cnt:%d}' % cnt)
        for item in data:
            ft.append( "%s".encode('utf-8') % '|'.join("%s" % item[f] for f in all_fields) )

        return HttpResponse( '\n'.join(ft), mimetype='text/plain;charset=utf-8' )
Ejemplo n.º 15
0
 def test_applicable_categories_for_user_permission_delete(self):
     categories = applicable_categories(self.user, 'articles.delete_article')
     #self.assert_equals(self.nested_second_level_two.pk, categories[0])
     self.assert_true(self.nested_second_level_two.pk in categories)
Ejemplo n.º 16
0
    def login(self, request):
        """
        Displays the login form for the given HttpRequest.
        """
        from django.contrib.auth.models import User

        ERROR_MESSAGE = _(
            "Please enter a correct username and password. Note that both fields are case-sensitive."
        )
        LOGIN_FORM_KEY = 'this_is_the_login_form'

        # If this isn't already the login page, display it.
        if not request.POST.has_key(LOGIN_FORM_KEY):
            if request.POST:
                message = _(
                    "Please log in again, because your session has expired.")
            else:
                message = ""
            return self.display_login_form(request, message)
            #return self.login(request)

        # Check that the user accepts cookies.
        if not request.session.test_cookie_worked():
            message = _(
                "Looks like your browser isn't configured to accept cookies. Please enable cookies, reload this page, and try again."
            )
            return self.display_login_form(request, message)
        else:
            request.session.delete_test_cookie()

        # Check the password.
        username = request.POST.get('username', None)
        password = request.POST.get('password', None)
        user = authenticate(username=username, password=password)
        if user is None:
            message = ERROR_MESSAGE
            if u'@' in username:
                # Mistakenly entered e-mail address instead of username? Look it up.
                try:
                    user = User.objects.get(email=username)
                except (User.DoesNotExist, User.MultipleObjectsReturned):
                    message = _("Usernames cannot contain the '@' character.")
                else:
                    if user.check_password(password):
                        message = _("Your e-mail address is not your username."
                                    " Try '%s' instead.") % user.username
                    else:
                        message = _(
                            "Usernames cannot contain the '@' character.")
            return self.display_login_form(request, message)

        # The user data is correct; log in the user in and continue.
        else:
            if user.is_active and user.is_staff:
                login(request, user)
                # user has no applicable categories, probably his role is undefined
                if not applicable_categories(user) and not user.is_superuser:
                    return self.norole(request, user)

                next_path = request.get_full_path()

                # load all user's specific settings into session
                for c in AdminSetting.objects.filter(user=user).values('var'):
                    uc = get_user_config(user, c['var'])
                    set_user_config_session(request.session, c['var'], uc)

                if request.POST.get('next'):
                    next_path += request.POST.get('next')
                return HttpResponseRedirect(next_path)
            else:
                return self.display_login_form(request, ERROR_MESSAGE)
Ejemplo n.º 17
0
 def test_applicable_categories_for_user_permission_delete(self):
     categories = applicable_categories(self.user,
                                        'articles.delete_article')
     #self.assert_equals(self.nested_second_level_two.pk, categories[0])
     self.assert_true(self.nested_second_level_two.pk in categories)
Ejemplo n.º 18
0
Archivo: options.py Proyecto: whit/ella
    def suggest_view(self, request, extra_context=None):
        self.register_newman_variables(request)

        if not ('f' in request.GET.keys() and 'q' in request.GET.keys()):
            raise AttributeError, 'Invalid query attributes. Example: ".../?f=field_a&f=field_b&q=search_term&o=offset"'
        elif len(request.GET.get(
                'q')) < newman_settings.SUGGEST_VIEW_MIN_LENGTH:
            return HttpResponse('', mimetype='text/plain;charset=utf-8')

        offset = 0
        if 'o' in request.GET.keys() and request.GET.get('o'):
            offset = int(request.GET.get('o'))
        limit = offset + newman_settings.SUGGEST_VIEW_LIMIT

        model_fields = [mf.name for mf in self.model._meta.fields]
        lookup_fields = []
        lookup_value = request.GET.get('q')
        lookup = None
        has_non_lookup_attr = False
        all_fields = [u'id'] + request.GET.getlist('f')

        for lf in all_fields:
            if lf in model_fields or lf.split('__')[0] in model_fields:
                lookup_fields.append(lf)
            elif hasattr(self.model, lf):
                has_non_lookup_attr = True
            else:
                raise AttributeError, 'Model "%s" has not field "%s". Possible fields are "%s".' \
                                    % (self.model._meta.object_name, lf, ', '.join(model_fields))

        for f in lookup_fields:
            lookup_key = str('%s__icontains' % f)
            if not lookup:
                lookup = models.Q(**{lookup_key: lookup_value})
            else:
                lookup = lookup | models.Q(**{lookup_key: lookup_value})
        # user role based category filtering
        if not is_category_model(self.model):
            category_field = model_category_fk(self.model)
            if category_field and request.user:
                applicable = applicable_categories(request.user)
                args_lookup = {'%s__in' % category_field.name: applicable}
                lookup = lookup & models.Q(**args_lookup)
        else:
            applicable = applicable_categories(request.user)
            lookup = lookup & models.Q(pk__in=applicable)
        # user category filter
        qs = utils.user_category_filter(self.model.objects.filter(lookup),
                                        request.user)

        if not has_non_lookup_attr:
            data = qs.values(*lookup_fields)
        else:
            data = qs.only(*lookup_fields)

        def construct_row(inst, fields):
            row = {}
            for f in fields:
                attr = getattr(inst, f)
                if callable(attr):
                    row[f] = attr()
                else:
                    row[f] = attr
                row[f] = truncatewords(striptags(unicode(row[f])), 5)
            return row

        if has_non_lookup_attr:
            outdata = []
            for i in data:
                outdata.append(construct_row(i, all_fields))
            data = outdata

        # sort the suggested items so that those starting with the sought term come first
        def compare(a, b):
            def _cmp(a, b, sought):
                a_starts = unicode(a).lower().startswith(sought)
                b_starts = unicode(b).lower().startswith(sought)
                # if exactly one of (a,b) starts with sought, the one starting with it comes first
                if a_starts ^ b_starts:
                    if a_starts: return -1
                    if b_starts: return +1
                # else compare lexicographically
                return cmp(a, b)

            return _cmp(a, b, unicode(lookup_value).lower())

        cnt = len(data)
        data = list(data)
        if offset >= len(data):
            return HttpResponse('SPECIAL: OFFSET OUT OF RANGE',
                                mimetype='text/plain')
        data.sort(cmp=compare, key=lambda x: x[lookup_fields[1]])
        data = data[offset:limit]

        ft = []
        ft.append('{cnt:%d}' % cnt)
        for item in data:
            ft.append("%s".encode('utf-8') % '|'.join("%s" % item[f]
                                                      for f in all_fields))

        return HttpResponse('\n'.join(ft), mimetype='text/plain;charset=utf-8')