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
Provenance
- Commit
3f82d1b- Tree
1d90006- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
704d94d
2 files changed+44 added−59 removed
modified:flask/sessions.py+42 added-58 removed
8 unmodified lines9 :copyright: (c) 2011 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11 """12 13-import cPickle as pickle13 from datetime import datetime15-from werkzeug.contrib.securecookie import SecureCookie14 from werkzeug.http import http_date, parse_date17-from .helpers import json, _assert_have_json15+from werkzeug.datastructures import CallbackDict16+from .helpers import json17 from . import Markup18 19+from itsdangerous import URLSafeTimedSerializer, BadSignature20 21+22 class SessionMixin(object):23 """Expands a basic dictionary with an accessors that are expected24 by Flask extensions and users for the session.25 """25 unmodified lines51 we take for granted when serializing (tuples, markup objects, datetime).52 """53 54 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 lines66 return value67 return json.dumps(_tag(value), separators=(',', ':'))68 69 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 lines83 84 session_json_serializer = TaggedJSONSerializer()85 86 90-class 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_serializer87+class SecureCookieSession(CallbackDict, SessionMixin):88+ """Baseclass for sessions based on signed cookies."""89 90+ def __init__(self, initial=None):91+ def on_update(self):92+ self.modified = True93+ CallbackDict.__init__(self, initial, on_update)94+ self.modified = False95 98-class _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)96 107-108-class 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.112-113- .. versionadded:: 0.10114- """115- serialization_method = _UpgradeSerializer()116-117-97 class 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 lines224 raise NotImplementedError()225 226 227 class 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_serializer231 232+ 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)238+239 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()252 253 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)274-275-276-class 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.280-281- .. 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 lines90 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