Hey Everyone I am working on creating a custom EmployeeForm
in which the form is for Business Administrators, to add employees. This creates a new user Account
in the database. In order to give this employee access to the platform, a temporary unique password is also set for them. On creation, an email is sent to the new employees account email providing them with their email, and randomly generated password. I would like to also include a link to send them straight to the Change password
view. With the click of this link, I want it to login the user, so that they donât have to go to the login page themselves, so that they are already authenticated/logged in, and all they have to do is type in their new password.
Iâm wondering if it is possible to log this user in automatically with the click of the âchange passwordâ link?
I am also wondering if there is even a possible way to not even set a random password, and allow the user to just click the email link, and they are free to set their initial password themselves. (Note: password is not a required field, so the employee account creation is possible to create without an initial password.)
class EmployeeForm(ModelForm):
class Meta:
model = Account # Inherits from AbstractBaseUser
fields = ['email', 'first_name', 'last_name', 'phone_no', ]
def save(self, commit=True):
"""Generate temp PW, trigger email"""
email = self.instance.email
temp_pass = get_random_string()
self.instance.set_password(temp_pass)
self.send_temp_password()
# Authenticate User to now Login
authenticate(username=email, password=temp_pass)
return super(EmployeeForm, self).save()
def send_temp_password(self):
domain = f'https://{Site.objects.get_current().domain}'
subject = "Temporary Password/Reset Link"
html_message = render_to_string('password_change.txt',
{'domain': domain,
'email': self.instance.email,
'temp_pass': self.instance.password,
})
send_mail(subject, html_message, settings.DEFAULT_FROM_EMAIL,
[self.instance.email, ], fail_silently=True)
I guess in general I am looking for a little direction as to the best design, and security to set this up in the most efficient way.
Any advice is greatly appreciated!