import uuid
from urllib.parse import  urlparse

from solo.vendor.old_session.old_session import get_session


class SessionCSRFStoragePolicy:
    """ Taken from
    https://github.com/Pylons/pyramid/blob/3ee04cc62205b10eb9041b0df5e156936765202f/pyramid/csrf.py#L57

    A CSRF storage policy that persists the CSRF token in the session.

    Note that using this CSRF implementation requires that
    a :term:`session factory` is configured.

    ``key``

        The session key where the CSRF token will be stored.
        Default: `_csrft_`.

    """
    _token_factory = staticmethod(lambda: uuid.uuid4().hex)

    def __init__(self, key: str = '_csrft_') -> None:
        self.key = key

    async def new_csrf_token(self, request):
        """ Sets a new CSRF token into the session and returns it. """
        session = await get_session(request)
        token = self._token_factory()
        session[self.key] = token
        return token

    async def get_csrf_token(self, request):
        """ Returns the currently active CSRF token from the session,
        generating a new one if needed."""
        session = await get_session(request)
        token = session.get(self.key, None)
        if not token:
            token = await self.new_csrf_token(request)