Domanda

In sostanza, ho bisogno di usare una password hash dell'utente per crittografare alcuni dati tramite un campo modello personalizzato. Controlla il frammento che ho usato qui:. Django crittografia

Ho provato questo:

class MyClass(models.Model):
    owner = models.ForeignKey(User)
    product_id = EncryptedCharField(max_length=255, user_field=owner)

.................................................................................

    def formfield(self, **kwargs):
        defaults = {'max_length': self.max_length, 'user_field': self.user_field}
        defaults.update(kwargs)
        return super(EncryptedCharField, self).formfield(**defaults))

Ma quando provo ad usare user_field, ottengo un'istanza ForeignKey (ovviamente!):

user_field = kwargs.get('user_field')
cipher = user_field.password[:32]

Ogni aiuto è apprezzato!

È stato utile?

Soluzione

forse qualcosa di simile - sovrascrivere il metodo save () in cui è possibile chiamare il metodo Encrypt

.

per decifrare è possibile utilizzare segnale post_init , così ogni volta che si istanziare il modello dal database campo product_id viene decifrato automaticamente

class MyClass(models.Model):
    user_field = models.ForeignKey(User)
    product_id = EncryptedCharField()
    ...other fields...

    def save(self):
        self.product_id._encrypt(product_id, self.user_field)
        super(MyClass,self).save()

    def decrypt(self):
        if self.product_id != None:
            user = self.user_field
            self.product_id._decrypt(user=user)

def post_init_handler(sender_class, model_instance):
    if isinstance(model_instance, MyClass):
        model_instance.decrypt()

from django.core.signals import post_init
post_init_connect.connect(post_init_handler)


obj = MyClass(user_field=request.user) 
#post_init will be fired but your decrypt method will have
#nothing to decrypt, so it won't garble your input
#you'll either have to remember not to pass value of crypted fields 
#with the constructor, or enforce it with either pre_init method 
#or carefully overriding __init__() method - 
#which is not recommended officially

#decrypt will do real decryption work when you load object form the database

obj.product_id = 'blah'
obj.save() #field will be encrypted

forse c'è un modo più elegante "divinatorio" di fare questo

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top