def save(self, **kwargs): email = self.cleaned_data["email"] token_generator = kwargs.get("token_generator", default_token_generator) for user in User.objects.filter(email__iexact=email): temp_key = token_generator.make_token(user) # save it to the password reset model password_reset = PasswordReset(user=user, temp_key=temp_key) password_reset.save() current_site = Site.objects.get_current() domain = unicode(current_site.domain) # send the password reset email subject = _("Password reset email sent") message = render_to_string( "account/password_reset_key_message.txt", { "user": user, "uid": int_to_base36(user.id), "temp_key": temp_key, "domain": domain, }) send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [user.email]) return self.cleaned_data["email"]
def generate_reset_email(username): email = "" #send email to email address associated with their username user = User.objects.filter(username=username) if user == None or len(user) <> 1: return False else: email = user[0].email pin = ''.join( random.choice("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") for _ in range(49)) url = "{}PasswordFunctions/?function=resetpinsuccessful&username={}&pin={}".format( settings.BASE_URL, username, pin) message = "Please Click the following URL to reset your password:\n%s" % ( url) #add reset stats to database current_timestamp = default = datetime.datetime.now() exptime = datetime.datetime.now() + datetime.timedelta(minutes=30) expire_timestamp = exptime passwordreset = PasswordReset(username=username, resetpin=pin, time_issued=current_timestamp, time_expire=expire_timestamp, used=False) passwordreset.save() send_email(email, "ChatDashboard Password Reset", message) return True
def passwordReset(): email_address = request.json['email'] user = db.session.query(User).filter_by(email=email_address).filter( User.deletion_marker == None).first() if not user: responseObject = {'message': 'Enter a vaild email address'} return make_response(jsonify(responseObject)), 422 else: #generate a reset token token = user.encode_auth_token(user.public_id) reset_public_id = str(uuid.uuid4()) reset_token = PasswordReset(public_id=reset_public_id, email=email_address, token=token.decode(), status=5, created_at=datetime.now()) db.session.add(reset_token) try: db.session.commit() #send an email payload = { ## <M69k65y> "datenow": datetime.now().strftime("%d %B %Y"), ## </M69k65y> 'reset_url': '{}/password/reset/{}'.format( app.config['SERVER_ADDRESS'], reset_public_id ), # testing purposes, remove while in production 'copyright_year': datetime.now().strftime("%Y") } sg = sendgrid.SendGridAPIClient(app.config['SENDGRID_API_KEY']) from_email = Email(app.config['MAIL_ADDRESS']) to_email = Email(email_address) subject = 'Password Reset' content = Content( "text/html", render_template('password_reset.html', data=payload)) mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) # send_email('Password Reset', app.config['MAIL_ADDRESS'], user.email, payload, 'password_reset.html') close(db) responseObject = { 'message': 'Sent an email to {0}. Check the email for instructions.'. format(email_address) } return make_response(jsonify(responseObject)), 200 except Exception as identifier: db.session.rollback() close(db) responseObject = { 'message': 'An error has occured {0}'.format(str(identifier)), 'trace_back': traceback.format_exc() } return make_response(jsonify(responseObject)), 500
def send_mail(self, instance=None): token = uuid.uuid4().hex data = {"token": token, "user": instance.id} db.session.add(PasswordReset(**data)) db.session.commit() from flask_mail import Message msg = Message("Reset Password", recipients=[instance.email, ]) msg.body = "Click the following link to reset your password" msg.html = "<p>Click <a href='http://127.0.0.1:5000/api/v1/users/password-reset/?email="+instance.email+"&&token="+token+"'>here</a> " \ "to reset your password</p>" mail.send(msg)
def reset_request(): if request.method == 'POST': emailaddress = request.form.get('emailaddress') staff = Staff.query.filter( Staff.emailaddress == emailaddress).one_or_none() if staff is not None: pwreset = PasswordReset(staff=staff) db.session.add(pwreset) db.session.commit() msg = Message('Password Reset', recipients=[staff.emailaddress]) msg.html = '<a href="%s">Click to reset your password</a>' % ( url_for('reset_password', secret=pwreset.secret, emailaddress=urllib.quote(staff.emailaddress), _external=True), ) mail.send(msg) flash('Password reset sent') return redirect(url_for('main')) else: flash('Invalid request') return render_template('reset_request.html', _csrf_token=generate_csrf_token())