Skip to content

Commit

Permalink
fix(username): retrieve using Django method for custom user model com…
Browse files Browse the repository at this point in the history
…patibility

Adjusted the retrieval method for usernames to cater for cases where the username might be omitted in custom user models.
  • Loading branch information
khashashin committed Aug 20, 2023
1 parent ce17b1c commit 8e84dea
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 9 deletions.
8 changes: 5 additions & 3 deletions django_appwrite/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,15 @@ def authenticate(self, request):
email = appwrite_settings['prefix_email'] + user_info['email']
password = settings.SECRET_KEY + user_info['$id']

username_field = getattr(User, 'USERNAME_FIELD', 'username')

# Get or create a corresponding Django user
django_user = User.objects.filter(username=email).first()
django_user = User.objects.filter(**{username_field: email}).first()
if not django_user:
User.objects.create_user(username=email, password=password, email=email)
User.objects.create_user(**{username_field: email, 'password': password})

# Ensure the user can be authenticated with Django's system
auth_user = authenticate(request, username=email, password=password)
auth_user = authenticate(request, **{username_field: email, 'password': password})
if not auth_user:
raise AuthenticationFailed('The user could not be authenticated with Django.')

Expand Down
12 changes: 6 additions & 6 deletions django_appwrite/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,18 +69,18 @@ def __call__(self, request, *args, **kwargs):

email = self.prefix_email + user_info['email']
password = settings.SECRET_KEY + user_info['$id']

username_field = getattr(User, 'USERNAME_FIELD', 'username')

# Get the Django user by its email
user = User.objects.filter(username=email).first()
user = User.objects.filter(**{username_field: email}).first()

# If the user doesn't exist, create it
if not user:
User.objects.create_user(
username=email,
password=password,
email=email)
User.objects.create_user(**{username_field: email, 'password': password})

# Authenticate the user using the email as the username
user = authenticate(request, username=email, password=password)
user = authenticate(request, **{username_field: email, 'password': password})

# If the authentication was successful, log the user in
if user:
Expand Down

0 comments on commit 8e84dea

Please sign in to comment.