Add a function to get cookie expiration time

This commit is contained in:
Shadab Zafar 2016-08-08 12:55:04 +05:30
parent 55f1ffe0b1
commit 03e6117042
2 changed files with 46 additions and 0 deletions

View File

@ -269,6 +269,32 @@ def refresh_set_cookie_header(c, delta):
return ret
def get_expiration_ts(cookie_attrs):
"""
Determines the time when the cookie will be expired.
Considering both 'expires' and 'max-age' parameters.
Returns: timestamp of when the cookie will expire.
None, if no expiration time is set.
"""
if 'expires' in cookie_attrs:
e = email.utils.parsedate_tz(cookie_attrs["expires"])
if e:
return email.utils.mktime_tz(e)
elif 'max-age' in cookie_attrs:
try:
max_age = int(cookie_attrs['Max-Age'])
except ValueError:
pass
else:
now_ts = time.time()
return now_ts + max_age
return None
def is_expired(cookie_attrs):
"""
Determines whether a cookie has expired.

View File

@ -1,6 +1,10 @@
import time
from netlib.http import cookies
from netlib.tutils import raises
import mock
def test_read_token():
tokens = [
@ -247,6 +251,22 @@ def test_refresh_cookie():
assert cookies.refresh_set_cookie_header(c, 0)
@mock.patch('time.time')
def test_get_expiration_ts(*args):
# Freeze time
now_ts = 17
time.time.return_value = now_ts
CA = cookies.CookieAttrs
F = cookies.get_expiration_ts
assert F(CA([("Expires", "Thu, 01-Jan-1970 00:00:00 GMT")])) == 0
assert F(CA([("Expires", "Thu, 24-Aug-2063 00:00:00 GMT")])) == 2955139200
assert F(CA([("Max-Age", "0")])) == now_ts
assert F(CA([("Max-Age", "31")])) == now_ts + 31
def test_is_expired():
CA = cookies.CookieAttrs