Search code examples
pythondjangoauthenticationhashopenedx

authenticate function in django using hashed password not the raw one


I am working on openedx(which runs on django) and the user will be redirected here from other site and i'm being given the hashed password from there. Authenticate(username,password) excepts raw password like "dragon" not the hashed one,

So I need to use the authenticate() with the hashed password so that I can get the ".backend" attribute and move on with my life.

When I use login(request,user) without the authenticate method. this error appears:

request.session[BACKEND_SESSION_KEY] = user.backend
AttributeError: 'User' object has no attribute 'backend'

So I need to use the authenticate function to get that .backend attribute in my user object.

user = authenticate(username=username, password=password) is the format of the authenticate function, the password here is a raw password like "abc", what I have is a hashed password (which is the way this "abc" password will be stored in db).

I am stuck now, is there a way to authenticate and login using hashed passwords in django?


Solution

  • 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)