mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-07-23 22:49:50 +03:00
This commit fixes #299 to add examples of a custom permission
This commit is contained in:
parent
f213299d7f
commit
c90303aa89
|
@ -110,6 +110,41 @@ To implement a custom permission, override `BasePermission` and implement the `.
|
||||||
|
|
||||||
The method should return `True` if the request should be granted access, and `False` otherwise.
|
The method should return `True` if the request should be granted access, and `False` otherwise.
|
||||||
|
|
||||||
|
Example of a custom permission checking authenticated user's first name for an attribute:
|
||||||
|
|
||||||
|
```
|
||||||
|
class IsNamedAfterBeatle(permissions.BasePermission):
|
||||||
|
"""
|
||||||
|
Custom permission allowing users with first name matching a Beatle
|
||||||
|
"""
|
||||||
|
def has_permission(self, request, view, obj=None):
|
||||||
|
if (request.user and
|
||||||
|
request.user.first_name in ("John", "Paul", "Ringo", "George",)):
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
return False
|
||||||
|
```
|
||||||
|
|
||||||
|
Example of a custom permission demonstrating object level permissions:
|
||||||
|
|
||||||
|
```
|
||||||
|
class IsOwnerOrReadOnly(permissions.BasePermission):
|
||||||
|
"""
|
||||||
|
Custom permission to only allow owners of an object to edit, otherwise
|
||||||
|
allow read only access
|
||||||
|
"""
|
||||||
|
|
||||||
|
def has_permission(self, request, view, obj=None):
|
||||||
|
if obj is None:
|
||||||
|
if (request.method in SAFE_METHODS or
|
||||||
|
request.user and
|
||||||
|
request.user.is_authenticated()):
|
||||||
|
return True
|
||||||
|
|
||||||
|
# Write permissions are only allowed to the owner
|
||||||
|
return obj.owner == request.user
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
[cite]: https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html
|
[cite]: https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html
|
||||||
[authentication]: authentication.md
|
[authentication]: authentication.md
|
||||||
|
|
Loading…
Reference in New Issue
Block a user