2016-08-30 17:38:59 +00:00
|
|
|
"""Identity policy for storing info directly into HTTP cookie.
|
2015-11-19 13:25:10 +00:00
|
|
|
|
|
|
|
Use mostly for demonstration purposes, SessionIdentityPolicy is much
|
|
|
|
more handy.
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
2020-12-18 17:58:38 +00:00
|
|
|
from aiohttp import web
|
|
|
|
from typing import Any, NewType, Optional, Union, cast
|
2015-07-08 17:30:24 +00:00
|
|
|
|
2020-12-18 17:58:38 +00:00
|
|
|
from .abc import AbstractIdentityPolicy
|
2015-07-08 17:30:24 +00:00
|
|
|
|
2020-12-18 17:58:38 +00:00
|
|
|
_Sentinel = NewType('_Sentinel', object)
|
|
|
|
sentinel = _Sentinel(object())
|
2015-07-29 20:41:16 +00:00
|
|
|
|
|
|
|
|
2015-07-08 17:30:24 +00:00
|
|
|
class CookiesIdentityPolicy(AbstractIdentityPolicy):
|
|
|
|
|
2020-12-18 17:58:38 +00:00
|
|
|
def __init__(self) -> None:
|
2015-07-08 17:30:24 +00:00
|
|
|
self._cookie_name = 'AIOHTTP_SECURITY'
|
|
|
|
self._max_age = 30 * 24 * 3600
|
|
|
|
|
2020-12-18 17:58:38 +00:00
|
|
|
async def identify(self, request: web.Request) -> Optional[str]:
|
|
|
|
return request.cookies.get(self._cookie_name)
|
2015-07-08 17:30:24 +00:00
|
|
|
|
2020-12-18 17:58:38 +00:00
|
|
|
async def remember(self, request: web.Request, response: web.StreamResponse,
|
|
|
|
identity: str, max_age: Union[_Sentinel, Optional[int]] = sentinel,
|
|
|
|
**kwargs: Any) -> None:
|
2015-07-29 20:41:16 +00:00
|
|
|
if max_age is sentinel:
|
|
|
|
max_age = self._max_age
|
2020-12-18 17:58:38 +00:00
|
|
|
max_age = cast(Optional[int], max_age)
|
2015-07-29 20:58:55 +00:00
|
|
|
response.set_cookie(self._cookie_name, identity,
|
|
|
|
max_age=max_age, **kwargs)
|
2015-07-08 17:30:24 +00:00
|
|
|
|
2020-12-18 17:58:38 +00:00
|
|
|
async def forget(self, request: web.Request, response: web.StreamResponse) -> None:
|
2015-07-29 20:41:16 +00:00
|
|
|
response.del_cookie(self._cookie_name)
|