From 4442577b0bb4e1e4f03eb9b82e2da4c3d54331c2 Mon Sep 17 00:00:00 2001 From: Matt Scott Date: Fri, 24 Nov 2023 06:26:38 -0500 Subject: [PATCH] Created a new model to represent the Flask-Session storage schema `sessions` with a method for removing expired sessions. Added a trigger for the Flask-Session model's session clean-up method to the `before_request` handler of the user router. --- powerdnsadmin/models/sessions.py | 39 ++++++++++++++++++++++++++++++++ powerdnsadmin/routes/user.py | 5 ++++ 2 files changed, 44 insertions(+) create mode 100644 powerdnsadmin/models/sessions.py diff --git a/powerdnsadmin/models/sessions.py b/powerdnsadmin/models/sessions.py new file mode 100644 index 0000000..b699a3d --- /dev/null +++ b/powerdnsadmin/models/sessions.py @@ -0,0 +1,39 @@ +from flask import current_app, session +from flask_login import current_user +from .base import db + + +class Sessions(db.Model): + id = db.Column(db.Integer, primary_key=True) + session_id = db.Column(db.String(255), index=True, unique=True) + data = db.Column(db.BLOB) + expiry = db.Column(db.DateTime) + + def __init__(self, + id=None, + session_id=None, + data=None, + expiry=None): + self.id = id + self.session_id = session_id + self.data = data + self.expiry = expiry + + def __repr__(self): + return ''.format(self.id) + + @staticmethod + def clean_up_expired_sessions(): + """Clean up expired sessions in the database""" + from datetime import datetime + from sqlalchemy import or_ + from sqlalchemy.exc import SQLAlchemyError + + try: + db.session.query(Sessions).filter(or_(Sessions.expiry < datetime.now(), Sessions.expiry is None)).delete() + db.session.commit() + except SQLAlchemyError as e: + db.session.rollback() + current_app.logger.error(e) + return False + return True diff --git a/powerdnsadmin/routes/user.py b/powerdnsadmin/routes/user.py index adba502..469b459 100644 --- a/powerdnsadmin/routes/user.py +++ b/powerdnsadmin/routes/user.py @@ -37,6 +37,11 @@ def before_request(): minutes=int(Setting().get('session_timeout'))) session.modified = True + # Clean up expired sessions in the database + if Setting().get('session_type') == 'sqlalchemy': + from ..models.sessions import Sessions + Sessions().clean_up_expired_sessions() + @user_bp.route('/profile', methods=['GET', 'POST']) @login_required