Skip to content

Commit

Permalink
Merge pull request #29 from minamorl/patch-for-invalid-token-error
Browse files Browse the repository at this point in the history
Handles cryptography.fernet.InvalidToken exception
  • Loading branch information
asvetlov committed Feb 21, 2016
2 parents d5842c4 + d2e92ad commit 3e91862
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 7 deletions.
12 changes: 8 additions & 4 deletions aiohttp_session/cookie_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import base64

from cryptography import fernet
from cryptography.fernet import InvalidToken

from . import AbstractStorage, Session

Expand Down Expand Up @@ -30,10 +31,13 @@ def load_session(self, request):
if cookie is None:
return Session(None, data=None, new=True)
else:
data = json.loads(
self._fernet.decrypt(cookie.encode('utf-8')).decode('utf-8')
)
return Session(None, data=data, new=False)
try:
data = json.loads(
self._fernet.decrypt(
cookie.encode('utf-8')).decode('utf-8'))
return Session(None, data=data, new=False)
except InvalidToken:
return Session(None, data=None, new=True)

@asyncio.coroutine
def save_session(self, request, response, session):
Expand Down
13 changes: 10 additions & 3 deletions tests/test_encrypted_cookie_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def test_invalid_key(self):
with self.assertRaises(ValueError):
EncryptedCookieStorage(b'123') # short key

def test_create_new_sesssion(self):
def test_create_new_sesssion_broken_by_fermat(self):

@asyncio.coroutine
def handler(request):
Expand All @@ -91,8 +91,15 @@ def handler(request):

@asyncio.coroutine
def go():
_, _, url = yield from self.create_server('GET', '/', handler)
resp = yield from request('GET', url, loop=self.loop)
key = fernet.Fernet.generate_key()
self.key = base64.urlsafe_b64decode(key)

_, _, url = yield from self.create_server(
'GET', '/', handler)
resp = yield from request(
'GET', url,
cookies=self.make_cookie({'a': 1, 'b': 12}),
loop=self.loop)
self.assertEqual(200, resp.status)

self.loop.run_until_complete(go())
Expand Down

0 comments on commit 3e91862

Please sign in to comment.