Coverage for src/model_permissions/middleware.py: 100.00%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

12 statements  

1""" 

2django-model-permissions - simple object permissions for django. 

3 

4Copyright (C) 2018 Mathias Stelzer 

5 

6This program is free software: you can redistribute it and/or modify 

7it under the terms of the GNU General Public License as published by 

8the Free Software Foundation, either version 3 of the License, or 

9(at your option) any later version. 

10 

11This program is distributed in the hope that it will be useful, 

12but WITHOUT ANY WARRANTY; without even the implied warranty of 

13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

14GNU General Public License for more details. 

15 

16You should have received a copy of the GNU General Public License 

17along with this program. If not, see <http://www.gnu.org/licenses/>. 

18""" 

19from django.conf import settings 

20from django.core.exceptions import PermissionDenied 

21from django.http import HttpResponseRedirect 

22 

23 

24class RedirectMiddleware(object): 

25 """ 

26 Middleware to redirect PermissionDenied exceptions. 

27 

28 By default, users are redirected to the :django:setting:`LOGIN_URL`. To change this, set 

29 ``MODEL_PERMISSIONS_REDIRECT_URL`` in your settings. 

30 

31 """ 

32 

33 def __init__(self, get_response): 

34 """Initialize middleware.""" 

35 self.get_response = get_response 

36 

37 def __call__(self, request): 

38 """Get and return the response for the given request.""" 

39 return self.get_response(request) 

40 

41 def process_exception(self, request, exception): 

42 """Redirect a `PermissionDenied` exception.""" 

43 if type(exception) == PermissionDenied: 

44 url = getattr(settings, 'MODEL_PERMISSIONS_REDIRECT_URL', settings.LOGIN_URL) 

45 return HttpResponseRedirect('{}?next={}'.format(url, request.path))