I am trying to send a random one-time password to the user when I create a new user and make him change the password when the user login for the first time.
I am trying to send a random one-time password to the user when I create a new user and make him change the password when the user login for the first time.
I would suggest different approach to this.
When you create a user, set the active flag to false. so the account is not active and then cannot log in.
No need to generate a password, leave it blank.
Instead, create a url with special token and send the url. If the user goes to this url, it will present a form to set the password for this user.
This link is only one time use, and it can even expire after certain number of days.
You can look at PasswordResetTokenGenerator in django.contrib.auth.tokens to see how to generate such tokens and change it accordingly.
You will also need to craft the url to include somehow which user to use ( probably obscure it somehow as it is not apparent ).
I think there is simple solution for that. First of all let me describe user model with minimal requirements for the task:
from django.contrib.auth.models import AbstractUser
# ... other import
class CustomUser(AbstractBaseUser):
has_set_password = models.BooleanField(default=False)
# ... other fields
On the other hand, If you do not want to pollute model with unnecessary fields, check out the value of the last_login field, which comes from the AbstractUser model and it's value should be None, if user has not logged in yet.
After the part above, I'd define post save method for the CustomUser model or in the view where user is created - I'd just assign random one-time password. After user signs in, I would check the has_set_password flag, if it is False redirect them to set new password (or do something else), if it is True just sign in.
Hope, this helps.
This will help you. I Have tried it for Custom User Creation. You can first generate a random password/pin like
from random import SystemRandom
def user_create(username):
new_random_obj = SystemRandom()
#generate: 6 digits pin
pin = new_random_obj.randrange(100000, 999999)
user = User.objects.create_user(username=username, password=pin)
Then your create_user Method In UserManager may look Like
def create_user(self, username, password=None, location=None):
if not username:
raise ValueError('User must have an username')
user = self.model(
username=username
)
user.set_password(password)
user.save(using=self._db)
return user