art049 / odmantic

Sync and Async ODM (Object Document Mapper) for MongoDB based on python type hints
http://art049.github.io/odmantic
ISC License
1.05k stars 93 forks source link

Custom fields serialisation & deserialisation #456

Open nikhildigde opened 4 months ago

nikhildigde commented 4 months ago

Hi, I am trying to create a custom field to implement client side encryption. I am able to perform serialisation during save, however I dont see a way to deserialise the data after a find (decrypt it). Is this possible by some means?

This is how I created the custom field

`class EncryptedFieldType(str):

@classmethod
def __get_validators__(cls):
    yield cls.validate

@classmethod
def validate(cls, v):
    if isinstance(v, bytes):  # Handle data coming from MongoDB
        print("In isinstance(v, bytes) ...")
        return "hello"
    if not isinstance(v, str):
        raise TypeError("string required")
    if not v.isascii():
        raise ValueError("Only ascii characters are allowed")
    return v

@classmethod
def __bson__(cls, v) -> str:
    print("In __bson__")
    return "*******"

class CollectionWithEncField(Model): encrypted_field: EncryptedFieldType`

nikhildigde commented 4 months ago

I just figured that I can use the below

def validate(cls, v): return decrypt(v)