Exemple #1
0
def wtf_reg():
    form = RegisterForm()
    if form.validate_on_submit():
        salt = '.'.join(random.sample('hbuwgcfwijFTYURUYBufyou16871234967',
                                      10))
        password = form.password.data
        m = hashlib.md5()
        m.update((password + salt).encode('utf8'))
        password = m.hexdigest()
        user = User(form.user_name.data, password, salt, form.email.data)
        database.session.add(user)
        database.session.commit()

        token = user.generate_comfirmation_token()
        send_email(form.email.data,
                   u'Please activte your account',
                   u'mail/new_user',
                   user=user,
                   token=token)

        login_user(user)
        next = request.args.get('next')
        if next != None:
            return redirect(next)
        return redirect('/profile/' + unicode(user.id))
    return render_template('reglogin/reglogin_register.html', form=form)
Exemple #2
0
def reset_password():
    if current_user.is_authenticated:
        return flask.redirect(flask.url_for('home'))

    if flask.request.method == 'POST':
        member_email = flask.request.form['member_email']
        user = Users.query.filter_by(email=member_email).first()

        # Check if the email is allowed:
        if validate_email(member_email) == False:
            flask.flash("You can't use that email here, sorry.")
            return flask.redirect(flask.url_for('reset_password'))

        # check if the account is activated:
        if user.account_confirmed == False:
            flask.flash("You must first activate your account, please check your email.")
            return flask.redirect(flask.url_for('reset_password'))

        if user is None:
            flask.flash("That email doesn't exist!")
            return flask.redirect(flask.url_for('reset_password'))

        if user is not None:
            new_pass = gen_password()
            html = flask.render_template("./mail_messages/password_reset_token.html", new_pass=new_pass)
            subject = "Reset your password"
            send_email(user.email, subject, html)
            user.set_password(new_pass)
            db.session.commit()

        else:
            flask.flash("Something went wrong, please try again.")
            return flask.redirect(flask.url_for('reset_password'))

    return flask.render_template('./main/password_reset.html')
Exemple #3
0
def reset():
    form = EmailForm()
    if form.validate_on_submit():
        email = form.email.data.lower()
        userId = GetUserId(email)

        if userId:
            subject = "TRILL Password Reset Request"

            token = ts.dumps(email, salt='recover-key')

            recover_url = url_for('reset_with_token',
                                  token=token,
                                  _external=True)

            html = render_template('email_text_forgot.html', url=recover_url)

            try:
                send_email(email, subject, html)
                print('Please use the following reset password link:',
                      recover_url)
            except:
                error = 'Unable to send email'
                return render_template('confirm_email.html',
                                       form=form,
                                       error=error)

            return redirect(url_for('index'))
        else:
            error = 'Not a valid email address'
            return render_template('confirm_email.html',
                                   form=form,
                                   error=error)

    return render_template('confirm_email.html', form=form)
Exemple #4
0
def reset():
    form = EmailForm()
    if form.validate_on_submit():
        email = form.email.data.lower()
        userId = GetUserId(email)

        if userId:
            subject = "TRILL Password Reset Request"

            token = ts.dumps(email, salt='recover-key')

            recover_url = url_for(
                'reset_with_token',
                token=token,
                _external=True)

            html = render_template(
                'email_text_forgot.html',
                url=recover_url)

            try:
                send_email(email, subject, html)
                print ('Please use the following reset password link:', recover_url)
            except:
                error = 'Unable to send email'
                return render_template('confirm_email.html', form = form, error=error)

            return redirect(url_for('index'))
        else:
            error = 'Not a valid email address'
            return render_template('confirm_email.html', form = form, error=error)

    return render_template('confirm_email.html', form=form)
Exemple #5
0
def export_posts(user_id):
    # needs to capture unexpected errors b/c RQ does not catch exceptions the
    # way Flask does (in RQ, errors need to be logged to a file)
    try:
        #  read user posts from database
        user = User.query.get(user_id)
        _set_task_progress(0)
        data = []
        i = 0
        total_posts = user.posts.count()
        for post in user.posts.order_by(Post.timestamp.asc()):
            data.append({
                'body': post.body,
                'timestamp': post.timestamp.isoformat() + 'Z'
            })
            #  Z indicates UTC timezone
            time.sleep(5)
            i += 1
            _set_task_progress(100 * i // total_posts)
        # send email with data to user
        send_email('[Microblog] Your blog posts',
                   sender=app.config['ADMINS'][0],
                   recipients=[user.email],
                   text_body=render_template('email/export_posts.txt',
                                             user=user),
                   html_body=render_template('email/export_posts.html',
                                             user=user),
                   attachments=[('posts.json', 'application/json',
                                 json.dumps({'posts': data}, indent=4))],
                   sync=True)
    except:
        _set_task_progress(100)
        app.logger.error('Unhandled exception', exc_info=sys.exc_info())
Exemple #6
0
def send_password_reset_email(user):
    token = user.get_reset_password_token()
    send_email('[Microblog] Reset Your Password',
               sender=current_app.config['ADMINS'][0],
               recipients=[user.email],
               text_body=render_template('email/reset_password.txt', user=user, token=token),
               html_body=render_template('email/reset_password.html', user=user, token=token))
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user:
            flash("Email address already exists.")
            return redirect(url_for("auth.register"))

        payload = {
            "first_name": form.first_name.data,
            "last_name": form.last_name.data,
            "email": form.email.data,
            "password": form.password.data,
        }
        user = User(**payload)

        # add the new user to the database
        db.session.add(user)
        db.session.commit()

        token = generate_confirmation_token(user.email)
        send_email(redirect="auth.confirm_email",
                   html="activate.html",
                   recipients=user.email,
                   subject="Please confirm your email",
                   token=token)

        login_user(user)
        flash("A confirmation email has been sent via email.")

        return redirect(url_for("auth.unconfirmed"))
    else:
        flash_errors(form)

    return render_template("register.html", form=form)
Exemple #8
0
def signup():
    if current_user.is_authenticated:
        return flask.redirect(flask.url_for('home'))
    if flask.request.method == 'POST':
        member_username = flask.request.form['member_username']
        member_email = flask.request.form['member_email']
        member_password = flask.request.form['member_passwd']
        repeat_password = flask.request.form['repeat_password']
        invitation_code = flask.request.form['invitation_code']
        existing_username = Users.query.filter_by(username=member_username).first()
        existing_email = Users.query.filter_by(email=member_email).first()

        # Check if the email is allowed:
        if validate_email(member_email) == False:
            flask.flash("You can't use that email here, sorry.")
            return flask.redirect(flask.url_for('signup'))

        # Check if username is allowed:
        if validate_username(member_username) == False:
            flask.flash("Usernames should be between 6-16 characters, contain letters, digits, underscore and dots.")
            return flask.redirect(flask.url_for('signup'))


        # Check if email or username is in use
        if existing_username or existing_email is not None:
            flask.flash("The email or username is in use.")
            return flask.redirect(flask.url_for('signup'))

        # Ensure the password is strong
        if validate_password(member_password) == False:
            flask.flash(f"""That password is weak, use this instead: {gen_password()}""")
            return flask.redirect(flask.url_for('signup'))

        # Ensure the password and repeat password match
        if member_password != repeat_password:
            flask.flash("Passwords didn't match, please try again.")
            return flask.redirect(flask.url_for('signup'))

        valid_token = Invitations.query.filter_by(invitation_code=invitation_code).first()
        # Check if the provided invitation_code is in Invitations table
        if  valid_token is not None:
            new_user = Users(username=member_username, email=member_email, invitation_code=invitation_code, ip_address=get_ip(),
                             account_confirmed=False, user_agent=flask.request.headers.get('User-Agent'))
            new_user.set_password(member_password)
            #valid_token.expired = True                      # to specify that an invitation has expired
            db.session.add(new_user)
            db.session.commit()

            token = generate_confirmation_token(new_user.email)
            confirm_url = flask.url_for('confirm_email', token=token, _external=True)
            html = flask.render_template('./mail_messages/account_activation.html', confirm_url=confirm_url)
            subject = 'Please confirm your email'
            send_email(new_user.email, subject, html)

            flask.flash("Singup was succeed, please check your email for account activation.")
            return flask.redirect(flask.url_for('login'))
        else:
            flask.flash("Something went wrong, please try again.")
            return flask.redirect(flask.url_for('signup'))
    return flask.render_template('./main/member_signup.html')
Exemple #9
0
def export_posts(user_id):
    try:
        user = User.query.get(user_id)
        _set_task_progress(0)
        data = []
        post_n = 0
        total_posts = user.posts.count()
        for post in user.posts.order_by(Post.timestamp.asc()):
            data.append({
                'body': post.body,
                # 'Z' at end of timestamp indicates UTC timezone
                'timestamp': post.timestamp.isoformat() + 'Z'
            })
            # makes export task last longer, for seeing progress go up
            time.sleep(5)
            post_n += 1
            _set_task_progress(100 * post_n // total_posts)

        send_email('[Microblog] Your blog posts',
                   sender=app.config['ADMINS'][0],
                   recipients=[user.email],
                   text_body=render_template('email/export_posts.txt',
                                             user=user),
                   html_body=render_template('email/export_posts.html',
                                             user=user),
                   attachments=[('posts.json', 'application/json',
                                 json.dumps({'posts': data}, indent=4))],
                   sync=True)
    except:
        _set_task_progress(100)
        """error and stack trace from sys.exc_info(); uses app Flask logger
        (e.g., admin error emails)"""
        app.logger.error('Unhandled exception', exc_info=sys.exc_info())
Exemple #10
0
def send_verification_email(user):
    token = user.get_verify_email_token()
    send_email(
        "[Sustainable-recipe-recommender] Verify email address",
        sender=current_app.config["MAIL_USERNAME"],
        recipients=[user.email],
        text_body=render_template("email/verify_email.txt", user=user, token=token),
        html_body=render_template("email/verify_email.html", user=user, token=token),
    )
def resend_confirmation():
    token = generate_confirmation_token(current_user.email)
    send_email(redirect="auth.confirm_email",
               html="activate.html",
               recipients=current_user.email,
               subject="Please confirm your email",
               token=token)
    flash("A new confirmation email has been sent.")
    return redirect(url_for("auth.unconfirmed"))
Exemple #12
0
def resend_confirmation():
    token = current_user.generate_confirmation_token()
    send_email(current_user.email,
               'Confirm Your Account',
               'auth/email/confirm',
               user=current_user,
               token=token)
    flash('A new confirmation email has been sent to you by email.')
    return redirect(url_for('main.index'))
Exemple #13
0
def send_password_reset_email(user):
    token = user.get_reset_password_token()
    send_email(
        "[Sustainable-recipe-recommender] Reset Your Password",
        sender=current_app.config["MAIL_USERNAME"],
        recipients=[user.email],
        text_body=render_template("email/reset_password.txt", user=user, token=token),
        html_body=render_template("email/reset_password.html", user=user, token=token),
    )
def resend_confirmation():
    """Generate and send new confirmation token by email."""
    token = current_user.generate_confirmation_token()
    send_email(subject='Confirm your account',
               recipients=current_user.email,
               template_name='auth/email/confirm',
               user=current_user,
               token=token)
    flash('A confirmation email has been resent to your inbox.')
    return redirect(url_for('main.index'))
Exemple #15
0
def send_password_reset_email(user):
    token = user.get_reset_password_token()
    send_email(('[Tasker] Reset Your Password'),
               sender=current_app.config['MAIL_USERNAME'],
               recipients=[user.email],
               text_body=render_template('email/reset_password.txt',
                                         user=user,
                                         token=token),
               html_body=render_template('email/reset_password.html',
                                         user=user,
                                         token=token))
Exemple #16
0
def send_confirmation_email(user):
    token = user.generate_confirmation_token()
    send_email(('[Tasker] Confirm your account'),
               sender=current_app.config['MAIL_USERNAME'],
               recipients=[user.email],
               text_body=render_template('auth/email/confirm.txt',
                                         user=user,
                                         token=token),
               html_body=render_template('auth/email/confirm.html',
                                         user=user,
                                         token=token))
def reset():
    form = EmailForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first_or_404()
        token = generate_confirmation_token(user.email)
        send_email(redirect="auth.reset_with_token",
                   html="recover.html",
                   recipients=user.email,
                   subject="Password reset requested",
                   token=token)
        flash("Check your email.")
        return redirect(url_for("auth.login"))
    return render_template("login.html")
Exemple #18
0
def send_password_reset_email(user):
    token = user.get_reset_password_token()
    app = create_app(config_class=EmailJobConfig)
    with app.app_context():
        send_email(
            '[书荒啦] 重置密码',
            sender=app.config['ADMINS'][0],
            recipients=[user.email],
            text_body=render_template('email/reset_password_request.txt',
                                      user=user,
                                      token=token),
            html_body=render_template('email/reset_password_request.html',
                                      user=user,
                                      token=token))
Exemple #19
0
def register():
    register_form = RegistrationForm()
    if register_form.validate_on_submit():
        user = User(email=register_form.email.data,
                    username=register_form.username.data,
                    password=register_form.password.data)
        db.session.add(user)
        db.session.commit()
        send_email(recipient=user.email,
                   subject='Thank you for register',
                   template='auth/email/welcome',
                   user=user)
        login_user(user, remember=True)
        return redirect(url_for('main.index'))
    return render_template('auth/register.html', register_form=register_form)
def password_reset_request():
    form = ResetPasswordRequestForm()
    if current_user.is_authenticated:
        return redirect(url_for('main.index'))
    elif form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data.lower()).first()
        if user:
            token = user.generate_reset_token()
            send_email(subject='Reset Your Password',
                       recipients=user.email,
                       template_name='auth/email/reset',
                       user=user,
                       token=token)
        flash('An email with instructions has been sent to your inbox.')
        return redirect(url_for('main.index'))
    return render_template('auth/reset_password.html', form=form)
Exemple #21
0
def change_email_request():
    form = ChangeEmailForm()
    if form.validate_on_submit():
        if current_user.verify_password(form.password.data):
            new_email = form.email.data
            token = current_user.generate_email_change_token(new_email)
            send_email(new_email,
                       'Confirm your email address',
                       'auth/email/change_email',
                       user=current_user,
                       token=token)
            flash('An email with instructions to confirm your new email '
                  'address has been sent to you.')
            return redirect(url_for('main.index'))
        else:
            flash('Invalid email or password.')
    return render_template("auth/change_email.html", form=form)
Exemple #22
0
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(email=form.email.data,
                    username=form.username.data,
                    password=form.password.data)
        db.session.add(user)
        db.session.commit()
        token = user.generate_confirmation_token()
        send_email(user.email,
                   'Confirm Your Account',
                   'auth/email/confirm',
                   user=user,
                   token=token)
        flash('A confirmation email has been sent to you by email.')
        return redirect(url_for('main.index'))
    return render_template('auth/register.html', form=form)
def register():
    form = Registration()
    if form.validate_on_submit():
        # noinspection PyArgumentList
        user = User(email=form.email.data,
                    username=form.username.data,
                    password=form.password.data)
        db.session.add(user)
        db.session.commit()
        token = user.generate_confirmation_token()
        send_email(subject='Confirm your account',
                   recipients=user.email,
                   template_name='auth/email/confirm',
                   user=user,
                   token=token)
        flash('A confirmation email has been sent to your inbox.')
        return redirect(url_for('main.index'))
    return render_template('auth/register.html', form=form)
Exemple #24
0
def password_reset_request():
    if not current_user.is_anonymous:
        return redirect(url_for('main.index'))
    form = PasswordResetRequestForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user:
            token = user.generate_reset_token()
            send_email(user.email,
                       'Reset Your Password',
                       'auth/email/reset_password',
                       user=user,
                       token=token,
                       next=request.args.get('next'))
        flash('An email with instructions to reset your password has been '
              'sent to you.')
        return redirect(url_for('auth.login'))
    return render_template('auth/reset_password.html', form=form)
Exemple #25
0
def reset_password_request():
    """
    :summary:
    :return:
    """
    form = ResetPasswordRequestForm()
    if not current_user.is_anonymous:
        return redirect(url_for('main.index'))
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user:
            token = user.generate_reset_token()
            send_email(recipient=form.email.data,
                       subject='Reset Your Password',
                       template='auth/email/reset_password',
                       token=token,
                       user=current_user)
        flash('The email of reset password has been sent to you, please check')
    return render_template('auth/reset_password_request.html', form=form)
Exemple #26
0
def monitor():
    from application.report import Report

    if request.args.get('analyse', None) == 'Monitor':
        data = CallData()
        a = Report(data[0], data[1])
        a.Monitoring()
        from datetime import datetime
        gra = Result.query.order_by("total desc").filter(
            Result.total >= 100).all()
        send_email('Monitoring', ADMINS[0], ADMINS,
                   render_template('email.html', date=datetime.now(), gra=gra))

    graph = None
    stats = [0, 0]

    page = request.args.get(get_page_parameter(), type=int, default=1)

    pagination = Pagination(css_framework='bootstrap4',
                            page=page,
                            total=Result.query.count(),
                            search=False,
                            record_name='Ingot',
                            stats=stats)
    id_ = request.args.get('nxgrapx', None)
    if id_ is not None:
        data = CallData()
        a = Report(data[0], data[1])
        stats = a.PrintGraph((int(id_) - 1))
        graph = True

    return render_template(
        'monitor.html',
        stats=stats,
        gra=Result.query.order_by("total desc").limit(10).offset(
            (page - 1) * 10).all(),
        pagination=pagination,
        page=page,
        graph=graph,
        nxgrapx=None)
Exemple #27
0
def user_settings():
    if flask.request.method == 'POST':

        # Check password now:
        current_pass = flask.request.form['current_password']
        user_data = Users.query.filter_by(username=current_user.username).first()

        if not user_data.check_password(current_pass) or current_pass == '':
            flask.flash("Please confirm that you entered the correct current password.")
            return flask.redirect(flask.url_for('user_settings'))


        # Check username now:
        new_username = flask.request.form.get('new_username')
        curr_user = Users.query.filter_by(username=new_username).first()

        if new_username != '':
            if validate_username(new_username) == False:
                flask.flash("Usernames should be between 6-16 characters, contain letters, digits, underscore and dots.")
                return flask.redirect(flask.url_for('user_settings'))

            if new_username == current_user.username:
                flask.flash("That username is your current username")
                return flask.redirect(flask.url_for('user_settings'))

            if curr_user is not None:
                flask.flash("Sorry, that username is in use.")
                return flask.redirect(flask.url_for('user_settings'))

            if validate_username(new_username) == True:
                user_data.username = new_username
                db.session.commit()
                flask.flash("Your username has been changed.")
                return flask.redirect(flask.url_for('user_settings'))


        # Check email now:
        new_email = flask.request.form.get('new_email')
        curr_email = Users.query.filter_by(email=current_user.email).first()
        user_data = Users.query.filter_by(email=new_email).first()

        if new_email != '':
            if validate_email(new_email) == False:
                flask.flash("You can't use that email here, sorry.")
                return flask.redirect(flask.url_for('user_settings'))

            if new_email == current_user.username:
                flask.flash("That email is your current email")
                return flask.redirect(flask.url_for('user_settings'))

            if user_data is not None:
                flask.flash("Sorry, that email is in use.")
                return flask.redirect(flask.url_for('user_settings'))

            if validate_email(new_email) == True:
                curr_email.email = new_email
                curr_email.account_confirmed = False
                db.session.commit()

                token = generate_confirmation_token(curr_email.email)
                confirm_url = flask.url_for('confirm_email', token=token, _external=True)
                html = flask.render_template('./mail_messages/account_activation.html', confirm_url=confirm_url)
                subject = 'Please confirm your email'
                send_email(curr_email.email, subject, html)
                flask.flash("Your email address has been changed, please confirm your account.")
                return flask.redirect(flask.url_for('user_settings'))


        # Change password now:
        new_password = flask.request.form.get('new_password')
        confirm_password = flask.request.form.get('confirm_password')
        user_data = Users.query.filter_by(username=current_user.username).first()

        if new_password != '':

            if validate_password(new_password) == False:
                flask.flash(f"""That password is weak, use this instead: {gen_password()}""")
                return flask.redirect(flask.url_for('user_settings'))

            if new_password != confirm_password:
                flask.flash("Make sure your passwords match.")
                return flask.redirect(flask.url_for('user_settings'))

            if new_password == confirm_password:
                user_data.set_password(new_password)
                db.session.commit()
                flask.flash("Your password has been changed.")
                return flask.redirect(flask.url_for('user_settings'))

    return flask.render_template('./logged_in/account/settings.html')