|
| 1 | +""" |
| 2 | +A Flask SessionInterface implementing server-side sessions stored in SQLAlchemy |
| 3 | +""" |
| 4 | +import base64 |
| 5 | +import os |
| 6 | +from datetime import datetime, timezone |
| 7 | +from typing import Callable, Protocol, Optional, Type, Dict, Any |
| 8 | + |
| 9 | +from flask import Flask, Response, Request, current_app |
| 10 | +from flask.json.tag import TaggedJSONSerializer |
| 11 | +from flask.sessions import SessionInterface, SessionMixin |
| 12 | +from sqlalchemy.orm import Session |
| 13 | +from werkzeug.datastructures import CallbackDict |
| 14 | + |
| 15 | + |
| 16 | +class UserSessionTableProtocol(Protocol): |
| 17 | + """ |
| 18 | + Defines the minimum set of fields necessary for a declarative SQLAlchemy model to work with the SessionInterface |
| 19 | + """ |
| 20 | + |
| 21 | + id: str |
| 22 | + session_id: str |
| 23 | + expires_at: datetime |
| 24 | + data: str |
| 25 | + user_id: Optional[str] |
| 26 | + |
| 27 | + |
| 28 | +class SerializerProtocol(Protocol): |
| 29 | + def dumps(self, value: Dict[Any, Any]) -> str: |
| 30 | + pass |
| 31 | + |
| 32 | + def loads(self, value: str) -> Dict[Any, Any]: |
| 33 | + pass |
| 34 | + |
| 35 | + |
| 36 | +def default_mint_session_id() -> str: |
| 37 | + return str(base64.b32encode(os.urandom(30)), encoding="utf8") |
| 38 | + |
| 39 | + |
| 40 | +class ServerSideSession(CallbackDict, SessionMixin): |
| 41 | + """Baseclass for server-side based sessions.""" |
| 42 | + |
| 43 | + def __init__(self, sid: str, initial: Optional[Dict[Any, Any]] = None, permanent: Optional[bool] = None) -> None: |
| 44 | + def on_update(s: ServerSideSession) -> None: |
| 45 | + s.modified = True |
| 46 | + |
| 47 | + super().__init__(initial, on_update) |
| 48 | + self.sid = sid |
| 49 | + self.modified = False |
| 50 | + if permanent: |
| 51 | + self.permanent = permanent |
| 52 | + |
| 53 | + |
| 54 | +class SQLAlchemySessionInterface(SessionInterface): |
| 55 | + session_class = ServerSideSession |
| 56 | + |
| 57 | + def __init__( |
| 58 | + self, |
| 59 | + orm_session: Session, |
| 60 | + sql_session_model: Type, |
| 61 | + make_id: Callable[[], str], |
| 62 | + make_session_id: Callable[[], str] = default_mint_session_id, |
| 63 | + permanent: Optional[bool] = None, |
| 64 | + serializer: Optional[SerializerProtocol] = None, |
| 65 | + ): |
| 66 | + self.permanent = permanent |
| 67 | + self.make_id = make_id |
| 68 | + self.make_session_id = make_session_id |
| 69 | + if serializer is None: |
| 70 | + serializer = TaggedJSONSerializer() |
| 71 | + self.serializer = serializer |
| 72 | + self.orm_session = orm_session |
| 73 | + self.sql_session_model = sql_session_model |
| 74 | + |
| 75 | + def open_session(self, app: Flask, request: Request): |
| 76 | + """This method has to be implemented and must either return ``None`` |
| 77 | + in case the loading failed because of a configuration error or an |
| 78 | + instance of a session object which implements a dictionary like |
| 79 | + interface + the methods and attributes on :class:`SessionMixin`. |
| 80 | + """ |
| 81 | + sid = request.cookies.get(app.session_cookie_name) |
| 82 | + if not sid: |
| 83 | + sid = self.make_session_id() |
| 84 | + return self.session_class(sid=sid, permanent=self.permanent) |
| 85 | + |
| 86 | + saved_session = ( |
| 87 | + self.orm_session.query(self.sql_session_model).filter(self.sql_session_model.session_id == sid).first() |
| 88 | + ) |
| 89 | + if saved_session and saved_session.expires_at <= datetime.now(timezone.utc): |
| 90 | + # delete the saved session if it has expired |
| 91 | + self.orm_session.delete(saved_session) |
| 92 | + self.orm_session.commit() |
| 93 | + saved_session = None |
| 94 | + |
| 95 | + if saved_session: |
| 96 | + try: |
| 97 | + json_data = saved_session.data |
| 98 | + data = self.serializer.loads(json_data) |
| 99 | + return self.session_class(sid=sid, initial=data) |
| 100 | + except Exception: |
| 101 | + return self.session_class(sid=self.make_session_id(), permanent=self.permanent) |
| 102 | + |
| 103 | + return self.session_class(sid=sid, permanent=self.permanent) |
| 104 | + |
| 105 | + def save_session(self, app: Flask, session: ServerSideSession, response: Response) -> None: |
| 106 | + """This is called for actual sessions returned by :meth:`open_session` |
| 107 | + at the end of the request. This is still called during a request |
| 108 | + context so if you absolutely need access to the request you can do |
| 109 | + that. |
| 110 | + """ |
| 111 | + domain = self.get_cookie_domain(app) |
| 112 | + path = self.get_cookie_path(app) |
| 113 | + sid = session.sid |
| 114 | + saved_session = ( |
| 115 | + self.orm_session.query(self.sql_session_model).filter(self.sql_session_model.session_id == sid).first() |
| 116 | + ) |
| 117 | + if not session: |
| 118 | + if session.modified: |
| 119 | + if saved_session: |
| 120 | + self.orm_session.delete(saved_session) |
| 121 | + self.orm_session.commit() |
| 122 | + response.delete_cookie(app.session_cookie_name, domain=domain, path=path) |
| 123 | + return |
| 124 | + |
| 125 | + if not self.should_set_cookie(app, session): |
| 126 | + return |
| 127 | + |
| 128 | + httponly = self.get_cookie_httponly(app) |
| 129 | + secure = self.get_cookie_secure(app) |
| 130 | + expires = self.get_expiration_time(app, session) |
| 131 | + |
| 132 | + val = self.serializer.dumps(dict(session)) |
| 133 | + if saved_session: |
| 134 | + saved_session.data = val |
| 135 | + saved_session.expiry = expires |
| 136 | + self.orm_session.commit() |
| 137 | + else: |
| 138 | + new_session: UserSessionTableProtocol = self.sql_session_model( |
| 139 | + id=self.make_id(), session_id=session.sid, data=val, expires_at=expires |
| 140 | + ) |
| 141 | + self.orm_session.add(new_session) |
| 142 | + self.orm_session.commit() |
| 143 | + |
| 144 | + session_id = session.sid |
| 145 | + response.set_cookie( |
| 146 | + app.session_cookie_name, |
| 147 | + session_id, |
| 148 | + expires=expires, |
| 149 | + httponly=httponly, |
| 150 | + domain=domain, |
| 151 | + path=path, |
| 152 | + secure=secure, |
| 153 | + samesite=current_app.config.get("SESSION_COOKIE_SAMESITE", "Strict"), |
| 154 | + ) |
0 commit comments