Example #1
0
    def part2_reimplement(self,user):
        '''select random answer to game of part2 (GameImpatience)
            store in db
        '''
        if  GameImpatience.query.filter(GameImpatience.user_id==user.id,\
                    GameImpatience.survey_id==self.survey.id).first() is None:
            ans = Answer.query.filter(\
                Answer.user_id==user.id,\
                Answer.question_id==self.select_game["part2",True][0]).first()
            if ans is not None:
                #game with real money
                question = random.choice(self.select_game["part2",True])
                is_real_money=True
            else:
                question = random.choice(self.select_game["part2",False])
                is_real_money=False

            answer = Answer.query.filter_by(user_id=user.id,question_id=question).first()
            game = GameImpatience(user=user, answer = answer,\
                survey=self.survey, is_real_money=is_real_money)
            self._flag_status(user.id, ("part2",is_real_money))
            db.session.add(game)
            db.session.commit()
            # email
            if game.prize:
                send_email(user.email,'Premio','game/email/premio_parte2',
                    user=user,
                    premio=game.answer.answerText)
def register():
    """Register the user directly (not through a social account)."""

    if current_user.is_authenticated():
        return redirect(url_for('mod_feed.index'))

    form = RegisterForm()

    if form.validate_on_submit():
        # Register User into database
        user = User(email=form.email.data,
                    password=form.password.data)
        db.session.add(user)
        db.session.commit()

        # Send email to confirm user
        token = user.generate_confirmation_token()
        send_email(user.email, 'Confirm your Account',
                   'auth/email/confirm', user=user, token=token)

        # Create a `Saved` magazine
        magazine = Magazine(name='Saved', public=False,
                            user_id=user.id, removable=False)
        db.session.add(magazine)
        db.session.commit()
        user.saved_magazine = magazine.id

        flash('An activation email has been sent to your account')
        return redirect(url_for('mod_feed.index'))

    return render_template('auth/register.html', form=form)
Example #3
0
def service():
    form = ServiceForm()
    if current_user.is_authenticated:
        form.pin.data = current_user.pin
    if form.validate_on_submit():
        brother = Brother.query.filter_by(pin=form.pin.data).first()
        serv = Service(brother_id=brother.id,
                       start=form.start.data,
                       end=form.end.data,
                       info=form.info.data,
                       name=form.name.data,
                       semester_id=g.current_semester.id)
        db.session.add(serv)
        db.session.commit()
        try:
            svcid = Position.query.filter_by(name="Service Chair").first()
            svcchair = Brother.query.filter_by(position_id=svcid.id).first()
            path = urlparse(request.base_url)
            body = "{} has submitted service hours for approval. Go to {}://{}{}?id={} to review.".format(
                    brother.name, path.scheme, path.netloc, url_for('service.edit_view'), serv.id)
            send_email("KDRPoints",
                    "Service hours submitted by " + brother.name,
                        [svcchair.email],
                        body,
                        body)
        except: pass

        flash("Service submitted successfully", category="good")
    else:
        flash_wtferrors(form)
    return render_template('service.html', title="Service", form=form)
    def test_done_task_send_email(self):
        '''タスク実行結果のメールが正しく送信できるかのテスト
        '''
        SEND_TO = '*****@*****.**'

        task_title = 'test task'
        done_datetime = datetime.datetime.now()
        set_time = 500
        start_hour = 13
        start_minute = 55
        serial_passed_time = 1000
        set_hour = set_time // 3600
        set_minute = (set_time % 3600) // 60
        serial_passed_hour = serial_passed_time // 3600
        serial_passed_minute = (serial_passed_time % 3600) // 60
        over_time = serial_passed_time - set_time
        over_hour = over_time // 3600
        over_minute = (over_time % 3600) // 60

        send_email(SEND_TO, task_title, 'mail/task_done',
                        task_title=task_title,
                        done_datetime=done_datetime,
                        set_hour=set_hour,
                        set_minute=set_minute,
                        start_hour=start_hour,
                        start_minute=start_minute,
                        serial_passed_hour=serial_passed_hour,
                        serial_passed_minute=serial_passed_minute,
                        over_time=over_time,
                        over_hour=over_hour,
                        over_minute=over_minute,
                        )
Example #5
0
def change_email_request():
    '''auth.change_email_request()'''
    form = ChangeEmailForm()
    if form.validate_on_submit():
        if current_user.verify_password(form.password.data):
            new_email = form.email.data.strip().lower()
            token = current_user.generate_email_change_token(new_email)
            send_email(
                recipient=new_email,
                subject='确认您的邮箱账户',
                template='auth/mail/change_email',
                user=current_user._get_current_object(),
                token=token
            )
            flash('一封确认邮件已经发送至您的邮箱', category='info')
            add_user_log(
                user=current_user._get_current_object(),
                event='请求修改邮箱为:{}'.format(new_email),
                category='auth'
            )
            return redirect(url_for('auth.change_email_request'))
        flash('无效的用户名或密码', category='error')
        return redirect(url_for('auth.change_email_request'))
    return minify(render_template(
        'auth/change_email.html',
        form=form
    ))
Example #6
0
def export_posts(user_id):
    try:
        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'})
            time.sleep(5)
            i += 1
            _set_task_progress(100 * i // 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)
        app.logger.error('Unhandled exception', exc_info=sys.exc_info())
Example #7
0
def sign_up():
    if 'remember_me' in session:
        return redirect(url_for("index"))
    form = SignUpForm()
    if form.validate_on_submit():
        u_nickname = User.query.filter_by \
            (nickname=form.nickname.data).first()
        u_mail = User.query.filter_by \
            (email=form.email.data).first()
        if u_nickname is not None:
            flash('user with such nickname exist', 'danger')
        elif  u_mail is not None:
            flash('user with such email exist', 'danger')
        else:
            user = User(nickname=form.nickname.data,
                        password=form.password.data,
                        email=form.email.data)
            if user:
                db.session.add(user)
                db.session.commit()
                token = generate_confirmation_token(user.email)
                confirm_url = url_for('confirm_email',
                                      token=token,
                                      _external=True)
                html = render_template('activation.html',
                                       confirm_url=confirm_url)
                subject = "Please confirm your email"
                send_email(user.email, subject, html)
                flash('You are signed up! Pleaese confirm your mail,'
                      ' confirmation email was sent to you email')
            else:
                flash('Wrong enter', 'danger')
    return render_template('sign_up.html',
                           title = 'Sign up',
                           form = form)
def contact():
	'''

	Contact view function

	.. function::
		renders cantact_base.html
		sends Emails to Admin and
		a Notification to the contact email address



	:return: redirect on submit, else logintemplate
	'''
	form = ContactForm()

	if request.method == 'POST' and form.validate_on_submit():
		send_email(form.contact_email.data,
		           'Notification',
		           'email/contact_notify')

		send_email('*****@*****.**',
		           'You Got a Message',
		           'email/contact_admin',
		           contact_email=form.contact_email,
		           contact_message=form.contact_message)
		flash('Email was sent!')
	# return redirect('/')

	return render_template('contact_base.html', contact_form=form)
Example #9
0
def registration():
    if request.method == 'GET':
        return render_template('auth/registration.html', title='Registration',
                               form=RegistrationForm())

    form = RegistrationForm()
    username = form.username.data
    full_name = form.full_name.data
    email = form.email.data
    password = form.password.data

    if form.validate_on_submit():
        try:
            mongo.db.users.insert({'_id': username,
                                   'full_name': full_name,
                                   'email': email,
                                   'password': User.generate_hash(password),
                                   'registered_in': datetime.datetime.utcnow()
                                   })

            flash('Successfully created an account!', category='success')
            send_email(email, full_name, username, password)
            return redirect(url_for("auth.login"))
        except DuplicateKeyError:
            flash('Username already exist', category='error')
    return render_template('auth/registration.html', form=form)
Example #10
0
 def on_model_change(self, form, model, is_created):
     if form.approved.data:
         semester = models.Semester.query.filter_by(current=True).one()
         donehrs = form.brother.data.total_service_hours(semester)
         svchrs = (form.end.data - form.start.data).seconds/3600.0
         remaining = semester.required_service - donehrs
         if not model.email_sent:
             svcmsg ="The service hours you reported for '{}' have just been approved by {} (The weight for this service was {}). ".format(
                 form.name.data,
                 current_user.name,
                 model.weight)
             if remaining > 0:
                 svcmsg += "You have {} service hour(s) left to do this semester (out of {}).".format(remaining, semester.required_service)
             else:
                 svcmsg += "You have completed your service hours for this semester! You currently have {}.".format(donehrs)
             send_email("Service Chair (points)",
                        str(svchrs*float(model.weight)) + " service hour" +
                        ("" if svchrs == 1 else "s") + " have been approved!",
                        [form.brother.data.email],
                        svcmsg,
                        svcmsg
                        )
             model.email_sent = True
             db.session.add(model)
             db.session.commit()
     else:
         model.email_sent = False
         db.session.add(model)
         db.session.commit()
Example #11
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.')
    return redirect(url_for('main.index'))
Example #12
0
def register():
    """Provides registering for user"""

    # if register form is submitted
    form = RegisterForm(request.form)

    # verify the register form
    if form.validate_on_submit():
        # create user and add to database
        user = User(
            username=form.username.data,
            password=generate_password_hash(form.password.data),
            email=form.email.data
        )
        db.session.add(user)
        db.session.commit()

        # sending email
        token = generate_confirmation_token(user.email)
        confirm_url = url_for('users.confirm_email', token=token, _external=True)
        html = render_template('users/activate.html', confirm_url=confirm_url)
        subject = gettext(u"Please confirm your email")
        send_email(user.email, subject, html)

        #login_user(user)

        # everything okay so far
        flash(gettext(u'Confirmation email has been sent'), 'info')
        return redirect(url_for('users.login'))

    return render_template('users/register.html', form=form)
Example #13
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))
Example #14
0
def login_user(token):
    '''api.login_user(token)'''
    data = load_y_vod_token(token=token)
    if verify_data_keys(data=data, keys=['email', 'password', 'device']):
        user = User.query.filter_by(
            email=data.get('email'),
            created=True,
            deleted=False
        ).first()
        if user is not None:
            if not user.activated:
                return jsonify({'error': '您的账户尚未激活'})
            if not user.confirmed:
                return jsonify({'error': '您的邮箱尚未确认'})
            if user.is_suspended:
                return jsonify({'error': '您的账户已被挂起'})
            if not user.locked:
                if user.verify_password(data.get('password')):
                    user.reset_invalid_login_count()
                    db.session.commit()
                    if user.plays('协管员'):
                        send_email(
                            user.email,
                            'Y-VOD登录提醒',
                            'auth/mail/y_vod/login',
                            user=user,
                            device=data.get('device'),
                            timestamp=datetime_now(utc_offset=current_app.config['UTC_OFFSET'])
                        )
                    add_user_log(
                        user=user,
                        event='登录Y-VOD(来源:{})'.format(data.get('device')),
                        category='access'
                    )
                    return jsonify(user.y_vod_user_json)
                user.increase_invalid_login_count()
                db.session.commit()
                if user.locked:
                    send_emails(
                        recipients=[staff.email for staff in User.all_can('管理用户').all() \
                            if staff.has_inner_domain_email],
                        subject='锁定用户:{}'.format(user.name_email),
                        template='auth/mail/y_vod/lock_user',
                        user=user,
                        device=data.get('device'),
                    )
                add_user_log(user=user, event='登录失败:密码错误(第{}次,来源:{})'.format(
                    user.invalid_login_count,
                    data.get('device')
                ), category='access')
                return jsonify({'error': '密码错误(第{}次,来源:{})'.format(
                    user.invalid_login_count,
                    data.get('device')
                )})
            return jsonify({'error': '您的账户已被锁定'})
        return jsonify({'error': '无效的用户名或密码'})
    return jsonify({'error': '用户信息无效'})
Example #15
0
def prueba_correo():
    from app import email
    from app.models import User

    user1 = User.query.get(1)
    flash(app.debug)
    flash ("enviando correo")
    email.send_email('*****@*****.**',"prueba","email/prueba", user=user1)
    return render_template('index.html')
Example #16
0
def resend_confirmation_email():
    # resending email
    token = generate_confirmation_token(current_user.email)
    confirm_url = url_for('users.confirm_email', token=token, _external=True)
    html = render_template('users/activate.html', confirm_url=confirm_url)
    subject = gettext(u'Please confirm your email')
    send_email(current_user.email, subject, html)

    flash(gettext(u'Confirmation email has been sent'), 'info')
    return redirect(url_for('users.account'))
Example #17
0
def sharing():
    form = ShareForm()
    if request.method == 'POST':
        email = request.form['email']
        # confirm_url = "http://www.tv.com/"
        # html = render_template('profile_views.html', confirm_url=confirm_url)
        subject = "Please see my wishlist"
        send_email(email, subject)
        return redirect("/")
    return render_template('sharing.html', form=form)
Example #18
0
 def _prize_decision4_6_playerB(self,user,decision):
     game = Game.query.filter(\
         Game.survey_id==self.survey.id,\
         Game.type==decision,\
         Game.userB_id==user).first()
     game.prizeB=True
     # email
     send_email(game.userB.email,'Premio','game/email/premio_parte3',
         user=game.userB,premio=game.moneyB)
     db.session.add(game)
Example #19
0
def login():
    '''auth.login()'''
    if current_user.is_authenticated:
        return redirect(request.args.get('next') or current_user.index_url)
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(
            email=form.email.data.strip().lower(),
            created=True,
            activated=True,
            deleted=False
        ).first()
        if user is not None:
            if not user.locked:
                if user.verify_password(form.password.data):
                    user.reset_invalid_login_count()
                    db.session.commit()
                    login_user(user, remember=form.remember_me.data)
                    if user.plays('协管员'):
                        send_email(
                            recipient=user.email,
                            subject='登录提醒',
                            template='auth/mail/login',
                            user=user,
                            timestamp=datetime_now(utc_offset=current_app.config['UTC_OFFSET'])
                        )
                    get_announcements(type_name='登录通知', flash_first=True)
                    add_user_log(user=user, event='登录系统', category='access')
                    return redirect(request.args.get('next') or user.index_url)
                user.increase_invalid_login_count()
                db.session.commit()
                if user.locked:
                    send_emails(
                        recipients=[staff.email for staff in User.all_can('管理用户').all() \
                            if staff.has_inner_domain_email],
                        subject='锁定用户:{}'.format(user.name_email),
                        template='auth/mail/lock_user',
                        user=user
                    )
                flash('登录失败:密码错误(第{}次)'.format(user.invalid_login_count), category='error')
                add_user_log(user=user, event='登录失败:密码错误(第{}次,来源:{})'.format(
                    user.invalid_login_count,
                    get_geo_info(
                        ip_address=request.headers.get('X-Forwarded-For', request.remote_addr),
                        show_ip=True
                    )
                ), category='access')
                return redirect(url_for('auth.login'))
            flash('登录失败:您的账户已被锁定', category='error')
            return redirect(url_for('auth.login'))
        flash('登录失败:无效的用户名或密码', category='error')
    return minify(render_template(
        'auth/login.html',
        form=form
    ))
Example #20
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_confirm_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("auth.login"))
    return render_template("auth/register.html", form=form)
Example #21
0
def new_user():
    the_form = UserForm()
    if the_form.validate_on_submit():
        user = User(login=the_form.login.data, password=the_form.password.data, email=the_form.email.data)
        modules['db'].session.add(user)
        modules['db'].session.commit()
        flash('Ok, user '+user.login+' registered successfully! Confirmation email has been sent to '+user.email)
        token = user.generate_confirmation_token()
        send_email(user.email, "Account confirmation", 'auth/email/confirm', user=user, token=token)
        return redirect(url_for('.index'))
    return render_template('new_user.html', new_user_form=the_form)
Example #22
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"))
Example #23
0
def confirm(token):
    if current_user.confirmed:
        return redirect(url_for('main.index'))
    if current_user.confirm(token):
        flash(_('Bạn đã xác nhận địa chỉ email thành công!'))
        send_email(current_app.config['MAIL_ADMIN'],
                   'Có thành viên mới xác nhận',
                   'admin/email/new_user', user=current_user)
    else:
        flash(_('Đường dẫn xác nhận không đúng hoặc đã hết hạn'))
    return redirect(url_for('main.index'))
def session():
    users = User.query.all()
    if request.method == 'POST':
        for user in users:
            if str(user.username+' ') == str(request.form.get('usernames')):
                print user.username
                chat_room = request.form.get('chat_room')
                session_link = request.form.get('session_link')
                send_email(current_user.email, user.email, "pairUp Invite", 'mail/invite', user=user,  current_user=current_user, chat_room=chat_room,
                           session_link=session_link)
                print str(chat_room) + ': '+str(session_link)
    return render_template('main/session.html', users=users)
Example #25
0
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(username=form.username.data, email=form.email.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 have been sent to you by email.')
        return redirect(url_for('main.index'))
    return render_template('auth/register.html', form=form)
Example #26
0
def invite():
    users = User.query.all()
    if request.method == 'POST':
        for user in users:
            print user.username == str(request.form.get('usernames'))
            if str(user.username) == str(request.form.get('usernames')):
                session_link = request.form.get('session_link')
                send_email(current_user.email, user.email, "Join me in my session!", 'mail/invite', user=user,  current_user=current_user, session_link=session_link)
                print str(session_link)
                print True

    return render_template('main/home.html', users=users)
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_token(new_email)
            send_email(new_email, 'Confirm your email address', 'mail/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)
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', 'mail/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)
Example #29
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, 'Xác nhận tài khoản của bạn',
                   'auth/email/confirm', user=user, token=token)
        flash(_('Một thư xác nhận đã được gửi tới địa chỉ email đăng ký'))
        return redirect(url_for('auth.login'))
    return render_template('auth/register.html', form=form)
def register():
    form = RegistrationForm()
    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()
        login_user(user)
        token = user.generate_confirmation_token()
        send_email(user.email, 'Confirm Your Account', 'mail/confirm', user=user, token=token)
        flash('Welcome %s! A confirmation email has been ent to you by email.' % user.username)
        return redirect(url_for('main.index'))

    return render_template('auth/registration.html', form=form)
Example #31
0
def reset_password_request():
    if current_user.is_authenticated:  # should never reach due to dynamically showing logout/ login
        return redirect(url_for('main.index'))
    form = ResetPasswordForm()
    if form.validate_on_submit():
        user_from_db = db.users.find_one({"email": form.email.data})
        if user_from_db:
            user_ = User(id=user_from_db['_id'], email=user_from_db['email'],
                         password_hash=user_from_db['password_hash'], favorites=user_from_db['favorites'])
            reset_token = user_.get_reset_password_token()
            send_email('Reset Your Password',
                       sender=current_app.config['ADMINS'][0],
                       recipients=[user_.email],
                       text_body=render_template('email/reset_password.txt', user=user_, token=reset_token),
                       html_body=render_template('email/reset_password.html', user=user_, token=reset_token)
                       )
            flash('Check your email for reset instructions')
            return redirect(url_for('auth.login'))
        else:
            flash('Email not recognized, please try again')

    return render_template('auth/reset_password_request.html', title='Reset Password', form=form)
    def post(self, current_user, args):
        ''' register user endpoint '''
        role_type = args.get('roleType', 'User')
        if role_type not in ['Admin', 'User']:
            raise BadRequest(message='Role type must be Admin or User')
        billing_type = args.get('billingType', 'Monthly')
        if billing_type not in ['Monthly', 'Metered']:
            raise BadRequest(message='Billing type must be Monthly or Metered')
        args['billingType'] = billing_type_repo.get_by_billing_type(
            billing_type).id
        args['roleType'] = role_type
        created_by = args.get(
            'username') if current_user is None else current_user.username
        args['createdBy'] = args.get('createdBy', created_by)
        if 'username' not in args and 'email' not in args:
            raise BadRequest(code=400,
                             message='Username or email must be required')
        args['password'] = flask_bcrypt.generate_password_hash(
            args['password'])

        user, message = user_repo.insert_one(args)
        if user is None:
            raise BadRequest(code=400, message=message)
        token = user_repo.generate_registration_token(user)
        url = "{path}/v1/admin/users/verify?token={token}".format(
            path=current_app.config.get('API_URL'), token=token)
        send_email(subject='[TheVault] Email Registration',
                   sender=current_app.config['MAIL_USERNAME'],
                   recipients=[user.email],
                   html_body=render_template('email/email_verification.html',
                                             user=user,
                                             url=url))
        data = user._data
        del data['password']
        return {
            'item': to_json(data),
            'message': 'Signup user is successful'
        }, 201
Example #33
0
    def notify(self):
        current_app.logger.info('Notifiying admin of comment')
        obj = None
        obj_name = ''
        obj_link = ''
        page = None

        if self.page_id:
            obj = self.page
            obj_name = obj.title
            obj_link = current_app.config['BASE_URL'] + obj.path
            page = self.page
        else:
            obj = self.product
            obj_name = obj.name
            obj_link = url_for('shop.view', slug=obj.slug)
            page = Page.query.filter_by(slug='home').first()

        sender = current_app.config['MAIL_DEFAULT_SENDER']
        subject=f"[New Comment] {obj_name} - {self.author()}"
        body=f"The following comment was made by {self.author()} on the {obj.__class__.__name__} {obj_name}.\n\n{self.body}\n\nRead more: {obj_link}"

        if current_app.config.get('ADMINS'):
            for recipient in current_app.config['ADMINS']:
                send_email(
                        subject,
                        sender,
                        [recipient],
                        body,
                        render_template('email/comment-notification.html', 
                                page=page, 
                                comment=self,
                                recipient=recipient,
                                obj=obj,
                                obj_name=obj_name,
                                obj_link=obj_link,
                            ),
                    )
Example #34
0
def reset_password_request():
    """Respond to existing user's request to reset their password."""
    if not current_user.is_anonymous:
        return redirect(url_for('main.index'))
    form = RequestResetPasswordForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user:
            token = user.generate_password_reset_token()
            reset_link = url_for(
                'account.reset_password', token=token, _external=True)
            flash('A password reset link has been sent to {}.'.format(
                form.email.data), 'warning')
            send_email(
                recipient=user.email,
                subject='Reset Your Password',
                template='account/email/reset_password',
                user_name=user.name,
                reset_link=reset_link,
                next=request.args.get('next')
            )
        return redirect(url_for('account.login'))
    return render_template('account/reset_password.html', form=form)
Example #35
0
    def mailsend(start, stop):
        """send expiring access today."""
        print("start: %s stop: %s" % (start, stop))
        if current_app.config['MAIL_ENABLED'] is False:
            print("mail sending is disabled")
            return

        access = Access.query.filter(
            func.datetime(Access.stop) > start,
            func.datetime(Access.stop) < stop).all()

        from app.email import send_email

        for a in access:
            stopdate = a.stop.strftime("%Y-%m-%d")

            send_email(f'[PYRA] Role: {a.role.name} is expiring at {stopdate}',
                       sender=current_app.config['MAIL_DEFAULT_SENDER'],
                       recipients=[a.user.email],
                       text_body=render_template('email/expiring_access.txt',
                                                 access=a),
                       html_body=render_template('email/expiring_access.html',
                                                 access=a))
Example #36
0
def post(id):
    post = Post.query.get_or_404(id)
    form = CommentForm()
    praised = False
    if form.validate_on_submit():
        comment = Comment(body=form.body.data,
                          disabled=False,
                          post=post,
                          author=current_user._get_current_object())
        db.session.add(comment)
        send_email(post.author.email, 'new comment', 'auth/email/comment',user=post.author,post=post)
        flash('你的评论已提交')
        return redirect(url_for('.post', id=post.id))
    page = request.args.get('page', 1, type=int)
    pagination = post.comments.filter_by(disabled=False).order_by(Comment.timestamp.desc()).paginate(
        page, per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'], error_out=False
    )
    comments = pagination.items
    if current_user.is_anonymous:
        praised = True
    elif post.praised_by_users.filter_by(id=current_user.id).first():
        praised = True
    return render_template('post.html', post=post, form=form, comments=comments, pagination=pagination, praised=praised)
Example #37
0
def confirm_request():
    """Respond to new user's request to confirm their account."""
    token = current_user.generate_confirmation_token()
    confirm_link = url_for('account.confirm', token=token, _external=True)
    status = send_email(recipient=current_user.email,
                        subject='Confirm Your Account',
                        template='account/email/confirm',
                        user=current_user._get_current_object(),
                        confirm_link=confirm_link)

    flash(
        'A new confirmation link has been sent to {}.'.format(
            current_user.email), 'warning')
    return redirect(url_for('main.index'))
Example #38
0
def sign_up():
    user_details = get_user_details()

    if is_user_registered(user_details[0]) and is_user_confirmed(user_details[0]):
        return redirect('/home')

    if is_user_registered(user_details[0]) and not is_user_confirmed(user_details[0]):
        return redirect(url_for('userManagement.unconfirmed'))

    r_form = RegistrationForm(request.form)
    if request.method == "GET":
        r_form.username.data = user_details[1]
        r_form.email.data = user_details[2]

    if r_form.validate_on_submit():
        user = User(username=r_form.username.data, email=r_form.email.data, eppn=user_details[0], role_id=2)
        db.session.add(user)
        db.session.commit()
        DirectoryAndFileWriter.create_user_directory(get_user_id(user_details[0]))
        send_email(current_app.config['ADMIN_MAIL_ADDRESS'], 'New user has registered', 'mail/new_user', user=user, comment=r_form.comment.data)
        return redirect(url_for('userManagement.unconfirmed'))

    return render_template('sign_up.html', r_form=r_form)
Example #39
0
    def send_email(self, subject, html_body, force_send=False):
        """ Send the user an email if they are active
        Allow overriding for things like account activation
        """
        if self is None:
            current_app.logger.error(
                "Could not send email becuase could not find user - subject '%s'"
                % (subject))
            return

        if not (self.active and self.confirmed) and not force_send:
            current_app.logger.info(
                "Did not send email to id %s (%s) because account inactive - subject '%s'"
                % (self.id, self.email, subject))
            return

        if not self.enable_notification_emails and not force_send:
            current_app.logger.info(
                "Did not send email to id %s (%s) because account disabled notification emails - subject '%s'"
                % (self.id, self.email, subject))
            return

        send_email(self.email, subject, html_body)
Example #40
0
def export_posts(user_id):
	try:
		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'})
			time.sleep(5)
			i += 1
			_set_task_progress(100 * i)

		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', 'apllication/json', json.dumps({'posts': data}, indent=4))],
					sync=True)
	except:
		_set_task_progress(100)
		app.logger.error('Unhandled exception', exc_info=sys.exc_info())
Example #41
0
def group_order(gid):
    form = OrderForm()
    if form.validate_on_submit():
        order = Orders(username=form.username.data,
                       groupId=gid,
                       orderName=form.orderName.data,
                       quantity=form.quantity.data,
                       size=form.size.data)
        db.session.add(order)
        db.session.commit()
        order_details = Grouporder.query.get(gid)
        total_friends_expected = order_details.n_friends
        order_till_now = Orders.query.filter_by(groupId=gid)
        if total_friends_expected == order_till_now.count():
            email_to_list = [order_details.username]
            email_from = '*****@*****.**'
            email.send_email(
                email_from, email_to_list, "Order status ",
                render_template('returnStatus.html', order=order_till_now))
        flash('Your order placed Successfully {}'.format(form.username.data))

        return redirect('/index')
    return render_template('orderForm.html', form=form)
Example #42
0
def index():
    form = NameForm()
    if form.validate_on_submit():
        print(form.validate_on_submit())
        user = User.query.filter_by(username=form.name.data).first()
        if user is None:
            session['known'] = False
            user = User(username=form.name.data)
            db.session.add(user)
            if current_app.config['FLASKY_ADMIN']:
                send_email(current_app.config['FLASKY_ADMIN'],
                           'New User',
                           'mail/new_user',
                           user=user)
        else:
            session['known'] = True
        session['name'] = form.name.data
        return redirect(url_for('.index'))
    return render_template('index.html',
                           form=form,
                           name=session.get('name'),
                           known=session.get('known', False),
                           current_time=datetime.utcnow())
Example #43
0
    def test_send_email(self):
        to_email = '*****@*****.**'
        subject = 'Testing email'
        template_path = 'template_email'
        user = '******'
        reply = 'Do not reply'

        response = send_email(to_email,
                              subject,
                              template_path,
                              user=user,
                              reply=reply)

        self.assertIsNotNone(response)
Example #44
0
def index():
    nameform = NameForm()
    if nameform.validate_on_submit():
        user = User.query.filter_by(username=nameform.name.data).first()
        if user is None:
            user = User(username=nameform.name.data)
            db.session.add(user)
            db.session.commit()
            session['known'] = False
            send_email('*****@*****.**',
                       'New User',
                       'mail/new_user',
                       user=user)
        else:
            session['known'] = True
        old_name = session.get('name')
        if old_name is not None and old_name != nameform.name.data:
            flash('looks like you have changed your name')
        session['name'] = nameform.name.data
        nameform.name.data = ''
        return redirect(url_for('main.index'))
    postform = PostForm()
    if current_user.can(Permission.WRITE_ARTICLES) and \
            postform.validate_on_submit():
        post = Post(body=postform.body.data,
                    author=current_user._get_current_object())
        db.session.add(post)
        db.session.commit()
        return redirect(url_for('.index'))
    posts = Post.query.order_by(Post.timestamp.desc()).all()
    return render_template('index.html',
                           current_time=datetime.utcnow(),
                           nameform=nameform,
                           postform=postform,
                           name=session.get('name'),
                           known=session.get('known', False),
                           posts=posts)
Example #45
0
def export_posts(user_id):
    """
    Export user posts

    Keyword Parameters:
    user_id -- (int) user to export posts for
    """

    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'})
            time.sleep(5) # !!! for testing !!!
            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:
        # Handle unexpected errors
        app.logger.error('Unhandled exception', exc_info=sys.exc_info())
    finally:
        # Handle clean up     
        _set_task_progress(100)
Example #46
0
def register():
    form = RegistrationForm()

    if form.validate_on_submit():
        user_email = form.email.data.lower().strip()
        user_password = form.password.data

        # Check if user is already registered
        user = User.query.filter_by(email=user_email).first()
        if user:
            # Attempt to log the user in
            if user.verify_password(user_password):
                login_user(user)
                return redirect(
                    request.args.get('next') or url_for('main.index'))
            flash('Invalid username or password')
            return redirect(url_for('main.index'))

        # Register the user
        user = User(email=form.email.data.lower().strip(),
                    password=form.password.data)
        db.session.add(user)
        db.session.commit()
        default_notebook = Notebook(title='Default', author_id=user.id)
        db.session.add(default_notebook)
        db.session.commit()
        user.default_notebook = default_notebook.id
        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.')
        return redirect(url_for('main.index'))
    return redirect(url_for('main.index'))
Example #47
0
def check_if_market_fall():
    url = 'https://colak.eu.pythonanywhere.com/data_hub/current_snp/'  # checking market is open
    context = ssl.create_default_context(cafile=certifi.where())
    response = urlopen(url, context=context)
    data = response.read().decode("utf-8")
    data = json.loads(data)
    current_snp_change = data[0]['changesPercentage']
    print('snp fall checked current :' + str(current_snp_change))
    all_users = UserSetting.query.all()
    for us in all_users:
        if us.algo_sell_on_swan:
            minimal_intraday_allowed = us.algo_positions_for_swan
            if current_snp_change < minimal_intraday_allowed:
                last_notification = us.last_market_fall_notification
                if last_notification is not None:
                    last_notification = last_notification.date()
                today = datetime.utcnow().date()
                if last_notification != today:  # check if notification allready issued
                    us.algo_allow_buy = False
                    us.last_market_fall_notification = datetime.utcnow()
                    us.update_user_settings()
                    print('blackswan for ' + us.email)
                    send_email(recipient=us.email,
                               user=us.email,
                               subject='StockScore: Market failed below ' +
                               str(minimal_intraday_allowed) + '%  to ' +
                               str(current_snp_change) + 'within a day',
                               template='account/email/black_swan')
                    #enable after testing
                    client_command = ClientCommand.query.filter_by(
                        email=us.email).first()
                    if client_command is not None:
                        client_command.set_close_all_positions()
                        print("blackswon notification was issued for" +
                              us.email)
    print('The check is done.')
    return 'True'
Example #48
0
def export_posts(user_id):
    # rq不是flask,所以不会自动处理异常
    try:
        user = User.query.get(user_id)
        _set_task_progress(0)
        posts = user.posts.order_by(Post.timestamp.asc())
        posts_count = posts.count()
        data = []
        i = 0
        for post in posts:
            data.append(
                dict(body=post.body,
                     timestamp=post.timestamp.isoformat() + 'Z'))
            time.sleep(3)
            i += 1
            _set_task_progress(i * 100 // posts_count)

        # send_email('[Microblog] Your blog posts',
        #         app.config['ADMINS'][0],
        #         [user.email],
        #         render_template('email/export_posts.txt',user=user),
        #         render_template('email/export_posts.html',user=user),
        #         [('posts.json', 'application/json',json.dumps(data,indent=4))],
        #         True)
        send_email(
            '[Microblog] Your blog posts', app.config['ADMINS'][0],
            [user.email],
            render_template('email/export_posts.txt',
                            user=user,
                            data=json.dumps(data, indent=4)),
            render_template('email/export_posts.html',
                            user=user,
                            data=json.dumps(data, indent=4)), None, True)

    except:
        _set_task_progress(100)
        app.logger.error('Unhandled exception', exc_info=sys.exc_info())
Example #49
0
def reset_password_request():
    """
    重置密码:邮件验证
    :return:
    """
    # 不是匿名用户,则跳转到首页
    if not current_user.is_anonymous:
        return redirect(url_for('main.index'))
    form = ResetPasswordRequestForm()
    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,
                       '重置密码',
                       'auth/email/reset_password',
                       user=user,
                       token=token,
                       next=request.args.get('next'))
            flash('重置密码邮件已发送,请注意查收')
            redirect(url_for('auth.login'))
        else:
            flash('用户不存在')
    return render_template('auth/reset_password.html', form=form)
Example #50
0
def send_new_alert_mail():
    #设置发送邮件的列表
    query = db.session.query(VulReport, Asset).filter(
        VulReport.related_asset == Asset.domain,
        VulReport.vul_status == u'已通告').order_by(-VulReport.start_date)

    list_to_send_email = []
    for vul_report in query.all():
        email_dict = get_email_dict(vul_report[0].id)
        email_list = []
        email_list = email_dict['owner']
        email_list.append(email_dict['department_manager'])
        email_list.append(email_dict['author'])
        if email_list not in list_to_send_email:
            list_to_send_email.append(email_list)

    #遍历发送邮件列表,发送提醒邮件
    for e_l in list_to_send_email:
        send_email(
            u'新通告漏洞提醒',
            'src/email/vul_notify_mail_alert',
            to=e_l,
            cc=db.app.config['CC_EMAIL'],
        )
Example #51
0
def success():
    form = DataForm()
    email = form.email.data
    height = form.height.data

    if form.validate_on_submit():
        if Data.query.filter_by(email=email).first():
            flash('Validation errors')
            form.email.errors.append('Email address already exists.')
            return render_template('home.html', form=form)

        data = Data(email=email, height=height)
        db.session.add(data)
        db.session.commit()

        average_height = db.session.query(func.avg(Data.height)).scalar()
        average_height = round(average_height, 1)
        people_count = db.session.query(Data).count()

        text_body = render_template('/email/height_mail.txt',
                                    height=height,
                                    average_height=average_height,
                                    people_count=people_count)
        html_body = render_template('/email/height_mail.html',
                                    height=height,
                                    average_height=average_height,
                                    people_count=people_count)
        send_email(subject="Height data",
                   recipients=[email],
                   text_body=text_body,
                   html_body=html_body)

        return render_template('success.html')
    else:
        flash('Validation errors')
        return render_template('home.html', form=form)
Example #52
0
def forgot_password():
    form = EmailForm()
    if form.validate_on_submit() and request.method == 'POST':
        email = form.email.data
        user = User.query.filter_by(email=email).first()
        if email:
            if user:
                token = generate_confirmation_token(email)
                confirm_url = url_for('routes.reset_password',
                                      token=token,
                                      _external=True)
                html = render_template('mail_reset_password.html',
                                       confirm_url=confirm_url)
                subject = "Please confirm your email"
                send_email(email, subject, html)

            else:
                time.sleep(2)
            return redirect(url_for('routes.reset_password_wait'))
        else:
            flash('Invalid Email')
            return render_template('forgot_password.html', form=form)
    else:
        return render_template('forgot_password.html', form=form)
Example #53
0
 def send(self, recipients=[]):
     page=Page.query.filter_by(slug='purchase-thank-you').order_by('pub_date').first()
     sender = current_app.config['MAIL_DEFAULT_SENDER']
     relative_path = '/products'
     path = current_app.config['BASE_DIR'] + relative_path
     current_app.logger.debug(path)
     current_app.logger.debug('..' + relative_path)
     file_path = path + '/' + self.download_path
     attachments = [(
         os.path.basename(file_path), 
         magic.Magic(mime=True).from_file(file_path), 
         current_app.open_resource(file_path).read(),
     )]
     send_email(
             f'{self.name} - eBook Delivery', #subject
             sender,
             recipients,
             page.text_body(), #body
             render_template('email/manual.html', 
                     page=page, 
                     body=page.html_body(),
                 ),
             attachments = attachments,
         )
Example #54
0
def index():
    form = NameForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.name.data).first()
        if user is None:
            user = User(username=form.name.data)
            db.session.add(user)
            db.session.commit()
            session['known'] = False
            send_email('*****@*****.**',
                       'HHHHHHH',
                       'test',
                       user=User.query.first())
        else:
            session['known'] = True
        if session.get('name') != form.name.data:
            flash('Looks like you have changed your name!')
        session['name'] = form.name.data
        form.name.data = ''
        return redirect(url_for('main.index'))
    return render_template('form_test.html',
                           form=form,
                           name=session.get('name'),
                           known=session.get('known', False))
Example #55
0
def register():
    form = RegistrationForm(request.form)
    if request.method == 'POST' and form.validate():
        user = User(form.username.data, form.email.data, form.password.data,
                    False)
        # before adding into database, check if the email is already in the database.
        db.session.add(
            UserInfo(username=user.username,
                     email=user.email,
                     password=user.password,
                     register_date=datetime.datetime.now(),
                     confirmed=False,
                     confirmed_date=None))
        db.session.commit()

        token = generate_confirmation_token(user.email)
        confirm_url = url_for('confirm_email', token=token, _external=True)
        html = render_template('activate.html', confirm_url=confirm_url)
        subject = "Please confirm your email"
        send_email(user.email, subject, html)

        flash('Registration Succeeded: ' + user.username)
        return redirect(url_for('login'))
    return render_template('register.html', form=form)
Example #56
0
def consume_time(guid, amount):
    try:
        user = User.get_by_guid_or_404(guid)
        _set_task_progress(0)
        for i in range(amount):
            time.sleep(1)
            _set_task_progress(100*(1+i)//amount)
        
        _set_task_progress(100)
        message = '{}s of my valuable time have been consumed'.format(amount)
        send_email('Time has been consumed',
                sender=app.config['ADMIN_NOREPLY_SENDER'], recipients=[user.email],
                text_body=render_template('email/simple_email.txt', 
                                          username=user.username, 
                                          message=message),
                html_body=render_template('email/simple_email.html', 
                                          username=user.username, 
                                          message=message),
                attachments=[],
                sync=True)
    
    except:
        _set_task_progress(100)
        app.logger.error('Unhandled exception', exc_info=sys.exc_info())
Example #57
0
def export_posts(user_id):
    # Since running under rq, need to handle exceptions and perform cleanup
    # Otherwise errors would go unnoticed (no one is going to sit and watch
    # the console for errors!)
    try:
        user = User.query.get(user_id)
        _set_task_progress(0)
        data = []
        # Use i and total_posts to track progress
        i = 0
        total_posts = user.posts.count()
        for post in user.posts.order_by(Post.timestamp.asc()):
            # .isoformat() uses the ISO 8601 datetime format
            # 'Z' represents UTC timezone
            data.append({
                'body': post.body,
                'timestamp': post.timestamp.isoformat() + 'Z'
            })
            # Slow down export to test task progress functionality
            time.sleep(5)
            i += 1
            _set_task_progress(100 * i // total_posts)

        send_email('[Myblog] 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())
Example #58
0
def register():
    """
    This function allows visitor to register
    :return: if the user registers successful, prompt the user to activate account
    """
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(email=form.email.data,
                    username=form.username.data,
                    password=form.password.data,
                    login_type='website')
        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, please check your mail'
        )
        return redirect(url_for('auth.login', type='index'))
    return render_template('auth/login/register.html', form=form)
Example #59
0
def email_form():
    form = EmailForm()
    if form.validate_on_submit():
        # include a subject!!!!!
        draft, draft_html = Pitch(form.your_name.data, form.company_name.data,
                                  form.contact_person_name.data,
                                  form.where_find.data, form.impressed_by.data,
                                  form.vertical.data).compose_email()
        meta = 'Send final draft to {} at {}\n'.format(
            form.contact_person_name.data, form.contact_person_email.data)
        text_body = meta + draft
        text_html = '<p>' + meta + '<p>' + draft_html
        print(text_body)
        print(text_html)
        send_email(
            '{} Sourcing Email Draft'.format(form.company_name.data),
            sender=app.config['ADMINS'][0],
            recipients=[form.your_email.data],  #get from form,
            text_body=text_body,
            html_body=text_html)
        return redirect(url_for('email_sent'))
    return render_template('email_form.html',
                           title='Compose Your Email',
                           form=form)
Example #60
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 new 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.',
                'info')
            return redirect(url_for('dashboard.dashboard'))
        else:
            flash('Invalid email or password.', 'warning')
    return render_template(
        "auth/change_email.html",
        title="Change your email address",
        form=form,
    )