Skip to content

Commit

Permalink
Merge pull request #66 from ivandervisevic/fix_cookie_deleted_domain
Browse files Browse the repository at this point in the history
Thank you
  • Loading branch information
alex-oleshkevich committed Sep 28, 2023
2 parents b002235 + ac49991 commit a283b88
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
12 changes: 8 additions & 4 deletions starsessions/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,11 +94,15 @@ async def send_wrapper(message: Message) -> None:
# we have to remove the cookie and clear the storage
if not self.cookie_path or self.cookie_path and scope["path"].startswith(self.cookie_path):
headers = MutableHeaders(scope=message)
header_value = "{}={}; {}".format(
self.cookie_name,
f"null; path={path}; expires=Thu, 01 Jan 1970 00:00:00 GMT;",
header_parts = [
f"{self.cookie_name}=''",
f"path={path}",
"expires=Thu, 01 Jan 1970 00:00:00 GMT",
self.security_flags,
)
]
if self.cookie_domain:
header_parts.append(f"domain={self.cookie_domain}")
header_value = "; ".join(header_parts)
headers.append("Set-Cookie", header_value)
await handler.destroy()
await send(message)
Expand Down
19 changes: 19 additions & 0 deletions tests/test_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,25 @@ async def app(scope: Scope, receive: Receive, send: Send) -> None:
assert "01 Jan 1970 00:00:00 GMT" in response.headers.get("set-cookie")


def test_send_cookie_with_domain_if_session_destroyed_and_domain_set(store: SessionStore) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
connection = HTTPConnection(scope, receive)

await store.write("session_id", b'{"key2": "value2"}', lifetime=60, ttl=60)
await load_session(connection)

connection.session.clear()
response = Response("")
await response(scope, receive, send)

app = SessionMiddleware(app, store=store, cookie_domain="example.com")
client = TestClient(app)
response = client.get("/", cookies={"session": "session_id"})
assert "session" in response.headers.get("set-cookie")
assert "01 Jan 1970 00:00:00 GMT" in response.headers.get("set-cookie")
assert "domain=example.com" in response.headers["set-cookie"].lower()


@pytest.mark.asyncio
async def test_will_clear_storage_if_session_destroyed(store: SessionStore) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
Expand Down

0 comments on commit a283b88

Please sign in to comment.