hobo/hobo/middleware/cookies_samesite.py

39 lines
1.7 KiB
Python

# hobo - portal to configure and deploy applications
# Copyright (C) 2015-2020 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from django.conf import settings
from django.utils.deprecation import MiddlewareMixin
class CookiesSameSiteFixMiddleware(MiddlewareMixin):
def process_response(self, request, response):
# adjust CSRF and session cookies to mark them with SameSite=None
# as required by newer Chrome versions.
# see: https://www.chromestatus.com/feature/5088147346030592
# this can be removed once django 2.2 is used and settings.
# CSRF_COOKIE_SAMESITE & SESSION_COOKIE_SAMESITE can be used.
if settings.CSRF_COOKIE_NAME in response.cookies:
same_site = settings.CSRF_COOKIE_SAMESITE or 'None'
response.cookies[settings.CSRF_COOKIE_NAME]['samesite'] = same_site.title()
if settings.SESSION_COOKIE_NAME in response.cookies:
response.cookies[settings.SESSION_COOKIE_NAME]['samesite'] = 'None'
return response
# required for Python <3.8
import http.cookies
http.cookies.Morsel._reserved.setdefault('samesite', 'SameSite')