From eff921af18240c7498a24b0cb6d8b26b34f9db37 Mon Sep 17 00:00:00 2001
From: Stein Elgethun <stein.elgethun@usit.uio.no>
Date: Tue, 9 Nov 2021 14:44:08 +0100
Subject: [PATCH] Add utility functions to set and delete cookies

Issue: GREG-89
---
 frontend/src/utils/index.test.ts | 29 +++++++++++++++++++++++++++++
 frontend/src/utils/index.ts      | 10 ++++++++++
 2 files changed, 39 insertions(+)

diff --git a/frontend/src/utils/index.test.ts b/frontend/src/utils/index.test.ts
index 871d4145..24f9d152 100644
--- a/frontend/src/utils/index.test.ts
+++ b/frontend/src/utils/index.test.ts
@@ -1,5 +1,7 @@
 import {
   getCookie,
+  deleteCookie,
+  setCookie,
   isValidEmail,
   isValidFnr,
   isValidMobilePhoneNumber,
@@ -77,6 +79,33 @@ test('Get unknown cookie returns null', async () => {
   document.cookie = 'csrftoken= ; expires = Thu, 01 Jan 1970 00:00:00 GMT'
 })
 
+test('Get known cookie returns value', async () => {
+  document.cookie = 'key=value'
+  expect(getCookie('key')).toEqual('value')
+  document.cookie = 'key= ; expires = Thu, 01, Jan 1970 00:00:00 GMT'
+})
+
+test('Deleting cookie removes it', async () => {
+  document.cookie = 'key=value'
+  expect(getCookie('key')).toEqual('value')
+  deleteCookie('key')
+  expect(getCookie('key')).toEqual(null)
+})
+
+test('setCookie creates a cookie with correct value', async () => {
+  setCookie('key', 'value')
+  expect(getCookie('key')).toEqual('value')
+  deleteCookie('key')
+})
+
+test('setCookie overrides value that was set before', async () => {
+  setCookie('key', 'value')
+  expect(getCookie('key')).toEqual('value')
+  setCookie('key', 'differentvalue')
+  expect(getCookie('key')).toEqual('differentvalue')
+  deleteCookie('key')
+})
+
 test('Valid fnr', async () => {
   expect(isValidFnr('04026514903')).toEqual(true)
 })
diff --git a/frontend/src/utils/index.ts b/frontend/src/utils/index.ts
index 11623666..08dfed2f 100644
--- a/frontend/src/utils/index.ts
+++ b/frontend/src/utils/index.ts
@@ -23,6 +23,16 @@ export function getCookie(name: string) {
   return decodeURIComponent(cookies[0].split('=')[1])
 }
 
+export function setCookie(name: string, value: string) {
+  document.cookie = `${name}=${value}; path=/`
+}
+
+export function deleteCookie(name: string) {
+  if (getCookie(name)) {
+    setCookie(name, '; expires=Thu, 01 jan 1970 00:00:00 GMT')
+  }
+}
+
 export function maybeCsrfToken() {
   const csrfToken = getCookie('csrftoken')
   if (!csrfToken) {
-- 
GitLab