authenticate function in django using hashed password not the raw one

百般思念 提交于 2019-12-06 05:22:40

Open edX uses the ratelimitbackend.backends.RateLimitModelBackend for authentication, as we can see in the settings. This backend requires the un-hashed password for authentication.

If you wish to authenticate a user based on its hashed password, you need to create a new authentication backend, as described in the django documentation.

I suggest you draw some inspiration from the Django ModelBackend, as implemented in django.contrib.auth.backends.

The error you see relative to the missing backend attribute is something that I have experienced before. In the impersonate_user view of FUN (an Open edX project) this is how we solve this problem (note the comment inside the source code of the view function):

user = get_object_or_404(User, username=username, is_superuser=False, is_active=True)
user.backend = None
login(request, user)

You can create a custom authentication backend for django and override its authenticate and get_user method to authenticate using hashed password and username.

Since hashed password is just another modelfield with text in it, you can lookup for users with username and the hash pass value in db.

Something like this should work:

from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User

class HashedPasswordAuthBackend(ModelBackend):

    def authenticate(self, username=None, password=None):
        try:
            return User.objects.get(username=username, password=password)
        except User.DoesNotExist:
            return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

After that, Include the path of this auth backend in your project settings.

AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
    'yourapp.backends.HashedPasswordAuthBackend',
]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!