georgemarshall / django-cryptography

Easily encrypt data in Django
https://django-cryptography.readthedocs.io/
BSD 3-Clause "New" or "Revised" License
371 stars 69 forks source link

Custom auth backend won't work after applied configurations on exists django project. #105

Open Vitaee opened 8 months ago

Vitaee commented 8 months ago

I have simple django web project and i have below auth backend:

class EmailBackend(ModelBackend):
    def authenticate(self, request, email, password, **kwargs):
        try:
            key = Fernet(b'-XDmDxaRPAiWfVu67gH-zc9R5QARb47IokU5Wu3rbK0=')
            # above byte value is my django project's secret key 

            decrypted_email = key.decrypt(email.encode()).decode()
            user = User.objects.get(email__iexact=decrypted_email)
        except User.DoesNotExist:
            return None
        if user.check_password(password):
            return user

I configured django-cryptography and i updated my auth backend like above. My exists data in now encrypted its working well.

Now i got Invalid Token error on my authentication. So currently my users can't authenticate. What is my mistake? why i can't decrypt the encrypted emails? to able to use django orm on it.

i created Fernet key based on Django's SECRET_KEY like below:

django_secret_key = settings.SECRET_KEY

key = PBKDF2HMAC(
    algorithm=hashes.SHA256(),
    salt=b'django-cryptography',
    iterations=100000, 
    length=32
).derive(django_secret_key.encode())

fernet_key = base64.urlsafe_b64encode(key)

In my settings.py i didn't put any variables related to django-cryptography. Should i use these variables?

My current user model looks like below:

class User(AbstractUser):
    email = encrypt(models.EmailField('Eposta Adresi', blank=True, null=True))
    phone=encrypt(PhoneNumberField(
        _('GSM Numarası'), unique=True, blank=False, null=True))

    device_id= encrypt(models.CharField(
        'Cihaz ID', max_length=50, null=True, blank=True))
    id_no = encrypt(models.CharField(
        verbose_name="Kullanıcı TC Kimlik No", blank=True, null=True, max_length=11))

     USERNAME_FIELD = 'phone'
    REQUIRED_FIELDS = []

My django version==4.2.6 and i am using latest release of the django-cryptography. As a database i am using postgresql.