Django Multiple Authentication Backend for one project, HOW?

后端 未结 4 1840
野性不改
野性不改 2020-12-05 00:52

Need serious help here.

I have an application written in django/python and I have to extend it and include some other solution as an \"app\" in this application. For

4条回答
  •  悲哀的现实
    2020-12-05 01:43

    I've been through this problem before. This is the code I used.

    This is the authentication backend at the api/backend.py

    from django.contrib.auth.models import User
    
    
    class EmailOrUsernameModelBackend(object):
    
        def authenticate(self, username=None, password=None):
            if '@' in username:
                kwargs = {'email': username}
            else:
                 kwargs = {'username': username}
            try:
                user = User.objects.get(**kwargs)
                if user.check_password(password):
                    return user
            except User.DoesNotExist:
                return None
    
        def get_user(self, user_id):
            try:
                return User.objects.get(pk=user_id)
            except User.DoesNotExist:
                return None
    

    And this is my settings.py

    AUTHENTICATION_BACKENDS = (
        'api.backend.EmailOrUsernameModelBackend',
        'django.contrib.auth.backends.ModelBackend',
    )
    

    Hope it helps. Please tell me if you're still in trouble. This code will enable you to use email to authenticate the default Django user even in Django admin.

提交回复
热议问题