summaryrefslogtreecommitdiff
path: root/python-django-dry-rest-permissions.spec
blob: be0f62d75ae8997467cd1cdefe361d94f1e8ff87 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
%global _empty_manifest_terminate_build 0
Name:		python-django-dry-rest-permissions
Version:	1.2.0
Release:	1
Summary:	Rules based permissions for the Django Rest Framework
License:	BSD
URL:		https://github.com/FJNR-inc/dry-rest-permissions
Source0:	https://mirrors.nju.edu.cn/pypi/web/packages/9b/7c/d3d23b64830a5bc0717399b23e51f8290332c941d59e0ad3144ab5614a74/django-dry-rest-permissions-1.2.0.tar.gz
BuildArch:	noarch


%description
## News :loudspeaker:
This project is a fork from [@dbkaplan/dry-rest-permissions](https://github.com/dbkaplan/dry-rest-permissions), 
multiple peoples tried to contact the old maintener but the community had no news from him in the last two years 
and the package was completely out of date.
This fork it's officially supported by FJNR-inc since June 10th 2020.
In this context:
 - Feel free to create issues in order to evaluate new needs
 - Feel free to create PR in order to merge any individual enhancement you may have done on your own
 - Feel free to contact us if you want to contribute on this package and maintain it
## Overview
This framework is a perfect fit for apps that have many tables and relationships between them. It provides a framework that allows you to define, for each action or groups of actions, what users have permission for based on existing data in your database.
## What does DRY Rest Permissions provide?
1. A framework for defining global and object level permissions per action.
  1. Support for broadly defining permissions by grouping actions into safe and unsafe types.
  2. Support for defining only global (table level) permissions or only object (row level) permissions.
  3. Support for custom list and detail actions.
2. A serializer field that will return permissions for an object to your client app. This is DRY and works with your existing permission definitions.
3. A framework for limiting list requests based on permissions
  1. Support for custom list actions
## Why is DRY Rest Permissions different than other DRF permission packages?
Most other DRF permissions are based on django-guardian. Django-guardian is an explicit approach to permissions that requires data to be saved in tables that explicitly grants permissions for certain actions. For apps that have many ways for a user to be given permission to certain actions, this approach can be very hard to maintain.
For example: you may have an app which lets you create and modify projects if you are an admin of an association that owns the project. This means that a user's permission will be granted or revoked based on many possibilities including ownership of the project transferring to a different association, the user's admin status in the association changing and the user entering or leaving the association. This would need a lot of triggers that would key off of these actions and explicitly change permissions.
DRY Rest Permissions allows developers to easily describe what gives someone permission using the current data in an implicit way.
## Requirements
-  Python (3.4+)
-  Django (2.2, 3.0)
-  Django REST Framework (3.8, 3.9, 3.10, 3.11)
## Installation
Install using ``pip``…
    $ pip install django-dry-rest-permissions
## Setup
Add to INSTALLED_APPS
```python
INSTALLED_APPS = (
    'dry_rest_permissions',
)
```
## Global vs. Object Permissions
DRY Rest Permissions allows you to define both global and object level permissions.
Global permissions are always checked first and define the ability of a user to take an action on an entire model. For example you can define whether a user has the ability to update any projects from the database.
Object permissions are checked if global permissions pass and define whether a user has the ability to perform a specific action on a single object. These are also known as row level permissions.
Note: list and create actions are the only standard actions that are only global. There is no such object level permission call because they are whole table actions.
## Read/Write permissions vs. Specific Actions
DRY Rest Permissions allows you to define permissions for both the standard actions (``list``, ``retrieve``, ``update``, ``destroy`` and ``create``) and custom actions defined using ``@detail_route`` and ``@list_route``.
If you don't need to define permissions on a granular action level you can generally define read or write permissions for a model. "Read" permissions groups together list and retrieve, while "write" permissions groups together destroy, update and create. All custom actions that use ``GET`` methods are considered read actions and all other methods are considered write.
Specific action permissions take precedence over general read or write permissions. For example you can lock down write permissions by always returning ``False`` and open up just update permissions for certain users.
The ``partial_update`` action is also supported, but by default is grouped with the update permission.
## Add permissions to an API
Permissions can be added to ModelViewSet based APIs.
### Add permission class to a ModelViewSet
First you must add ``DRYPermissions`` to the viewset's ``permission_classes``
```python
from rest_framework import viewsets
from dry_rest_permissions.generics import DRYPermissions
class ProjectViewSet(viewsets.ModelViewSet):
    permission_classes = (DRYPermissions,)
    queryset = Project.objects.all()
    serializer_class = ProjectSerializer
```
You may also use ``DRYGlobalPermissions`` and ``DRYObjectPermissions``, which will only check global or object permissions.
If you want to define DRYPermissions for only some method types you can override the get_permissions function on the view like this:
```python
def get_permissions(self):
    if self.request.method == 'GET' or self.request.method == 'PUT':
        return [DRYPermissions(),]
    return []
```
### Define permission logic on the model
Permissions for DRY Rest permissions are defined on the model so that they can be accessed both from the view for checking and from the serializer for display purposes with the ``DRYPermissionsField``.
**Global permissions** are defined as either ``@staticmethod`` or ``@classmethod`` methods with the format ``has_<action/read/write>_permission``.
**Object permissions** are defined as methods with the format ``has_object_<action/read/write>_permission``.
The following example shows how you would allow all users to read and create projects, while locking down the ability for any user to perform any other write action. In the example, read global and object permissions return ``True``, which grants permission to those actions. Write, globally returns False, which locks down write actions. However, create is a specific action and therefore takes precedence over write and gives all users the ability to create projects.
```python
from django.db import models
from django.contrib.auth.models import User
class Project(models.Model):
    owner = models.ForeignKey('User')
    @staticmethod
    def has_read_permission(request):
        return True
    def has_object_read_permission(self, request):
        return True
    @staticmethod
    def has_write_permission(request):
        return False
    @staticmethod
    def has_create_permission(request):
        return True
``` 
  Now we will add to this example and allow project owners to update or destroy a project.
```python
class Project(models.Model):
    owner = models.ForeignKey('User')
    @staticmethod
    def has_write_permission(request):
        """
        We can remove the has_create_permission because this implicitly grants that permission.
        """
        return True
    def has_object_write_permission(self, request):
        return request.user == self.owner
```
  If we just wanted to grant update permission, but not destroy we could do this:
```python
class Project(models.Model):
    owner = models.ForeignKey('User')
    @staticmethod
    def has_write_permission(request):
        """
        We can remove the has_create_permission because this implicitly grants that permission.
        """
        return True
    def has_object_write_permission(self, request):
        return False
    def has_object_update_permission(self, request):
        return request.user == self.owner
```
### Custom action permissions
If a custom action, ``publish``, were created using ``@detail_route`` then permissions could be defined like so:
```python
class Project(models.Model):
    owner = models.ForeignKey('User')
    @staticmethod
    def has_publish_permission(request):
        return True
    def has_object_publish_permission(self, request):
        return request.user == self.owner
``` 
### Helpful decorators
Three decorators were defined for common permission checks
``@allow_staff_or_superuser`` - Allows any user that has staff or superuser status to have the permission.
``@authenticated_users`` - This permission will only be checked for authenticated users. Unauthenticated users will automatically be denied permission.
``@unauthenticated_users`` - This permission will only be checked for unauthenticated users. Authenticated users will automatically be denied permission.
Example:
```python
from dry_rest_permissions.generics import allow_staff_or_superuser, authenticated_users
class Project(models.Model):
    owner = models.ForeignKey('User')
    @staticmethod
    @authenticated_users
    def has_publish_permission(request):
        return True
    @allow_staff_or_superuser
    def has_object_publish_permission(self, request):
        return request.user == self.owner
```
## Returning Permissions to the Client App
You often need to know all of the possible permissions that are available to the current user from within your client 
app so that you can show certain create, edit and destroy options. Sometimes you need to know the permissions on the 
client app so that you can display messages to them. ``DRYPermissionsField`` & ``DRYGlobalPermissionsField`` allows 
you to return these permissions in a serializer without having to redefine your permission logic. DRY!
### DryPermissionsField
```python
from dry_rest_permissions.generics import DRYPermissionsField
class ProjectSerializer(serializers.ModelSerializer):
    permissions = DRYPermissionsField()
    class Meta:
        model = Project
        fields = ('id', 'owner', 'permissions')
```  
This response object will look like this:
```json
{
    "id": 1,
    "owner": 100,
    "permissions": {
        "read": true,
        "write": false,
        "create": true,
        "update": true
    }
}
```
#### Definition
``DRYPermissionsField(actions=None, additional_actions=None, global_only=False, object_only=False, **kwargs):``
``actions`` - This can be passed a list in order to limit the actions that are looked up.
``additional_actions`` - If you add custom actions then you can have DRYPermissionsField look them up by adding an array of the actions as so ``permissions = DRYPermissionsField(additional_actions=['publish'])``.
``global_only`` - If set to ``True`` then it will only look up global permissions.
``object_only`` - If set to ``True`` then it will only look up object permissions.
This field only returns what is defined on the model. By default it retrieves all default action types that are defined.
A serializer with this field MUST have the request accessible via the serializer's context. By default DRF passes the request to all serializers that is creates. However, if you create a serializer yourself you will have to add the request manually like this:
```python
serializer = TestSerializer(data=request.data, context={'request': request})
```
#### DryGlobalPermissionsField
```python
from dry_rest_permissions.generics import DRYGlobalPermissionsField
class ProjectSerializer(serializers.ModelSerializer):
    permissions = DRYGlobalPermissionsField()
    class Meta:
        model = Project
        fields = ('id', 'owner', 'permissions')
```  
This response object will look like this:
```json
{
    "id": 1,
    "owner": 100,
    "permissions": {
        "Project": {
            "read": true,
            "write": false
        },
        "MyOtherModel": {
            "create": true,
            "destroy": false
        }
    }
}
```
#### Definition
``DRYGlobalPermissionsField(actions=None, additional_actions=None, **kwargs):``
``actions`` - This can be passed a list in order to limit the actions that are looked up.
``additional_actions`` - If you add custom actions then you can have DRYPermissionsField look them up by adding an array of the actions as so ``permissions = DRYPermissionsField(additional_actions=['publish'])``.
This field only returns what is defined on the model. By default it retrieves all default action types that are defined.
A serializer with this field MUST have the request accessible via the serializer's context. By default DRF passes the request to all serializers that is creates. However, if you create a serializer yourself you will have to add the request manually like this:
```python
serializer = TestSerializer(data=request.data, context={'request': request})
```
## Filtering lists by action type
Many times it is not enough to say that a user does not have permission to view a list of items. Instead you want a user to only be able to view a partial list of items. In this case DRY Rest Permissions built on the filter concept using ``DRYPermissionFiltersBase`` to apply permissions to specific actions.
If you want to apply the same permissions to all list requests (the standard one and custom list actions) you could do the following:
```python
from django.db.models import Q
from rest_framework import viewsets
from dry_rest_permissions.generics import DRYPermissionFiltersBase
class ProjectFilterBackend(DRYPermissionFiltersBase):
    def filter_list_queryset(self, request, queryset, view):
        """
        Limits all list requests to only be seen by the owners or creators.
        """
        return queryset.filter(Q(owner=request.user) | Q(creator=request.user))
class ProjectViewSet(viewsets.ModelViewSet):
    serializer_class = ProjectSerializer
    queryset = Project.objects.all()
    filter_backends = (ProjectFilterBackend,)
```
If you had a custom list action called ``owned`` that returned just the owned projects you could do this:
```python
from django.db.models import Q
from rest_framework import viewsets
from dry_rest_permissions.generics import DRYPermissionFiltersBase
class ProjectFilterBackend(DRYPermissionFiltersBase):
    action_routing = True
    def filter_list_queryset(self, request, queryset, view):
        """
        Limits all list requests to only be seen by the owners or creators.
        """
        return queryset.filter(Q(owner=request.user) | Q(creator=request.user))
    def filter_owned_queryset(self, request, queryset, view):
        return queryset.filter(owner=request.user)
class ProjectViewSet(viewsets.ModelViewSet):
    serializer_class = ProjectSerializer
    queryset = Project.objects.all()
    filter_backends = (ProjectFilterBackend,)
```
# History
## 1.2.0
* Added type hints
* Added support for python 3.9
## 1.1.0
* Add DRYGlobalPermissionsField
## 1.0.0 (2020-06-10)
* First release on PyPI.
* Forked from https://github.com/dbkaplan/dry-rest-permissions on the same day
* Added support for Django 2.2
* Added support for Django 3.0
* Remove support for all Django version < 2.2
* Added support for Django-Rest-Framework 3.8
* Added support for Django-Rest-Framework 3.9
* Added support for Django-Rest-Framework 3.10
* Added support for Django-Rest-Framework 3.11
* Remove support for all Django-Rest-Framework version < 3.8
* Added support for Python 3.7
* Added support for Python 3.8
* Remove support for Python 2.7

%package -n python3-django-dry-rest-permissions
Summary:	Rules based permissions for the Django Rest Framework
Provides:	python-django-dry-rest-permissions
BuildRequires:	python3-devel
BuildRequires:	python3-setuptools
BuildRequires:	python3-pip
%description -n python3-django-dry-rest-permissions
## News :loudspeaker:
This project is a fork from [@dbkaplan/dry-rest-permissions](https://github.com/dbkaplan/dry-rest-permissions), 
multiple peoples tried to contact the old maintener but the community had no news from him in the last two years 
and the package was completely out of date.
This fork it's officially supported by FJNR-inc since June 10th 2020.
In this context:
 - Feel free to create issues in order to evaluate new needs
 - Feel free to create PR in order to merge any individual enhancement you may have done on your own
 - Feel free to contact us if you want to contribute on this package and maintain it
## Overview
This framework is a perfect fit for apps that have many tables and relationships between them. It provides a framework that allows you to define, for each action or groups of actions, what users have permission for based on existing data in your database.
## What does DRY Rest Permissions provide?
1. A framework for defining global and object level permissions per action.
  1. Support for broadly defining permissions by grouping actions into safe and unsafe types.
  2. Support for defining only global (table level) permissions or only object (row level) permissions.
  3. Support for custom list and detail actions.
2. A serializer field that will return permissions for an object to your client app. This is DRY and works with your existing permission definitions.
3. A framework for limiting list requests based on permissions
  1. Support for custom list actions
## Why is DRY Rest Permissions different than other DRF permission packages?
Most other DRF permissions are based on django-guardian. Django-guardian is an explicit approach to permissions that requires data to be saved in tables that explicitly grants permissions for certain actions. For apps that have many ways for a user to be given permission to certain actions, this approach can be very hard to maintain.
For example: you may have an app which lets you create and modify projects if you are an admin of an association that owns the project. This means that a user's permission will be granted or revoked based on many possibilities including ownership of the project transferring to a different association, the user's admin status in the association changing and the user entering or leaving the association. This would need a lot of triggers that would key off of these actions and explicitly change permissions.
DRY Rest Permissions allows developers to easily describe what gives someone permission using the current data in an implicit way.
## Requirements
-  Python (3.4+)
-  Django (2.2, 3.0)
-  Django REST Framework (3.8, 3.9, 3.10, 3.11)
## Installation
Install using ``pip``…
    $ pip install django-dry-rest-permissions
## Setup
Add to INSTALLED_APPS
```python
INSTALLED_APPS = (
    'dry_rest_permissions',
)
```
## Global vs. Object Permissions
DRY Rest Permissions allows you to define both global and object level permissions.
Global permissions are always checked first and define the ability of a user to take an action on an entire model. For example you can define whether a user has the ability to update any projects from the database.
Object permissions are checked if global permissions pass and define whether a user has the ability to perform a specific action on a single object. These are also known as row level permissions.
Note: list and create actions are the only standard actions that are only global. There is no such object level permission call because they are whole table actions.
## Read/Write permissions vs. Specific Actions
DRY Rest Permissions allows you to define permissions for both the standard actions (``list``, ``retrieve``, ``update``, ``destroy`` and ``create``) and custom actions defined using ``@detail_route`` and ``@list_route``.
If you don't need to define permissions on a granular action level you can generally define read or write permissions for a model. "Read" permissions groups together list and retrieve, while "write" permissions groups together destroy, update and create. All custom actions that use ``GET`` methods are considered read actions and all other methods are considered write.
Specific action permissions take precedence over general read or write permissions. For example you can lock down write permissions by always returning ``False`` and open up just update permissions for certain users.
The ``partial_update`` action is also supported, but by default is grouped with the update permission.
## Add permissions to an API
Permissions can be added to ModelViewSet based APIs.
### Add permission class to a ModelViewSet
First you must add ``DRYPermissions`` to the viewset's ``permission_classes``
```python
from rest_framework import viewsets
from dry_rest_permissions.generics import DRYPermissions
class ProjectViewSet(viewsets.ModelViewSet):
    permission_classes = (DRYPermissions,)
    queryset = Project.objects.all()
    serializer_class = ProjectSerializer
```
You may also use ``DRYGlobalPermissions`` and ``DRYObjectPermissions``, which will only check global or object permissions.
If you want to define DRYPermissions for only some method types you can override the get_permissions function on the view like this:
```python
def get_permissions(self):
    if self.request.method == 'GET' or self.request.method == 'PUT':
        return [DRYPermissions(),]
    return []
```
### Define permission logic on the model
Permissions for DRY Rest permissions are defined on the model so that they can be accessed both from the view for checking and from the serializer for display purposes with the ``DRYPermissionsField``.
**Global permissions** are defined as either ``@staticmethod`` or ``@classmethod`` methods with the format ``has_<action/read/write>_permission``.
**Object permissions** are defined as methods with the format ``has_object_<action/read/write>_permission``.
The following example shows how you would allow all users to read and create projects, while locking down the ability for any user to perform any other write action. In the example, read global and object permissions return ``True``, which grants permission to those actions. Write, globally returns False, which locks down write actions. However, create is a specific action and therefore takes precedence over write and gives all users the ability to create projects.
```python
from django.db import models
from django.contrib.auth.models import User
class Project(models.Model):
    owner = models.ForeignKey('User')
    @staticmethod
    def has_read_permission(request):
        return True
    def has_object_read_permission(self, request):
        return True
    @staticmethod
    def has_write_permission(request):
        return False
    @staticmethod
    def has_create_permission(request):
        return True
``` 
  Now we will add to this example and allow project owners to update or destroy a project.
```python
class Project(models.Model):
    owner = models.ForeignKey('User')
    @staticmethod
    def has_write_permission(request):
        """
        We can remove the has_create_permission because this implicitly grants that permission.
        """
        return True
    def has_object_write_permission(self, request):
        return request.user == self.owner
```
  If we just wanted to grant update permission, but not destroy we could do this:
```python
class Project(models.Model):
    owner = models.ForeignKey('User')
    @staticmethod
    def has_write_permission(request):
        """
        We can remove the has_create_permission because this implicitly grants that permission.
        """
        return True
    def has_object_write_permission(self, request):
        return False
    def has_object_update_permission(self, request):
        return request.user == self.owner
```
### Custom action permissions
If a custom action, ``publish``, were created using ``@detail_route`` then permissions could be defined like so:
```python
class Project(models.Model):
    owner = models.ForeignKey('User')
    @staticmethod
    def has_publish_permission(request):
        return True
    def has_object_publish_permission(self, request):
        return request.user == self.owner
``` 
### Helpful decorators
Three decorators were defined for common permission checks
``@allow_staff_or_superuser`` - Allows any user that has staff or superuser status to have the permission.
``@authenticated_users`` - This permission will only be checked for authenticated users. Unauthenticated users will automatically be denied permission.
``@unauthenticated_users`` - This permission will only be checked for unauthenticated users. Authenticated users will automatically be denied permission.
Example:
```python
from dry_rest_permissions.generics import allow_staff_or_superuser, authenticated_users
class Project(models.Model):
    owner = models.ForeignKey('User')
    @staticmethod
    @authenticated_users
    def has_publish_permission(request):
        return True
    @allow_staff_or_superuser
    def has_object_publish_permission(self, request):
        return request.user == self.owner
```
## Returning Permissions to the Client App
You often need to know all of the possible permissions that are available to the current user from within your client 
app so that you can show certain create, edit and destroy options. Sometimes you need to know the permissions on the 
client app so that you can display messages to them. ``DRYPermissionsField`` & ``DRYGlobalPermissionsField`` allows 
you to return these permissions in a serializer without having to redefine your permission logic. DRY!
### DryPermissionsField
```python
from dry_rest_permissions.generics import DRYPermissionsField
class ProjectSerializer(serializers.ModelSerializer):
    permissions = DRYPermissionsField()
    class Meta:
        model = Project
        fields = ('id', 'owner', 'permissions')
```  
This response object will look like this:
```json
{
    "id": 1,
    "owner": 100,
    "permissions": {
        "read": true,
        "write": false,
        "create": true,
        "update": true
    }
}
```
#### Definition
``DRYPermissionsField(actions=None, additional_actions=None, global_only=False, object_only=False, **kwargs):``
``actions`` - This can be passed a list in order to limit the actions that are looked up.
``additional_actions`` - If you add custom actions then you can have DRYPermissionsField look them up by adding an array of the actions as so ``permissions = DRYPermissionsField(additional_actions=['publish'])``.
``global_only`` - If set to ``True`` then it will only look up global permissions.
``object_only`` - If set to ``True`` then it will only look up object permissions.
This field only returns what is defined on the model. By default it retrieves all default action types that are defined.
A serializer with this field MUST have the request accessible via the serializer's context. By default DRF passes the request to all serializers that is creates. However, if you create a serializer yourself you will have to add the request manually like this:
```python
serializer = TestSerializer(data=request.data, context={'request': request})
```
#### DryGlobalPermissionsField
```python
from dry_rest_permissions.generics import DRYGlobalPermissionsField
class ProjectSerializer(serializers.ModelSerializer):
    permissions = DRYGlobalPermissionsField()
    class Meta:
        model = Project
        fields = ('id', 'owner', 'permissions')
```  
This response object will look like this:
```json
{
    "id": 1,
    "owner": 100,
    "permissions": {
        "Project": {
            "read": true,
            "write": false
        },
        "MyOtherModel": {
            "create": true,
            "destroy": false
        }
    }
}
```
#### Definition
``DRYGlobalPermissionsField(actions=None, additional_actions=None, **kwargs):``
``actions`` - This can be passed a list in order to limit the actions that are looked up.
``additional_actions`` - If you add custom actions then you can have DRYPermissionsField look them up by adding an array of the actions as so ``permissions = DRYPermissionsField(additional_actions=['publish'])``.
This field only returns what is defined on the model. By default it retrieves all default action types that are defined.
A serializer with this field MUST have the request accessible via the serializer's context. By default DRF passes the request to all serializers that is creates. However, if you create a serializer yourself you will have to add the request manually like this:
```python
serializer = TestSerializer(data=request.data, context={'request': request})
```
## Filtering lists by action type
Many times it is not enough to say that a user does not have permission to view a list of items. Instead you want a user to only be able to view a partial list of items. In this case DRY Rest Permissions built on the filter concept using ``DRYPermissionFiltersBase`` to apply permissions to specific actions.
If you want to apply the same permissions to all list requests (the standard one and custom list actions) you could do the following:
```python
from django.db.models import Q
from rest_framework import viewsets
from dry_rest_permissions.generics import DRYPermissionFiltersBase
class ProjectFilterBackend(DRYPermissionFiltersBase):
    def filter_list_queryset(self, request, queryset, view):
        """
        Limits all list requests to only be seen by the owners or creators.
        """
        return queryset.filter(Q(owner=request.user) | Q(creator=request.user))
class ProjectViewSet(viewsets.ModelViewSet):
    serializer_class = ProjectSerializer
    queryset = Project.objects.all()
    filter_backends = (ProjectFilterBackend,)
```
If you had a custom list action called ``owned`` that returned just the owned projects you could do this:
```python
from django.db.models import Q
from rest_framework import viewsets
from dry_rest_permissions.generics import DRYPermissionFiltersBase
class ProjectFilterBackend(DRYPermissionFiltersBase):
    action_routing = True
    def filter_list_queryset(self, request, queryset, view):
        """
        Limits all list requests to only be seen by the owners or creators.
        """
        return queryset.filter(Q(owner=request.user) | Q(creator=request.user))
    def filter_owned_queryset(self, request, queryset, view):
        return queryset.filter(owner=request.user)
class ProjectViewSet(viewsets.ModelViewSet):
    serializer_class = ProjectSerializer
    queryset = Project.objects.all()
    filter_backends = (ProjectFilterBackend,)
```
# History
## 1.2.0
* Added type hints
* Added support for python 3.9
## 1.1.0
* Add DRYGlobalPermissionsField
## 1.0.0 (2020-06-10)
* First release on PyPI.
* Forked from https://github.com/dbkaplan/dry-rest-permissions on the same day
* Added support for Django 2.2
* Added support for Django 3.0
* Remove support for all Django version < 2.2
* Added support for Django-Rest-Framework 3.8
* Added support for Django-Rest-Framework 3.9
* Added support for Django-Rest-Framework 3.10
* Added support for Django-Rest-Framework 3.11
* Remove support for all Django-Rest-Framework version < 3.8
* Added support for Python 3.7
* Added support for Python 3.8
* Remove support for Python 2.7

%package help
Summary:	Development documents and examples for django-dry-rest-permissions
Provides:	python3-django-dry-rest-permissions-doc
%description help
## News :loudspeaker:
This project is a fork from [@dbkaplan/dry-rest-permissions](https://github.com/dbkaplan/dry-rest-permissions), 
multiple peoples tried to contact the old maintener but the community had no news from him in the last two years 
and the package was completely out of date.
This fork it's officially supported by FJNR-inc since June 10th 2020.
In this context:
 - Feel free to create issues in order to evaluate new needs
 - Feel free to create PR in order to merge any individual enhancement you may have done on your own
 - Feel free to contact us if you want to contribute on this package and maintain it
## Overview
This framework is a perfect fit for apps that have many tables and relationships between them. It provides a framework that allows you to define, for each action or groups of actions, what users have permission for based on existing data in your database.
## What does DRY Rest Permissions provide?
1. A framework for defining global and object level permissions per action.
  1. Support for broadly defining permissions by grouping actions into safe and unsafe types.
  2. Support for defining only global (table level) permissions or only object (row level) permissions.
  3. Support for custom list and detail actions.
2. A serializer field that will return permissions for an object to your client app. This is DRY and works with your existing permission definitions.
3. A framework for limiting list requests based on permissions
  1. Support for custom list actions
## Why is DRY Rest Permissions different than other DRF permission packages?
Most other DRF permissions are based on django-guardian. Django-guardian is an explicit approach to permissions that requires data to be saved in tables that explicitly grants permissions for certain actions. For apps that have many ways for a user to be given permission to certain actions, this approach can be very hard to maintain.
For example: you may have an app which lets you create and modify projects if you are an admin of an association that owns the project. This means that a user's permission will be granted or revoked based on many possibilities including ownership of the project transferring to a different association, the user's admin status in the association changing and the user entering or leaving the association. This would need a lot of triggers that would key off of these actions and explicitly change permissions.
DRY Rest Permissions allows developers to easily describe what gives someone permission using the current data in an implicit way.
## Requirements
-  Python (3.4+)
-  Django (2.2, 3.0)
-  Django REST Framework (3.8, 3.9, 3.10, 3.11)
## Installation
Install using ``pip``…
    $ pip install django-dry-rest-permissions
## Setup
Add to INSTALLED_APPS
```python
INSTALLED_APPS = (
    'dry_rest_permissions',
)
```
## Global vs. Object Permissions
DRY Rest Permissions allows you to define both global and object level permissions.
Global permissions are always checked first and define the ability of a user to take an action on an entire model. For example you can define whether a user has the ability to update any projects from the database.
Object permissions are checked if global permissions pass and define whether a user has the ability to perform a specific action on a single object. These are also known as row level permissions.
Note: list and create actions are the only standard actions that are only global. There is no such object level permission call because they are whole table actions.
## Read/Write permissions vs. Specific Actions
DRY Rest Permissions allows you to define permissions for both the standard actions (``list``, ``retrieve``, ``update``, ``destroy`` and ``create``) and custom actions defined using ``@detail_route`` and ``@list_route``.
If you don't need to define permissions on a granular action level you can generally define read or write permissions for a model. "Read" permissions groups together list and retrieve, while "write" permissions groups together destroy, update and create. All custom actions that use ``GET`` methods are considered read actions and all other methods are considered write.
Specific action permissions take precedence over general read or write permissions. For example you can lock down write permissions by always returning ``False`` and open up just update permissions for certain users.
The ``partial_update`` action is also supported, but by default is grouped with the update permission.
## Add permissions to an API
Permissions can be added to ModelViewSet based APIs.
### Add permission class to a ModelViewSet
First you must add ``DRYPermissions`` to the viewset's ``permission_classes``
```python
from rest_framework import viewsets
from dry_rest_permissions.generics import DRYPermissions
class ProjectViewSet(viewsets.ModelViewSet):
    permission_classes = (DRYPermissions,)
    queryset = Project.objects.all()
    serializer_class = ProjectSerializer
```
You may also use ``DRYGlobalPermissions`` and ``DRYObjectPermissions``, which will only check global or object permissions.
If you want to define DRYPermissions for only some method types you can override the get_permissions function on the view like this:
```python
def get_permissions(self):
    if self.request.method == 'GET' or self.request.method == 'PUT':
        return [DRYPermissions(),]
    return []
```
### Define permission logic on the model
Permissions for DRY Rest permissions are defined on the model so that they can be accessed both from the view for checking and from the serializer for display purposes with the ``DRYPermissionsField``.
**Global permissions** are defined as either ``@staticmethod`` or ``@classmethod`` methods with the format ``has_<action/read/write>_permission``.
**Object permissions** are defined as methods with the format ``has_object_<action/read/write>_permission``.
The following example shows how you would allow all users to read and create projects, while locking down the ability for any user to perform any other write action. In the example, read global and object permissions return ``True``, which grants permission to those actions. Write, globally returns False, which locks down write actions. However, create is a specific action and therefore takes precedence over write and gives all users the ability to create projects.
```python
from django.db import models
from django.contrib.auth.models import User
class Project(models.Model):
    owner = models.ForeignKey('User')
    @staticmethod
    def has_read_permission(request):
        return True
    def has_object_read_permission(self, request):
        return True
    @staticmethod
    def has_write_permission(request):
        return False
    @staticmethod
    def has_create_permission(request):
        return True
``` 
  Now we will add to this example and allow project owners to update or destroy a project.
```python
class Project(models.Model):
    owner = models.ForeignKey('User')
    @staticmethod
    def has_write_permission(request):
        """
        We can remove the has_create_permission because this implicitly grants that permission.
        """
        return True
    def has_object_write_permission(self, request):
        return request.user == self.owner
```
  If we just wanted to grant update permission, but not destroy we could do this:
```python
class Project(models.Model):
    owner = models.ForeignKey('User')
    @staticmethod
    def has_write_permission(request):
        """
        We can remove the has_create_permission because this implicitly grants that permission.
        """
        return True
    def has_object_write_permission(self, request):
        return False
    def has_object_update_permission(self, request):
        return request.user == self.owner
```
### Custom action permissions
If a custom action, ``publish``, were created using ``@detail_route`` then permissions could be defined like so:
```python
class Project(models.Model):
    owner = models.ForeignKey('User')
    @staticmethod
    def has_publish_permission(request):
        return True
    def has_object_publish_permission(self, request):
        return request.user == self.owner
``` 
### Helpful decorators
Three decorators were defined for common permission checks
``@allow_staff_or_superuser`` - Allows any user that has staff or superuser status to have the permission.
``@authenticated_users`` - This permission will only be checked for authenticated users. Unauthenticated users will automatically be denied permission.
``@unauthenticated_users`` - This permission will only be checked for unauthenticated users. Authenticated users will automatically be denied permission.
Example:
```python
from dry_rest_permissions.generics import allow_staff_or_superuser, authenticated_users
class Project(models.Model):
    owner = models.ForeignKey('User')
    @staticmethod
    @authenticated_users
    def has_publish_permission(request):
        return True
    @allow_staff_or_superuser
    def has_object_publish_permission(self, request):
        return request.user == self.owner
```
## Returning Permissions to the Client App
You often need to know all of the possible permissions that are available to the current user from within your client 
app so that you can show certain create, edit and destroy options. Sometimes you need to know the permissions on the 
client app so that you can display messages to them. ``DRYPermissionsField`` & ``DRYGlobalPermissionsField`` allows 
you to return these permissions in a serializer without having to redefine your permission logic. DRY!
### DryPermissionsField
```python
from dry_rest_permissions.generics import DRYPermissionsField
class ProjectSerializer(serializers.ModelSerializer):
    permissions = DRYPermissionsField()
    class Meta:
        model = Project
        fields = ('id', 'owner', 'permissions')
```  
This response object will look like this:
```json
{
    "id": 1,
    "owner": 100,
    "permissions": {
        "read": true,
        "write": false,
        "create": true,
        "update": true
    }
}
```
#### Definition
``DRYPermissionsField(actions=None, additional_actions=None, global_only=False, object_only=False, **kwargs):``
``actions`` - This can be passed a list in order to limit the actions that are looked up.
``additional_actions`` - If you add custom actions then you can have DRYPermissionsField look them up by adding an array of the actions as so ``permissions = DRYPermissionsField(additional_actions=['publish'])``.
``global_only`` - If set to ``True`` then it will only look up global permissions.
``object_only`` - If set to ``True`` then it will only look up object permissions.
This field only returns what is defined on the model. By default it retrieves all default action types that are defined.
A serializer with this field MUST have the request accessible via the serializer's context. By default DRF passes the request to all serializers that is creates. However, if you create a serializer yourself you will have to add the request manually like this:
```python
serializer = TestSerializer(data=request.data, context={'request': request})
```
#### DryGlobalPermissionsField
```python
from dry_rest_permissions.generics import DRYGlobalPermissionsField
class ProjectSerializer(serializers.ModelSerializer):
    permissions = DRYGlobalPermissionsField()
    class Meta:
        model = Project
        fields = ('id', 'owner', 'permissions')
```  
This response object will look like this:
```json
{
    "id": 1,
    "owner": 100,
    "permissions": {
        "Project": {
            "read": true,
            "write": false
        },
        "MyOtherModel": {
            "create": true,
            "destroy": false
        }
    }
}
```
#### Definition
``DRYGlobalPermissionsField(actions=None, additional_actions=None, **kwargs):``
``actions`` - This can be passed a list in order to limit the actions that are looked up.
``additional_actions`` - If you add custom actions then you can have DRYPermissionsField look them up by adding an array of the actions as so ``permissions = DRYPermissionsField(additional_actions=['publish'])``.
This field only returns what is defined on the model. By default it retrieves all default action types that are defined.
A serializer with this field MUST have the request accessible via the serializer's context. By default DRF passes the request to all serializers that is creates. However, if you create a serializer yourself you will have to add the request manually like this:
```python
serializer = TestSerializer(data=request.data, context={'request': request})
```
## Filtering lists by action type
Many times it is not enough to say that a user does not have permission to view a list of items. Instead you want a user to only be able to view a partial list of items. In this case DRY Rest Permissions built on the filter concept using ``DRYPermissionFiltersBase`` to apply permissions to specific actions.
If you want to apply the same permissions to all list requests (the standard one and custom list actions) you could do the following:
```python
from django.db.models import Q
from rest_framework import viewsets
from dry_rest_permissions.generics import DRYPermissionFiltersBase
class ProjectFilterBackend(DRYPermissionFiltersBase):
    def filter_list_queryset(self, request, queryset, view):
        """
        Limits all list requests to only be seen by the owners or creators.
        """
        return queryset.filter(Q(owner=request.user) | Q(creator=request.user))
class ProjectViewSet(viewsets.ModelViewSet):
    serializer_class = ProjectSerializer
    queryset = Project.objects.all()
    filter_backends = (ProjectFilterBackend,)
```
If you had a custom list action called ``owned`` that returned just the owned projects you could do this:
```python
from django.db.models import Q
from rest_framework import viewsets
from dry_rest_permissions.generics import DRYPermissionFiltersBase
class ProjectFilterBackend(DRYPermissionFiltersBase):
    action_routing = True
    def filter_list_queryset(self, request, queryset, view):
        """
        Limits all list requests to only be seen by the owners or creators.
        """
        return queryset.filter(Q(owner=request.user) | Q(creator=request.user))
    def filter_owned_queryset(self, request, queryset, view):
        return queryset.filter(owner=request.user)
class ProjectViewSet(viewsets.ModelViewSet):
    serializer_class = ProjectSerializer
    queryset = Project.objects.all()
    filter_backends = (ProjectFilterBackend,)
```
# History
## 1.2.0
* Added type hints
* Added support for python 3.9
## 1.1.0
* Add DRYGlobalPermissionsField
## 1.0.0 (2020-06-10)
* First release on PyPI.
* Forked from https://github.com/dbkaplan/dry-rest-permissions on the same day
* Added support for Django 2.2
* Added support for Django 3.0
* Remove support for all Django version < 2.2
* Added support for Django-Rest-Framework 3.8
* Added support for Django-Rest-Framework 3.9
* Added support for Django-Rest-Framework 3.10
* Added support for Django-Rest-Framework 3.11
* Remove support for all Django-Rest-Framework version < 3.8
* Added support for Python 3.7
* Added support for Python 3.8
* Remove support for Python 2.7

%prep
%autosetup -n django-dry-rest-permissions-1.2.0

%build
%py3_build

%install
%py3_install
install -d -m755 %{buildroot}/%{_pkgdocdir}
if [ -d doc ]; then cp -arf doc %{buildroot}/%{_pkgdocdir}; fi
if [ -d docs ]; then cp -arf docs %{buildroot}/%{_pkgdocdir}; fi
if [ -d example ]; then cp -arf example %{buildroot}/%{_pkgdocdir}; fi
if [ -d examples ]; then cp -arf examples %{buildroot}/%{_pkgdocdir}; fi
pushd %{buildroot}
if [ -d usr/lib ]; then
	find usr/lib -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/lib64 ]; then
	find usr/lib64 -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/bin ]; then
	find usr/bin -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/sbin ]; then
	find usr/sbin -type f -printf "/%h/%f\n" >> filelist.lst
fi
touch doclist.lst
if [ -d usr/share/man ]; then
	find usr/share/man -type f -printf "/%h/%f.gz\n" >> doclist.lst
fi
popd
mv %{buildroot}/filelist.lst .
mv %{buildroot}/doclist.lst .

%files -n python3-django-dry-rest-permissions -f filelist.lst
%dir %{python3_sitelib}/*

%files help -f doclist.lst
%{_docdir}/*

%changelog
* Fri May 05 2023 Python_Bot <Python_Bot@openeuler.org> - 1.2.0-1
- Package Spec generated