| 1 |
import warnings |
| 2 |
from datetime import datetime |
| 3 |
from datetime import timedelta as TimeDelta |
| 4 |
from decimal import Decimal |
| 5 |
from typing import Optional |
| 6 |
|
| 7 |
import boto3 |
| 8 |
from mypy_boto3_dynamodb.service_resource import DynamoDBServiceResource |
| 9 |
from flask import Flask |
| 10 |
from itsdangerous import want_bytes |
| 11 |
|
| 12 |
from ..base import ServerSideSession, ServerSideSessionInterface |
| 13 |
from ..defaults import Defaults |
| 14 |
|
| 15 |
|
| 16 |
class DynamoDBSession(ServerSideSession): |
| 17 |
pass |
| 18 |
|
| 19 |
|
| 20 |
class DynamoDBSessionInterface(ServerSideSessionInterface): |
| 21 |
"""A Session interface that uses dynamodb as backend. (`boto3` required) |
| 22 |
|
| 23 |
:param client: A ``DynamoDBServiceResource`` instance. |
| 24 |
:param key_prefix: A prefix that is added to all DynamoDB store keys. |
| 25 |
:param use_signer: Whether to sign the session id cookie or not. |
| 26 |
:param permanent: Whether to use permanent session or not. |
| 27 |
:param sid_length: The length of the generated session id in bytes. |
| 28 |
:param table_name: DynamoDB table name to store the session. |
| 29 |
|
| 30 |
.. versionadded:: 0.6 |
| 31 |
The `sid_length` parameter was added. |
| 32 |
|
| 33 |
.. versionadded:: 0.2 |
| 34 |
The `use_signer` parameter was added. |
| 35 |
""" |
| 36 |
|
| 37 |
session_class = DynamoDBSession |
| 38 |
|
| 39 |
def __init__( |
| 40 |
self, |
| 41 |
app: Flask, |
| 42 |
client: Optional[DynamoDBServiceResource] = Defaults.SESSION_DYNAMODB, |
| 43 |
key_prefix: str = Defaults.SESSION_KEY_PREFIX, |
| 44 |
use_signer: bool = Defaults.SESSION_USE_SIGNER, |
| 45 |
permanent: bool = Defaults.SESSION_PERMANENT, |
| 46 |
sid_length: int = Defaults.SESSION_ID_LENGTH, |
| 47 |
serialization_format: str = Defaults.SESSION_SERIALIZATION_FORMAT, |
| 48 |
table_name: str = Defaults.SESSION_DYNAMODB_TABLE, |
| 49 |
): |
| 50 |
|
| 51 |
if client is None: |
| 52 |
warnings.warn( |
| 53 |
"No valid DynamoDBServiceResource instance provided, attempting to create a new instance on localhost:8000.", |
| 54 |
RuntimeWarning, |
| 55 |
stacklevel=1, |
| 56 |
) |
| 57 |
client = boto3.resource( |
| 58 |
"dynamodb", |
| 59 |
endpoint_url="http://localhost:8000", |
| 60 |
region_name="us-west-2", |
| 61 |
aws_access_key_id="dummy", |
| 62 |
aws_secret_access_key="dummy", |
| 63 |
) |
| 64 |
|
| 65 |
try: |
| 66 |
client.create_table( |
| 67 |
AttributeDefinitions=[ |
| 68 |
{"AttributeName": "id", "AttributeType": "S"}, |
| 69 |
], |
| 70 |
TableName=table_name, |
| 71 |
KeySchema=[ |
| 72 |
{"AttributeName": "id", "KeyType": "HASH"}, |
| 73 |
], |
| 74 |
BillingMode="PAY_PER_REQUEST", |
| 75 |
) |
| 76 |
client.meta.client.get_waiter("table_exists").wait(TableName=table_name) |
| 77 |
client.meta.client.update_time_to_live( |
| 78 |
TableName=self.table_name, |
| 79 |
TimeToLiveSpecification={ |
| 80 |
"Enabled": True, |
| 81 |
"AttributeName": "expiration", |
| 82 |
}, |
| 83 |
) |
| 84 |
except (AttributeError, client.meta.client.exceptions.ResourceInUseException): |
| 85 |
# TTL already exists, or table already exists |
| 86 |
pass |
| 87 |
|
| 88 |
self.client = client |
| 89 |
self.store = client.Table(table_name) |
| 90 |
super().__init__( |
| 91 |
app, |
| 92 |
key_prefix, |
| 93 |
use_signer, |
| 94 |
permanent, |
| 95 |
sid_length, |
| 96 |
serialization_format, |
| 97 |
) |
| 98 |
|
| 99 |
def _retrieve_session_data(self, store_id: str) -> Optional[dict]: |
| 100 |
# Get the saved session (document) from the database |
| 101 |
document = self.store.get_item(Key={"id": store_id}).get("Item") |
| 102 |
if document: |
| 103 |
serialized_session_data = want_bytes(document.get("val").value) |
| 104 |
return self.serializer.decode(serialized_session_data) |
| 105 |
return None |
| 106 |
|
| 107 |
def _delete_session(self, store_id: str) -> None: |
| 108 |
self.store.delete_item(Key={"id": store_id}) |
| 109 |
|
| 110 |
def _upsert_session( |
| 111 |
self, session_lifetime: TimeDelta, session: ServerSideSession, store_id: str |
| 112 |
) -> None: |
| 113 |
storage_expiration_datetime = datetime.utcnow() + session_lifetime |
| 114 |
# Serialize the session data |
| 115 |
serialized_session_data = self.serializer.encode(session) |
| 116 |
|
| 117 |
self.store.update_item( |
| 118 |
Key={ |
| 119 |
"id": store_id, |
| 120 |
}, |
| 121 |
UpdateExpression="SET val = :value, expiration = :exp", |
| 122 |
ExpressionAttributeValues={ |
| 123 |
":value": serialized_session_data, |
| 124 |
":exp": Decimal(storage_expiration_datetime.timestamp()), |
| 125 |
}, |
| 126 |
) |