Skip to content

Django support: MongoEngineBackend does not respect custom user model's USERNAME_FIELD #884

@mikelrob

Description

@mikelrob

I've created a custom user model which does not have a username field, but rather uses the email field in lieu.

I followed the article @ http://docs.mongoengine.org/django.html#custom-user-model, carrying out both modifications in the settings.py:

INSTALLED_APPS = (
    ...
    'django.contrib.auth',
    'mongoengine.django.mongo_auth',
    ...
)

AUTH_USER_MODEL = 'mongo_auth.MongoUser'

and importantly:

MONGOENGINE_USER_DOCUMENT = 'MongoLogOn.models.User'  # my custom User Model

My custom User model specifies the following:

class User(MongoUser):
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['password']

It is worth noting that the above inherited MongoUserDoc is a direct copy of mongoengine.django.auth.User with the username field removed as the 30 char limit is far too restrictive.

The trouble I'm having is that when I call authenticate(<email>, <password>) in my log in view, it returns None.

I suspect the trouble is caused by the MongoEngineBackend as it blindly tries to retrieve the User document using the username field instead respecting the USERNAME_FIELD which is set in the custom User model as seen below:

class MongoEngineBackend(object):
    ...
    def authenticate(self, username=None, password=None):
        user = self.user_document.objects(username=username).first()

My work around uses the following to circumvent the issue:

class MongoEngineBackend(object):
    ...
    def authenticate(self, username=None, password=None):
        filter_dict = {self.user_document.USERNAME_FIELD: username}
        user = self.user_document.objects(**filter_dict).first()

So far I have had success with this work around.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions