Merge branch 'pre-auth' into basic_auth
[mediagoblin.git] / mediagoblin / tools / session.py
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
17 import itsdangerous
18 import logging
19
20 import crypto
21
22 _log = logging.getLogger(__name__)
23
24 class Session(dict):
25 def __init__(self, *args, **kwargs):
26 self.send_new_cookie = False
27 dict.__init__(self, *args, **kwargs)
28
29 def save(self):
30 self.send_new_cookie = True
31
32 def is_updated(self):
33 return self.send_new_cookie
34
35 def delete(self):
36 self.clear()
37 self.save()
38
39
40 class SessionManager(object):
41 def __init__(self, cookie_name='MGSession', namespace=None):
42 if namespace is None:
43 namespace = cookie_name
44 self.signer = crypto.get_timed_signer_url(namespace)
45 self.cookie_name = cookie_name
46
47 def load_session_from_cookie(self, request):
48 cookie = request.cookies.get(self.cookie_name)
49 if not cookie:
50 return Session()
51 ### FIXME: Future cookie-blacklisting code
52 # m = BadCookie.query.filter_by(cookie = cookie)
53 # if m:
54 # _log.warn("Bad cookie received: %s", m.reason)
55 # raise BadRequest()
56 try:
57 return Session(self.signer.loads(cookie))
58 except itsdangerous.BadData:
59 return Session()
60
61 def save_session_to_cookie(self, session, request, response):
62 if not session.is_updated():
63 return
64 elif not session:
65 response.delete_cookie(self.cookie_name)
66 else:
67 response.set_cookie(self.cookie_name, self.signer.dumps(session),
68 httponly=True)