| 1 |
import warnings |
| 2 |
from datetime import datetime |
| 3 |
from datetime import timedelta as TimeDelta |
| 4 |
from typing import Optional |
| 5 |
|
| 6 |
from flask import Flask |
| 7 |
from itsdangerous import want_bytes |
| 8 |
from pymongo import MongoClient, version |
| 9 |
|
| 10 |
from ..base import ServerSideSession, ServerSideSessionInterface |
| 11 |
from ..defaults import Defaults |
| 12 |
|
| 13 |
|
| 14 |
class MongoDBSession(ServerSideSession): |
| 15 |
pass |
| 16 |
|
| 17 |
|
| 18 |
class MongoDBSessionInterface(ServerSideSessionInterface): |
| 19 |
"""A Session interface that uses mongodb as session storage. (`pymongo` required) |
| 20 |
|
| 21 |
:param client: A ``pymongo.MongoClient`` instance. |
| 22 |
:param key_prefix: A prefix that is added to all storage keys. |
| 23 |
:param use_signer: Whether to sign the session id cookie or not. |
| 24 |
:param permanent: Whether to use permanent session or not. |
| 25 |
:param sid_length: The length of the generated session id in bytes. |
| 26 |
:param serialization_format: The serialization format to use for the session data. |
| 27 |
:param db: The database to use. |
| 28 |
:param collection: The collection to use. |
| 29 |
|
| 30 |
.. versionadded:: 0.7 |
| 31 |
The `serialization_format` and `app` parameters were added. |
| 32 |
|
| 33 |
.. versionadded:: 0.6 |
| 34 |
The `sid_length` parameter was added. |
| 35 |
|
| 36 |
.. versionadded:: 0.2 |
| 37 |
The `use_signer` parameter was added. |
| 38 |
""" |
| 39 |
|
| 40 |
session_class = MongoDBSession |
| 41 |
ttl = True |
| 42 |
|
| 43 |
def __init__( |
| 44 |
self, |
| 45 |
app: Flask, |
| 46 |
client: Optional[MongoClient] = Defaults.SESSION_MONGODB, |
| 47 |
key_prefix: str = Defaults.SESSION_KEY_PREFIX, |
| 48 |
use_signer: bool = Defaults.SESSION_USE_SIGNER, |
| 49 |
permanent: bool = Defaults.SESSION_PERMANENT, |
| 50 |
sid_length: int = Defaults.SESSION_ID_LENGTH, |
| 51 |
serialization_format: str = Defaults.SESSION_SERIALIZATION_FORMAT, |
| 52 |
db: str = Defaults.SESSION_MONGODB_DB, |
| 53 |
collection: str = Defaults.SESSION_MONGODB_COLLECT, |
| 54 |
): |
| 55 |
|
| 56 |
if client is None or not isinstance(client, MongoClient): |
| 57 |
warnings.warn( |
| 58 |
"No valid MongoClient instance provided, attempting to create a new instance on localhost with default settings.", |
| 59 |
RuntimeWarning, |
| 60 |
stacklevel=1, |
| 61 |
) |
| 62 |
client = MongoClient() |
| 63 |
|
| 64 |
self.client = client |
| 65 |
self.store = client[db][collection] |
| 66 |
self.use_deprecated_method = int(version.split(".")[0]) < 4 |
| 67 |
|
| 68 |
# Create a TTL index on the expiration time, so that mongo can automatically delete expired sessions |
| 69 |
self.store.create_index("expiration", expireAfterSeconds=0) |
| 70 |
|
| 71 |
super().__init__( |
| 72 |
app, key_prefix, use_signer, permanent, sid_length, serialization_format |
| 73 |
) |
| 74 |
|
| 75 |
def _retrieve_session_data(self, store_id: str) -> Optional[dict]: |
| 76 |
# Get the saved session (document) from the database |
| 77 |
document = self.store.find_one({"id": store_id}) |
| 78 |
if document: |
| 79 |
serialized_session_data = want_bytes(document["val"]) |
| 80 |
return self.serializer.decode(serialized_session_data) |
| 81 |
return None |
| 82 |
|
| 83 |
def _delete_session(self, store_id: str) -> None: |
| 84 |
if self.use_deprecated_method: |
| 85 |
self.store.remove({"id": store_id}) |
| 86 |
else: |
| 87 |
self.store.delete_one({"id": store_id}) |
| 88 |
|
| 89 |
def _upsert_session( |
| 90 |
self, session_lifetime: TimeDelta, session: ServerSideSession, store_id: str |
| 91 |
) -> None: |
| 92 |
storage_expiration_datetime = datetime.utcnow() + session_lifetime |
| 93 |
|
| 94 |
# Serialize the session data |
| 95 |
serialized_session_data = self.serializer.encode(session) |
| 96 |
|
| 97 |
# Update existing or create new session in the database |
| 98 |
if self.use_deprecated_method: |
| 99 |
self.store.update( |
| 100 |
{"id": store_id}, |
| 101 |
{ |
| 102 |
"id": store_id, |
| 103 |
"val": serialized_session_data, |
| 104 |
"expiration": storage_expiration_datetime, |
| 105 |
}, |
| 106 |
True, |
| 107 |
) |
| 108 |
else: |
| 109 |
self.store.update_one( |
| 110 |
{"id": store_id}, |
| 111 |
{ |
| 112 |
"$set": { |
| 113 |
"id": store_id, |
| 114 |
"val": serialized_session_data, |
| 115 |
"expiration": storage_expiration_datetime, |
| 116 |
} |
| 117 |
}, |
| 118 |
True, |
| 119 |
) |