Delete the session cookie on an empty session.
[mediagoblin.git] / mediagoblin / tools / session.py
CommitLineData
c7424612
BS
1# GNU MediaGoblin -- federated, autonomous media hosting
2# Copyright (C) 2013 MediaGoblin contributors. See AUTHORS.
3#
4# This program is free software: you can redistribute it and/or modify
5# it under the terms of the GNU Affero General Public License as published by
6# the Free Software Foundation, either version 3 of the License, or
7# (at your option) any later version.
8#
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12# GNU Affero General Public License for more details.
13#
14# You should have received a copy of the GNU Affero General Public License
15# along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17import itsdangerous
18import logging
19
20import crypto
21
22_log = logging.getLogger(__name__)
23
24class Session(dict):
25 def save(self):
26 self.send_new_cookie = True
27
28 def is_updated(self):
29 return getattr(self, 'send_new_cookie')
30
31 def delete(self):
32 self.clear()
33 self.save()
34
35
36class SessionManager(object):
37 def __init__(self, cookie_name='MGSession', namespace=None):
38 if namespace is None:
39 namespace = cookie_name
40 self.signer = crypto.get_timed_signer_url(namespace)
41 self.cookie_name = cookie_name
42
43 def load_session_from_cookie(self, request):
44 cookie = request.cookies.get(self.cookie_name)
45 if not cookie:
46 return Session()
47 ### FIXME: Future cookie-blacklisting code
48 # m = BadCookie.query.filter_by(cookie = cookie)
49 # if m:
50 # _log.warn("Bad cookie received: %s", m.reason)
51 # raise BadRequest()
52 try:
53 return Session(self.signer.loads(cookie))
54 except itsdangerous.BadData:
55 return Session()
56
57 def save_session_to_cookie(self, session, response):
58 if not session.is_updated:
59 return
627a721c
BS
60 elif not session:
61 response.delete_cookie(self.cookie_name)
62 else:
63 response.set_cookie(self.cookie_name, self.signer.dumps(session))