Skip to content

Commit

Permalink
Merge pull request tornadoweb#2524 from kinow/define-xsrf-expires-day
Browse files Browse the repository at this point in the history
Define XSRF cookie expires_day via settings
  • Loading branch information
bdarnell authored Nov 21, 2018
2 parents 8abbb90 + 80c5357 commit 940fd87
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 8 deletions.
14 changes: 13 additions & 1 deletion tornado/test/web_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -2902,11 +2902,23 @@ def get(self):
self.write(self.xsrf_token)

def get_app_kwargs(self):
return dict(xsrf_cookies=True, xsrf_cookie_kwargs=dict(httponly=True))
return dict(
xsrf_cookies=True, xsrf_cookie_kwargs=dict(httponly=True, expires_days=2)
)

def test_xsrf_httponly(self):
response = self.fetch("/")
self.assertIn("httponly;", response.headers["Set-Cookie"].lower())
self.assertIn("expires=", response.headers["Set-Cookie"].lower())
header = response.headers.get("Set-Cookie")
match = re.match(".*; expires=(?P<expires>.+);.*", header)
assert match is not None

expires = datetime.datetime.utcnow() + datetime.timedelta(days=2)
parsed = email.utils.parsedate(match.groupdict()["expires"])
assert parsed is not None
header_expires = datetime.datetime(*parsed[:6])
self.assertTrue(abs((expires - header_expires).total_seconds()) < 10)


class FinishExceptionTest(SimpleHandlerTestCase):
Expand Down
10 changes: 3 additions & 7 deletions tornado/web.py
Original file line number Diff line number Diff line change
Expand Up @@ -1418,13 +1418,9 @@ def xsrf_token(self) -> bytes:
else:
raise ValueError("unknown xsrf cookie version %d", output_version)
if version is None:
expires_days = 30 if self.current_user else None
self.set_cookie(
"_xsrf",
self._xsrf_token,
expires_days=expires_days,
**cookie_kwargs
)
if self.current_user and "expires_days" not in cookie_kwargs:
cookie_kwargs["expires_days"] = 30
self.set_cookie("_xsrf", self._xsrf_token, **cookie_kwargs)
return self._xsrf_token

def _get_raw_xsrf_token(self) -> Tuple[Optional[int], bytes, float]:
Expand Down

0 comments on commit 940fd87

Please sign in to comment.