From 23f6b8a46d783b9c9eae8a8df41bc00a03a282fc Mon Sep 17 00:00:00 2001 From: evazion Date: Mon, 14 Dec 2020 14:58:32 -0600 Subject: [PATCH] js: refactor Cookie.put. * Set Max-Age= flag instead of Expires= flag. * Set Secure flag when using HTTPS. * Extend default cookie lifetime from 1 year to 20 years. * Remove "session" expiration option (unused). * Remove max cookie size check. The cookie size check was previously added in #2518 to deal with running out of space due to tag scripts and blacklists. This should no longer happen since we no longer use cookies for these things. Remove the warning because it should never happen, we can't fix it if it does, and the user probably won't know how to fix it either. --- app/javascript/src/javascripts/cookie.js | 26 ++++++++---------------- 1 file changed, 8 insertions(+), 18 deletions(-) diff --git a/app/javascript/src/javascripts/cookie.js b/app/javascript/src/javascripts/cookie.js index 1c457d11b..707d95389 100644 --- a/app/javascript/src/javascripts/cookie.js +++ b/app/javascript/src/javascripts/cookie.js @@ -1,27 +1,17 @@ -import Utility from "./utility"; - let Cookie = {}; -Cookie.put = function(name, value, days) { - var expires = ""; - if (days !== "session") { - if (!days) { - days = 365; - } +Cookie.put = function(name, value, max_age_in_days = 365 * 20) { + let cookie = `${name}=${encodeURIComponent(value)}; Path=/; SameSite=Lax;`; - var date = new Date(); - date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); - expires = "expires=" + date.toGMTString() + "; "; + if (max_age_in_days) { + cookie += ` Max-Age=${max_age_in_days * 24 * 60 * 60};` } - var new_val = name + "=" + encodeURIComponent(value) + "; " + expires + "path=/; SameSite=Lax"; - if (document.cookie.length < (4090 - new_val.length)) { - document.cookie = new_val; - return true; - } else { - Utility.error("You have too many cookies on this site. Consider deleting them all.") - return false; + if (location.protocol === "https:") { + cookie += " Secure;"; } + + document.cookie = cookie; } Cookie.raw_get = function(name) {