File: cookies_identity.py

package info (click to toggle)
python-aiohttp-security 0.5.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 416 kB
  • sloc: python: 1,133; makefile: 193
file content (37 lines) | stat: -rw-r--r-- 1,226 bytes parent folder | download
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
"""Identity policy for storing info directly into HTTP cookie.

Use mostly for demonstration purposes, SessionIdentityPolicy is much
more handy.

"""

from typing import Any, NewType, Optional, Union, cast

from aiohttp import web

from .abc import AbstractIdentityPolicy

_Sentinel = NewType("_Sentinel", object)
sentinel = _Sentinel(object())


class CookiesIdentityPolicy(AbstractIdentityPolicy):

    def __init__(self) -> None:
        self._cookie_name = 'AIOHTTP_SECURITY'
        self._max_age = 30 * 24 * 3600

    async def identify(self, request: web.Request) -> Optional[str]:
        return request.cookies.get(self._cookie_name)

    async def remember(self, request: web.Request, response: web.StreamResponse,
                       identity: str, max_age: Union[_Sentinel, Optional[int]] = sentinel,
                       **kwargs: Any) -> None:
        if max_age is sentinel:
            max_age = self._max_age
        max_age = cast(Optional[int], max_age)
        response.set_cookie(self._cookie_name, identity,
                            max_age=max_age, **kwargs)

    async def forget(self, request: web.Request, response: web.StreamResponse) -> None:
        response.del_cookie(self._cookie_name)