def confirm_reset_password(token): """ Confirms if the confirm_token is valid and - if it is valid - sends an email with a new password. :param token: :return: """ user = User.verify_password_reset_token(token) if user is None: flash('This Token is invalid or has expired.', 'danger') return redirect(url_for('main_page.main_index')) if user.validated: new_pass = random_string_digits(16) user.password = gen_password(new_pass) db.session.add(user) db.session.commit() send_mail(None, [user.email], "Your new Password: "******"\nYou can change it in your profile.", subject="[MESA] Your new Password for MESA DNA Simulator") flash( 'A new password hat been generated and will be sent to you by mail', 'success') session['user_id'] = user.user_id else: flash('Account not activated yet!', 'warning') return redirect(url_for('main_page.main_index'))
def new_reset_password(): """ Confirms the user if the confirm_token is valid and the user isn't already confirmed. :param token: :return: """ if request.method == "GET": return render_template('reset_password.html') else: email = request.form["email"] if not email: flash('The reset-token is invalid or has expired.', 'danger') return redirect(url_for('main_page.main_index')) user = User.query.filter_by(email=email).first() if user and user.validated: send_mail( None, [user.email], "Use this link to reset your Password: "******"/reset_password/" + user.get_password_reset_token() + "\nIf you did not request a Password reset you can ignore this E-Mail", subject="[MESA] Your requested Password-reset") flash( 'If this E-Mail belongs to an activated (!) account it should receive an E-Mail containing a Reset-Link', 'success') return redirect(url_for('main_page.main_index'))
def send_record_notification_mail(record: models.ImageQtyRecordPack, users: t.Sequence[AbstractUser]) -> None: send_mail( subject='New image record!', content=get_template('new_record_mail.html').render({ 'record': record, }), recipients=[user.email for user in users], )
def register(): """ Registers a new user if the user isn't already logged in and the email isn't used. Also sends an email to the user to confirm the email address. :return: """ user_logged_in = session.get("user_id") if user_logged_in: flash("You cant create a new Account. You are already logged in.", "warning") return redirect(url_for("main_page.main_index")) if request.method == "POST": # You should really validate that these fields # are provided, rather than displaying an ugly # error message, but for the sake of a simple # example we'll just assume they are provided email = request.form["email"] password = request.form["password"] user = User.query.filter_by(email=email).first() # _or_404() if user: # Again, throwing an error is not a user-friendly # way of handling this, but this is just an example flash("Account already exists for this E-Mail", "warning") return render_template('signup.html') else: user = User(email=email, password=gen_password(password), created=int(time.time()), validated=False) db.session.add(user) db.session.commit() # Note we don't *return* the response immediately # session['user_id'] = user.user_id # response = redirect(url_for("main_page.main_index")) # response.set_cookie('YourSessionCookie', user.user_id) send_mail( None, [user.email], "Use this link to confirm your E-Mail: " + request.host_url + "/confirm/" + generate_confirmation_token(user.email)) if current_app.config['MAIL_ENABLED']: flash("Signup complete, please confirm your E-Mail", "info") else: flash( "Account created. E-Mail verification disabled, please contact the administrator to activate your account!", "info") return redirect(url_for("main_page.main_index")) else: return render_template('signup.html')
def request_validation_c_error(): user_id = session.get('user_id') user = User.query.filter_by(user_id=user_id).first() error_method = request.json.get('method') validation_desc = request.json.get('validation_desc') try: q_class = \ {'synth': SynthesisErrorRates, 'seq': SequencingErrorRates, 'pcr': PcrErrorRates, 'storage': StorageErrorRates}[ error_method] except: return jsonify({'did_succeed': False}) e_id = request.json.get('id') if user_id and user and error_method is not None and e_id is not None: try: if user.is_admin: curr_error = db.session.query(q_class).filter_by( id=e_id).first() requesting_user = User.query.filter_by( user_id=curr_error.user_id).first() if requesting_user.user_id != user_id: send_mail(None, [requesting_user.email], "Your Error-Method '" + curr_error.name + "' has been validated!", subject="[MESA] Validation Request") curr_error.validated = True else: curr_error = db.session.query(q_class).filter_by( user_id=user_id, id=e_id).first() curr_error.validated = False curr_error.validation_desc = validation_desc send_mail(None, get_admin_mails(), "The user " + str(user_id) + " (" + user.email + ") has requested a validation!", subject="[MESA] Validation Request") curr_error.awaits_validation = curr_error.validated is False db.session.add(curr_error) db.session.commit() return jsonify({ 'did_succeed': True, 'id': curr_error.id, 'validated': curr_error.validated, 'awaits_validation': curr_error.awaits_validation }) except Exception as ex: print(ex) return jsonify({'did_succeed': False}) else: return jsonify({'did_succeed': False})
def apply_validation_subseq(): user_id = session.get('user_id') user = User.query.filter_by(user_id=user_id).first() sequence_id = request.form.get('sequence_id') validation_desc = sanitize_input(request.form.get('validation_desc')) if user_id and user and sequence_id is not None: try: if user.is_admin: curr_sub_seq = db.session.query( UndesiredSubsequences).filter_by(id=sequence_id).first() requesting_user = User.query.filter_by( user_id=curr_sub_seq.owner_id).first() if requesting_user.user_id != user_id: send_mail(None, requesting_user.email, "Your Motif / Subsequence '" + curr_sub_seq.description + "' has been validated!", subject="[MESA] Validation Request") curr_sub_seq.validated = True else: curr_sub_seq = db.session.query( UndesiredSubsequences).filter_by(owner_id=user_id, id=sequence_id).first() curr_sub_seq.validated = False curr_sub_seq.validation_desc = validation_desc send_mail(None, get_admin_mails(), "The user " + str(user_id) + " (" + user.email + ") has requested a validation!", subject="[MESA] Validation Request") curr_sub_seq.awaits_validation = curr_sub_seq.validated is False db.session.add(curr_sub_seq) db.session.commit() return jsonify({ 'did_succeed': True, 'sequence': curr_sub_seq.sequence, 'error_prob': curr_sub_seq.error_prob, 'id': curr_sub_seq.id, 'created': curr_sub_seq.created, 'validated': curr_sub_seq.validated, 'description': curr_sub_seq.description, 'awaits_validation': curr_sub_seq.awaits_validation }) except: return jsonify({'did_succeed': False}) else: return jsonify({'did_succeed': False})
def register(): body = request.get_json() email = body['email'] hashed = bcrypt.hashpw(bytes(body['password'], 'utf8'), bcrypt.gensalt()) user = User(email=email, password=hashed) db.session.add(user) db.session.flush() confirmation = EmailConfirmation(user_id=user.id) db.session.add(confirmation) db.session.commit() send_mail('confirm-email', [email], id=confirmation.id) return jsonify(user.to_dict())
def send_mails(self, request, queryset): for meeting in queryset: meeting = send_mail(meeting) print(meeting.request_status, meeting) if meeting.is_mail_success == 1: messages.success(request, '会议:{},发送通知邮件:成功.'.format(meeting.topic)) else: messages.error(request, '会议:{},发送通知邮件:失败.'.format(meeting.topic))
def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) issuer = request.user key = None for _ in range(128): key = ''.join( random.choice(string.ascii_letters) for _ in range(255)) hasher = hashlib.sha3_256() hasher.update(key.encode('ASCII')) try: models.Invite.objects.create( key_hash=hasher.hexdigest(), email=serializer.validated_data['email'], issued_by=issuer, ) break except IntegrityError: pass if not key: raise Exception('Could not generate unique invite key') send_mail( subject='YOU HAVE BEEN INVITED TO JOIN EXCLUSIVE CLUB!!eleven', content=get_template('invite_mail.html').render({ 'inviter': issuer.username, 'invite_link': 'http://{host}/sign-up/?invite_code={key}'.format( host=settings.HOST, key=key, ), }), recipients=[ serializer.validated_data['email'], ]) return Response(status=status.HTTP_200_OK, )
def request_validation_g_error(): user_id = session.get('user_id') user = User.query.filter_by(user_id=user_id).first() e_id = request.json.get('id') validation_desc = request.json.get('validation_desc') if user_id and user and e_id is not None: try: if user.is_admin: curr_error = ErrorProbability.query.filter_by(id=e_id).first() requesting_user = User.query.filter_by( user_id=curr_error.user_id).first() if requesting_user.user_id != user_id: send_mail(None, requesting_user.email, "Your Graph '" + curr_error.name + "' has been validated!", subject="[MESA] Validation Request") curr_error.validated = True else: curr_error = ErrorProbability.query.filter_by(user_id=user_id, id=e_id).first() curr_error.validated = False curr_error.validation_desc = validation_desc send_mail(None, get_admin_mails(), "The user " + str(user_id) + " (" + user.email + ") has requested a validation!", subject="[MESA] Validation Request") curr_error.awaits_validation = curr_error.validated is False db.session.add(curr_error) db.session.commit() return jsonify({ 'did_succeed': True, 'id': curr_error.id, 'validated': curr_error.validated, 'awaits_validation': curr_error.awaits_validation }) except: return jsonify({'did_succeed': False}) else: return jsonify({'did_succeed': False})
def post(self, request, *args, **kwargs): serializer: serializers.ResetSerializer = self.get_serializer( data=request.data) serializer.is_valid(raise_exception=True) try: user = get_user_model().objects.get( username=serializer.validated_data['username'], email=serializer.validated_data['email'], ) except (UserModel.DoesNotExist, UserModel.MultipleObjectsReturned): return Response('Invalid user', status=status.HTTP_400_BAD_REQUEST) if models.PasswordReset.objects.filter( user=user, created_at__gte=datetime.datetime.now() - datetime.timedelta(hours=1), ).count() >= 2: return Response('To many password resets, try again later', status=status.HTTP_400_BAD_REQUEST) reset = models.PasswordReset.create(user) send_mail( subject='Password reset', content=get_template('reset_mail.html').render({ 'reset_link': 'http://{host}/claim-password-reset/?code={code}'.format( host=settings.HOST, code=reset.code, ), }), recipients=[user.email], ) return Response(status=status.HTTP_200_OK)