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 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 password_reset(request): if request.method == "POST": form = RequestPasswordResetForm(request.POST) if form.is_valid(): user = form.get_user() if not user.is_active: messages.warning(request, _("Your account is still inactive! You won't be able to log in until you reactivate with the link sent by e-mail.")) expire = datetime.now() + timedelta(days=1) variable_part = expire.strftime("%Y-%m-%d %H:%i:%s") + str(int(random.random() * 10)) h = sha_constructor(settings.SECRET_KEY + variable_part).hexdigest()[:24] # make sure the hash is unique enough reset = PasswordReset(user=user, expire=expire, h=h) try: reset.save() except IntegrityError: extrapart = int(random.random() * 10) h = sha_constructor(settings.SECRET_KEY + variable_part + extrapart).hexdigest()[:24] reset = PasswordReset(user=user, expire=expire, h=h) reset.save() #send email nickname = user.get_profile().forum_nickname email = user.email if not email: email = '*****@*****.**' domain = Site.objects.get_current().domain url = "http://%s%s?h=%s" % ( domain, reverse(do_password_reset), h ) text_content = _("""Hello %(nickname)s, \n You or someone else has requested a password reset for your Modelbrouwers.nl account. This request will expire after 24 hours.\n Go to %(url)s to complete your password reset.\n Sincerely,\n The Modelbrouwers.nl staff""" % { 'nickname': nickname, 'url': url } ) html_content = _(TEMPLATE_RESET_PW_HTML % { 'nickname': nickname, 'url': url } ) subject, from_email = _("Modelbrouwers.nl password reset"), '*****@*****.**' msg = EmailMultiAlternatives(subject, text_content, from_email, [email]) msg.attach_alternative(html_content, "text/html") msg.send() messages.success(request, _("An e-mail was sent to '%(email)s' with a link to reset your pasword.") % {'email': email}) return HttpResponseRedirect(reverse(custom_login)) else: form = RequestPasswordResetForm() return render(request, 'general/password_reset.html', {'form': form})
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 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())
def save(self): self.success = True reset = PasswordReset(key = str(uuid.uuid4()), user = self.user) reset.save() send_reset(self.user, reset)