0
我有一個模型存儲用戶輸入的數據庫密碼。因爲我的應用需要連接到這些數據庫。密碼在數據庫中被加密。但是,當它被檢索時,我需要將decrypt
函數應用於密碼字段。我在哪裏可以這樣做,以便僅在查詢數據庫時才應用,而不是在保存字段時應用。Django ORM - 調整字段值返回
這裏是我的模型:
class Databases(models.Model):
"""
Handles the storing of database connections
"""
# Initialize the encryption class
e = Encryption()
# Our unique id for the database
id = models.AutoField(primary_key=True)
# Database name to display to the user
database_display_name = models.CharField(max_length=128, db_index=True, unique=True)
# Database name
database_name = models.CharField(max_length=128, db_index=True)
# Database status
active = models.BooleanField(default=True, db_index=True)
# The host name
host = models.CharField(max_length=256)
# The default port
port = models.IntegerField(default=3306)
# The username for the database
username = models.CharField(max_length=128)
# The password for the database
password = models.CharField(max_length=256)
# Set the database type
database_type = models.CharField(max_length=64, db_index=True, default="mysql")
# Timestamps
created_at = models.DateTimeField(db_index=True)
updated_at = models.DateTimeField(db_index=True)
event_at = models.DateTimeField(db_index=True)
def get_password(self, obj):
print("Retrieving")
return Databases.e.decrypt(obj.password)
def save(self, *args, **kwargs):
"""
On save, update timestamps
"""
# If the record does not currently exist in the database
if not self.id:
self.created_at = timezone.now()
self.updated_at = timezone.now()
# Encrypt the password
self.password = Databases.e.encrypt(self.password)
return super(Databases, self).save(*args, **kwargs)
class Meta:
db_table = 'databases'
這裏是我的串行:
class DatabasesSerializer(serializers.ModelSerializer):
class Meta:
model = Databases
我想我可能已經造成了一些困惑:我試圖用self.e.decrypt(self.password)覆蓋字段密碼,以便每當使用密碼字段時它會顯示自己的結果.e.decrypt(self.password) – user2694306
我建議不要在數據庫中存儲純文本密碼,如果有人獲得未經授權的訪問,您的所有數據庫都將受到攻擊。無論如何,如果你想以純文本的形式存儲它們,爲什麼還要在首先保存時加密? – rafalmp