| 
 | 1 | +"""  | 
 | 2 | +© Ocado Group  | 
 | 3 | +Created on 12/08/2025 at 10:28:24(+01:00).  | 
 | 4 | +"""  | 
 | 5 | + | 
 | 6 | +import typing as t  | 
 | 7 | + | 
 | 8 | +from cryptography.fernet import Fernet  | 
 | 9 | +from django.conf import settings  | 
 | 10 | +from django.db import models  | 
 | 11 | + | 
 | 12 | + | 
 | 13 | +class EncryptedCharField(models.CharField):  | 
 | 14 | +    """  | 
 | 15 | +    A custom CharField that encrypts data before saving and decrypts it when  | 
 | 16 | +    retrieved.  | 
 | 17 | +    """  | 
 | 18 | + | 
 | 19 | +    _fernet = Fernet(settings.SECRET_KEY)  | 
 | 20 | +    _prefix = "ENC:"  | 
 | 21 | + | 
 | 22 | +    def __init__(self, *args, **kwargs):  | 
 | 23 | +        kwargs["max_length"] += len(self._prefix)  | 
 | 24 | +        super().__init__(*args, **kwargs)  | 
 | 25 | + | 
 | 26 | +    # pylint: disable-next=unused-argument  | 
 | 27 | +    def from_db_value(self, value: t.Optional[str], expression, connection):  | 
 | 28 | +        """  | 
 | 29 | +        Converts a value as returned by the database to a Python object. It is  | 
 | 30 | +        the reverse of get_prep_value().  | 
 | 31 | +
  | 
 | 32 | +        https://docs.djangoproject.com/en/5.1/howto/custom-model-fields/#converting-values-to-python-objects  | 
 | 33 | +        """  | 
 | 34 | +        if isinstance(value, str):  | 
 | 35 | +            return self.decrypt_value(value)  | 
 | 36 | +        return value  | 
 | 37 | + | 
 | 38 | +    def to_python(self, value: t.Optional[str]):  | 
 | 39 | +        """  | 
 | 40 | +        Converts the value into the correct Python object. It acts as the  | 
 | 41 | +        reverse of value_to_string(), and is also called in clean().  | 
 | 42 | +
  | 
 | 43 | +        https://docs.djangoproject.com/en/5.1/howto/custom-model-fields/#converting-values-to-python-objects  | 
 | 44 | +        """  | 
 | 45 | +        if isinstance(value, str):  | 
 | 46 | +            return self.decrypt_value(value)  | 
 | 47 | +        return value  | 
 | 48 | + | 
 | 49 | +    def get_prep_value(self, value: t.Optional[str]):  | 
 | 50 | +        """  | 
 | 51 | +        'value' is the current value of the model's attribute, and the method  | 
 | 52 | +        should return data in a format that has been prepared for use as a  | 
 | 53 | +        parameter in a query.  | 
 | 54 | +
  | 
 | 55 | +        https://docs.djangoproject.com/en/5.1/howto/custom-model-fields/#converting-python-objects-to-query-values  | 
 | 56 | +        """  | 
 | 57 | +        if isinstance(value, str):  | 
 | 58 | +            return self.encrypt_value(value)  | 
 | 59 | +        return value  | 
 | 60 | + | 
 | 61 | +    def encrypt_value(self, value: str):  | 
 | 62 | +        """Encrypt the value if it's not encrypted."""  | 
 | 63 | +        if not value.startswith(self._prefix):  | 
 | 64 | +            return self._prefix + self._fernet.encrypt(value.encode()).decode()  | 
 | 65 | +        return value  | 
 | 66 | + | 
 | 67 | +    def decrypt_value(self, value: str):  | 
 | 68 | +        """Decrpyt the value if it's encrypted.."""  | 
 | 69 | +        if value.startswith(self._prefix):  | 
 | 70 | +            value = value[len(self._prefix) :]  | 
 | 71 | +            return self._fernet.decrypt(value).decode()  | 
 | 72 | +        return value  | 
0 commit comments