Skip to content

Commit

Permalink
Merge pull request #814 from circulon/feature/cookie_encrypt_opt_out
Browse files Browse the repository at this point in the history
opt-out of encrypt for a cookie
  • Loading branch information
josephmancuso authored Aug 13, 2024
2 parents 77a5499 + 3ad4973 commit bd03d85
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/masonite/cookies/Cookie.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ def __init__(
timezone=None,
secure=False,
samesite="Strict",
encrypt=True,
):
self.name = name
self.value = value
Expand All @@ -18,6 +19,7 @@ def __init__(
self.timezone = timezone
self.samesite = samesite
self.path = path
self.encrypt = encrypt

def render(self):
response = f"{self.name}={self.value};"
Expand Down
6 changes: 6 additions & 0 deletions src/masonite/middleware/route/EncryptCookies.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
class EncryptCookies:
def before(self, request, response):
for _, cookie in request.cookie_jar.all().items():
if not cookie.encrypt:
continue

try:
cookie.value = request.app.make("sign").unsign(cookie.value)
except InvalidToken:
Expand All @@ -13,6 +16,9 @@ def before(self, request, response):

def after(self, request, response):
for _, cookie in response.cookie_jar.all().items():
if not cookie.encrypt:
continue

try:
cookie.value = request.app.make("sign").sign(cookie.value)
except InvalidToken:
Expand Down
13 changes: 13 additions & 0 deletions tests/core/middleware/test_encrypt_cookies.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,16 @@ def test_encrypts_cookies(self):
response.cookie("test", "value")
EncryptCookies().after(request, response)
self.assertNotEqual(response.cookie("test"), "value")

def test_encrypt_cookies_opt_out(self):
request = self.make_request(
{"HTTP_COOKIE": f"test_key=test value"}
)

response = self.make_response()
EncryptCookies().before(request, None)
self.assertEqual(request.cookie("test_key", encrypt=False), "test value")

response.cookie("test", "value")
EncryptCookies().after(request, response)
self.assertNotEqual(response.cookie("test_key", encrypt=False), "test value")

0 comments on commit bd03d85

Please sign in to comment.