33
44from django .db import models
55
6+ from utils .encryption_utils import email_encryption
7+
68
79class NewsletterSubscriber (models .Model ):
10+ email_encrypted = models .TextField (help_text = "Encrypted email address" )
811 email_hash = models .CharField (
9- max_length = 128 , unique = True , help_text = "SHA-256 hash of the email"
12+ max_length = 128 ,
13+ unique = True ,
14+ help_text = "SHA-256 hash of the email for uniqueness checks" ,
1015 )
1116 subscribed_at = models .DateTimeField (auto_now_add = True )
1217 is_active = models .BooleanField (default = True )
@@ -30,7 +35,7 @@ def __str__(self):
3035
3136 @staticmethod
3237 def hash_email (email ):
33- """Create a SHA-256 hash of the email address"""
38+ """Create a SHA-256 hash of the email address for uniqueness checks """
3439 return hashlib .sha256 (email .lower ().strip ().encode ("utf-8" )).hexdigest ()
3540
3641 @classmethod
@@ -44,10 +49,25 @@ def get_by_email(cls, email):
4449
4550 @classmethod
4651 def create_subscriber (cls , email ):
47- """Create a new subscriber with hashed email"""
52+ """Create a new subscriber with encrypted email"""
4853 email_hash = cls .hash_email (email )
49- return cls .objects .create (email_hash = email_hash , is_active = True )
54+ email_encrypted = email_encryption .encrypt_email (email )
55+ return cls .objects .create (
56+ email_encrypted = email_encrypted , email_hash = email_hash , is_active = True
57+ )
58+
59+ def get_email (self ):
60+ """Decrypt and return the actual email address"""
61+ return email_encryption .decrypt_email (self .email_encrypted )
5062
5163 def get_email_display (self ):
5264 """Return a masked version of the email for display purposes"""
53- return f"***@{ self .email_hash [:4 ]} ..."
65+ email = self .get_email ()
66+ if email :
67+ # Show first 2 chars and domain
68+ local , domain = email .split ("@" , 1 )
69+ masked_local = (
70+ local [:2 ] + "*" * (len (local ) - 2 ) if len (local ) > 2 else local
71+ )
72+ return f"{ masked_local } @{ domain } "
73+ return "***@***"
0 commit comments