<commit_before>from arches.app.models.models import Node
from arches.app.models.system_settings import settings
from guardian.backends import check_support
from guardian.backends import ObjectPermissionBackend
from django.core.exceptions import ObjectDoesNotExist
from guardian.core import ObjectPermissionChecker
from guardian.shortcuts import (
    get_perms,
    get_objects_for_user,
    get_group_perms,
    get_user_perms,
    get_users_with_perms,
    remove_perm,
    assign_perm,
)
from guardian.exceptions import WrongAppError
from django.contrib.auth.models import User, Group, Permission
from arches.app.models.models import ResourceInstance
from arches.app.search.search_engine_factory import SearchEngineFactory
from arches.app.search.elasticsearch_dsl_builder import Bool, Query, Terms


class PermissionBackend(ObjectPermissionBackend):
    def has_perm(self, user_obj, perm, obj=None):
        # check if user_obj and object are supported (pulled directly from guardian)
        support, user_obj = check_support(user_obj, obj)
        if not support:
            return False

        if "." in perm:
            app_label, perm = perm.split(".")
            if app_label != obj._meta.app_label:
                raise WrongAppError("Passed perm has app label of '%s' and " "given obj has '%s'" % (app_label, obj._meta.app_label))

        explicitly_defined_perms = get_perms(user_obj, obj)
        if len(explicitly_defined_perms) > 0:
            if "no_access_to_nodegroup" in explicitly_defined_perms:
                return False
            else:
                return perm in explicitly_defined_perms
        else:
            default_perms = []
            for group in user_obj.groups.all():
                for permission in group.permissions.all():
                    if perm in permission.codename:
                        return True
            return False


def get_restricted_users(resource):
    """
    Takes a resource instance and identifies which users are explicitly restricted from
    reading, editing, deleting, or accessing it.

    """

    user_perms = get_users_with_perms(resource, attach_perms=True, with_group_users=False)
    user_and_group_perms = get_users_with_perms(resource, attach_perms=True, with_group_users=True)

    result = {
        "no_access": [],
        "cannot_read": [],
        "cannot_write": [],
        "cannot_delete": [],
    }

    for user, perms in user_and_group_perms.items():
        if user.is_superuser:
            pass
        elif user in user_perms and "no_access_to_resourceinstance" in user_perms[user]:
            for k, v in result.items():
                v.append(user.id)
        else:
            if "view_resourceinstance" not in perms:
                result["cannot_read"].append(user.id)
            if "change_resourceinstance" not in perms:
                result["cannot_write"].append(user.id)
            if "delete_resourceinstance" not in perms:
                result["cannot_delete"].append(user.id)
            if "no_access_to_resourceinstance" in perms and len(perms) == 1:
                result["no_access"].append(user.id)

    return result


def get_restricted_instances(user):
    if user.is_superuser is False:
        se = SearchEngineFactory().create()
        query = Query(se, start=0, limit=settings.SEARCH_RESULT_LIMIT)
        has_access = Bool()
        terms = Terms(field="permissions.users_with_no_access", terms=[str(user.id)])
        has_access.must(terms)
        query.add_query(has_access)
        results = query.search(index="resources", scroll="1m")
        scroll_id = results["_scroll_id"]
        total = results["hits"]["total"]["value"]
        if total > settings.SEARCH_RESULT_LIMIT:
            pages = total // settings.SEARCH_RESULT_LIMIT
            for page in range(pages):
                results_scrolled = query.se.es.scroll(scroll_id=scroll_id, scroll="1m")
                results["hits"]["hits"] += results_scrolled["hits"]["hits"]
        restricted_ids = [res['_id'] for res in results['hits']['hits']]
        return restricted_ids
    else:<commit_msg>Fixing style errors.<commit_after>from arches.app.models.models import Node
from arches.app.models.system_settings import settings
from guardian.backends import check_support
from guardian.backends import ObjectPermissionBackend
from django.core.exceptions import ObjectDoesNotExist
from guardian.core import ObjectPermissionChecker
from guardian.shortcuts import (
    get_perms,
    get_objects_for_user,
    get_group_perms,
    get_user_perms,
    get_users_with_perms,
    remove_perm,
    assign_perm,
)
from guardian.exceptions import WrongAppError
from django.contrib.auth.models import User, Group, Permission
from arches.app.models.models import ResourceInstance
from arches.app.search.search_engine_factory import SearchEngineFactory
from arches.app.search.elasticsearch_dsl_builder import Bool, Query, Terms


class PermissionBackend(ObjectPermissionBackend):
    def has_perm(self, user_obj, perm, obj=None):
        # check if user_obj and object are supported (pulled directly from guardian)
        support, user_obj = check_support(user_obj, obj)
        if not support:
            return False

        if "." in perm:
            app_label, perm = perm.split(".")
            if app_label != obj._meta.app_label:
                raise WrongAppError("Passed perm has app label of '%s' and " "given obj has '%s'" % (app_label, obj._meta.app_label))

        explicitly_defined_perms = get_perms(user_obj, obj)
        if len(explicitly_defined_perms) > 0:
            if "no_access_to_nodegroup" in explicitly_defined_perms:
                return False
            else:
                return perm in explicitly_defined_perms
        else:
            default_perms = []
            for group in user_obj.groups.all():
                for permission in group.permissions.all():
                    if perm in permission.codename:
                        return True
            return False


def get_restricted_users(resource):
    """
    Takes a resource instance and identifies which users are explicitly restricted from
    reading, editing, deleting, or accessing it.

    """

    user_perms = get_users_with_perms(resource, attach_perms=True, with_group_users=False)
    user_and_group_perms = get_users_with_perms(resource, attach_perms=True, with_group_users=True)

    result = {
        "no_access": [],
        "cannot_read": [],
        "cannot_write": [],
        "cannot_delete": [],
    }

    for user, perms in user_and_group_perms.items():
        if user.is_superuser:
            pass
        elif user in user_perms and "no_access_to_resourceinstance" in user_perms[user]:
            for k, v in result.items():
                v.append(user.id)
        else:
            if "view_resourceinstance" not in perms:
                result["cannot_read"].append(user.id)
            if "change_resourceinstance" not in perms:
                result["cannot_write"].append(user.id)
            if "delete_resourceinstance" not in perms:
                result["cannot_delete"].append(user.id)
            if "no_access_to_resourceinstance" in perms and len(perms) == 1:
                result["no_access"].append(user.id)

    return result


def get_restricted_instances(user):
    if user.is_superuser is False:
        se = SearchEngineFactory().create()
        query = Query(se, start=0, limit=settings.SEARCH_RESULT_LIMIT)
        has_access = Bool()
        terms = Terms(field="permissions.users_with_no_access", terms=[str(user.id)])
        has_access.must(terms)
        query.add_query(has_access)
        results = query.search(index="resources", scroll="1m")
        scroll_id = results["_scroll_id"]
        total = results["hits"]["total"]["value"]
        if total > settings.SEARCH_RESULT_LIMIT:
            pages = total // settings.SEARCH_RESULT_LIMIT
            for page in range(pages):
                results_scrolled = query.se.es.scroll(scroll_id=scroll_id, scroll="1m")
                results["hits"]["hits"] += results_scrolled["hits"]["hits"]
        restricted_ids = [res["_id"] for res in results["hits"]["hits"]]
        return restricted_ids
    else:
{'fraction_non_alphanumeric': 0.09062234623316753, 'fraction_numerical': 0.001213150551983501, 'mean_word_length': 2.760948905109489, 'pattern_counts': {'":': 8, '<': 3, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4905733', 'n_tokens_mistral': 2410, 'n_tokens_neox': 2329, 'n_words': 557}