|
| 1 | +# Copyright 2019 The Casbin Authors. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import casbin |
| 16 | + |
| 17 | +from django.core.exceptions import PermissionDenied |
| 18 | + |
| 19 | + |
| 20 | +class CasbinMiddleware: |
| 21 | + """ |
| 22 | + Casbin middleware. |
| 23 | + """ |
| 24 | + |
| 25 | + def __init__(self, get_response): |
| 26 | + self.get_response = get_response |
| 27 | + self.enforcer = casbin.Enforcer("casbin_middleware/authz_model.conf", "casbin_middleware/authz_policy.csv") |
| 28 | + # One-time configuration and initialization. |
| 29 | + |
| 30 | + def __call__(self, request): |
| 31 | + # Code to be executed for each request before |
| 32 | + # the view (and later middleware) are called. |
| 33 | + |
| 34 | + if not self.check_permission(request): |
| 35 | + raise PermissionDenied |
| 36 | + |
| 37 | + response = self.get_response(request) |
| 38 | + |
| 39 | + # Code to be executed for each request/response after |
| 40 | + # the view is called. |
| 41 | + |
| 42 | + return response |
| 43 | + |
| 44 | + def check_permission(self, request): |
| 45 | + user = request.user.username |
| 46 | + if request.user.is_anonymous: |
| 47 | + user = 'anonymous' |
| 48 | + path = request.path |
| 49 | + method = request.method |
| 50 | + return self.enforcer.enforce(user, path, method) |
| 51 | + |
| 52 | + def require_permission(self,): |
| 53 | + raise PermissionDenied |
0 commit comments