Exemplo n.º 1
0
def student_bulk():
    students = Student.query.filter_by(approved=True).all()
    if request.method == 'POST':
        error = ''
        try:
            bulk_message = get_message_from_form(request)
            include_schedule = True if request.form.get(
                'include-schedule') else False
            send_copy_to_parents = True if request.form.get(
                'parent') else False
            for student in students:
                schedule = ''
                if include_schedule:
                    schedule = get_schedule_from_student(student)
                recipients = [student.student_email]
                if send_copy_to_parents:
                    recipients.append(student.parent_email)
                message = Message(subject=bulk_message.subject,
                                  body=bulk_message.body + schedule,
                                  recipients=recipients)
                send_mail(message)
        except IncompleteFormException:
            error = Errors.INCOMPLETE_FORM_ERROR
        except Exception as e:
            logging.exception(e)
            traceback.print_exc()
        finally:
            if error:
                return render_template('student_bulk.html',
                                       error=error,
                                       students=students)
        return redirect(url_for('administrator.administrator_landing'))
    if request.method == 'GET':
        return render_template('student_bulk.html', students=students)
Exemplo n.º 2
0
def unconfirmed_students():
    students = Student.query.filter_by(approved=False).all()
    if request.method == 'POST':
        error = ''
        try:
            confirmed_students = get_confirmed_students_from_form(request)
            for confirmed_student in confirmed_students:
                confirmed_student.approved = True
            db.session.commit()
            approved_student_message = Notification.query.filter_by(
                identifier=NotificationIdentifiers.APPROVAL).first().message
            for confirmed_student in confirmed_students:
                send_mail(
                    Message('Approved For Open Doors Opportunity',
                            body=approved_student_message,
                            recipients=[
                                confirmed_student.student_email,
                                confirmed_student.parent_email
                            ]))
        except Exception as e:
            error = 'Unknown error'
            logging.exception(e)
            traceback.print_exc()
        finally:
            if error:
                db.session.rollback()
                return render_template('unconfirmed_students.html',
                                       students=students,
                                       error=error)
        return redirect(url_for('administrator.administrator_landing'))
    if request.method == 'GET':
        return render_template('unconfirmed_students.html', students=students)
Exemplo n.º 3
0
def send_confirm_message(user):
    if not user.confirmed:
        token = generate_confirmation_token(user.email)
        confirm_url = url_for('user.confirm_email',
                              token=token,
                              _external=True)
        subject = 'Пожалуйста подтвердите вашу почту'
        template = render_template('activate.html', confirm_url=confirm_url)
        confirm_message = Message(subject,
                                  recipients=[user.email],
                                  html=template,
                                  sender=app.config['MAIL_DEFAULT_SENDER'])
        try:
            send_mail(confirm_message)
        except smtplib.SMTPAuthenticationError:
            return {
                'status': False,
                'message': 'Не удалось отправить сообщение'
            }

        return {
            'status': True,
            'message':
            'На вашу почту отправлена инструкция для активации аккаунта'
        }
    else:
        return {'status': False, 'message': 'Аккаунт уже подтвержден'}
Exemplo n.º 4
0
    def post(self):
        form = RegisterForm()
        
        if form.validate_on_submit():
            user = User(account=form.account.data,
                        password=bcrypt.generate_password_hash(form.password.data).decode(),
                        name=form.name.data,
                        store_name=form.name.data,
                        email=form.email.data,
                        phone=form.phone.data,
                        birth=form.birth.data,
                        address='',
                        prefer_begin_time='',
                        prefer_end_time='')
            
            user.save()

            information = Information(user_id = user.id)
            information.save()

            send_mail("HiShop帳號認證", [form.email.data], url_for("verification", _external=True, user_id=user.id))

            return redirect(url_for('login'))
        
        return render_template('auth/register.html', form=form)
Exemplo n.º 5
0
def suggest_scenario(scenario_id):
    errors = []
    content = request.form.get('content', '')
    if content == '':
        errors.append(gettext('Suggest content is required'))
        return json.dumps(errors), 400
    
    scenario = Scenario.query.get(scenario_id)
    if scenario is None:
        errors.append('Scenario not found')
        return json.dumps(errors), 404
    comment_topic = scenario.comment_topic
    
    new_comment = Comment(g.user, comment_topic, content)
    new_comment.description = gettext('Suggest for scenario')
    db.session.add(new_comment)
    db.session.commit()

    #send email to admins about the suggested content
    admin_group = Group.query.get(1)
    admins = admin_group.users
    admin_emails = []
    for admin in admins:
        admin_emails.append(admin.email)
    send_mail(admin_emails, '[SketchupOulu] New suggest for ' + scenario.name, render_template("users/suggest_scenario_email_content.html", suggest_content=content, scenario=scenario.to_dict(), user=g.user.username))
    return json.dumps(new_comment.to_dict(include_owner=True)), 200
Exemplo n.º 6
0
def suggest_scenario(scenario_id):
    errors = []
    content = request.form.get('content', '')
    if content == '':
        errors.append(gettext('Suggest content is required'))
        return json.dumps(errors), 400

    scenario = Scenario.query.get(scenario_id)
    if scenario is None:
        errors.append('Scenario not found')
        return json.dumps(errors), 404
    comment_topic = scenario.comment_topic

    new_comment = Comment(g.user, comment_topic, content)
    new_comment.description = gettext('Suggest for scenario')
    db.session.add(new_comment)
    db.session.commit()

    #send email to admins about the suggested content
    admin_group = Group.query.get(1)
    admins = admin_group.users
    admin_emails = []
    for admin in admins:
        admin_emails.append(admin.email)
    send_mail(
        admin_emails, '[SketchupOulu] New suggest for ' + scenario.name,
        render_template("users/suggest_scenario_email_content.html",
                        suggest_content=content,
                        scenario=scenario.to_dict(),
                        user=g.user.username))
    return json.dumps(new_comment.to_dict(include_owner=True)), 200
Exemplo n.º 7
0
def change_email():
    form = ChangeEmailForm()
    if form.validate_on_submit():
        token = current_user.generate_confirmation_token()
        send_mail(form.email.data, 'Change email address', 'mail/change_email_mail', user = current_user, token = token, email = form.email.data)
        flash('Mail to confirm has been send in your new address')
        return redirect(url_for('index'))
    return render_template('auth/change_email.html', form = form)
Exemplo n.º 8
0
 def post(self, id):
     from app import send_mail
     args = parser.parse_args(strict=True)
     u = User(email=args["email"],
              password=args["password"],
              role_id=(args["role_id"] if args["role_id"] else 1))
     db.session.add(u)
     db.session.commit()
     send_mail(u.email, u, u.generate_confirmation_token())
     return {"msg": "user created and email send!"}, 200
Exemplo n.º 9
0
def validate_account(form, account):
    user = User.objects(account=account.data).first()
    if user == None:
        raise ValidationError('此帳號尚未註冊')
    elif user.status == 0:
        send_mail("HiShop帳號認證", [user.email],
                  url_for("verification", _external=True, user_id=user.id))
        raise ValidationError('此帳號尚未認證')
    elif user.status == 3:
        raise ValidationError('此帳號已被凍結')
Exemplo n.º 10
0
def change_password():
    form = ChangePasswordForm()
    if form.validate_on_submit():
        current_user.password = form.password.data
        db.session.add(current_user)
        db.session.commit()
        send_mail(current_user.email, 'Password was change', 'mail/change_password_mail', user = current_user)
        flash('Email about changing password has been sent to you by email.')
        return redirect(url_for('login'))
    return render_template('change_password.html', form = form)
Exemplo n.º 11
0
def reset_password():

    token = request.args.get('token', '')
    if token != '':
        user = User.query.filter_by(password_token=token).first()
        if user is not None:

            new_password = utilities.generate_random_string(20)
            user.password = generate_password_hash(new_password)
            user.password_token = ''
            db.session.commit()
            
            email_content = Journal.query.filter(Journal.id==122).first().get_journal_content(session['locale'])
            send_mail([user.email], email_content.title, render_template_string(email_content.content, new_password=new_password))
            return render_template("users/reset_password_confirmed.html"), 200


    form = ResetPasswordForm(request.form)
    errors = []
    # make sure data are valid, but doesn't validate password is right
    if form.is_submitted():
        is_validated = True
        if form.email.data.strip() == '':
            is_validated = False
            errors.append(gettext('Email is required'))
        #validate valid email
        match = re.search(r'^.+@([^.@][^@]+)$', form.email.data.strip())
        if not match:
            is_validated = False
            errors.append(gettext('Invalid email address'))
            
        if is_validated:
            user = User.query.filter_by(email=form.email.data).first()  # @UndefinedVariable

            if user is None:
                errors.append(gettext('Account not found'))
                return render_template("users/reset_password.html", form=form, errors=errors), 404

            if user.banned == 1:
                errors.append(gettext('The account was banned, please contact an admin for more information'))
                return render_template("users/reset_password.html", form=form, errors=errors), 400

            user.password_token = utilities.generate_random_string(50)
            db.session.commit()

            # we use werzeug to validate user's password
            email_content = Journal.query.filter(Journal.id==121).first().get_journal_content(session['locale'])
            send_mail([user.email], email_content.title, render_template_string(email_content.content, link=url_for('users.reset_password', token=user.password_token, _external=True)))
            db.session.commit()
            return render_template("users/reset_password_submited.html"), 200
        else:
            return render_template("users/reset_password.html", form=form, errors=errors), 200

    return render_template("users/reset_password.html", form=form, errors=[])
Exemplo n.º 12
0
def resend_activation_email(code):
    if code.strip() == '':
        return render_template("404.html"), 404
    user = User.query.filter(User.verification_code==code).first()
    if user is None:
        return render_template("404.html"), 404
    
    email_activation = Journal.query.filter(Journal.id==120).first().get_journal_content(session['locale'])
    send_mail([user.email], email_activation.title, render_template_string(email_activation.content, activate_link=url_for('users.verify_account', code=code, _external=True)))
    
    return render_template("users/register_finish.html", email=user.email)
Exemplo n.º 13
0
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(email = form.email.data, username = form.username.data)
        user.password = form.password.data
        db.session.add(user)
        db.session.commit()
        token = user.generate_confirmation_token()
        send_mail(user.email, 'Confirm Your Account', 'mail/confirm', user = user, token = token)
        flash('A confirmation email has been sent to you by email.')
        return redirect(url_for('index'))
    return render_template('auth/register.html', form = form)
Exemplo n.º 14
0
def reset_password():
    form = ResetPasswordFirstForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email = form.email.data).first()
        if not user:
            flash('Invalid email')
        else:
            token = user.generate_confirmation_token()
            send_mail(user.email, 'Reset password', 'mail/reset_password_mail', user = user, token = token)
            flash('Email to reset your password has been sent to you by email.')
            return redirect(url_for('index'))
    return render_template('reset_password.html', form = form)
Exemplo n.º 15
0
def register(mid):
    mentor = Mentor.query.get(mid)
    configuration = Configuration.query.first()
    if not mentor or configuration.program_status != 'Active':
        return redirect(url_for('student.landing'))
    if mentor.waitlist_active:
        return redirect(url_for('student.get_notifications', mid=mid))
    disclaimer = Notification.query.filter_by(
        identifier=NotificationIdentifiers.DISCLAIMER).first().message
    registration_fields = Notification.query.filter_by(
        identifier=NotificationIdentifiers.REGISTRATION_FIELDS).first().message
    submission = Notification.query.filter_by(
        identifier=NotificationIdentifiers.SUBMISSION_TEXT).first().message
    if request.method == 'POST':
        error = ''
        try:
            registered_student = get_student_from_form(request, mentor)
            db.session.add(registered_student)
            if mentor_fully_registered(mentor):
                mentor.waitlist_active = True
            db.session.commit()
            send_mail(
                Message('You Have Applied For a Open Doors Opportunity',
                        body=submission,
                        recipients=[registered_student.student_email]))
        except IncompleteFormException:
            error = Errors.INCOMPLETE_FORM_ERROR
        except InvalidEmailException:
            error = Errors.INVALID_EMAIL_ERROR
        except InvalidSelectedOpportunityException:
            error = Errors.INVALID_SELECTED_OPPORTUNITY_ERROR
        except Exception as e:
            logging.exception(e)
            traceback.print_exc()
        finally:
            if error:
                db.session.rollback()
                return render_template('register.html',
                                       error=error,
                                       mentor=mentor,
                                       format_date=format_date,
                                       get_session=get_session,
                                       disclaimer=disclaimer,
                                       registration_fields=registration_fields)
        return redirect(url_for('student.landing', success=submission))
    if request.method == 'GET':
        return render_template('register.html',
                               mentor=mentor,
                               format_date=format_date,
                               get_session=get_session,
                               disclaimer=disclaimer,
                               registration_fields=registration_fields)
Exemplo n.º 16
0
def feedback():
    if not current_user.is_authenticated:
        flash('Авторизуйтесь для использования обратной связи', 'warning')
        return redirect(url_for('main.index'))
    if request.method == 'POST':
        content = request.form.get('content', None)
        template = render_template('feedback_template.html', content=content)
        message = Message(
            subject=f'Обратная связь блог от {current_user.login}',
            sender=app.config.get('MAIL_DEFAULT_SENDER'),
            html=template,
            recipients=[app.config.get('FEEDBACK_MAIL')])
        send_mail(message)
    return render_template('feedback.html')
Exemplo n.º 17
0
def send_email():

    form = SendEmailForm(request.form)
    errors = []
    serialized_users = []

    if form.is_submitted():
        is_validated = True
        emails = form.emails.data.split(',')

        if len(emails) == 0:
            is_validated = False
            errors.append(gettext("Insert users to send email"))
        if form.title.data.strip() == '':
            is_validated = False
            errors.append(gettext("Email title is required"))
        if form.content.data.strip() == '':
            is_validated = False
            errors.append(gettext("Email content is required"))

        if is_validated:
            if form.action.data == 'send':
                send_mail(emails, form.title.data, form.content.data)
            else:
                send_mail([g.user.email], form.title.data, form.content.data)

        query_text = ''
        for index, email in enumerate(emails):
            if email != '':
                if index == 0:
                    query_text += "email='" + email + "'"
                else:
                    query_text += "or email='" + email + "'"
        users = User.query.filter(query_text).all()
        for user in users:
            serialized_users.append({
                'email': user.email,
                'name': user.username
            })
        return render_template("admin/send_email.html",
                               form=form,
                               errors=errors,
                               users=serialized_users)

    form.title.data = ''
    form.emails.data = ''
    form.content.data = ''
    return render_template("admin/send_email.html", form=form, errors=[])
Exemplo n.º 18
0
def resend_activation_email(code):
    if code.strip() == '':
        return render_template("404.html"), 404
    user = User.query.filter(User.verification_code == code).first()
    if user is None:
        return render_template("404.html"), 404

    email_activation = Journal.query.filter(
        Journal.id == 120).first().get_journal_content(session['locale'])
    send_mail([user.email], email_activation.title,
              render_template_string(email_activation.content,
                                     activate_link=url_for(
                                         'users.verify_account',
                                         code=code,
                                         _external=True)))

    return render_template("users/register_finish.html", email=user.email)
Exemplo n.º 19
0
    def post(self):
        form = ForgotPasswordForm()
        if form.validate_on_submit():
            user = User.objects(account=form.account.data).first()
            user.reset_token = str(uuid.uuid4()).replace('-', '') + str(
                uuid.uuid4()).replace('-', '')
            user.save()

            send_mail(
                "重設密碼", [user.email],
                url_for('reset',
                        reset_token=user.reset_token,
                        account=user.account,
                        _external=True))

            flash('重設密碼連結已發送', category='success')

        return render_template('auth/forgot.html', form=form)
Exemplo n.º 20
0
def mentor_bulk():
    mentors = Mentor.query.all()
    registered_mentors = []
    for mentor in mentors:
        if has_registered_students(mentor):
            registered_mentors.append(mentor)
    if request.method == 'POST':
        error = ''
        try:
            bulk_message = get_message_from_form(request)
            registered_mentors_only = True if request.form.get(
                'registered-mentors-only') else False
            include_registered_students = True if request.form.get(
                'include-registered-students') else False
            if registered_mentors_only:
                for mentor in registered_mentors:
                    message = Message(bulk_message.subject,
                                      body=bulk_message.body,
                                      recipients=[mentor.email])
                    if include_registered_students:
                        message.html = get_schedule_from_mentor(mentor)
                    send_mail(message)
            else:
                for mentor in mentors:
                    message = Message(bulk_message.subject,
                                      body=bulk_message.body,
                                      recipients=[mentor.email])
                    send_mail(message)
        except IncompleteFormException:
            error = Errors.INCOMPLETE_FORM_ERROR
        except Exception as e:
            logging.exception(e)
            traceback.print_exc()
        finally:
            if error:
                return render_template('mentor_bulk.html',
                                       error=error,
                                       mentors=mentors,
                                       registered_mentors=registered_mentors)
        return redirect(url_for('administrator.administrator_landing'))
    if request.method == 'GET':
        return render_template('mentor_bulk.html',
                               mentors=mentors,
                               registered_mentors=registered_mentors)
Exemplo n.º 21
0
def send_email():

    form = SendEmailForm(request.form)
    errors = []
    serialized_users = []

    if form.is_submitted():
        is_validated = True
        emails = form.emails.data.split(",")

        if len(emails) == 0:
            is_validated = False
            errors.append(gettext("Insert users to send email"))
        if form.title.data.strip() == "":
            is_validated = False
            errors.append(gettext("Email title is required"))
        if form.content.data.strip() == "":
            is_validated = False
            errors.append(gettext("Email content is required"))

        if is_validated:
            if form.action.data == "send":
                send_mail(emails, form.title.data, form.content.data)
            else:
                send_mail([g.user.email], form.title.data, form.content.data)

        query_text = ""
        for index, email in enumerate(emails):
            if email != "":
                if index == 0:
                    query_text += "email='" + email + "'"
                else:
                    query_text += "or email='" + email + "'"
        users = User.query.filter(query_text).all()
        for user in users:
            serialized_users.append({"email": user.email, "name": user.username})
        return render_template("admin/send_email.html", form=form, errors=errors, users=serialized_users)

    form.title.data = ""
    form.emails.data = ""
    form.content.data = ""
    return render_template("admin/send_email.html", form=form, errors=[])
Exemplo n.º 22
0
def send_recovery_password(user):
    token = generate_confirmation_token(user.email)
    recovery_url = url_for('user.recovery_password_last',
                           token=token,
                           _external=True)
    subject = 'Восстановление пароля'
    template = render_template('recovery_password_message.html',
                               recovery_url=recovery_url)
    confirm_message = Message(subject,
                              recipients=[user.email],
                              html=template,
                              sender=app.config['MAIL_DEFAULT_SENDER'])
    try:
        send_mail(confirm_message)
    except smtplib.SMTPAuthenticationError:
        return {'status': False, 'message': 'Не удалось отправить сообщение'}
    return {
        'status': True,
        'message':
        'На вашу почту отправлена инструкция для восстановления пароля'
    }
Exemplo n.º 23
0
def confirm_student(sid):
    confirmed_student = Student.query.get(sid)
    if not confirmed_student:
        return redirect(url_for('administrator.administrator_landing'))
    if request.method == 'POST':
        error = ''
        try:
            confirm_student_from_form(request)
            confirmed_student.approved = True
            db.session.commit()
            approved_student_message = Notification.query.filter_by(
                identifier=NotificationIdentifiers.APPROVAL).first().message
            send_mail(
                Message('Approved For Open Doors Opportunity',
                        body=approved_student_message,
                        recipients=[
                            confirmed_student.student_email,
                            confirmed_student.parent_email
                        ]))
        except StudentConfirmationUnconfirmedException:
            error = Errors.STUDENT_CONFIRMATION_UNCONFIRMED_ERROR
        except Exception as e:
            logging.exception(e)
            traceback.print_exc()
        finally:
            if error:
                db.session.rollback()
                return render_template('confirm_student.html',
                                       error=error,
                                       student=confirmed_student,
                                       format_date=format_date,
                                       get_session=get_session)
        return redirect(
            url_for('mentor.mentor_schedule',
                    mid=confirmed_student.opportunity.mentor.id))
    if request.method == 'GET':
        return render_template('confirm_student.html',
                               student=confirmed_student,
                               format_date=format_date,
                               get_session=get_session)
Exemplo n.º 24
0
def delete_student(sid):
    deleted_student = Student.query.get(sid)
    approved = deleted_student.approved
    student_email = deleted_student.student_email
    mentor = deleted_student.opportunity.mentor
    if not deleted_student:
        return redirect(url_for('administrator.administrator_landing'))
    if request.method == 'POST':
        error = ''
        try:
            delete_student_from_form(request)
            mentor.waitlist_active = False
            db.session.delete(deleted_student)
            db.session.commit()
            if approved:
                delete_approved_student_message = Notification.query.filter_by(
                    identifier=NotificationIdentifiers.DELETED).first().message
                send_mail(
                    Message('Removed From Open Doors Opportunity',
                            body=delete_approved_student_message,
                            recipients=[student_email]))
            else:
                denied_student_message = Notification.query.filter_by(
                    identifier=NotificationIdentifiers.DENIED).first().message
                send_mail(
                    Message('Denied From Open Doors Opportunity',
                            body=denied_student_message,
                            recipients=[student_email]))
            notifications = MentorNotification.query.filter_by(
                mentor=mentor).all()
            available_opportunity_message = Notification.query.filter_by(
                identifier=NotificationIdentifiers.MENTOR_NOTIFICATION).first(
                ).message
            for notification in notifications:
                send_mail(
                    Message(
                        'An Opportunity For ' + mentor.mentor_name +
                        ' Is Available',
                        body=available_opportunity_message +
                        '\n Remember, this opportunity is a first come, first serve basis. To see if this opportunity is available, see if registrations are available on this mentor.',
                        recipients=[notification.email]))
        except UnconfirmedDeletionException:
            error = Errors.UNCONFIRMED_DELETION_ERRROR
        except Exception as e:
            logging.exception(e)
            traceback.print_exc()
        finally:
            if error:
                db.session.rollback()
                return render_template('delete_student.html',
                                       error=error,
                                       student=deleted_student,
                                       format_date=format_date,
                                       get_session=get_session)
        return redirect(url_for('administrator.administrator_landing'))
    if request.method == 'GET':
        return render_template('delete_student.html',
                               student=deleted_student,
                               format_date=format_date,
                               get_session=get_session)
Exemplo n.º 25
0
 def test_send_mail(self):
     # TODO: Mock the real Mailgun response
     r = send_mail(self.mail_from, self.mail_to, self.mail_subject,
                   self.mail_text)
     self.assertEqual(r.status_code, requests.codes.ok)
     self.assertEqual(r.json()["message"], "Queued. Thank you.")
Exemplo n.º 26
0
	def test_sendmail(self):
		result = appl.send_mail("*****@*****.**","unit_testing_by_hari")
		self.assertEqual(result,"ok")
Exemplo n.º 27
0
def resend_confirmation():
    token = current_user.generate_confirmation_token()
    send_mail(current_user.email, 'Confirm Your Account', 'mail/confirm', user = current_user, token = token)
    flash('A new confirmation email has been sent to you')
    return redirect(url_for('index'))
Exemplo n.º 28
0
def register():
    """
    Registration Form
    """
    
    form = RegisterForm(request.form)
    errors = []
    

    if form.is_submitted():
        is_validated = True
        if form.name.data.strip() == '':
            is_validated = False
            errors.append(gettext('Username is required'))
        #validate email
        if form.email.data.strip() == '':
            is_validated = False
            errors.append(gettext('Email is required'))
        #validate valid email
        match = re.search(r'^.+@([^.@][^@]+)$', form.email.data.strip())
        if not match:
            is_validated = False
            errors.append(gettext('Invalid email address'))
        
        if form.password.data.strip() == '':
            is_validated = False
            errors.append(gettext('Password field is required'))
            
        if form.confirm.data.strip() == '':
            is_validated = False
            errors.append(gettext('You have to confirm your password'))
        if form.confirm.data != form.password.data:
            is_validated = False
            errors.append(gettext('Passwords must match'))
        
        if len(form.recaptcha.errors) > 0:
            is_validated = False
            errors.append(gettext('Captcha was incorrect'))
            
        if is_validated:
            same_username_user = User.query.filter_by(username=form.name.data).first()
            same_email_user = User.query.filter_by(email=form.email.data).first()
            if same_email_user is not None:
                errors.append(gettext('Duplicate email address'))
            if same_username_user is not None:
                errors.append(gettext('Duplicate username'))

            if len(errors) > 0:
                return render_template("users/register.html", form=form, errors=errors)

            # Insert the record in our database and commit it
            user = User(username=form.name.data.lower(), email=form.email.data,
                        password=generate_password_hash(form.password.data))
            user.verification_code = utilities.generate_random_string(50)
            user.banned = 2
            db.session.add(user)
            db.session.commit()
            
            # send confirm email and redirect to confirm page
            email_activation = Journal.query.filter(Journal.id==120).first().get_journal_content(session['locale'])
            send_mail([user.email], email_activation.title, render_template_string(email_activation.content, activate_link=url_for('users.verify_account', code=user.verification_code, _external=True)))
            return render_template("users/register_finish.html", email=user.email)
        else:
            return render_template("users/register.html", form=form, errors=errors)
    return render_template("users/register.html", form=form, errors=[])
Exemplo n.º 29
0
def send_email(id):
    user = User.query.filter_by(id=id).first()
    token = user.generate_confirmation_token()
    send_mail(user.email, '确认账户', 'auth/confirm', user=user, token=token)
    return redirect(url_for('main.index'))
Exemplo n.º 30
0
def register():
    """
    Registration Form
    """

    form = RegisterForm(request.form)
    errors = []

    if form.is_submitted():
        is_validated = True
        if form.name.data.strip() == '':
            is_validated = False
            errors.append(gettext('Username is required'))
        #validate email
        if form.email.data.strip() == '':
            is_validated = False
            errors.append(gettext('Email is required'))
        #validate valid email
        match = re.search(r'^.+@([^.@][^@]+)$', form.email.data.strip())
        if not match:
            is_validated = False
            errors.append(gettext('Invalid email address'))

        if form.password.data.strip() == '':
            is_validated = False
            errors.append(gettext('Password field is required'))

        if form.confirm.data.strip() == '':
            is_validated = False
            errors.append(gettext('You have to confirm your password'))
        if form.confirm.data != form.password.data:
            is_validated = False
            errors.append(gettext('Passwords must match'))

        if len(form.recaptcha.errors) > 0:
            is_validated = False
            errors.append(gettext('Captcha was incorrect'))

        if is_validated:
            same_username_user = User.query.filter_by(
                username=form.name.data).first()
            same_email_user = User.query.filter_by(
                email=form.email.data).first()
            if same_email_user is not None:
                errors.append(gettext('Duplicate email address'))
            if same_username_user is not None:
                errors.append(gettext('Duplicate username'))

            if len(errors) > 0:
                return render_template("users/register.html",
                                       form=form,
                                       errors=errors)

            # Insert the record in our database and commit it
            user = User(username=form.name.data.lower(),
                        email=form.email.data,
                        password=generate_password_hash(form.password.data))
            user.verification_code = utilities.generate_random_string(50)
            user.banned = 2
            db.session.add(user)
            db.session.commit()

            # send confirm email and redirect to confirm page
            email_activation = Journal.query.filter(
                Journal.id == 120).first().get_journal_content(
                    session['locale'])
            send_mail([user.email], email_activation.title,
                      render_template_string(email_activation.content,
                                             activate_link=url_for(
                                                 'users.verify_account',
                                                 code=user.verification_code,
                                                 _external=True)))
            return render_template("users/register_finish.html",
                                   email=user.email)
        else:
            return render_template("users/register.html",
                                   form=form,
                                   errors=errors)
    return render_template("users/register.html", form=form, errors=[])
Exemplo n.º 31
0
def reset_password():

    token = request.args.get('token', '')
    if token != '':
        user = User.query.filter_by(password_token=token).first()
        if user is not None:

            new_password = utilities.generate_random_string(20)
            user.password = generate_password_hash(new_password)
            user.password_token = ''
            db.session.commit()

            email_content = Journal.query.filter(
                Journal.id == 122).first().get_journal_content(
                    session['locale'])
            send_mail([user.email], email_content.title,
                      render_template_string(email_content.content,
                                             new_password=new_password))
            return render_template("users/reset_password_confirmed.html"), 200

    form = ResetPasswordForm(request.form)
    errors = []
    # make sure data are valid, but doesn't validate password is right
    if form.is_submitted():
        is_validated = True
        if form.email.data.strip() == '':
            is_validated = False
            errors.append(gettext('Email is required'))
        #validate valid email
        match = re.search(r'^.+@([^.@][^@]+)$', form.email.data.strip())
        if not match:
            is_validated = False
            errors.append(gettext('Invalid email address'))

        if is_validated:
            user = User.query.filter_by(
                email=form.email.data).first()  # @UndefinedVariable

            if user is None:
                errors.append(gettext('Account not found'))
                return render_template("users/reset_password.html",
                                       form=form,
                                       errors=errors), 404

            if user.banned == 1:
                errors.append(
                    gettext(
                        'The account was banned, please contact an admin for more information'
                    ))
                return render_template("users/reset_password.html",
                                       form=form,
                                       errors=errors), 400

            user.password_token = utilities.generate_random_string(50)
            db.session.commit()

            # we use werzeug to validate user's password
            email_content = Journal.query.filter(
                Journal.id == 121).first().get_journal_content(
                    session['locale'])
            send_mail([user.email], email_content.title,
                      render_template_string(email_content.content,
                                             link=url_for(
                                                 'users.reset_password',
                                                 token=user.password_token,
                                                 _external=True)))
            db.session.commit()
            return render_template("users/reset_password_submited.html"), 200
        else:
            return render_template("users/reset_password.html",
                                   form=form,
                                   errors=errors), 200

    return render_template("users/reset_password.html", form=form, errors=[])