Exemplo n.º 1
0
def test_no_root_view_permissions(po_directory, nobody, default, admin, view,
                                  no_permission_sets, no_projects,
                                  project_foo, project_bar):
    """Tests user-accessible projects when there are no permissions set at
    the root.
    """
    ALL_PROJECTS = [project_foo.code, project_bar.code]

    foo_user = UserFactory.create(username='******')
    bar_user = UserFactory.create(username='******')

    # By setting explicit `view` permissions for `foo_user` in `project_foo`,
    # only `foo_user` will be able to access that project
    _require_permission_set(foo_user, project_foo.directory, [view])

    assert items_equal(Project.accessible_by_user(admin), ALL_PROJECTS)
    assert items_equal(
        Project.accessible_by_user(foo_user),
        [project_foo.code])
    assert items_equal(Project.accessible_by_user(bar_user), [])
    assert items_equal(Project.accessible_by_user(default), [])
    assert items_equal(Project.accessible_by_user(nobody), [])

    # Now let's allow showing `project_bar` to all registered users, but keep
    # `project_foo` visible only to `foo_user`.
    _require_permission_set(default, project_bar.directory, [view])

    assert items_equal(Project.accessible_by_user(admin), ALL_PROJECTS)
    assert items_equal(Project.accessible_by_user(foo_user), ALL_PROJECTS)
    assert items_equal(
        Project.accessible_by_user(bar_user),
        [project_bar.code])
    assert items_equal(Project.accessible_by_user(default), [project_bar.code])
    assert items_equal(Project.accessible_by_user(nobody), [])
Exemplo n.º 2
0
def test_no_root_view_permissions(po_directory, nobody, default, admin, view,
                                  no_permission_sets, no_projects,
                                  project_foo, project_bar):
    """Tests user-accessible projects when there are no permissions set at
    the root.
    """
    ALL_PROJECTS = [project_foo.code, project_bar.code]

    foo_user = UserFactory.create(username='******')
    bar_user = UserFactory.create(username='******')

    # By setting explicit `view` permissions for `foo_user` in `project_foo`,
    # only `foo_user` will be able to access that project
    _require_permission_set(foo_user, project_foo.directory, [view])

    assert items_equal(Project.accessible_by_user(admin), ALL_PROJECTS)
    assert items_equal(
        Project.accessible_by_user(foo_user),
        [project_foo.code])
    assert items_equal(Project.accessible_by_user(bar_user), [])
    assert items_equal(Project.accessible_by_user(default), [])
    assert items_equal(Project.accessible_by_user(nobody), [])

    # Now let's allow showing `project_bar` to all registered users, but keep
    # `project_foo` visible only to `foo_user`.
    _require_permission_set(default, project_bar.directory, [view])

    assert items_equal(Project.accessible_by_user(admin), ALL_PROJECTS)
    assert items_equal(Project.accessible_by_user(foo_user), ALL_PROJECTS)
    assert items_equal(
        Project.accessible_by_user(bar_user),
        [project_bar.code])
    assert items_equal(Project.accessible_by_user(default), [project_bar.code])
    assert items_equal(Project.accessible_by_user(nobody), [])
Exemplo n.º 3
0
    def get_for_user(self, user, include_disabled=False):
        """Filters units for a specific user.

        - Admins always get all non-obsolete units, optionally filtered to
            include units from disabled projects too.
        - Regular users only get units from enabled projects accessible
            to them.

        :param user: The user for whom units need to be retrieved for.
        :param include_disabled: whether to include units from disabled
            projects or not. This only affects superusers.
        :return: A filtered queryset with `Unit`s for `user`.
        """
        from pootle_project.models import Project

        if user.is_superuser:
            if include_disabled:
                return self.live()
            return self.live().filter(
                store__translation_project__project__disabled=False)

        user_projects = Project.accessible_by_user(user)
        filter_by = {
            "store__translation_project__project__disabled": False,
            "store__translation_project__project__code__in": user_projects,
        }
        return self.live().filter(**filter_by)
Exemplo n.º 4
0
    def wrapped(request, *args, **kwargs):
        language_code = kwargs.pop('language_code', None)
        project_code = kwargs.pop('project_code', None)
        pootle_path = request.GET.get('path', None)
        if pootle_path is not None:
            language_code, project_code, dir_path, filename = \
                split_pootle_path(pootle_path)
            kwargs['dir_path'] = dir_path
            kwargs['filename'] = filename

        if language_code and project_code:
            try:
                path_obj = TranslationProject.objects.enabled().get(
                    language__code=language_code,
                    project__code=project_code,
                    project__disabled=False
                )
            except TranslationProject.DoesNotExist:
                path_obj = None

            if path_obj is None and not request.is_ajax():
                # Explicit selection via the UI: redirect either to
                # ``/language_code/`` or ``/projects/project_code/``.
                user_choice = request.COOKIES.get('user-choice', None)
                if user_choice and user_choice in ('language', 'project',):
                    url = {
                        'language': reverse('pootle-language-overview',
                                            args=[language_code]),
                        'project': reverse('pootle-project-overview',
                                           args=[project_code, '', '']),
                    }
                    response = redirect(url[user_choice])
                    response.delete_cookie('user-choice')

                    return response

                raise Http404
        elif language_code:
            path_obj = get_object_or_404(Language, code=language_code)
        elif project_code:
            path_obj = get_object_or_404(Project, code=project_code,
                                         disabled=False)
        else:  # No arguments: all user-accessible projects
            user_projects = Project.accessible_by_user(request.user)
            user_projects = Project.objects.enabled() \
                                   .filter(code__in=user_projects)

            path_obj = ProjectSet(user_projects, '/projects/')

            # HACKISH: inject directory so that permissions can be
            # queried
            directory = Directory.objects.get(pootle_path='/projects/')
            setattr(path_obj, 'directory', directory)

        request.ctx_obj = path_obj
        request.ctx_path = path_obj.pootle_path
        request.resource_obj = path_obj
        request.pootle_path = path_obj.pootle_path

        return func(request, path_obj, *args, **kwargs)
Exemplo n.º 5
0
def test_no_root_hide_permissions(
    po_directory,
    nobody,
    default,
    admin,
    hide,
    view,
    no_projects,
    no_permission_sets,
    project_foo,
    project_bar,
    root,
):
    """Tests user-accessible projects when there are no `hide` permissions
    set at the root.
    """

    ALL_PROJECTS = [project_foo.code, project_bar.code]

    foo_user = UserFactory.create(username="******")
    bar_user = UserFactory.create(username="******")

    # By default everyone has access to projects
    _require_permission_set(default, root, [view])
    _require_permission_set(nobody, root, [view])

    # At the same time, `project_foo` is inaccessible registered users...
    _require_permission_set(default,
                            project_foo.directory,
                            negative_permissions=[hide])

    assert items_equal(Project.accessible_by_user(admin), ALL_PROJECTS)
    assert items_equal(Project.accessible_by_user(default), [project_bar.code])
    assert items_equal(Project.accessible_by_user(nobody), [project_bar.code])
    assert items_equal(Project.accessible_by_user(foo_user),
                       [project_bar.code])
    assert items_equal(Project.accessible_by_user(bar_user),
                       [project_bar.code])

    # ...and anonymous users as well
    _require_permission_set(nobody,
                            project_foo.directory,
                            negative_permissions=[hide])

    assert items_equal(Project.accessible_by_user(nobody), [project_bar.code])

    # Let's make `project_foo` accessible for `foo_user`
    _require_permission_set(foo_user, project_foo.directory, [view])

    assert items_equal(Project.accessible_by_user(foo_user), ALL_PROJECTS)

    # `project_bar` is now inaccessible for anonymous users
    _require_permission_set(nobody,
                            project_bar.directory,
                            negative_permissions=[hide])

    assert items_equal(Project.accessible_by_user(nobody), [])
Exemplo n.º 6
0
    def wrapped(request, *args, **kwargs):
        language_code = kwargs.pop('language_code', None)
        project_code = kwargs.pop('project_code', None)
        if request.is_ajax():
            pootle_path = request.GET.get('path', None)
            if pootle_path is not None:
                language_code, project_code, dir_path, filename = \
                    split_pootle_path(pootle_path)
                kwargs['dir_path'] = dir_path
                kwargs['filename'] = filename

        if language_code and project_code:
            try:
                path_obj = TranslationProject.objects.enabled().get(
                    language__code=language_code,
                    project__code=project_code,
                    project__disabled=False
                )
            except TranslationProject.DoesNotExist:
                path_obj = None

            if path_obj is None and not request.is_ajax():
                # Explicit selection via the UI: redirect either to
                # ``/language_code/`` or ``/projects/project_code/``.
                user_choice = request.COOKIES.get('user-choice', None)
                if user_choice and user_choice in ('language', 'project',):
                    url = {
                        'language': reverse('pootle-language-overview',
                                            args=[language_code]),
                        'project': reverse('pootle-project-overview',
                                           args=[project_code, '', '']),
                    }
                    response = redirect(url[user_choice])
                    response.delete_cookie('user-choice')

                    return response

                raise Http404
        elif language_code:
            path_obj = get_object_or_404(Language, code=language_code)
        elif project_code:
            path_obj = get_object_or_404(Project, code=project_code,
                                         disabled=False)
        else:  # No arguments: all user-accessible projects
            user_projects = Project.accessible_by_user(request.user)
            user_projects = Project.objects.filter(code__in=user_projects)
            path_obj = ProjectSet(user_projects, '/projects/')

            # HACKISH: inject directory so that permissions can be
            # queried
            directory = Directory.objects.get(pootle_path='/projects/')
            setattr(path_obj, 'directory', directory)

        request.ctx_obj = path_obj
        request.ctx_path = path_obj.pootle_path
        request.resource_obj = path_obj
        request.pootle_path = path_obj.pootle_path

        return func(request, path_obj, *args, **kwargs)
Exemplo n.º 7
0
    def is_accessible_by(self, user):
        """Returns `True` if the current unit is accessible by `user`."""
        if user.is_superuser:
            return True

        from pootle_project.models import Project
        user_projects = Project.accessible_by_user(user)
        return self.store.translation_project.project.code in user_projects
Exemplo n.º 8
0
    def is_accessible_by(self, user):
        """Returns `True` if the current translation project is accessible
        by `user`.
        """
        if user.is_superuser:
            return True

        return self.project.code in Project.accessible_by_user(user)
Exemplo n.º 9
0
    def is_accessible_by(self, user):
        """Returns `True` if the current unit is accessible by `user`."""
        if user.is_superuser:
            return True

        from pootle_project.models import Project
        user_projects = Project.accessible_by_user(user)
        return self.store.translation_project.project.code in user_projects
Exemplo n.º 10
0
    def is_accessible_by(self, user):
        """Returns `True` if the current translation project is accessible
        by `user`.
        """
        if user.is_superuser:
            return True

        return self.project.code in Project.accessible_by_user(user)
Exemplo n.º 11
0
def test_view_projects_browse(client, request_users):
    user = request_users["user"]
    client.login(
        username=user.username,
        password=request_users["password"])
    response = client.get(reverse("pootle-projects-browse"))
    assert response.cookies["pootle-language"].value == "projects"
    ctx = response.context
    request = response.wsgi_request
    user_projects = Project.accessible_by_user(request.user)
    user_projects = (
        Project.objects.for_user(request.user)
                       .filter(code__in=user_projects))
    obj = ProjectSet(user_projects)
    items = [
        make_project_list_item(project)
        for project in obj.children]
    items.sort(lambda x, y: locale.strcoll(x['title'], y['title']))
    table_fields = [
        'name', 'progress', 'total', 'need-translation',
        'suggestions', 'critical', 'last-updated', 'activity']
    table = {
        'id': 'projects',
        'fields': table_fields,
        'headings': get_table_headings(table_fields),
        'items': items}

    if request.user.is_superuser:
        url_action_continue = obj.get_translate_url(state='incomplete')
        url_action_fixcritical = obj.get_critical_url()
        url_action_review = obj.get_translate_url(state='suggestions')
        url_action_view_all = obj.get_translate_url(state='all')
    else:
        (url_action_continue,
         url_action_fixcritical,
         url_action_review,
         url_action_view_all) = [None] * 4

    User = get_user_model()
    top_scorers = User.top_scorers(limit=10)
    assertions = dict(
        page="browse",
        pootle_path="/projects/",
        resource_path="",
        resource_path_parts=[],
        object=obj,
        table=table,
        browser_extends="projects/all/base.html",
        stats=obj.data_tool.get_stats(user=request.user),
        checks=get_qualitycheck_list(obj),
        top_scorers=top_scorers,
        top_scorers_data=get_top_scorers_data(top_scorers, 10),
        translation_states=get_translation_states(obj),
        url_action_continue=url_action_continue,
        url_action_fixcritical=url_action_fixcritical,
        url_action_review=url_action_review,
        url_action_view_all=url_action_view_all)
    view_context_test(ctx, **assertions)
Exemplo n.º 12
0
def test_view_projects_browse(client, request_users):
    user = request_users["user"]
    client.login(username=user.username, password=request_users["password"])
    response = client.get(reverse("pootle-projects-browse"))
    assert response.cookies["pootle-language"].value == "projects"
    ctx = response.context
    request = response.wsgi_request
    user_projects = Project.accessible_by_user(request.user)
    user_projects = (Project.objects.for_user(
        request.user).filter(code__in=user_projects))
    obj = ProjectSet(user_projects)
    items = [make_project_list_item(project) for project in obj.children]
    items.sort(lambda x, y: locale.strcoll(x['title'], y['title']))
    stats = obj.data_tool.get_stats(user=request.user)
    for item in items:
        if item["code"] in stats["children"]:
            item["stats"] = stats["children"][item["code"]]
    table_fields = [
        'name', 'progress', 'total', 'need-translation', 'suggestions',
        'critical', 'last-updated', 'activity'
    ]
    table = {
        'id': 'projects',
        'fields': table_fields,
        'headings': get_table_headings(table_fields),
        'items': items
    }

    if request.user.is_superuser:
        url_action_continue = obj.get_translate_url(state='incomplete')
        url_action_fixcritical = obj.get_critical_url()
        url_action_review = obj.get_translate_url(state='suggestions')
        url_action_view_all = obj.get_translate_url(state='all')
    else:
        (url_action_continue, url_action_fixcritical, url_action_review,
         url_action_view_all) = [None] * 4
    checks = ChecksDisplay(obj).checks_by_category
    stats = StatsDisplay(obj, stats=stats).stats
    del stats["children"]
    User = get_user_model()
    top_scorers = User.top_scorers(limit=10)
    assertions = dict(page="browse",
                      pootle_path="/projects/",
                      resource_path="",
                      resource_path_parts=[],
                      object=obj,
                      table=table,
                      browser_extends="projects/all/base.html",
                      top_scorers=top_scorers,
                      top_scorers_data=get_top_scorers_data(top_scorers, 10),
                      translation_states=get_translation_states(obj),
                      url_action_continue=url_action_continue,
                      url_action_fixcritical=url_action_fixcritical,
                      url_action_review=url_action_review,
                      url_action_view_all=url_action_view_all,
                      checks=checks,
                      stats=stats)
    view_context_test(ctx, **assertions)
Exemplo n.º 13
0
def test_view_projects_translate(client, settings, request_users):
    user = request_users["user"]
    client.login(
        username=user.username,
        password=request_users["password"])
    response = client.get(reverse("pootle-projects-translate"))

    if not user.is_superuser:
        assert response.status_code == 403
        return
    ctx = response.context
    request = response.wsgi_request
    user_projects = Project.accessible_by_user(request.user)
    user_projects = (
        Project.objects.for_user(request.user)
                       .filter(code__in=user_projects))
    obj = ProjectSet(user_projects)
    checks = get_qualitychecks()
    schema = {sc["code"]: sc for sc in get_qualitycheck_schema()}
    check_data = obj.data_tool.get_checks()
    _checks = {}
    for check, checkid in checks.items():
        if check not in check_data:
            continue
        _checkid = schema[checkid]["name"]
        _checks[_checkid] = _checks.get(
            _checkid, dict(checks=[], title=schema[checkid]["title"]))
        _checks[_checkid]["checks"].append(
            dict(
                code=check,
                title=check_names[check],
                count=check_data[check]))
    _checks = OrderedDict(
        (k, _checks[k])
        for k in CATEGORY_IDS.keys()
        if _checks.get(k))
    assertions = dict(
        page="translate",
        has_admin_access=user.is_superuser,
        language=None,
        project=None,
        pootle_path="/projects/",
        ctx_path="/projects/",
        resource_path="",
        resource_path_parts=[],
        editor_extends="projects/all/base.html",
        checks=_checks,
        previous_url=get_previous_url(request),
        display_priority=False,
        cantranslate=check_permission("translate", request),
        cansuggest=check_permission("suggest", request),
        canreview=check_permission("review", request),
        search_form=make_search_form(request=request),
        current_vfolder_pk="",
        POOTLE_MT_BACKENDS=settings.POOTLE_MT_BACKENDS,
        AMAGAMA_URL=settings.AMAGAMA_URL)
    view_context_test(ctx, **assertions)
Exemplo n.º 14
0
def test_view_projects_browse(client, request_users):
    user = request_users["user"]
    client.login(
        username=user.username,
        password=request_users["password"])
    response = client.get(reverse("pootle-projects-browse"))
    assert response.cookies["pootle-language"].value == "projects"
    ctx = response.context
    request = response.wsgi_request
    user_projects = Project.accessible_by_user(request.user)
    user_projects = (
        Project.objects.for_user(request.user)
                       .filter(code__in=user_projects))
    obj = ProjectSet(user_projects)
    stats = obj.data_tool.get_stats(user=request.user)

    if request.user.is_superuser:
        url_action_continue = obj.get_translate_url(state='incomplete')
        url_action_fixcritical = obj.get_critical_url()
        url_action_review = obj.get_translate_url(state='suggestions')
        url_action_view_all = obj.get_translate_url(state='all')
    else:
        (url_action_continue,
         url_action_fixcritical,
         url_action_review,
         url_action_view_all) = [None] * 4
    checks = ChecksDisplay(obj).checks_by_category
    stats = StatsDisplay(obj, stats=stats).stats
    del stats["children"]
    chunk_size = TOP_CONTRIBUTORS_CHUNK_SIZE
    score_data = scores.get(ProjectSet)(obj)

    def scores_to_json(score):
        score["user"] = score["user"].to_dict()
        return score
    top_scorers = score_data.display(
        limit=chunk_size,
        formatter=scores_to_json)
    top_scorer_data = dict(
        items=list(top_scorers),
        has_more_items=len(score_data.top_scorers) > chunk_size)
    assertions = dict(
        page="browse",
        pootle_path="/projects/",
        resource_path="",
        resource_path_parts=[],
        object=obj,
        browser_extends="projects/all/base.html",
        top_scorers=top_scorer_data,
        translation_states=get_translation_states(obj),
        url_action_continue=url_action_continue,
        url_action_fixcritical=url_action_fixcritical,
        url_action_review=url_action_review,
        url_action_view_all=url_action_view_all,
        checks=checks,
        stats=stats)
    view_context_test(ctx, **assertions)
Exemplo n.º 15
0
def test_view_projects_browse(client, request_users):
    user = request_users["user"]
    client.login(
        username=user.username,
        password=request_users["password"])
    response = client.get(reverse("pootle-projects-browse"))
    assert response.cookies["pootle-language"].value == "projects"
    ctx = response.context
    request = response.wsgi_request
    user_projects = Project.accessible_by_user(request.user)
    user_projects = (
        Project.objects.for_user(request.user)
                       .filter(code__in=user_projects))
    ob = ProjectSet(user_projects)
    items = [
        make_project_list_item(project)
        for project in ob.children]
    items.sort(lambda x, y: locale.strcoll(x['title'], y['title']))
    table_fields = [
        'name', 'progress', 'total', 'need-translation',
        'suggestions', 'critical', 'last-updated', 'activity']
    table = {
        'id': 'projects',
        'fields': table_fields,
        'headings': get_table_headings(table_fields),
        'items': items}

    if request.user.is_superuser:
        url_action_continue = ob.get_translate_url(state='incomplete')
        url_action_fixcritical = ob.get_critical_url()
        url_action_review = ob.get_translate_url(state='suggestions')
        url_action_view_all = ob.get_translate_url(state='all')
    else:
        (url_action_continue,
         url_action_fixcritical,
         url_action_review,
         url_action_view_all) = [None] * 4

    assertions = dict(
        page="browse",
        pootle_path="/projects/",
        resource_path="",
        resource_path_parts=[],
        object=ob,
        table=table,
        browser_extends="projects/all/base.html",
        stats=jsonify(ob.get_stats()),
        check_categories=get_qualitycheck_schema(ob),
        translation_states=get_translation_states(ob),
        url_action_continue=url_action_continue,
        url_action_fixcritical=url_action_fixcritical,
        url_action_review=url_action_review,
        url_action_view_all=url_action_view_all)
    view_context_test(ctx, **assertions)
Exemplo n.º 16
0
def test_view_projects_browse(client, request_users):
    user = request_users["user"]
    client.login(username=user.username, password=request_users["password"])
    response = client.get(reverse("pootle-projects-browse"))
    assert response.cookies["pootle-language"].value == "projects"
    ctx = response.context
    request = response.wsgi_request
    user_projects = Project.accessible_by_user(request.user)
    user_projects = (Project.objects.for_user(
        request.user).filter(code__in=user_projects))
    obj = ProjectSet(user_projects)
    stats = obj.data_tool.get_stats(user=request.user)

    if request.user.is_superuser:
        url_action_continue = obj.get_translate_url(state='incomplete')
        url_action_fixcritical = obj.get_critical_url()
        url_action_review = obj.get_translate_url(state='suggestions')
        url_action_view_all = obj.get_translate_url(state='all')
    else:
        (url_action_continue, url_action_fixcritical, url_action_review,
         url_action_view_all) = [None] * 4
    checks = ChecksDisplay(obj).checks_by_category
    stats = StatsDisplay(obj, stats=stats).stats
    del stats["children"]
    chunk_size = TOP_CONTRIBUTORS_CHUNK_SIZE
    score_data = scores.get(ProjectSet)(obj)

    def scores_to_json(score):
        score["user"] = score["user"].to_dict()
        return score

    top_scorers = score_data.display(limit=chunk_size,
                                     formatter=scores_to_json)
    top_scorer_data = dict(
        items=list(top_scorers),
        has_more_items=len(score_data.top_scorers) > chunk_size)
    assertions = dict(page="browse",
                      pootle_path="/projects/",
                      resource_path="",
                      resource_path_parts=[],
                      object=obj,
                      browser_extends="projects/all/base.html",
                      top_scorers=top_scorer_data,
                      translation_states=get_translation_states(obj),
                      url_action_continue=url_action_continue,
                      url_action_fixcritical=url_action_fixcritical,
                      url_action_review=url_action_review,
                      url_action_view_all=url_action_view_all,
                      checks=checks,
                      stats=stats)
    view_context_test(ctx, **assertions)
Exemplo n.º 17
0
def test_view_projects_translate(client, settings, request_users):
    user = request_users["user"]
    client.login(username=user.username, password=request_users["password"])
    response = client.get(reverse("pootle-projects-translate"))

    if not user.is_superuser:
        assert response.status_code == 403
        return
    ctx = response.context
    request = response.wsgi_request
    user_projects = Project.accessible_by_user(request.user)
    user_projects = (Project.objects.for_user(
        request.user).filter(code__in=user_projects))
    obj = ProjectSet(user_projects)
    checks = get_qualitychecks()
    schema = {sc["code"]: sc for sc in get_qualitycheck_schema()}
    check_data = obj.data_tool.get_checks()
    _checks = {}
    for check, checkid in checks.items():
        if check not in check_data:
            continue
        _checkid = schema[checkid]["name"]
        _checks[_checkid] = _checks.get(
            _checkid, dict(checks=[], title=schema[checkid]["title"]))
        _checks[_checkid]["checks"].append(
            dict(code=check, title=check_names[check],
                 count=check_data[check]))
    _checks = OrderedDict(
        (k, _checks[k]) for k in CATEGORY_IDS.keys() if _checks.get(k))
    assertions = dict(page="translate",
                      has_admin_access=user.is_superuser,
                      language=None,
                      project=None,
                      pootle_path="/projects/",
                      ctx_path="/projects/",
                      resource_path="",
                      resource_path_parts=[],
                      editor_extends="projects/all/base.html",
                      checks=_checks,
                      previous_url=get_previous_url(request),
                      display_priority=False,
                      cantranslate=check_permission("translate", request),
                      cansuggest=check_permission("suggest", request),
                      canreview=check_permission("review", request),
                      search_form=make_search_form(request=request),
                      current_vfolder_pk="",
                      POOTLE_MT_BACKENDS=settings.POOTLE_MT_BACKENDS,
                      AMAGAMA_URL=settings.AMAGAMA_URL)
    view_context_test(ctx, **assertions)
Exemplo n.º 18
0
def test_no_root_hide_permissions(po_directory, nobody, default, admin, hide,
                                  view, no_projects, no_permission_sets,
                                  project_foo, project_bar, root):
    """Tests user-accessible projects when there are no `hide` permissions
    set at the root.
    """

    ALL_PROJECTS = [project_foo.code, project_bar.code]

    foo_user = UserFactory.create(username='******')
    bar_user = UserFactory.create(username='******')

    # By default everyone has access to projects
    _require_permission_set(default, root, [view])
    _require_permission_set(nobody, root, [view])

    # At the same time, `project_foo` is inaccessible registered users...
    _require_permission_set(default, project_foo.directory,
                            negative_permissions=[hide])

    assert items_equal(Project.accessible_by_user(admin), ALL_PROJECTS)
    assert items_equal(Project.accessible_by_user(default), [project_bar.code])
    assert items_equal(Project.accessible_by_user(nobody), [project_bar.code])
    assert items_equal(
        Project.accessible_by_user(foo_user),
        [project_bar.code])
    assert items_equal(
        Project.accessible_by_user(bar_user),
        [project_bar.code])

    # ...and anonymous users as well
    _require_permission_set(nobody, project_foo.directory,
                            negative_permissions=[hide])

    assert items_equal(Project.accessible_by_user(nobody), [project_bar.code])

    # Let's make `project_foo` accessible for `foo_user`
    _require_permission_set(foo_user, project_foo.directory, [view])

    assert items_equal(Project.accessible_by_user(foo_user), ALL_PROJECTS)

    # `project_bar` is now inaccessible for anonymous users
    _require_permission_set(nobody, project_bar.directory,
                            negative_permissions=[hide])

    assert items_equal(Project.accessible_by_user(nobody), [])
Exemplo n.º 19
0
def test_view_projects_browse(client, request_users):
    user = request_users["user"]
    client.login(
        username=user.username,
        password=request_users["password"])
    response = client.get(reverse("pootle-projects-browse"))
    assert response.cookies["pootle-language"].value == "projects"
    ctx = response.context
    request = response.wsgi_request
    user_projects = Project.accessible_by_user(request.user)
    user_projects = (
        Project.objects.for_user(request.user)
                       .filter(code__in=user_projects))
    obj = ProjectSet(user_projects)
    stats = obj.data_tool.get_stats(user=request.user)

    if request.user.is_superuser:
        url_action_continue = obj.get_translate_url(state='incomplete')
        url_action_fixcritical = obj.get_critical_url()
        url_action_review = obj.get_translate_url(state='suggestions')
        url_action_view_all = obj.get_translate_url(state='all')
    else:
        (url_action_continue,
         url_action_fixcritical,
         url_action_review,
         url_action_view_all) = [None] * 4
    checks = ChecksDisplay(obj).checks_by_category
    stats = StatsDisplay(obj, stats=stats).stats
    del stats["children"]
    User = get_user_model()
    top_scorers = User.top_scorers(limit=10)
    assertions = dict(
        page="browse",
        pootle_path="/projects/",
        resource_path="",
        resource_path_parts=[],
        object=obj,
        browser_extends="projects/all/base.html",
        top_scorers=top_scorers,
        top_scorers_data=get_top_scorers_data(top_scorers, 10),
        translation_states=get_translation_states(obj),
        url_action_continue=url_action_continue,
        url_action_fixcritical=url_action_fixcritical,
        url_action_review=url_action_review,
        url_action_view_all=url_action_view_all,
        checks=checks,
        stats=stats)
    view_context_test(ctx, **assertions)
Exemplo n.º 20
0
def projects_index(request, root):
    """Page listing all projects."""
    user_accessible_projects = Project.accessible_by_user(request.user)
    user_projects = Project.objects.filter(code__in=user_accessible_projects)
    items = [make_project_list_item(project) for project in user_projects]

    table_fields = ['name']

    ctx = {
        'table': {
            'id': 'projects',
            'fields': table_fields,
            'headings': get_table_headings(table_fields),
            'items': items,
        },
    }

    return render(request, "projects/list.html", ctx)
Exemplo n.º 21
0
def projects_index(request, root):
    """Page listing all projects."""
    user_accessible_projects = Project.accessible_by_user(request.user)
    user_projects = Project.objects.filter(code__in=user_accessible_projects)
    items = [make_project_list_item(project) for project in user_projects]

    table_fields = ["name"]

    ctx = {
        "table": {
            "id": "projects",
            "fields": table_fields,
            "headings": get_table_headings(table_fields),
            "items": items,
        }
    }

    return render(request, "projects/list.html", ctx)
Exemplo n.º 22
0
    def for_user(self, user, select_related=None):
        """Filters translation projects for a specific user.

        - Admins always get all translation projects.
        - Regular users only get enabled translation projects
            accessible to them.

        :param user: The user for whom the translation projects need to be
            retrieved for.
        :return: A filtered queryset with `TranslationProject`s for `user`.
        """
        qs = self.live()
        if select_related is not None:
            qs = qs.select_related(*select_related)

        if user.is_superuser:
            return qs

        return qs.filter(project__disabled=False,
                         project__code__in=Project.accessible_by_user(user))
Exemplo n.º 23
0
    def get_for_user(self, user):
        """Filters units for a specific user.

        - Admins always get all non-obsolete units
        - Regular users only get units from enabled projects accessible
            to them.

        :param user: The user for whom units need to be retrieved for.
        :return: A filtered queryset with `Unit`s for `user`.
        """
        from pootle_project.models import Project

        if user.is_superuser:
            return self.live()

        user_projects = Project.accessible_by_user(user)
        filter_by = {
            "store__translation_project__project__disabled": False,
            "store__translation_project__project__code__in": user_projects
        }
        return self.live().filter(**filter_by)
Exemplo n.º 24
0
def test_get_contributors_projects(client, request_users):

    user = request_users["user"]
    if user.username != "nobody":
        client.login(
            username=user.username,
            password=request_users["password"])

    directory = Directory.objects.projects
    response = client.get(
        "/xhr/stats/contributors/?path=%s" % directory.pootle_path,
        HTTP_X_REQUESTED_WITH='XMLHttpRequest')
    assert response.status_code == 200
    result = json.loads(response.content)
    user_projects = Project.accessible_by_user(user)
    user_projects = (
        Project.objects.for_user(user)
                       .filter(code__in=user_projects))
    top_scorers_data = get_top_scorers_test_data(ProjectSet(user_projects))
    for k, v in result.items():
        assert json.loads(json.dumps(top_scorers_data[k])) == v
Exemplo n.º 25
0
def pootle_context(request):
    """Exposes settings to templates."""
    # FIXME: maybe we should expose relevant settings only?
    return {
        'settings': {
            'POOTLE_TITLE': settings.POOTLE_TITLE,
            'POOTLE_INSTANCE_ID': settings.POOTLE_INSTANCE_ID,
            'POOTLE_CONTACT_ENABLED': (settings.POOTLE_CONTACT_ENABLED and
                                       settings.POOTLE_CONTACT_EMAIL),
            'POOTLE_MARKUP_FILTER': get_markup_filter_name(),
            'POOTLE_SIGNUP_ENABLED': settings.POOTLE_SIGNUP_ENABLED,
            'SCRIPT_NAME': settings.SCRIPT_NAME,
            'POOTLE_CACHE_TIMEOUT': settings.POOTLE_CACHE_TIMEOUT,
            'DEBUG': settings.DEBUG,
        },
        'custom': settings.POOTLE_CUSTOM_TEMPLATE_CONTEXT,
        'ALL_LANGUAGES': Language.live.cached_dict(translation.get_language()),
        'ALL_PROJECTS': Project.accessible_by_user(request.user),
        'SOCIAL_AUTH_PROVIDERS': jsonify(_get_social_auth_providers(request)),
        'display_agreement': _agreement_context(request),
    }
Exemplo n.º 26
0
    def for_user(self, user, select_related=None):
        """Filters translation projects for a specific user.

        - Admins always get all translation projects.
        - Regular users only get enabled translation projects
            accessible to them.

        :param user: The user for whom the translation projects need to be
            retrieved for.
        :return: A filtered queryset with `TranslationProject`s for `user`.
        """
        qs = self.live()
        if select_related is not None:
            qs = qs.select_related(*select_related)

        if user.is_superuser:
            return qs

        return qs.filter(
            project__disabled=False,
            project__code__in=Project.accessible_by_user(user))
Exemplo n.º 27
0
def test_view_projects_browse(site_permissions, site_matrix_with_vfolders,
                              site_matrix_with_announcements,
                              client, nobody, default):
    response = client.get(reverse("pootle-projects-browse"))
    assert response.cookies["pootle-language"].value == "projects"
    ctx = response.context
    request = response.wsgi_request
    user_projects = Project.accessible_by_user(request.user)
    user_projects = (
        Project.objects.for_user(request.user)
                       .filter(code__in=user_projects))
    ob = ProjectSet(user_projects)
    items = [
        make_project_list_item(project)
        for project in ob.children]
    items.sort(lambda x, y: locale.strcoll(x['title'], y['title']))
    table_fields = [
        'name', 'progress', 'total', 'need-translation',
        'suggestions', 'critical', 'last-updated', 'activity']
    table = {
        'id': 'projects',
        'fields': table_fields,
        'headings': get_table_headings(table_fields),
        'items': items}
    assertions = dict(
        page="browse",
        pootle_path="/projects/",
        resource_path="",
        resource_path_parts=[],
        object=ob,
        table=table,
        browser_extends="projects/all/base.html",
        stats=jsonify(ob.get_stats()),
        check_categories=get_qualitycheck_schema(ob),
        translation_states=get_translation_states(ob),
        url_action_continue=ob.get_translate_url(state='incomplete'),
        url_action_fixcritical=ob.get_critical_url(),
        url_action_review=ob.get_translate_url(state='suggestions'),
        url_action_view_all=ob.get_translate_url(state='all'))
    view_context_test(ctx, **assertions)
Exemplo n.º 28
0
def test_view_projects_browse(
    site_permissions, site_matrix_with_vfolders, site_matrix_with_announcements, client, nobody, default
):
    response = client.get(reverse("pootle-projects-browse"))
    assert response.cookies["pootle-language"].value == "projects"
    ctx = response.context
    request = response.wsgi_request
    user_projects = Project.accessible_by_user(request.user)
    user_projects = Project.objects.for_user(request.user).filter(code__in=user_projects)
    ob = ProjectSet(user_projects)
    items = [make_project_list_item(project) for project in ob.children]
    items.sort(lambda x, y: locale.strcoll(x["title"], y["title"]))
    table_fields = [
        "name",
        "progress",
        "total",
        "need-translation",
        "suggestions",
        "critical",
        "last-updated",
        "activity",
    ]
    table = {"id": "projects", "fields": table_fields, "headings": get_table_headings(table_fields), "items": items}
    assertions = dict(
        page="browse",
        pootle_path="/projects/",
        resource_path="",
        resource_path_parts=[],
        resource_obj=ob,
        table=table,
        browser_extends="projects/all/base.html",
        stats=jsonify(ob.get_stats()),
        check_categories=get_qualitycheck_schema(ob),
        translation_states=get_translation_states(ob),
        url_action_continue=ob.get_translate_url(state="incomplete"),
        url_action_fixcritical=ob.get_critical_url(),
        url_action_review=ob.get_translate_url(state="suggestions"),
        url_action_view_all=ob.get_translate_url(state="all"),
    )
    view_context_test(ctx, **assertions)
Exemplo n.º 29
0
def test_root_hide_permissions(po_directory, nobody, default, admin, hide,
                               view, no_permission_sets, no_projects,
                               project_foo, project_bar, root):
    """Tests user-accessible projects when there are `hide` permissions
    set at the root.
    """

    ALL_PROJECTS = [project_foo.code, project_bar.code]

    foo_user = UserFactory.create(username='******')
    bar_user = UserFactory.create(username='******')

    # By default all projects are not accessible
    _require_permission_set(default, root, negative_permissions=[hide])
    _require_permission_set(nobody, root, negative_permissions=[hide])

    assert items_equal(Project.accessible_by_user(admin), ALL_PROJECTS)
    assert items_equal(Project.accessible_by_user(default), [])
    assert items_equal(Project.accessible_by_user(nobody), [])
    assert items_equal(Project.accessible_by_user(foo_user), [])
    assert items_equal(Project.accessible_by_user(bar_user), [])

    # Now let's make `project_foo` accessible to `foo_user`.
    _require_permission_set(foo_user, project_foo.directory, [view])

    assert items_equal(Project.accessible_by_user(admin), ALL_PROJECTS)
    assert items_equal(Project.accessible_by_user(default), [])
    assert items_equal(Project.accessible_by_user(nobody), [])
    assert items_equal(
        Project.accessible_by_user(foo_user),
        [project_foo.code])
    assert items_equal(Project.accessible_by_user(bar_user), [])

    # Making projects accessible for anonymous users should open the door for
    # everyone
    _require_permission_set(nobody, root, [view])

    assert items_equal(Project.accessible_by_user(admin), ALL_PROJECTS)
    assert items_equal(Project.accessible_by_user(default), ALL_PROJECTS)
    assert items_equal(Project.accessible_by_user(nobody), ALL_PROJECTS)
    assert items_equal(Project.accessible_by_user(foo_user), ALL_PROJECTS)
    assert items_equal(Project.accessible_by_user(bar_user), ALL_PROJECTS)
Exemplo n.º 30
0
def test_root_view_permissions(po_directory, nobody, default, admin, view,
                               no_projects, no_permission_sets,
                               project_foo, project_bar, root):
    """Tests user-accessible projects with view permissions at the root."""
    ALL_PROJECTS = [project_foo.code, project_bar.code]

    foo_user = UserFactory.create(username='******')
    bar_user = UserFactory.create(username='******')

    # We'll only give `bar_user` access to all projects server-wide
    _require_permission_set(bar_user, root, [view])

    assert items_equal(Project.accessible_by_user(admin), ALL_PROJECTS)
    assert items_equal(Project.accessible_by_user(bar_user), ALL_PROJECTS)
    assert items_equal(Project.accessible_by_user(foo_user), [])
    assert items_equal(Project.accessible_by_user(default), [])
    assert items_equal(Project.accessible_by_user(nobody), [])

    # Now we'll also allow `foo_user` access `project_foo`
    _require_permission_set(foo_user, project_foo.directory, [view])

    assert items_equal(
        Project.accessible_by_user(foo_user),
        [project_foo.code])

    # Let's change server-wide defaults: all registered users have access to
    # all projects. `foo_user`, albeit having explicit access for
    # `project_foo`, will be able to access any project because they fall back
    # and extend with the defaults.
    _require_permission_set(default, root, [view])

    assert items_equal(Project.accessible_by_user(admin), ALL_PROJECTS)
    assert items_equal(Project.accessible_by_user(foo_user), ALL_PROJECTS)
    assert items_equal(Project.accessible_by_user(bar_user), ALL_PROJECTS)
    assert items_equal(Project.accessible_by_user(default), ALL_PROJECTS)
    assert items_equal(Project.accessible_by_user(nobody), [])

    # Let's give anonymous users access to all projects too
    _require_permission_set(nobody, root, [view])

    assert items_equal(Project.accessible_by_user(nobody), ALL_PROJECTS)
Exemplo n.º 31
0
Arquivo: index.py Projeto: ii0/pootle
 def project_set(self):
     user_projects = Project.accessible_by_user(self.request.user)
     user_projects = (
         Project.objects.for_user(self.request.user)
                        .filter(code__in=user_projects))
     return ProjectSet(user_projects)
Exemplo n.º 32
0
    def wrapped(request, *args, **kwargs):
        if request.is_ajax():
            pootle_path = request.GET.get('path', None)
            if pootle_path is None:
                raise Http400(_('Arguments missing.'))

            language_code, project_code, dir_path, filename = \
                split_pootle_path(pootle_path)
            kwargs['dir_path'] = dir_path
            kwargs['filename'] = filename

            # Remove potentially present but unwanted args
            try:
                del kwargs['language_code']
                del kwargs['project_code']
            except KeyError:
                pass
        else:
            language_code = kwargs.pop('language_code', None)
            project_code = kwargs.pop('project_code', None)

        if language_code and project_code:
            try:
                path_obj = TranslationProject.objects.get_for_user(
                    user=request.user,
                    language_code=language_code,
                    project_code=project_code,
                )
            except TranslationProject.DoesNotExist:
                path_obj = None

            if path_obj is None:
                if not request.is_ajax():
                    # Explicit selection via the UI: redirect either to
                    # ``/language_code/`` or ``/projects/project_code/``
                    user_choice = request.COOKIES.get('user-choice', None)
                    if user_choice and user_choice in ('language', 'project',):
                        url = {
                            'language': reverse('pootle-language-browse',
                                                args=[language_code]),
                            'project': reverse('pootle-project-browse',
                                               args=[project_code, '', '']),
                        }
                        response = redirect(url[user_choice])
                        response.delete_cookie('user-choice')

                        return response

                raise Http404
        elif language_code:
            user_projects = Project.accessible_by_user(request.user)
            language = get_object_or_404(Language, code=language_code)
            children = language.children \
                               .filter(project__code__in=user_projects)
            language.set_children(children)
            path_obj = language
        elif project_code:
            try:
                path_obj = Project.objects.get_for_user(project_code,
                                                        request.user)
            except Project.DoesNotExist:
                raise Http404
        else:  # No arguments: all user-accessible projects
            user_projects = Project.accessible_by_user(request.user)
            user_projects = Project.objects.for_user(request.user) \
                                           .filter(code__in=user_projects)

            path_obj = ProjectSet(user_projects)

        request.ctx_obj = path_obj
        request.ctx_path = path_obj.pootle_path
        request.resource_obj = path_obj
        request.pootle_path = path_obj.pootle_path

        return func(request, path_obj, *args, **kwargs)
Exemplo n.º 33
0
def test_root_hide_permissions(po_directory, nobody, default, admin, hide,
                               view, no_permission_sets, no_projects,
                               project_foo, project_bar, root):
    """Tests user-accessible projects when there are `hide` permissions
    set at the root.
    """

    ALL_PROJECTS = [project_foo.code, project_bar.code]

    foo_user = UserFactory.create(username='******')
    bar_user = UserFactory.create(username='******')

    # By default all projects are not accessible
    _require_permission_set(default, root, negative_permissions=[hide])
    _require_permission_set(nobody, root, negative_permissions=[hide])

    assert items_equal(Project.accessible_by_user(admin), ALL_PROJECTS)
    assert items_equal(Project.accessible_by_user(default), [])
    assert items_equal(Project.accessible_by_user(nobody), [])
    assert items_equal(Project.accessible_by_user(foo_user), [])
    assert items_equal(Project.accessible_by_user(bar_user), [])

    # Now let's make `project_foo` accessible to `foo_user`.
    _require_permission_set(foo_user, project_foo.directory, [view])

    assert items_equal(Project.accessible_by_user(admin), ALL_PROJECTS)
    assert items_equal(Project.accessible_by_user(default), [])
    assert items_equal(Project.accessible_by_user(nobody), [])
    assert items_equal(
        Project.accessible_by_user(foo_user),
        [project_foo.code])
    assert items_equal(Project.accessible_by_user(bar_user), [])

    # Making projects accessible for anonymous users should open the door for
    # everyone
    _require_permission_set(nobody, root, [view])

    assert items_equal(Project.accessible_by_user(admin), ALL_PROJECTS)
    assert items_equal(Project.accessible_by_user(default), ALL_PROJECTS)
    assert items_equal(Project.accessible_by_user(nobody), ALL_PROJECTS)
    assert items_equal(Project.accessible_by_user(foo_user), ALL_PROJECTS)
    assert items_equal(Project.accessible_by_user(bar_user), ALL_PROJECTS)
Exemplo n.º 34
0
 def project_set(self):
     user_projects = Project.accessible_by_user(self.request.user)
     user_projects = (
         Project.objects.for_user(self.request.user)
                        .filter(code__in=user_projects))
     return ProjectSet(user_projects)
Exemplo n.º 35
0
def test_root_view_permissions(po_directory, nobody, default, admin, view,
                               no_projects, no_permission_sets,
                               project_foo, project_bar, root):
    """Tests user-accessible projects with view permissions at the root."""
    ALL_PROJECTS = [project_foo.code, project_bar.code]

    foo_user = UserFactory.create(username='******')
    bar_user = UserFactory.create(username='******')

    # We'll only give `bar_user` access to all projects server-wide
    _require_permission_set(bar_user, root, [view])

    assert items_equal(Project.accessible_by_user(admin), ALL_PROJECTS)
    assert items_equal(Project.accessible_by_user(bar_user), ALL_PROJECTS)
    assert items_equal(Project.accessible_by_user(foo_user), [])
    assert items_equal(Project.accessible_by_user(default), [])
    assert items_equal(Project.accessible_by_user(nobody), [])

    # Now we'll also allow `foo_user` access `project_foo`
    _require_permission_set(foo_user, project_foo.directory, [view])

    assert items_equal(
        Project.accessible_by_user(foo_user),
        [project_foo.code])

    # Let's change server-wide defaults: all registered users have access to
    # all projects. `foo_user`, albeit having explicit access for
    # `project_foo`, will be able to access any project because they fall back
    # and extend with the defaults.
    _require_permission_set(default, root, [view])

    assert items_equal(Project.accessible_by_user(admin), ALL_PROJECTS)
    assert items_equal(Project.accessible_by_user(foo_user), ALL_PROJECTS)
    assert items_equal(Project.accessible_by_user(bar_user), ALL_PROJECTS)
    assert items_equal(Project.accessible_by_user(default), ALL_PROJECTS)
    assert items_equal(Project.accessible_by_user(nobody), [])

    # Let's give anonymous users access to all projects too
    _require_permission_set(nobody, root, [view])

    assert items_equal(Project.accessible_by_user(nobody), ALL_PROJECTS)