diff --git a/app/core/cookies.py b/app/core/cookies.py index 27b92de..0dcca77 100644 --- a/app/core/cookies.py +++ b/app/core/cookies.py @@ -1,6 +1,11 @@ +import json +import logging + from django.conf import settings from django.http import HttpRequest, HttpResponse +logger = logging.getLogger(__name__) + def set_ga_cookie_policy(response: HttpResponse, preference: str) -> None: """Set Google Analytics (GA) policy. @@ -8,9 +13,19 @@ def set_ga_cookie_policy(response: HttpResponse, preference: str) -> None: Sets the cookies that are required for Google Tag Manager (GTM) to function correctly. """ + + cookie_object = { + "essential": True, + "settings": True, + "usage": preference == "true", + "campaigns": False, + } + + json_string_cookie_object = json.dumps(cookie_object) + response.set_cookie( key=settings.COOKIE_ACCEPTED_GA_NAME, - value=preference, + value=json_string_cookie_object, max_age=365 * 24 * 60 * 60, ) response.set_cookie( @@ -26,4 +41,12 @@ def get_ga_cookie_preference(request: HttpRequest) -> str: Returns value of the GA cookie preference if it exists, otherwise returns "false". """ - return request.COOKIES.get(settings.COOKIE_ACCEPTED_GA_NAME, "false") + cookie_object = request.COOKIES.get(settings.COOKIE_ACCEPTED_GA_NAME) + if cookie_object: + try: + cookie_value = json.loads(cookie_object) + return str(cookie_value.get("usage", False)).lower() + except json.JSONDecodeError as e: + logger.error(f"Error parsing GA cookie: {e}") + + return "false" diff --git a/app/core/views.py b/app/core/views.py index 25fa9e4..60c6ca5 100644 --- a/app/core/views.py +++ b/app/core/views.py @@ -1,3 +1,6 @@ +import json +import logging + from django.conf import settings from django.http import HttpRequest, HttpResponse, HttpResponseRedirect from django.shortcuts import redirect, render @@ -9,6 +12,8 @@ from .forms import CookiePreferenceForm from .healthcheck import application_service_health +logger = logging.getLogger(__name__) + @require_http_methods(["GET"]) def home(request: HttpRequest) -> HttpResponse: @@ -118,6 +123,16 @@ def set_cookie_banner_preference(request) -> HttpResponseRedirect: query parameter. This parameter is used to display a confirmation message banner. """ + + cookie_object = request.COOKIES.get(settings.COOKIE_ACCEPTED_GA_NAME) + preference = "false" + if cookie_object: + try: + cookie_value = json.loads(cookie_object) + preference = str(cookie_value.get("usage", False)).lower() + except json.JSONDecodeError as e: + logger.error(f"Error parsing GA cookie: {e}") + preference = request.GET.get(settings.COOKIE_ACCEPTED_GA_NAME, "false") current_page = request.GET.get("current_page") if not url_has_allowed_host_and_scheme( diff --git a/app/templates/cookie_banner.html b/app/templates/cookie_banner.html index e40d1d3..ad8a99a 100644 --- a/app/templates/cookie_banner.html +++ b/app/templates/cookie_banner.html @@ -35,7 +35,7 @@