from django.core.cache import cache
from .. import get_setting
from .base import BaseNonceBackend


class DjangoCacheNonceBackend(BaseNonceBackend):
    """
    Nonce backend which uses Django's cache system.

    Simple, but not great. Prone to race conditions.
    """

    def validate_nonce(self, timestamp: int, nonce: str) -> bool:
        """
        Confirm that the given nonce hasn't already been used.
        """
        key = self._create_nonce_key(nonce)
        return not bool(cache.get(key))

    def log_used_nonce(self, timestamp: int, nonce: str) -> None:
        """
        Log a nonce as being used, and therefore henceforth invalid.
        """
        key = self._create_nonce_key(nonce)
        timestamp_tolerance = get_setting('TIMESTAMP_TOLERANCE')
        cache.set(key, True, timestamp_tolerance * 2)  # zuban: ignore[operator]

    def _create_nonce_key(self, nonce: str) -> str:
        """
        Create and return the cache key for storing nonces
        """
        return f"{self.__class__.__name__}-paseto-nonces-{nonce}"
