2009-11-16 2 views
1

기본적으로 사용자 지정 암호 필드를 통해 일부 데이터를 암호화하려면 사용자 암호 해시를 사용해야합니다. 여기에 사용 된 스 니펫을 확인하십시오 : Django Encryption.사용자 모델을 양식 필드 (django)로 전달하는 방법은 무엇입니까?

나는이 시도 :

 
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)) 

을하지만 user_field 사용하려고하면, 나는 외래 키 인스턴스를 가져 (물론!) :

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

어떤 도움에 감사드립니다!

답변

1

어쩌면 암호화 된 메서드를 호출 할 수있는 save() 메서드를 재정의합니다. 당신이 signal post_init를 사용할 수 있습니다 해독을 위해

그래서 때마다 당신은 PRODUCT_ID 필드가 자동으로 해독 데이터베이스에서 모델을 인스턴스화

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 

어쩌면이

+0

일을 더 우아한 "파이썬"방법이있다 우선, 답장을 보내 주셔서 감사합니다! 바라기를 나는 이것과 비슷한 것을 생각해 낼 수있다. 그러나 신호로 어떻게 그 일을 수행 할 수 있는지에 대한 기본적인 예를 들어보십시오. 나는 전반적으로 신호에 관한 매우 제한된 지식을 가지고있다 ... – Bryan

+0

은 신호 처리기, 건배를 추가했다. – Evgeny

+0

감사합니다. 와우, 나는 정말로 감명 받았다. 나는 나중에 이것을 돌려 줄 것이다. 다시 한 번 감사드립니다! – Bryan

관련 문제