Skip to content
Myr

Switch to itsdangerous

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent 704d94d · Browse files · 2 files+44 added−59 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+44 added−59 removed

  • other:+44 added−59 removed

2 files+44 added−59 removed

modified:flask/sessions.py+42 added-58 removed
8 unmodified lines
9 :copyright: (c) 2011 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""1213import cPickle as pickle13from datetime import datetime15from werkzeug.contrib.securecookie import SecureCookie14from werkzeug.http import http_date, parse_date17from .helpers import json, _assert_have_json15from werkzeug.datastructures import CallbackDict16from .helpers import json17from . import Markup1819from itsdangerous import URLSafeTimedSerializer, BadSignature202122class SessionMixin(object):23 """Expands a basic dictionary with an accessors that are expected24 by Flask extensions and users for the session.25 """
25 unmodified lines
51 we take for granted when serializing (tuples, markup objects, datetime).52 """5354 def dumps(self, value):54 if __debug__:55 _assert_have_json()55 def _tag(value):56 if isinstance(value, tuple):57 return {'##t': [_tag(x) for x in value]}58 elif callable(getattr(value, '__html__', None)):
7 unmodified lines
66 return value67 return json.dumps(_tag(value), separators=(',', ':'))6869 def loads(self, value):71 if __debug__:72 _assert_have_json()70 def object_hook(obj):71 if len(obj) != 1:72 return obj73 the_key, the_value = obj.iteritems().next()
9 unmodified lines
8384session_json_serializer = TaggedJSONSerializer()858690class SecureCookieSession(SecureCookie, SessionMixin):91 """Expands the session with support for switching between permanent92 and non-permanent sessions and changes the default pickle based93 serialization format to a tagged json one.94 """95 serialization_method = session_json_serializer87class SecureCookieSession(CallbackDict, SessionMixin):88 """Baseclass for sessions based on signed cookies."""8990 def __init__(self, initial=None):91 def on_update(self):92 self.modified = True93 CallbackDict.__init__(self, initial, on_update)94 self.modified = False9598class _UpgradeSerializer(object):99 def dumps(self, value):100 return session_json_serializer.dumps(value)101 def loads(self, value):102 try:103 return session_json_serializer.loads(value)104 except Exception:105 return pickle.loads(value)96107108class UpgradeSecureCookieSession(SecureCookieSession):109 """This cookie sesion implementation tries json first but will also110 support pickle based session. This exists mainly to upgrade existing111 pickle based users transparently to json.112113 .. versionadded:: 0.10114 """115 serialization_method = _UpgradeSerializer()11611797class NullSession(SecureCookieSession):98 """Class used to generate nicer error messages if sessions are not99 available. Will still allow read-only access to the empty session100 but fail on setting.
123 unmodified lines
224 raise NotImplementedError()225226227class SecureCookieSessionInterface(SessionInterface):249 """The cookie session interface that uses the Werkzeug securecookie250 as client side session backend.251 """228 salt = 'cookie-session'229 session_class = SecureCookieSession230 serializer = session_json_serializer231232 def get_serializer(self, app):233 if not app.secret_key:234 return None235 return URLSafeTimedSerializer(app.secret_key,236 salt=self.salt,237 serializer=self.serializer)238239 def open_session(self, app, request):255 key = app.secret_key256 if key is not None:257 return self.session_class.load_cookie(request,258 app.session_cookie_name,259 secret_key=key)240 s = self.get_serializer(app)241 if s is None:242 return None243 val = request.cookies.get(app.session_cookie_name)244 if not val:245 return self.session_class()246 max_age = app.permanent_session_lifetime.total_seconds()247 try:248 data = s.loads(val, max_age=max_age)249 return self.session_class(data)250 except BadSignature:251 return self.session_class()252253 def save_session(self, app, session, response):262 expires = self.get_expiration_time(app, session)254 domain = self.get_cookie_domain(app)255 path = self.get_cookie_path(app)256 httponly = self.get_cookie_httponly(app)257 secure = self.get_cookie_secure(app)267 if session.modified and not session:268 response.delete_cookie(app.session_cookie_name, path=path,269 domain=domain)270 else:271 session.save_cookie(response, app.session_cookie_name, path=path,272 expires=expires, httponly=httponly,273 secure=secure, domain=domain)274275276class UpgradeSecureCookieSessionInterface(SecureCookieSessionInterface):277 """This session interface works exactly like the regular one but uses278 the :class:`UpgradeSecureCookieSession` classes to upgrade from pickle279 sessions to JSON sessions.280281 .. versionadded:: 0.10282 """283 session_class = UpgradeSecureCookieSession258 if not session:259 if session.modified:260 response.delete_cookie(app.session_cookie_name,261 domain=domain, path=path)262 return263 expires = self.get_expiration_time(app, session)264 val = self.get_serializer(app).dumps(dict(session))265 response.set_cookie(app.session_cookie_name, val,266 expires=expires, httponly=httponly,267 domain=domain, path=path, secure=secure)
modified:setup.py+2 added-1 removed
89 unmodified lines
90 zip_safe=False,91 platforms='any',92 install_requires=[93 'Werkzeug>=0.7',94 'Jinja2>=2.4'94 'Jinja2>=2.4',95 'itsdangerous>=0.16'96 ],97 classifiers=[98 'Development Status :: 4 - Beta',99 'Environment :: Web Environment',
13 unmodified lines