from cryptography.hazmat.backends import default_backend
from cryptography.x509.base import load_pem_x509_certificate
from cryptography.hazmat.primitives.serialization import load_pem_private_key
from django.core.exceptions import ValidationError


# ---------------------------------------------------------------------------
def validate_key(value: str) -> None:
    """
    Validate that the path to the certificate contains a valid key
    """
    with open(value, 'rb') as key:
        try:
            load_pem_private_key(key.read(), password=None, backend=default_backend())
        except (ValueError, FileNotFoundError):
            raise ValidationError(f'{value} is not a valid key') from None


# ---------------------------------------------------------------------------
def validate_certificate(value: str) -> None:
    """
    Validate that the path to the certificate contains a valid certificate
    """
    with open(value, 'rb') as cert:
        try:
            load_pem_x509_certificate(cert.read(), backend=default_backend())
        except (ValueError, FileNotFoundError):
            raise ValidationError(f'{value} is not a valid certificate') from None


__all__ = (
    'validate_key',
    'validate_certificate',
)
