2
0
mirror of https://github.com/inventree/InvenTree.git synced 2025-04-28 11:36:44 +00:00

create allauth email from django_auth_ldap if configured (#9350)

This commit is contained in:
Jacob Felknor 2025-03-20 20:48:30 -06:00 committed by GitHub
parent bd0dc3fe50
commit 3ec8832925
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -18,6 +18,7 @@ from django.urls import reverse
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
import structlog import structlog
from allauth.account.models import EmailAddress
from rest_framework.authtoken.models import Token as AuthToken from rest_framework.authtoken.models import Token as AuthToken
import InvenTree.cache import InvenTree.cache
@ -44,6 +45,25 @@ User.add_to_class('__str__', user_model_str) # Overriding User.__str__
# OVERRIDE END # OVERRIDE END
if settings.LDAP_AUTH:
from django_auth_ldap.backend import populate_user
@receiver(populate_user)
def create_email_address(user, **kwargs):
"""If a django user is from LDAP and has an email attached to it, create an allauth email address for them automatically.
https://django-auth-ldap.readthedocs.io/en/latest/users.html#populating-users
https://django-auth-ldap.readthedocs.io/en/latest/reference.html#django_auth_ldap.backend.populate_user
"""
# User must exist in the database before we can create their EmailAddress. By their recommendation,
# we can just call .save() now
user.save()
# if they got an email address from LDAP, create it now and make it the primary
if user.email:
EmailAddress.objects.create(user=user, email=user.email, primary=True)
def default_token(): def default_token():
"""Generate a default value for the token.""" """Generate a default value for the token."""
return ApiToken.generate_key() return ApiToken.generate_key()