diff --git a/InvenTree/InvenTree/api.py b/InvenTree/InvenTree/api.py index 44e7ec383f..1bdfb79ceb 100644 --- a/InvenTree/InvenTree/api.py +++ b/InvenTree/InvenTree/api.py @@ -30,6 +30,8 @@ class InfoView(AjaxView): Use to confirm that the server is running, etc. """ + permission_classes = [permissions.AllowAny] + def get(self, request, *args, **kwargs): data = { diff --git a/InvenTree/InvenTree/context.py b/InvenTree/InvenTree/context.py index 7de41eef15..f9d856f566 100644 --- a/InvenTree/InvenTree/context.py +++ b/InvenTree/InvenTree/context.py @@ -17,3 +17,43 @@ def status_codes(request): 'BuildStatus': BuildStatus, 'StockStatus': StockStatus, } + + +def user_roles(request): + """ + Return a map of the current roles assigned to the user. + + Roles are denoted by their simple names, and then the permission type. + + Permissions can be access as follows: + + - roles.part.view + - roles.build.delete + + Each value will return a boolean True / False + """ + + user = request.user + + roles = { + } + + for group in user.groups.all(): + for rule in group.rule_sets.all(): + + # Ensure the role name is in the dict + if rule.name not in roles: + roles[rule.name] = { + 'view': user.is_superuser, + 'add': user.is_superuser, + 'change': user.is_superuser, + 'delete': user.is_superuser + } + + # Roles are additive across groups + roles[rule.name]['view'] |= rule.can_view + roles[rule.name]['add'] |= rule.can_add + roles[rule.name]['change'] |= rule.can_change + roles[rule.name]['delete'] |= rule.can_delete + + return {'roles': roles} diff --git a/InvenTree/InvenTree/helpers.py b/InvenTree/InvenTree/helpers.py index 9b470902b1..13b770539c 100644 --- a/InvenTree/InvenTree/helpers.py +++ b/InvenTree/InvenTree/helpers.py @@ -15,6 +15,8 @@ from django.http import StreamingHttpResponse from django.core.exceptions import ValidationError from django.utils.translation import ugettext as _ +from django.contrib.auth.models import Permission + import InvenTree.version from .settings import MEDIA_URL, STATIC_URL @@ -441,3 +443,21 @@ def validateFilterString(value): results[k] = v return results + + +def addUserPermission(user, permission): + """ + Shortcut function for adding a certain permission to a user. + """ + + perm = Permission.objects.get(codename=permission) + user.user_permissions.add(perm) + + +def addUserPermissions(user, permissions): + """ + Shortcut function for adding multiple permissions to a user. + """ + + for permission in permissions: + addUserPermission(user, permission) diff --git a/InvenTree/InvenTree/settings.py b/InvenTree/InvenTree/settings.py index 21b8a0ead1..c6f8b40069 100644 --- a/InvenTree/InvenTree/settings.py +++ b/InvenTree/InvenTree/settings.py @@ -210,6 +210,7 @@ TEMPLATES = [ 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'InvenTree.context.status_codes', + 'InvenTree.context.user_roles', ], }, }, @@ -231,6 +232,10 @@ REST_FRAMEWORK = { 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), + 'DEFAULT_PERMISSION_CLASSES': ( + 'rest_framework.permissions.IsAuthenticated', + 'rest_framework.permissions.DjangoModelPermissions', + ), 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema' } diff --git a/InvenTree/InvenTree/views.py b/InvenTree/InvenTree/views.py index d940229ebe..bb7c1e6f5d 100644 --- a/InvenTree/InvenTree/views.py +++ b/InvenTree/InvenTree/views.py @@ -22,6 +22,7 @@ from django.views.generic.base import TemplateView from part.models import Part, PartCategory from stock.models import StockLocation, StockItem from common.models import InvenTreeSetting, ColorTheme +from users.models import check_user_role, RuleSet from .forms import DeleteForm, EditUserForm, SetPasswordForm, ColorThemeSelectForm from .helpers import str2bool @@ -107,31 +108,72 @@ class TreeSerializer(views.APIView): return JsonResponse(response, safe=False) -class AjaxMixin(PermissionRequiredMixin): +class InvenTreeRoleMixin(PermissionRequiredMixin): + """ + Permission class based on user roles, not user 'permissions'. + + To specify which role is required for the mixin, + set the class attribute 'role_required' to something like the following: + + role_required = 'part.add' + role_required = [ + 'part.change', + 'build.add', + ] + """ + + # By default, no roles are required + # Roles must be specified + role_required = None + + def has_permission(self): + """ + Determine if the current user + """ + + roles_required = [] + + if type(self.role_required) is str: + roles_required.append(self.role_required) + elif type(self.role_required) in [list, tuple]: + roles_required = self.role_required + + user = self.request.user + + # Superuser can have any permissions they desire + if user.is_superuser: + return True + + for required in roles_required: + + (role, permission) = required.split('.') + + if role not in RuleSet.RULESET_NAMES: + raise ValueError(f"Role '{role}' is not a valid role") + + if permission not in RuleSet.RULESET_PERMISSIONS: + raise ValueError(f"Permission '{permission}' is not a valid permission") + + # Return False if the user does not have *any* of the required roles + if not check_user_role(user, role, permission): + return False + + # We did not fail any required checks + return True + + +class AjaxMixin(InvenTreeRoleMixin): """ AjaxMixin provides basic functionality for rendering a Django form to JSON. Handles jsonResponse rendering, and adds extra data for the modal forms to process on the client side. Any view which inherits the AjaxMixin will need - correct permissions set using the 'permission_required' attribute + correct permissions set using the 'role_required' attribute """ - # By default, allow *any* permissions - permission_required = '*' - - def has_permission(self): - """ - Override the default behaviour of has_permission from PermissionRequiredMixin. - - Basically, if permission_required attribute = '*', - no permissions are actually required! - """ - - if self.permission_required == '*': - return True - else: - return super().has_permission() + # By default, allow *any* role + role_required = None # By default, point to the modal_form template # (this can be overridden by a child class) diff --git a/InvenTree/build/api.py b/InvenTree/build/api.py index c0faee6c15..d4e458c506 100644 --- a/InvenTree/build/api.py +++ b/InvenTree/build/api.py @@ -7,7 +7,7 @@ from __future__ import unicode_literals from django_filters.rest_framework import DjangoFilterBackend from rest_framework import filters -from rest_framework import generics, permissions +from rest_framework import generics from django.conf.urls import url, include @@ -28,10 +28,6 @@ class BuildList(generics.ListCreateAPIView): queryset = Build.objects.all() serializer_class = BuildSerializer - permission_classes = [ - permissions.IsAuthenticated, - ] - filter_backends = [ DjangoFilterBackend, filters.SearchFilter, @@ -99,10 +95,6 @@ class BuildDetail(generics.RetrieveUpdateAPIView): queryset = Build.objects.all() serializer_class = BuildSerializer - permission_classes = [ - permissions.IsAuthenticated, - ] - class BuildItemList(generics.ListCreateAPIView): """ API endpoint for accessing a list of BuildItem objects @@ -137,10 +129,6 @@ class BuildItemList(generics.ListCreateAPIView): return queryset - permission_classes = [ - permissions.IsAuthenticated, - ] - filter_backends = [ DjangoFilterBackend, ] diff --git a/InvenTree/build/templates/build/build_base.html b/InvenTree/build/templates/build/build_base.html index 915433b055..f076013def 100644 --- a/InvenTree/build/templates/build/build_base.html +++ b/InvenTree/build/templates/build/build_base.html @@ -35,25 +35,27 @@ src="{% static 'img/blank_image.png' %}"