| 1 |
""" |
| 2 |
Provides a set of pluggable permission policies. |
| 3 |
""" |
| 4 |
from django.http import Http404 |
| 5 |
|
| 6 |
from rest_framework import exceptions |
| 7 |
|
| 8 |
SAFE_METHODS = ('GET', 'HEAD', 'OPTIONS') |
| 9 |
|
| 10 |
|
| 11 |
class OperationHolderMixin: |
| 12 |
def __and__(self, other): |
| 13 |
return OperandHolder(AND, self, other) |
| 14 |
|
| 15 |
def __or__(self, other): |
| 16 |
return OperandHolder(OR, self, other) |
| 17 |
|
| 18 |
def __rand__(self, other): |
| 19 |
return OperandHolder(AND, other, self) |
| 20 |
|
| 21 |
def __ror__(self, other): |
| 22 |
return OperandHolder(OR, other, self) |
| 23 |
|
| 24 |
def __invert__(self): |
| 25 |
return SingleOperandHolder(NOT, self) |
| 26 |
|
| 27 |
|
| 28 |
class SingleOperandHolder(OperationHolderMixin): |
| 29 |
def __init__(self, operator_class, op1_class): |
| 30 |
self.operator_class = operator_class |
| 31 |
self.op1_class = op1_class |
| 32 |
|
| 33 |
def __call__(self, *args, **kwargs): |
| 34 |
op1 = self.op1_class(*args, **kwargs) |
| 35 |
return self.operator_class(op1) |
| 36 |
|
| 37 |
|
| 38 |
class OperandHolder(OperationHolderMixin): |
| 39 |
def __init__(self, operator_class, op1_class, op2_class): |
| 40 |
self.operator_class = operator_class |
| 41 |
self.op1_class = op1_class |
| 42 |
self.op2_class = op2_class |
| 43 |
|
| 44 |
def __call__(self, *args, **kwargs): |
| 45 |
op1 = self.op1_class(*args, **kwargs) |
| 46 |
op2 = self.op2_class(*args, **kwargs) |
| 47 |
return self.operator_class(op1, op2) |
| 48 |
|
| 49 |
def __eq__(self, other): |
| 50 |
return ( |
| 51 |
isinstance(other, OperandHolder) and |
| 52 |
self.operator_class == other.operator_class and |
| 53 |
self.op1_class == other.op1_class and |
| 54 |
self.op2_class == other.op2_class |
| 55 |
) |
| 56 |
|
| 57 |
def __hash__(self): |
| 58 |
return hash((self.operator_class, self.op1_class, self.op2_class)) |
| 59 |
|
| 60 |
|
| 61 |
class AND: |
| 62 |
def __init__(self, op1, op2): |
| 63 |
self.op1 = op1 |
| 64 |
self.op2 = op2 |
| 65 |
|
| 66 |
def has_permission(self, request, view): |
| 67 |
return ( |
| 68 |
self.op1.has_permission(request, view) and |
| 69 |
self.op2.has_permission(request, view) |
| 70 |
) |
| 71 |
|
| 72 |
def has_object_permission(self, request, view, obj): |
| 73 |
return ( |
| 74 |
self.op1.has_object_permission(request, view, obj) and |
| 75 |
self.op2.has_object_permission(request, view, obj) |
| 76 |
) |
| 77 |
|
| 78 |
|
| 79 |
class OR: |
| 80 |
def __init__(self, op1, op2): |
| 81 |
self.op1 = op1 |
| 82 |
self.op2 = op2 |
| 83 |
|
| 84 |
def has_permission(self, request, view): |
| 85 |
return ( |
| 86 |
self.op1.has_permission(request, view) or |
| 87 |
self.op2.has_permission(request, view) |
| 88 |
) |
| 89 |
|
| 90 |
def has_object_permission(self, request, view, obj): |
| 91 |
return ( |
| 92 |
self.op1.has_permission(request, view) |
| 93 |
and self.op1.has_object_permission(request, view, obj) |
| 94 |
) or ( |
| 95 |
self.op2.has_permission(request, view) |
| 96 |
and self.op2.has_object_permission(request, view, obj) |
| 97 |
) |
| 98 |
|
| 99 |
|
| 100 |
class NOT: |
| 101 |
def __init__(self, op1): |
| 102 |
self.op1 = op1 |
| 103 |
|
| 104 |
def has_permission(self, request, view): |
| 105 |
return not self.op1.has_permission(request, view) |
| 106 |
|
| 107 |
def has_object_permission(self, request, view, obj): |
| 108 |
return not self.op1.has_object_permission(request, view, obj) |
| 109 |
|
| 110 |
|
| 111 |
class BasePermissionMetaclass(OperationHolderMixin, type): |
| 112 |
pass |
| 113 |
|
| 114 |
|
| 115 |
class BasePermission(metaclass=BasePermissionMetaclass): |
| 116 |
""" |
| 117 |
A base class from which all permission classes should inherit. |
| 118 |
""" |
| 119 |
|
| 120 |
def has_permission(self, request, view): |
| 121 |
""" |
| 122 |
Return `True` if permission is granted, `False` otherwise. |
| 123 |
""" |
| 124 |
return True |
| 125 |
|
| 126 |
def has_object_permission(self, request, view, obj): |
| 127 |
""" |
| 128 |
Return `True` if permission is granted, `False` otherwise. |
| 129 |
""" |
| 130 |
return True |
| 131 |
|
| 132 |
|
| 133 |
class AllowAny(BasePermission): |
| 134 |
""" |
| 135 |
Allow any access. |
| 136 |
This isn't strictly required, since you could use an empty |
| 137 |
permission_classes list, but it's useful because it makes the intention |
| 138 |
more explicit. |
| 139 |
""" |
| 140 |
|
| 141 |
def has_permission(self, request, view): |
| 142 |
return True |
| 143 |
|
| 144 |
|
| 145 |
class IsAuthenticated(BasePermission): |
| 146 |
""" |
| 147 |
Allows access only to authenticated users. |
| 148 |
""" |
| 149 |
|
| 150 |
def has_permission(self, request, view): |
| 151 |
return bool(request.user and request.user.is_authenticated) |
| 152 |
|
| 153 |
|
| 154 |
class IsAdminUser(BasePermission): |
| 155 |
""" |
| 156 |
Allows access only to admin users. |
| 157 |
""" |
| 158 |
|
| 159 |
def has_permission(self, request, view): |
| 160 |
return bool(request.user and request.user.is_staff) |
| 161 |
|
| 162 |
|
| 163 |
class IsAuthenticatedOrReadOnly(BasePermission): |
| 164 |
""" |
| 165 |
The request is authenticated as a user, or is a read-only request. |
| 166 |
""" |
| 167 |
|
| 168 |
def has_permission(self, request, view): |
| 169 |
return bool( |
| 170 |
request.method in SAFE_METHODS or |
| 171 |
request.user and |
| 172 |
request.user.is_authenticated |
| 173 |
) |
| 174 |
|
| 175 |
|
| 176 |
class DjangoModelPermissions(BasePermission): |
| 177 |
""" |
| 178 |
The request is authenticated using `django.contrib.auth` permissions. |
| 179 |
See: https://docs.djangoproject.com/en/dev/topics/auth/#permissions |
| 180 |
|
| 181 |
It ensures that the user is authenticated, and has the appropriate |
| 182 |
`add`/`change`/`delete` permissions on the model. |
| 183 |
|
| 184 |
This permission can only be applied against view classes that |
| 185 |
provide a `.queryset` attribute. |
| 186 |
""" |
| 187 |
|
| 188 |
# Map methods into required permission codes. |
| 189 |
# Override this if you need to also provide 'view' permissions, |
| 190 |
# or if you want to provide custom permission codes. |
| 191 |
perms_map = { |
| 192 |
'GET': [], |
| 193 |
'OPTIONS': [], |
| 194 |
'HEAD': [], |
| 195 |
'POST': ['%(app_label)s.add_%(model_name)s'], |
| 196 |
'PUT': ['%(app_label)s.change_%(model_name)s'], |
| 197 |
'PATCH': ['%(app_label)s.change_%(model_name)s'], |
| 198 |
'DELETE': ['%(app_label)s.delete_%(model_name)s'], |
| 199 |
} |
| 200 |
|
| 201 |
authenticated_users_only = True |
| 202 |
|
| 203 |
def get_required_permissions(self, method, model_cls): |
| 204 |
""" |
| 205 |
Given a model and an HTTP method, return the list of permission |
| 206 |
codes that the user is required to have. |
| 207 |
""" |
| 208 |
kwargs = { |
| 209 |
'app_label': model_cls._meta.app_label, |
| 210 |
'model_name': model_cls._meta.model_name |
| 211 |
} |
| 212 |
|
| 213 |
if method not in self.perms_map: |
| 214 |
raise exceptions.MethodNotAllowed(method) |
| 215 |
|
| 216 |
return [perm % kwargs for perm in self.perms_map[method]] |
| 217 |
|
| 218 |
def _queryset(self, view): |
| 219 |
assert hasattr(view, 'get_queryset') \ |
| 220 |
or getattr(view, 'queryset', None) is not None, ( |
| 221 |
'Cannot apply {} on a view that does not set ' |
| 222 |
'`.queryset` or have a `.get_queryset()` method.' |
| 223 |
).format(self.__class__.__name__) |
| 224 |
|
| 225 |
if hasattr(view, 'get_queryset'): |
| 226 |
queryset = view.get_queryset() |
| 227 |
assert queryset is not None, ( |
| 228 |
f'{view.__class__.__name__}.get_queryset() returned None' |
| 229 |
) |
| 230 |
return queryset |
| 231 |
return view.queryset |
| 232 |
|
| 233 |
def has_permission(self, request, view): |
| 234 |
if not request.user or ( |
| 235 |
not request.user.is_authenticated and self.authenticated_users_only): |
| 236 |
return False |
| 237 |
|
| 238 |
# Workaround to ensure DjangoModelPermissions are not applied |
| 239 |
# to the root view when using DefaultRouter. |
| 240 |
if getattr(view, '_ignore_model_permissions', False): |
| 241 |
return True |
| 242 |
|
| 243 |
queryset = self._queryset(view) |
| 244 |
perms = self.get_required_permissions(request.method, queryset.model) |
| 245 |
|
| 246 |
return request.user.has_perms(perms) |
| 247 |
|
| 248 |
|
| 249 |
class DjangoModelPermissionsOrAnonReadOnly(DjangoModelPermissions): |
| 250 |
""" |
| 251 |
Similar to DjangoModelPermissions, except that anonymous users are |
| 252 |
allowed read-only access. |
| 253 |
""" |
| 254 |
authenticated_users_only = False |
| 255 |
|
| 256 |
|
| 257 |
class DjangoObjectPermissions(DjangoModelPermissions): |
| 258 |
""" |
| 259 |
The request is authenticated using Django's object-level permissions. |
| 260 |
It requires an object-permissions-enabled backend, such as Django Guardian. |
| 261 |
|
| 262 |
It ensures that the user is authenticated, and has the appropriate |
| 263 |
`add`/`change`/`delete` permissions on the object using .has_perms. |
| 264 |
|
| 265 |
This permission can only be applied against view classes that |
| 266 |
provide a `.queryset` attribute. |
| 267 |
""" |
| 268 |
perms_map = { |
| 269 |
'GET': [], |
| 270 |
'OPTIONS': [], |
| 271 |
'HEAD': [], |
| 272 |
'POST': ['%(app_label)s.add_%(model_name)s'], |
| 273 |
'PUT': ['%(app_label)s.change_%(model_name)s'], |
| 274 |
'PATCH': ['%(app_label)s.change_%(model_name)s'], |
| 275 |
'DELETE': ['%(app_label)s.delete_%(model_name)s'], |
| 276 |
} |
| 277 |
|
| 278 |
def get_required_object_permissions(self, method, model_cls): |
| 279 |
kwargs = { |
| 280 |
'app_label': model_cls._meta.app_label, |
| 281 |
'model_name': model_cls._meta.model_name |
| 282 |
} |
| 283 |
|
| 284 |
if method not in self.perms_map: |
| 285 |
raise exceptions.MethodNotAllowed(method) |
| 286 |
|
| 287 |
return [perm % kwargs for perm in self.perms_map[method]] |
| 288 |
|
| 289 |
def has_object_permission(self, request, view, obj): |
| 290 |
# authentication checks have already executed via has_permission |
| 291 |
queryset = self._queryset(view) |
| 292 |
model_cls = queryset.model |
| 293 |
user = request.user |
| 294 |
|
| 295 |
perms = self.get_required_object_permissions(request.method, model_cls) |
| 296 |
|
| 297 |
if not user.has_perms(perms, obj): |
| 298 |
# If the user does not have permissions we need to determine if |
| 299 |
# they have read permissions to see 403, or not, and simply see |
| 300 |
# a 404 response. |
| 301 |
|
| 302 |
if request.method in SAFE_METHODS: |
| 303 |
# Read permissions already checked and failed, no need |
| 304 |
# to make another lookup. |
| 305 |
raise Http404 |
| 306 |
|
| 307 |
read_perms = self.get_required_object_permissions('GET', model_cls) |
| 308 |
if not user.has_perms(read_perms, obj): |
| 309 |
raise Http404 |
| 310 |
|
| 311 |
# Has read permissions. |
| 312 |
return False |
| 313 |
|
| 314 |
return True |