forked from mozilla/django-csp
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
mozillaGH-72 Add FormattedPolicyCSPMiddleware
- Loading branch information
1 parent
a1ee611
commit 71bb768
Showing
1 changed file
with
36 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
from string import Formatter | ||
|
||
from django.conf import settings | ||
|
||
from csp.middleware import CSPMiddleware | ||
|
||
|
||
class FormattedPolicyCSPMiddleware(CSPMiddleware): | ||
"""A CSP middleware that formats elements of the policy based on the | ||
request and response and formatting functions defined in | ||
CSP_POLICY_FORMATTERS.""" | ||
|
||
formatter = Formatter() | ||
|
||
def build_policy(self, request, response): | ||
formatter = self.formatter | ||
formatters = getattr( | ||
settings, | ||
'CSP_POLICY_FORMATTERS', | ||
{'host': lambda request, response: request.META['HTTP_HOST']}, | ||
) | ||
all_replacements = {} | ||
for (csp, report_only, exclude_prefixes) in super().build_policy( | ||
request, response, | ||
): | ||
format_kwargs = { | ||
field_name for _, field_name, _, _ in formatter.parse(csp) | ||
} | ||
if format_kwargs: | ||
for name in format_kwargs: | ||
if name not in all_replacements: | ||
all_replacements[name] = formatters[name]( | ||
request, response, | ||
) | ||
csp = formatter.format(csp, **all_replacements) | ||
yield csp, report_only, exclude_prefixes |