Search code examples
djangoauthenticationhashwagtailabstractuser

How to get the plane password of Django admin user in pre_save signal when creating user from admin panel?


I need to log Django admin users in 3ed party authentication service. For that I need plane password without hashing. Here I used pre_save signal. That approach works well when I create an API endpoint for registration. But when I create an admin user from Django it always comes with defalut hashed password.

Any idea how to get the plane password?


Solution

  • You have to access the request object to get that data.

    You can use @hooks.register('before_create_user') to register a method to run before creating the user and get the password using password=request.POST['password1']. Keep in mind that, this hook runs when form loaded and also when form submitted. To get the password, you need to run this only when form submitted.

    @hooks.register('before_create_user')
    def before_create(request: 'HttpRequest') -> 'HttpResponse':
        if request.method != 'POST': 
            return    # Ignore execution when form loads
        body = request.POST
        form = get_user_creation_form()(body, request.FILES)    # Get the associated form
        if not form.is_valid():
            return     # If the form submission is invalid, return
        password=body['password1']    # Get raw password