Skip to content

Commit

Permalink
Add cookie consent (#378)
Browse files Browse the repository at this point in the history
  • Loading branch information
Puththiran authored Jul 5, 2022
1 parent 780e6bd commit 68c8b9b
Show file tree
Hide file tree
Showing 13 changed files with 326 additions and 3 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ templates/static/css/libraries/*
# Allow images within static
!templates/static/images

#Allow cookie consent
!templates/static/cookie-consent

# Ignore the contents of /static but keep the directory
/static/*
!/static/.gitkeep
Expand Down
5 changes: 5 additions & 0 deletions config/settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,11 @@
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"django.middleware.security.SecurityMiddleware",
"wagtail.contrib.redirects.middleware.RedirectMiddleware",
"etna.core.middleware.SetDefaultCookiePreferencesMiddleware",
]

COOKIE_DOMAIN = os.getenv("COOKIE_DOMAIN", "nationalarchives.gov.uk")

ROOT_URLCONF = "config.urls"

TEMPLATES = [
Expand Down Expand Up @@ -364,3 +367,5 @@
FEATURE_RELATED_INSIGHTS_ON_EXPLORE_PAGES = strtobool(
os.getenv("FEATURE_RELATED_INSIGHTS_ON_EXPLORE_PAGES", "True")
)

FEATURE_COOKIE_BANNER_ENABLED = True
3 changes: 3 additions & 0 deletions config/settings/dev.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@
RECORD_DETAIL_REQUIRE_LOGIN = False
SEARCH_VIEWS_REQUIRE_LOGIN = False

FEATURE_COOKIE_BANNER_ENABLED = False
COOKIE_DOMAIN = "localhost"

try:
from .local import * # noqa: F401
except ImportError:
Expand Down
26 changes: 26 additions & 0 deletions etna/core/middleware.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from datetime import datetime, timedelta
from urllib.parse import quote

from django.conf import settings


class SetDefaultCookiePreferencesMiddleware:
def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):
response = self.get_response(request)
if not settings.FEATURE_COOKIE_BANNER_ENABLED:
return response
cookie_name = "cookies_policy"
if not request.COOKIES.get(cookie_name, None):
expires = datetime.utcnow() + timedelta(days=90)
value = '{"usage":false,"settings":false,"essential":true}'
response.set_cookie(
cookie_name,
expires=expires,
path="/",
domain=settings.COOKIE_DOMAIN,
value=quote(value),
)
return response
32 changes: 32 additions & 0 deletions etna/core/templatetags/cookie_tags.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import json

from json.decoder import JSONDecodeError
from typing import Union
from urllib.parse import unquote

from django import template

register = template.Library()


@register.filter
def cookie_use_permitted(value: Union[str, None]) -> bool:
"""
Return the True/False based on cookie usage value
if no cookie set it will return False
"""
usage = False

try:
if value is not None:
cookie_str = unquote(value)
usage = json.loads(cookie_str)["usage"]
except (
JSONDecodeError, # invalid json
TypeError, # decoded json isn't a dict
KeyError, # dict doesn't contain 'usage'
ValueError, # 'usage' value cannot be converted to boolean
):
usage = False

return usage
33 changes: 33 additions & 0 deletions etna/core/tests/test_cookie_tags.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from django.test import SimpleTestCase

from etna.core.templatetags.cookie_tags import cookie_use_permitted


class TestCookieUsePermittedTag(SimpleTestCase):

empty_cookie = ""
none_cookie = None
json_usage_true_cookie = '{"usage":true,"settings":false,"essential":true}'
json_unicoded_usage_true_cookie = (
"%7b%22usage%22%3atrue%2c%22settings%22%3afalse%2c%22essential%22%3atrue%7d"
)
json_usage_false_cookie = '{"usage":false,"settings":false,"essential":true}'
invalid_json_cookie = "NOT_JSON"
unexpected_json_format = '["item_one", "item_two"]'
incorrect_bool_cookie = '{"usage":fase,"settings":false,"essential":true}'

def test_default(self):
for attribute_name, expected_result in (
("empty_cookie", False),
("none_cookie", False),
("json_usage_true_cookie", True),
("json_unicoded_usage_true_cookie", True),
("json_usage_false_cookie", False),
("invalid_json_cookie", False),
("unexpected_json_format", False),
("incorrect_bool_cookie", False),
):
with self.subTest(attribute_name):
source = getattr(self, attribute_name)

self.assertEqual(cookie_use_permitted(source), expected_result)
1 change: 1 addition & 0 deletions sass/etna.scss
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,4 @@ These are Etna specific components, created using BEM and following our guidelin
@import 'includes/search/long-filters';
@import 'includes/sub-heading';
@import 'includes/section-image';
@import 'includes/cookie-consent';
28 changes: 28 additions & 0 deletions sass/includes/_cookie-consent.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#ds-cookie-consent-banner {
.container {
.row {
display: block;
flex-wrap: nowrap;
}

.cookie_head {
font-family: $font__roboto !important;
}

.button {
font-family: $font__open-sans !important;

&:hover {
cursor: pointer;
}
}

#btn_preferences {
color: $color__white;
padding: 0.5rem;
&:hover {
transition: none;
}
}
}
}
23 changes: 20 additions & 3 deletions templates/base.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{% load static wagtailuserbar wagtailcore_tags wagtailsettings_tags %}<!DOCTYPE html>
{% load static wagtailuserbar wagtailcore_tags wagtailsettings_tags cookie_tags %}<!DOCTYPE html>
{% get_settings %}
<html class="no-js" lang="en">
<head>
Expand All @@ -21,6 +21,11 @@
{# Global stylesheets #}
<link rel="stylesheet" type="text/css" href="{% static 'css/dist/etna.css' %}">

{# Cookie consent #}
{% if FEATURE_COOKIE_BANNER_ENABLED %}
<link rel="stylesheet" type="text/css" href="{% static 'cookie-consent/ds-cookie-consent.css' %}">
{% endif %}

{% block extra_css %}
{# Override this in templates to add extra stylesheets #}
{% endblock %}
Expand All @@ -33,8 +38,10 @@

{# Google Fonts #}
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@0,400;0,700;1,400;1,700&family=Roboto:ital,wght@0,400;0,500;0,700;1,400;1,500;1,700&display=swap"
<link href="https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@0,400;0,700;1,400;1,700&family=Roboto:ital,wght@0,400;0,500;0,700;1,400;1,500;1,700&family=Roboto+Mono&display=swap"
rel="stylesheet">


<script>document.documentElement.className = document.documentElement.className.replace(/\bno-js\b/g, '') + ' js ';</script>

{# Adobe Fonts #}
Expand All @@ -47,9 +54,14 @@
</head>

<body class="{% block body_class %}{% endblock %}">
{% if FEATURE_COOKIE_BANNER_ENABLED %}
{% include 'includes/cookie-consent.html' %}
{% endif %}
<a href="#maincontent" class="skip-to-content-link sr-only sr-only-focusable" data-link="Skip to main content">Skip to main content</a>

{% include 'includes/gtm-no-script.html' %}
{% if request.COOKIES.cookies_policy|cookie_use_permitted %}
{% include 'includes/gtm-no-script.html' %}
{% endif %}

{% block header %}
{% include 'includes/header.html' %}
Expand All @@ -70,5 +82,10 @@
{% endblock %}
<script src="{% static 'scripts/global_search.js' %}"></script>
<script src="{% static 'scripts/hamburger_menu.js' %}"></script>

{% if FEATURE_COOKIE_BANNER_ENABLED %}
<script src="{% static 'cookie-consent/ds-cookie-consent.js' %}"></script>
{% endif %}

</body>
</html>
13 changes: 13 additions & 0 deletions templates/includes/cookie-consent.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<div id="ds-cookie-consent-banner" class="cookieConsent" role="region" aria-label="Cookie banner">
<div class="container" role="region" aria-label="Cookies on The National Archives">
<div class="row">
<p class="cookie_head">This website uses cookies</p>
<p class="cookie-p">
We place some essential cookies on your device to make this website work. <br><br>
We'd like to use additional cookies to remember your settings and understand how you use our services. <br><br>
This information will help us make improvements to the website.
</p>
<a href="https://www.nationalarchives.gov.uk/legal/cookies/" id="btn_preferences" class="button">Set cookie preferences</a>
</div>
</div>
</div>
Loading

0 comments on commit 68c8b9b

Please sign in to comment.