1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
|
"""User sessions for aiohttp.web."""
__version__ = "2.12.1"
import abc
import json
import time
from typing import (
Any,
Callable,
Dict,
Iterator,
MutableMapping,
Optional,
TypedDict,
Union,
cast,
)
from aiohttp import web
from aiohttp.typedefs import Handler, Middleware
class _CookieParams(TypedDict, total=False):
domain: Optional[str]
max_age: Optional[int]
path: str
secure: Optional[bool]
httponly: bool
samesite: Optional[str]
expires: str
class SessionData(TypedDict, total=False):
created: int
session: Dict[str, Any]
class Session(MutableMapping[str, Any]):
"""Session dict-like object."""
def __init__(
self,
identity: Optional[Any],
*,
data: Optional[SessionData],
new: bool,
max_age: Optional[int] = None,
) -> None:
self._changed: bool = False
self._mapping: Dict[str, Any] = {}
self._identity = identity if data != {} else None
self._new = new if data != {} else True
self._max_age = max_age
created = data.get("created", None) if data else None
session_data = data.get("session", None) if data else None
now = int(time.time())
age = now - created if created else now
if max_age is not None and age > max_age:
session_data = None
if self._new or created is None:
self._created = now
else:
self._created = created
if session_data is not None:
self._mapping.update(session_data)
def __repr__(self) -> str:
return "<{} [new:{}, changed:{}, created:{}] {!r}>".format(
self.__class__.__name__,
self.new,
self._changed,
self.created,
self._mapping,
)
@property
def new(self) -> bool:
return self._new
@property
def identity(self) -> Optional[Any]: # type: ignore[misc]
return self._identity
@property
def created(self) -> int:
return self._created
@property
def empty(self) -> bool:
return not bool(self._mapping)
@property
def max_age(self) -> Optional[int]:
return self._max_age
@max_age.setter
def max_age(self, value: Optional[int]) -> None:
self._max_age = value
def changed(self) -> None:
self._changed = True
def invalidate(self) -> None:
self._changed = True
self._mapping = {}
def set_new_identity(self, identity: Optional[Any]) -> None:
if not self._new:
raise RuntimeError("Can't change identity for a session which is not new")
self._identity = identity
def __len__(self) -> int:
return len(self._mapping)
def __iter__(self) -> Iterator[str]:
return iter(self._mapping)
def __contains__(self, key: object) -> bool:
return key in self._mapping
def __getitem__(self, key: str) -> Any:
return self._mapping[key]
def __setitem__(self, key: str, value: Any) -> None:
self._mapping[key] = value
self._changed = True
self._created = int(time.time())
def __delitem__(self, key: str) -> None:
del self._mapping[key]
self._changed = True
self._created = int(time.time())
SESSION_KEY = "aiohttp_session"
STORAGE_KEY = "aiohttp_session_storage"
async def get_session(request: web.Request) -> Session:
session = request.get(SESSION_KEY)
if session is None:
storage = request.get(STORAGE_KEY)
if storage is None:
raise RuntimeError(
"Install aiohttp_session middleware " "in your aiohttp.web.Application"
)
session = await storage.load_session(request)
if not isinstance(session, Session):
raise RuntimeError(
"Installed {!r} storage should return session instance "
"on .load_session() call, got {!r}.".format(storage, session)
)
request[SESSION_KEY] = session
return session
async def new_session(request: web.Request) -> Session:
storage = request.get(STORAGE_KEY)
if storage is None:
raise RuntimeError(
"Install aiohttp_session middleware " "in your aiohttp.web.Application"
)
session = await storage.new_session()
if not isinstance(session, Session):
raise RuntimeError(
"Installed {!r} storage should return session instance "
"on .load_session() call, got {!r}.".format(storage, session)
)
request[SESSION_KEY] = session
return session
def session_middleware(storage: "AbstractStorage") -> Middleware:
if not isinstance(storage, AbstractStorage):
raise RuntimeError(f"Expected AbstractStorage got {storage}")
@web.middleware
async def factory(request: web.Request, handler: Handler) -> web.StreamResponse:
request[STORAGE_KEY] = storage
raise_response = False
# TODO aiohttp 4:
# Remove Union from response, and drop the raise_response variable
response: Union[web.StreamResponse, web.HTTPException]
try:
response = await handler(request)
except web.HTTPException as exc:
response = exc
raise_response = True
if not isinstance(response, (web.StreamResponse, web.HTTPException)):
raise RuntimeError(f"Expect response, not {type(response)!r}")
if not isinstance(response, (web.Response, web.HTTPException)):
# likely got websocket or streaming
return response
if response.prepared:
raise RuntimeError("Cannot save session data into prepared response")
session = request.get(SESSION_KEY)
if session is not None:
if session._changed:
await storage.save_session(request, response, session)
if raise_response:
raise cast(web.HTTPException, response)
return response
return factory
def setup(app: web.Application, storage: "AbstractStorage") -> None:
"""Setup the library in aiohttp fashion."""
app.middlewares.append(session_middleware(storage))
class AbstractStorage(metaclass=abc.ABCMeta):
def __init__(
self,
*,
cookie_name: str = "AIOHTTP_SESSION",
domain: Optional[str] = None,
max_age: Optional[int] = None,
path: str = "/",
secure: Optional[bool] = None,
httponly: bool = True,
samesite: Optional[str] = None,
encoder: Callable[[object], str] = json.dumps,
decoder: Callable[[str], Any] = json.loads,
) -> None:
self._cookie_name = cookie_name
self._cookie_params = _CookieParams(
domain=domain,
max_age=max_age,
path=path,
secure=secure,
httponly=httponly,
samesite=samesite,
)
self._max_age = max_age
self._encoder = encoder
self._decoder = decoder
@property
def cookie_name(self) -> str:
return self._cookie_name
@property
def max_age(self) -> Optional[int]:
return self._max_age
@property
def cookie_params(self) -> _CookieParams:
return self._cookie_params
def _get_session_data(self, session: Session) -> SessionData:
if session.empty:
return {}
return {"created": session.created, "session": session._mapping}
async def new_session(self) -> Session:
return Session(None, data=None, new=True, max_age=self.max_age)
@abc.abstractmethod
async def load_session(self, request: web.Request) -> Session:
pass
@abc.abstractmethod
async def save_session(
self, request: web.Request, response: web.StreamResponse, session: Session
) -> None:
pass
def load_cookie(self, request: web.Request) -> Optional[str]:
return request.cookies.get(self._cookie_name)
def save_cookie(
self,
response: web.StreamResponse,
cookie_data: str,
*,
max_age: Optional[int] = None,
) -> None:
params = self._cookie_params.copy()
if max_age is not None:
params["max_age"] = max_age
t = time.gmtime(time.time() + max_age)
params["expires"] = time.strftime("%a, %d-%b-%Y %T GMT", t)
if not cookie_data:
response.del_cookie(
self._cookie_name, domain=params["domain"], path=params["path"]
)
else:
response.set_cookie(self._cookie_name, cookie_data, **params)
class SimpleCookieStorage(AbstractStorage):
"""Simple JSON storage.
Doesn't any encryption/validation, use it for tests only"""
def __init__(
self,
*,
cookie_name: str = "AIOHTTP_SESSION",
domain: Optional[str] = None,
max_age: Optional[int] = None,
path: str = "/",
secure: Optional[bool] = None,
httponly: bool = True,
samesite: Optional[str] = None,
encoder: Callable[[object], str] = json.dumps,
decoder: Callable[[str], Any] = json.loads,
) -> None:
super().__init__(
cookie_name=cookie_name,
domain=domain,
max_age=max_age,
path=path,
secure=secure,
httponly=httponly,
samesite=samesite,
encoder=encoder,
decoder=decoder,
)
async def load_session(self, request: web.Request) -> Session:
cookie = self.load_cookie(request)
if cookie is None:
return Session(None, data=None, new=True, max_age=self.max_age)
data = self._decoder(cookie)
return Session(None, data=data, new=False, max_age=self.max_age)
async def save_session(
self, request: web.Request, response: web.StreamResponse, session: Session
) -> None:
cookie_data = self._encoder(self._get_session_data(session))
self.save_cookie(response, cookie_data, max_age=session.max_age)
|