mirror of
https://github.com/GSA/notifications-admin.git
synced 2026-02-05 02:42:26 -05:00
108536490: Use ItsDangerousSessionInterface in the app.
Start using http://flask.pocoo.org/snippets/51/
This commit is contained in:
@@ -9,6 +9,7 @@ from flask_wtf import CsrfProtect
|
||||
from webassets.filter import get_filter
|
||||
from werkzeug.exceptions import abort
|
||||
|
||||
from app.its_dangerous_session import ItsdangerousSessionInterface
|
||||
from config import configs
|
||||
|
||||
db = SQLAlchemy()
|
||||
@@ -31,6 +32,7 @@ def create_app(config_name):
|
||||
from app.main import main as main_blueprint
|
||||
application.register_blueprint(main_blueprint)
|
||||
|
||||
application.session_interface = ItsdangerousSessionInterface()
|
||||
return application
|
||||
|
||||
|
||||
|
||||
50
app/its_dangerous_session.py
Normal file
50
app/its_dangerous_session.py
Normal file
@@ -0,0 +1,50 @@
|
||||
from werkzeug.datastructures import CallbackDict
|
||||
from flask.sessions import SessionInterface, SessionMixin
|
||||
from itsdangerous import URLSafeTimedSerializer, BadSignature
|
||||
|
||||
|
||||
class ItsdangerousSession(CallbackDict, SessionMixin):
|
||||
|
||||
def __init__(self, initial=None):
|
||||
def on_update(self):
|
||||
self.modified = True
|
||||
CallbackDict.__init__(self, initial, on_update)
|
||||
self.modified = False
|
||||
|
||||
|
||||
class ItsdangerousSessionInterface(SessionInterface):
|
||||
salt = 'cookie-session'
|
||||
session_class = ItsdangerousSession
|
||||
|
||||
def get_serializer(self, app):
|
||||
if not app.secret_key:
|
||||
return None
|
||||
return URLSafeTimedSerializer(app.secret_key,
|
||||
salt=self.salt)
|
||||
|
||||
def open_session(self, app, request):
|
||||
s = self.get_serializer(app)
|
||||
if s is None:
|
||||
return None
|
||||
val = request.cookies.get(app.session_cookie_name)
|
||||
if not val:
|
||||
return self.session_class()
|
||||
max_age = app.permanent_session_lifetime.total_seconds()
|
||||
try:
|
||||
data = s.loads(val, max_age=max_age)
|
||||
return self.session_class(data)
|
||||
except BadSignature:
|
||||
return self.session_class()
|
||||
|
||||
def save_session(self, app, session, response):
|
||||
domain = self.get_cookie_domain(app)
|
||||
if not session:
|
||||
if session.modified:
|
||||
response.delete_cookie(app.session_cookie_name,
|
||||
domain=domain)
|
||||
return
|
||||
expires = self.get_expiration_time(app, session)
|
||||
val = self.get_serializer(app).dumps(dict(session))
|
||||
response.set_cookie(app.session_cookie_name, val,
|
||||
expires=expires, httponly=True,
|
||||
domain=domain)
|
||||
Reference in New Issue
Block a user