Amine Messaoudi
Amine Messaoudi

Reputation: 2279

django admin disable password change for specific user

I'm currently working on a SAAS project and I would like to create an admin user for demo that anyone can access. To remove change password, I tried using set_unusable_password() but it does not work as it says password is incorrect when I try to log in.

This is the code I'm using :

admin = Admin.objects.create_user('admin', password='admin')
admin.is_superuser = True
admin.is_staff = True
admin.set_unusable_password()
admin.save()

After looking at the docs, I found out that set_unusable_password marks the user as having no password set, and doesn’t save the User object. This explains why I could not login at the first place.

So clearly set_unusable_password is not the solution. What I actually want is to login as usual, but for that specific user, the change password should be disabled, as the demo account will be used by all other testers and therefore the password should not be changed by anyone.

Upvotes: 2

Views: 1404

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

set_unusable_password() will make sure that you can no longer login with this user through a password. In that case, you login the user through other means, for example with a custom login mechanism like an ssh key, or a one-time password (OTP).

If you have made a custom user model, like Admin seems to suggest, you can however alter the set_password logic:

from django.core.exceptions import ValidationError

class Admin(models.Model):
    # …
    editable_password = models.BooleanField(default=True)

    def set_password(self, *args, **kwargs):
        if not self.editable_password:
            raise ValidationError('Can not set the password')
        return super().set_password(*args, **kwargs)

We thus prevent setting the password if editable_password is False.

You thus can protect the password with:

admin = Admin.objects.create_user('admin', password='admin')
admin.is_superuser = True
admin.is_staff = True
admin.editable_password = False
admin.save()

Upvotes: 4

Related Questions