How can I reuse the django permissions in django rest framework?

4

I have already asked this question and it can be a song but I hope that someone will help me, I am currently doing a project with django restframework, in which I will have two groups (Teachers, Students, School) and these already have their permissions assigned in django admin.

How do I use group permissions in django rest-framework.

I leave part of my code Model.py

class MyUser(AbstractUser):
    P_LIST = ((1,'Tourist'),(2,'Enterprise'),(3,'Other'))
    Profile = models.IntegerField(choices = P_LIST, default = 1)

class BaseModel(models.Model):
    create = models.DateField(auto_now_add = True, null = False, blank = False)
    update = models.DateField(auto_now = True, null = False, blank = False)

    class Meta:
        abstract = True

class CatLanguage(BaseModel):
    idLanguage = models.AutoField(primary_key = True)
    Name = models.CharField(max_length = 50, null = False, blank = False)
    Acronym = models.CharField(max_length = 5, null = False)
    Note = models.CharField(max_length = 2500, null = True, blank = True)

    def __str__(self):
        return self.Name

class TblGallery(BaseModel):
    IdGallery = models.AutoField(primary_key = True)
    Location = models.CharField(max_length = 1500, null = False)

    def  __str__(self):
        return str(self.IdGallery)

Serializer and Viesets:

from django.contrib.auth.models import User
from django.contrib.auth.models import AbstractUser

from django.views import generic

from rest_framework.authentication import SessionAuthentication,    BasicAuthentication
from rest_framework import serializers, viewsets, permissions
from rest_framework_jwt.authentication import JSONWebTokenAuthentication

#Models Import
from Base.models import *
from Base.permissions import *

from rest_framework.authentication import SessionAuthentication 

class CsrfExemptSessionAuthentication(SessionAuthentication):

    def enforce_csrf(self, request):
        return  # To not perform the csrf check previously happening


"""
class MyUserSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = MyUser
        fields = ('id','Profile','email', 'first_name', 'last_name', 'password', 'is_superuser')


class MyUserViewSet(viewsets.ModelViewSet):
    serializer_class = MyUserSerializer
    queryset = MyUser.objects.all()

    def get_serializer_class(self):
        return MyUserSerializer


""" 
#Serialiazers
class LanguageSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = CatLanguage
        fields = ['idLanguage','Name','Acronym','Note','create','update']


class GallerySerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = TblGallery
        fields = ('IdGallery','Location','create','update')


class GalleryDetailSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = TblGalleryDetail
        fields = ('IdGalleryDetail','IdGallery','IdLanguage','Name','Description')

#---------------    ViewSets      ----------------------------------------------
class LanguageViewSet(viewsets.ModelViewSet):
    #authentication_classes = [SessionAuthentication, BasicAuthentication, JSONWebTokenAuthentication]
    authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication)
    permissions_classes = [UserPermission]
    queryset = CatLanguage.objects.all()
    serializers_class = LanguageSerializer

    def get_serializer_class(self):
        return LanguageSerializer

#---------------    
class GalleryViewSet(viewsets.ModelViewSet):
    serializers_class = GallerySerializer
    queryset = TblGallery.objects.all()

   def get_serializer_class(self):
        return GallerySerializer


class GalleryDetailViewSet(viewsets.ModelViewSet):
    serializers_class = GalleryDetailSerializer
    queryset = TblGalleryDetail.objects.all()

    def get_serializer_class(self):
        return GalleryDetailSerializer

I leave the Permissions.py there are varas class that I try, besides none of them is to look for permissions and groups.

from rest_framework.exceptions import PermissionDenied, NotAuthenticated 
from rest_framework import permissions
from rest_framework.permissions import BasePermission
from django.contrib.auth.models import User

#---
from django.contrib.auth.decorators import user_passes_test

def group_required(*group_names):
    """Requires user membership in at least one of the groups passed in."""
    def in_groups(u):
        if u.is_authenticated():
            if bool(u.groups.filter(name__in=group_names)) | u.is_superuser:
                return True
        return False

    return user_passes_test(in_groups, login_url='403')



SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS','POST']

class Profile(BasePermission):

    def has_object_permission(self, request, view, obj):
        """
        Return True if the user is the owner of the ..
        """
        if request.method in SAFE_METHODS:
            return False
        elif request.method == 'PUT' or request.method =='POST':
            if request.user.Profile == 1:
                return True
            return False


class UserPermission(permissions.BasePermission):

    def has_permission(self, request, view):                                                        
        if view.action == 'list':                                                                   
            return request.user.is_authenticated() and request.user.is_admin                        
        elif view.action == 'create':                                                               
            return True                                                                             
        elif view.action in ['retrieve', 'update', 'partial_update', 'destroy']:                    
            return True                                                                             
        else:                                                                                       
            return False                                                                            

    def has_object_permission(self, request, view, obj):                                            
        if view.action == 'retrieve':                                                               
            return request.user.is_authenticated() and (obj == request.user or request.user.is_admin)    
        elif view.action in ['update', 'partial_update']:                                           
            return request.user.is_authenticated() and (obj == request.user or request.user.is_admin)    
        elif view.action == 'destroy':
            return request.user.is_authenticated() and request.user.Profile == 1                        
        else:
            return False

In Finish, I repeat what I try to do is read the group and individual persists of a user and on that basis allow them to read, create, update and delete records.

Thanks in advance

    
asked by Nestor Moran 24.05.2016 в 00:24
source

1 answer

2

Try this:

Example for group Estudiante :

from django.contrib.auth.models import  Group


class StudentPermission(BasePermission):
    group = Group.objects.get(name='Estudiante')    

    def has_object_permission(self, request, view, obj):
        """
        Returns True if the user belongs to the "Estudiante" group
        """
        if request.is_superuser:
            return True

        # toma todos los permisos grupales e individuales del usuario
        user_perms = request.user.get_all_permissions()
        group_perms = []
        group_values = self.group.permissions.prefetch_related('content_type')\
                                            .values('content_type__app_label', 'codename')
        # Se formatea los permisos del grupo 'Estudiantes'
        for p in group_perms: 
            group_perms.append('%s.%s' % (p['content_type__app_label'], p['codename']))
        # Se comparan los permisos, si los del grupo
        # estan contenidos en los del usuario devuelve True
        return set(group_perms).issubset(user_perms)
    
answered by 02.11.2016 / 08:06
source