django-analytical/analytical/context_providers/matomo.py
SilverStrings024 d1d1be189a Added conditional tracking consent for Matomo
Modified utils.build_paq_cmd to remove the trailing comma and white space as well as add a semi colon to the end of the push command.
Added context_providers directory with matomo.py file with a context provider that builds the tracking consent code and adds it to the context.
Modified matomo.MatomoNode.render. Removed original ugly settings check code with simply rendering the 'consent_script' context variable and adding it to the html variable only if its length is greater than 1.
NOTE: The context provider and rendering it (line 110 templatetags/matomo.py) are untested. Both utils.build_paq_cmd and utils.get_event_bind_js are tested but need need more rigorous testing to be sure it won't break.
2021-07-13 00:35:26 -04:00

34 lines
No EOL
1.3 KiB
Python

import utils
from django.conf import settings
def matomo_consent_provider(request):
"""
Add Mamoto consent script to the requests context.
:Cases:
- If MATOMO_REQURE_CONSENT is True OR If ALWAYS_TRACK_REGISTERED True == continue on
- If ALWAYS_TRACK_REGISTERED is True AND the user is authenticated
"""
# Do we require consent?
if getattr(settings, 'MATOMO_REQUIRE_CONSENT', False):
provide_script = True
if request.user.is_authenticated and not getattr(settings, "ALWAYS_TRACK_REGISTERED", True):
provide_script = False
if provide_script:
grant_class_name = getattr(settings, 'GRANT_CONSENT_TAG_CLASSNAME')
revoke_class_name = getattr(settings, 'REVOKE_CONSENT_CLASSNAME')
return {"consent_script":"""
%s;
%s
%s
""" % (
utils.build_paq_cmd('requireConsent'),
utils.get_event_bind_js(
class_name=grant_class_name,
matomo_event="rememberConsentGiven",
),
utils.get_event_bind_js(
class_name=revoke_class_name,
matomo_event="forgetConsentGiven",
)
)}
return {'consent_script': ""}