<commit_before>#!/usr/bin/env python3
#
# Copyright 2018 Red Hat, Inc.
#
# Authors:
#     <NAME> <<EMAIL>>
#
# This work is licensed under the MIT License.  Please see the LICENSE file or
# http://opensource.org/licenses/MIT.

from collections import OrderedDict
from django.contrib.auth.models import User
from django.http import Http404
from django.template import loader

from mod import dispatch_module_hook
from .models import Project, ProjectResult, Message, MessageResult, Result
from .search import SearchEngine
from rest_framework import (permissions, serializers, viewsets, filters,
    mixins, generics, renderers, status)
from rest_framework.decorators import detail_route, action
from rest_framework.fields import SerializerMethodField, CharField, JSONField, EmailField
from rest_framework.relations import HyperlinkedIdentityField
from rest_framework.response import Response
import rest_framework
from mbox import addr_db_to_rest, MboxMessage
from rest_framework.parsers import JSONParser, BaseParser

SEARCH_PARAM = 'q'

# patchew-specific permission classes

class PatchewPermission(permissions.BasePermission):
    """
    Generic code to lookup for permissions based on message and project
    objects.  If the view has a "project" property, it should return an
    api.models.Project, and has_permission will check that property too.

    Subclasses can override the methods, or specify a set of groups that
    are granted authorization independent of object permissions.
    """

    allowed_groups = ()

    def is_superuser(self, request):
        return request.user and request.user.is_superuser

    def has_project_permission(self, request, view, obj):
        return obj.maintained_by(request.user)

    def has_message_permission(self, request, view, obj):
        return obj.project.maintained_by(request.user)

    def has_group_permission(self, request, view):
        for grp in request.user.groups.all():
            if grp.name in self.allowed_groups:
                return True
        return False

    def has_generic_permission(self, request, view):
        return (request.method in permissions.SAFE_METHODS) or \
               self.is_superuser(request) or \
               self.has_group_permission(request, view)

    def has_permission(self, request, view):
        return self.has_generic_permission(request, view) or \
               (hasattr(view, 'project') and view.project and \
                self.has_project_permission(request, view, view.project))

    def has_object_permission(self, request, view, obj):
        return self.has_generic_permission(request, view) or \
               (isinstance(obj, Message) and \
                self.has_message_permission(request, view, obj)) or \
               (isinstance(obj, Project) and \
                self.has_project_permission(request, view, obj))

class ImportPermission(PatchewPermission):
    allowed_groups = ('importers',)

# utility function to generate REST API URLs

def reverse_detail(obj, request):
    if isinstance(obj, Project):
        return rest_framework.reverse.reverse("project-detail",
                                              request=request,
                                              kwargs={"pk": obj.id})
    if isinstance(obj, Message):
        assert obj.is_series_head
        return rest_framework.reverse.reverse("series-detail",
                                              request=request,
                                              kwargs={"projects_pk": obj.project.id,
                                                      "message_id": obj.message_id})<commit_msg>rest: simplify PatchewPermission<commit_after>#!/usr/bin/env python3
#
# Copyright 2018 Red Hat, Inc.
#
# Authors:
#     <NAME> <<EMAIL>>
#
# This work is licensed under the MIT License.  Please see the LICENSE file or
# http://opensource.org/licenses/MIT.

from collections import OrderedDict
from django.contrib.auth.models import User
from django.http import Http404
from django.template import loader

from mod import dispatch_module_hook
from .models import Project, ProjectResult, Message, MessageResult, Result
from .search import SearchEngine
from rest_framework import (permissions, serializers, viewsets, filters,
    mixins, generics, renderers, status)
from rest_framework.decorators import detail_route, action
from rest_framework.fields import SerializerMethodField, CharField, JSONField, EmailField
from rest_framework.relations import HyperlinkedIdentityField
from rest_framework.response import Response
import rest_framework
from mbox import addr_db_to_rest, MboxMessage
from rest_framework.parsers import JSONParser, BaseParser

SEARCH_PARAM = 'q'

# patchew-specific permission classes

class PatchewPermission(permissions.BasePermission):
    """
    Generic code to lookup for permissions based on message and project
    objects.  If the view has a "project" property, it should return an
    api.models.Project, and has_permission will check that property too.

    Subclasses can override the methods, or specify a set of groups that
    are granted authorization independent of object permissions.
    """

    allowed_groups = ()

    def is_superuser(self, request):
        return request.user and request.user.is_superuser

    def has_project_permission(self, request, view, obj):
        return obj.maintained_by(request.user)

    def has_group_permission(self, request, view, groups):
        for grp in request.user.groups.all():
            if grp.name in groups:
                return True
        return False

    def has_generic_permission(self, request, view):
        return (request.method in permissions.SAFE_METHODS) or \
               self.is_superuser(request) or \
               self.has_group_permission(request, view, self.allowed_groups)

    def has_permission(self, request, view):
        # The user can get permissions to operate on an object or a list from one of:
        # - the HTTP method (has_generic_permission)
        # - the groups that are allowed for the view (has_generic_permission)
        # - the parent project of an object (view.project + has_project_permission)
        return self.has_generic_permission(request, view) or \
               (hasattr(view, 'project') and view.project and \
                self.has_project_permission(request, view, view.project))

    def has_object_permission(self, request, view, obj):
        # For non-project objects, has_project_permission has been evaluated
        # already in has_permission, based on the primary key included in the
        # URL.
        return self.has_generic_permission(request, view) or \
               not isinstance(obj, Project) or \
               self.has_project_permission(request, view, obj)

class ImportPermission(PatchewPermission):
    allowed_groups = ('importers',)

# utility function to generate REST API URLs

def reverse_detail(obj, request):
    if isinstance(obj, Project):
        return rest_framework.reverse.reverse("project-detail",
                                              request=request,
                                              kwargs={"pk": obj.id})
    if isinstance(obj, Message):
        assert obj.is_series_head
        return rest_framework.reverse.reverse("series-detail",
                                              request=request,
                                              kwargs={"projects_pk": obj.project.id,
                                                      "message_id": obj.message_id})
{'fraction_non_alphanumeric': 0.07305389221556886, 'fraction_numerical': 0.0021290751829673984, 'mean_word_length': 2.8113590263691686, 'pattern_counts': {'":': 6, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 20, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2296606', 'n_tokens_mistral': 1903, 'n_tokens_neox': 1855, 'n_words': 606}