Coverage for /Users/davegaeddert/Development/dropseed/plain/plain/plain/internal/middleware/https.py: 83%

18 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-10-16 22:24 -0500

1import re 

2 

3from plain.http import ResponsePermanentRedirect 

4from plain.runtime import settings 

5 

6 

7class HttpsRedirectMiddleware: 

8 def __init__(self, get_response): 

9 self.get_response = get_response 

10 

11 # Settings for https (compile regexes once) 

12 self.https_redirect_enabled = settings.HTTPS_REDIRECT_ENABLED 

13 self.https_redirect_host = settings.HTTPS_REDIRECT_HOST 

14 self.https_redirect_exempt = [ 

15 re.compile(r) for r in settings.HTTPS_REDIRECT_EXEMPT 

16 ] 

17 

18 def __call__(self, request): 

19 """ 

20 Rewrite the URL based on settings.APPEND_SLASH 

21 """ 

22 

23 if redirect_response := self.maybe_https_redirect(request): 

24 return redirect_response 

25 

26 return self.get_response(request) 

27 

28 def maybe_https_redirect(self, request): 

29 path = request.path.lstrip("/") 

30 if ( 

31 self.https_redirect_enabled 

32 and not request.is_https() 

33 and not any(pattern.search(path) for pattern in self.https_redirect_exempt) 

34 ): 

35 host = self.https_redirect_host or request.get_host() 

36 return ResponsePermanentRedirect(f"https://{host}{request.get_full_path()}")