#32181 closed New feature (wontfix)

ModelBackend used hardcoded global variable UserModel that cannot be overrided.

Reported by: Maxim Danilov Owned by: nobody
Component: contrib.auth Version: 3.1
Severity: Normal Keywords: custombackend, ModelBackend
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

It is not possible override Usermodel for custombackend which depends on ModelBackend.

if i want to change something un Usermodel class i should override whole authenticate method. it is not difficult but stupid and brakes SOLID rule

it's easy to change:

  1. add usermodel=UserModel in ModelBackend class definitions
  2. Change global variable UserModel to local self.usermodel
class ModelBackend(BaseBackend):
    """
    Authenticates against settings.AUTH_USER_MODEL.
    """
    usermodel=UserModel

    def authenticate(self, request, username=None, password=None, **kwargs):
        if username is None:
            username = kwargs.get(self.usermodel.USERNAME_FIELD)
        if username is None or password is None:
            return
        try:
            user = self.usersermodel._default_manager.get_by_natural_key(username)
        except UserModel.DoesNotExist:
            # Run the default password hasher once to reduce the timing
            # difference between an existing and a nonexistent user (#20760).
            self.usermodel().set_password(password)
        else:
            if user.check_password(password) and self.user_can_authenticate(user):
                return user

after that it can be possible to do something like that:

class LoginBackend(ModelBackend):
    """docstring for LoginBackend."""

    def authenticate(self, *args, **kwargs):
         self.usermodel = change_something_in(self.usermodel, *args, **kwargs)
         return super().authenticate(self, *args, **kwargs).

Change History (1)

comment:1 Changed 15 months ago by Mariusz Felisiak

Easy pickings: unset
Has patch: unset
Resolution: wontfix
Status: newclosed
Summary: ModelBackend used hardcoded global variable UserModel, it can not be overrided.ModelBackend used hardcoded global variable UserModel that cannot be overrided.
Type: UncategorizedNew feature

I'm not really sure if I understand your use case. Do you have different user models for different authorization backends? (because ModelBackend supports a custom model for users). If so, it's fair that you need to override authenticate() in such an advanced usage, IMO. We cannot maintain hooks for all niche scenarios. You can start a discussion on DevelopersMailingList if you don't agree.

Note: See TracTickets for help on using tickets.
Back to Top