def contact(): form = ContactForm() if form.validate_on_submit(): name = form.name.data email = form.email.data message = form.message.data print(name) print(email) print(message) # 数据库操作 feedback = Feedback(name=name, email=email, message=message) db.session.add(feedback) db.session.commit() send_mail( "New Feedback", current_app.config['MAIL_USERNAME'], 'mail/feedback.html', name=name, email=email, message=message) print("\nData received. Now redirecting ...") flash("Message Recived", "Success") return redirect(url_for('.contact')) return render_template('contact.html', form=form)
def registration(): form = RegistrationForm() if request.method == 'POST' and form.validate_on_submit(): form_name = request.form.get('name') form_login = request.form.get('login') form_email = request.form.get('email') form_password = request.form.get('password') user_email = db.session.query(User).filter( User.email == form_email).first() user_login = db.session.query(User).filter( User.email == form_login).first() if user_email: flash('Пользователь с данным email уже существует') return render_template('auth/registration.html', form=form) if user_login: flash('Пользователь с данный login уже существует') return render_template('auth/registration.html', form=form) new_user = User(name=form_name, login=form_login, email=form_email) new_user.set_password(form_password) db.session.add(new_user) db.session.commit() send_mail('Регистрация на сайте Photodrom', user.email, 'mail/registration_mail.html', name=user.name) return redirect(url_for('login')) return render_template('auth/registration.html', form=form)
def smtp_test_post(): data = request.get_json() settings = Settings.query.first() if "mail_to" not in data.keys(): return jsonify({"status": "error", "detail": "Missing recipient"}), 400 if is_email(data["mail_to"]) and check_length(data["mail_to"], 256): try: send_mail(receiver=data["mail_to"]) settings.smtp_status = True db.session.commit() return jsonify({ "status": "OK", "detail": "SMTP configuration test successful" }), 200 except: settings.smtp_status = False db.session.commit() return ( jsonify({ "status": "error", "detail": "Could not send test email. Please review your SMTP configuration and don't forget to save it before testing it. ", }), 400, ) else: return jsonify({"status": "error", "detail": "Invalid recipient"}), 400
def send_mail_periodic(): email = "*****@*****.**" message_to_send = f"Hey {email}, it is your periodic mail" theme_to_send = "Periodic" print(message_to_send) send_mail(MAIL_USERNAME, email, theme_to_send, message_to_send, f"{message_to_send}")
def create_user(): data = request.get_json() code = generate_code() if not data: return jsonify({ 'error': { 'message': 'Invalid Credentials' }, 'data': None }), 400 try: user = User(username=data['username'], email=data['email'], code=code, password_hash=data['password']) user.insert() token = Token(user_id=user.id, code=code) token.insert() except exc.IntegrityError: return jsonify({ 'error': { 'message': 'user already exists' }, 'data': None }), 400 send_mail('Email Verification', user.email, 'mail.html', code=code, username=user.username) return jsonify({'error': None, 'data': "success"}), 201
def test_send_mail(client): login(client, username='******', password='******', remember=False) post_settings(client, smtp_host='127.0.0.1', smtp_port=25, mail_from='*****@*****.**') rv = send_test_mail(client) assert b'Missing recipient' in rv.data rv = send_test_mail(client, mail_to='test') assert b'Invalid recipient' in rv.data rv = send_test_mail(client, mail_to='*****@*****.**') assert b'Could not send test email' in rv.data post_settings(client, smtp_host='127.0.0.1', smtp_port=587, ssl_tls=True, mail_from='*****@*****.**') rv = send_test_mail(client, mail_to='*****@*****.**') assert b'Could not send test email' in rv.data try: send_mail() except MissingDataError: assert True except: assert False
def register(): """ 用户注册页面 :return: """ # 创建表单对象 form = RegisterForm() # 判断表单是否提交 if form.validate_on_submit(): if not User.query.filter_by(username=form.username.data).first(): # 创建user模型对象 u = User(username=form.username.data, password=form.password.data, email=form.email.data) # 提交到数据库中 db.session.add(u) db.session.commit() # 发送邮箱用于账户激活 send_mail(u.email, '账户激活', 'mail/active_account', token=u.generate_token()) flash('邮件已发送,请到邮箱中查看邮件并激活!') else: flash('用户已存在!') # 重定向到主页面 return redirect(request.args.get('next') or url_for('.login')) return render_template('user/register.html', form=form)
def confirm(): if current_user.is_confirmed: # If user is confirmed, then user should be redirected to their profile page flash('Your account has been confirmed', 'info') return redirect(url_for('profile')) send_mail(current_user, 'mail.html', 'Confirm Account') # sends mail to the user flash('A confirmation has been sent to your mail', 'info') return redirect(url_for('profile'))
def send(): send_form = SendForm() if send_form.validate_on_submit(): utils.send_mail(send_form.username.data, send_form.user_email.data, send_form.message_body.data) print(send_form.username.data, send_form.user_email.data, send_form.message_body.data) return redirect(url_for('home')) return redirect(url_for('home'))
def put(self, pid): args = request.get_json(cache=False, force=True) if not checkParams(['text'], args): return {"ERROR": "One or more parameters are missing !"}, 400 text = args['text'] user = session.get("user") mails = [] # On vérifie que la période existe period = getPeriod(pid) if period is None: return {"ERROR": "This period does not exists !"}, 405 # On vérifie que l'utilisateur actuel a le droit de modifier ce livret (étudiant ou tuteur) livret = getLivret(lid=period["livret_id"]) if user["id"] != livret["etutor_id"]["id"] and user["id"] != livret[ "tutorship_id"]["student_id"]["id"]: return {"ERROR": "UNAUTHORIZED"}, 401 # Si c'est le commentaire de l'étudiant, on prévient le tuteur if user["role"] == str(Roles.etudiant): mail = mailsModels.getMailContent("STUD_COMMENT_ADDED", { "ETUDIANT": user["name"], "URL": getParam('OLA_URL') }) mails.append((user["email"], mail)) query = PERIOD.update().values(student_desc=text).where( PERIOD.c.id == pid) else: # Sinon on vérifie que c'est une période d'entreprise if period["type"] == TypesPeriode.universitaire: return { "ERROR": "A tutor can't modify a university period !" }, 405 mail = mailsModels.getMailContent("ETUTOR_COMMENT_ADDED", { "TUTEUR": user["name"], "URL": getParam('OLA_URL') }) mails.append((user["email"], mail)) query = PERIOD.update().values(etutor_desc=text).where( PERIOD.c.id == pid) query.execute() for m in mails: addr = m[0] mail = m[1] send_mail(mail[0], addr, mail[1]) return {"PID": pid}, 200
def send_message(): form = SendEmail() user_email = Owner.query.filter_by(id=int(current_user.get_id())).first() if form.validate_on_submit(): email = form.email.data text = form.text.data text_msg = f'<p>Пользователь {email} пишет: <br><p>{text}</p>' recipients = ['*****@*****.**'] send_mail(recipients=recipients, text_msg=text_msg) flash('Письмо отправлено!') return redirect(url_for('.index')) return render_template('send_message.html', form=form, user_email=user_email.email)
def test_send_mail(client): access_header, _ = login_get_headers(client, "admin", "xss") patch_settings(client, access_header, smtp_host="127.0.0.1", smtp_port=25, mail_from="*****@*****.**") rv = send_test_mail(client, access_header) assert b"Missing recipient" in rv.data rv = send_test_mail(client, access_header, mail_to="test") assert b"Invalid recipient" in rv.data rv = send_test_mail(client, access_header, mail_to="*****@*****.**") assert b"Could not send test email" in rv.data patch_settings(client, access_header, smtp_host="127.0.0.1", smtp_port=587, ssl_tls=True, mail_from="*****@*****.**") rv = send_test_mail(client, access_header, mail_to="*****@*****.**") assert b"Could not send test email" in rv.data with pytest.raises(MissingDataError): send_mail()
def test_send_mail(): """should fail on incorrect email address""" rv = send_mail('', 'hello, this is testing!') rv_obj = json.loads(rv) assert rv_obj[ 'message'] == "'to' parameter is not a valid address. please check documentation" # change email rv = send_mail('*****@*****.**', 'hello, this is testing!') rv_obj = json.loads(rv) assert 'id' in rv_obj
def forgot_pssword(): data = request.get_json() u = User.query.filter_by(email=data['email']).first() if not u: return jsonify({ 'error': { 'message': 'Invalid User', }, 'data': None }), 404 token = generate_token({'id': u.id}) send_mail('Password Rest Request', u.email, 'reset_password.html', link=f'http://localhost:5000/reset_password/{token}', username=u.username) return jsonify({'error': None, 'data': "success"}), 200
def ignore_password(): # 创建表单对象 form = IgnorePasswordForm() if form.validate_on_submit(): # 获取用户信息 u = User.query.filter_by(email=form.email.data).first() # 判断旧密码是否输入正确 if u: send_mail(u.email, '重置密码', 'mail/reset_password', token=u.generate_token(use_username=0, use_email=1)) flash('邮件已发送,请到邮箱中查看邮件并重置密码!') # 重定向到登录页面 return redirect(url_for('user.login')) else: flash('请输入正确的邮箱!') return render_template('user/edit_password.html', form=form)
def register(): form = RegisterForm() if form.validate_on_submit(): username = form.username.data password = generate_password_hash(form.password.data) email = form.email.data user = User(username=username, password=password, is_recruiter=form.is_recruiter.data, email=email, fname=form.fname.data, lname=form.lname.data) db.session.add(user) db.session.commit() send_mail(user, 'welcome.html', 'Thanks for joining') flash('Account created successfully.', 'success') login_user(user) return redirect(url_for('profile')) return render_template('register.html', form=form)
def contact(): form = ContactForm() if form.validate_on_submit(): name = form.name.data email = form.email.data message = form.message.data # логика БД здесь feedback = Feedback(name=name, email=email, message=message) db.session.add(feedback) db.session.commit() send_mail("New Feedback", current_app.config['MAIL_DEFAULT_SENDER'], 'mail/feedback.html', name=name, email=email) flash("Message Received", "success") return redirect(url_for('.contact')) return render_template('contact.html', form=form)
def reset_password(): '''View function for getting link to reset password''' if current_user.is_authenticated: # If user is authenticated, then user should be redirected to their profile page return redirect(url_for('profile')) form = ResetPasswordForm() #If form is validated and submitted if form.validate_on_submit(): email = form.email.data user = User.query.filter_by(email=email).first() send_mail(user, 'passwordmail.html', 'Reset Password', 1800) flash( 'Instructions has been sent to your mail on how to reset your password', 'info') return render_template('reset_password.html', title='Reset Password', form=form)
def smtp_test_post(): data = request.form settings = Settings.query.first() if 'mail_to' not in data.keys(): return jsonify({'status': 'error', 'detail': 'Missing recipient'}), 400 if is_email(data['mail_to']) and check_length(data['mail_to'], 256): try: send_mail(receiver=data['mail_to']) settings.smtp_status = True db.session.commit() return jsonify({'status': 'OK', 'detail': 'SMTP configuration test successful'}), 200 except: settings.smtp_status = False db.session.commit() return jsonify({'status': 'error', 'detail': 'Could not send test email. Please review your SMTP configuration and don\'t forget to save it before testing it. '}), 400 else: return jsonify({'status': 'error', 'detail': 'Invalid recipient'}), 400
def save_order(self, d): dt = d['date'].split('.') session = Session() try: item = session.query(CatalogItemModel).filter_by(id=d['id']).one() except Exception as e: session.close() print('FormsHandler.save_order(): cannot get catalog item by id\n',\ e, file=sys.stderr) raise e session.close() full_date = datetime.combine( date(int(dt[2]), int(dt[1]), int(dt[0])), time(int(d['hours']), int(d['minutes']))), order = OrderModel( name=d['name'], callback=d['callback'], date=full_date, item_id=item.id ) session = Session() try: session.add(order) session.commit() except Exception as e: session.close() print('FormsHandler.save_order(): cannot save order to DB\n',\ e, file=sys.stderr) raise e session.close() send_mail( msg='<h1>Заказ "%s"</h1>' % item.title + '<dl><dt>Имя:</dt><dd>%s</dd>' % d['name'] + '<dt>Контакты:</dt><dd>%s</dd>' % d['callback'] + '<dt>Дата заказа:</dt><dd>%s</dd></dl>' % ( full_date[0].strftime('%d.%m.%Y %H:%M')), theme='АвтоЛюкс: заказ "%s"' % item.title )
def send_verification_code(): data = request.get_json() user = User.query.filter_by(email=data['email']).first() if not user: return jsonify({ 'error': { 'message': 'Invalid Credentials' }, 'data': None }), 400 if user.verified: return jsonify({'error': {'message': 'Verified'}, 'data': None}), 400 code = generate_code() token = Token(user_id=user.id, code=code) db.session.add(token) db.session.commit() send_mail('Email Verification', user.email, 'mail.html', code=code, username=user.username) return jsonify({'error': None, 'data': "success"}), 200
def save_call(self, d): call = CallModel( name = d['name'], phone = d['phone'], date = datetime.utcnow() ) session = Session() try: session.add(call) session.commit() except Exception as e: session.close() print('FormsHandler.save_call(): cannot save call to DB\n',\ e, file=sys.stderr) raise e session.close() send_mail( msg='<h1>Заказ звонка</h1>' + '<dl><dt>Имя:</dt><dd>%s</dd>' % d['name'] + '<dt>Телефон:</dt><dd>%s</dd></dl>' % d['phone'], theme='АвтоЛюкс: заказ звонка' )
def contact(): form = ContactForm() if form.validate_on_submit(): name = form.name.data email = form.email.data message = form.message.data feedback = Feedback(name=name, email=email, message=message) db.session.add(feedback) db.session.commit() msg_body = f'You have recieved a new feedback from {name} <{email}>' send_mail('New Feedback', current_app.config['MAIL_DEFAULT_SENDER'], 'mail/feedback.html', name=name, email=email) flash('Message Received', 'success') return redirect(url_for('.contact')) return render_template('contact.html', form=form)
def send_mail(): """Render testmail page which sends email on request""" app.logger.debug('Loading testmail page...') if request.method == 'POST': subject = "Test mail from your CAVE installation" body = "It's alive!" success = 'Mail sent. Check your inbox!' fail = "Error message: " message = utils.send_mail(subject, body, success, fail) return render_template('testmail.html', form=request.form, message=message) return render_template('testmail.html', form=request.form)
def forgot_password(): form = ForgotForm() if request.method == 'POST' and form.validate_on_submit(): user = User.query.filter( User.email == request.form.get('email')).first() if user: faker = Faker() new_password = faker.password() user.set_password(new_password) db.session.commit() send_mail('Восстановление пароля', user.email, 'mail/recovery_password.html', name=user.name, password=new_password) return redirect(url_for('index')) else: flash("Пользователя с данным email не существует") return render_template('auth/forgot.html', form=form) return render_template('auth/forgot.html', form=form)
def catch_xss(flavor, uid): """Catches an XSS""" client = Client.query.filter_by(uid=uid).first() if client == None: return jsonify({'status': 'OK'}), 200 if flavor == 'r': xss_type = 'reflected' else: xss_type = 'stored' if 'X-Forwarded-For' in request.headers: ip_addr = request.headers['X-Forwarded-For'].split(', ')[0] else: ip_addr = request.remote_addr if request.method == 'GET': parameters = request.args.to_dict() elif request.method == 'POST': parameters = request.form headers = [] for header in request.headers: headers.append({header[0]: header[1]}) data = {} for param, value in parameters.items(): if param == 'cookies': if value != '': if 'cookies' not in data.keys(): data['cookies'] = [] cookies_list = value.split('; ') for cookie in cookies_list: cookie_array = cookie.split('=') cookie_name = cookie_array[0] cookie_value = ''.join(cookie_array[1:]) data['cookies'].append({cookie_name: cookie_value}) elif param == 'local_storage': if value != '' and value != '{}': if 'local_storage' not in data.keys(): data['local_storage'] = [] local_storage = json.loads(value) for element in local_storage.items(): data['local_storage'].append({element[0]: element[1]}) elif param == 'session_storage': if value != '' and value != '{}': if 'session_storage' not in data.keys(): data['session_storage'] = [] session_storage = json.loads(value) for element in session_storage.items(): data['session_storage'].append({element[0]: element[1]}) else: if value != '' and value != '{}': if param == 'fingerprint': data['fingerprint'] = json.loads(value) if param == 'dom': data['dom'] = '<html>\n{}\n</html>'.format(value) else: data[param] = value xss = XSS(headers=json.dumps(headers), ip_addr=ip_addr, client_id=client.id, xss_type=xss_type, data=json.dumps(data), timestamp=int(time.time())) db.session.add(xss) db.session.commit() settings = Settings.query.first() if xss.client.mail_to != None and settings.smtp_host != None: try: send_mail(xss=xss) settings.smtp_status = True db.session.commit() except: settings.smtp_status = False db.session.commit() return jsonify({'status': 'OK'}), 200
def post(self): """Reset user password validate email. --- tags: - User authentication and authorization parameters: - in: body name: body schema: required: - email - url properties: email: type: string description: user email url: type: string description: reset password route responses: 200: description: Email sent successfully schema: properties: response_message: type: string status_code: type: integer 406: description: Invalid email, Null required parameters schema: properties: response_message: type: string """ req_data = request.get_json() email = req_data.get('email') url = req_data.get('url') if not email: response_message = jsonify({ 'response_message': 'Email is required!', 'status_code': 406 }) return response_message if not url: response_message = jsonify({ 'response_message': 'reset password route is required!', 'status_code': 406 }) return response_message if email_exist(email): try: serializer = Serializer(os.getenv('SECRET_KEY'), salt='email-confirmation-salt') token = serializer.dumps(email) user = User.query.filter_by(email=email).first() link = url + '/' + token html = render_template('user/email.html', link=link, user_name=user.username) mail_response = send_mail(email, html) response = jsonify({ 'response_message': mail_response, 'status_code': 200, 'token': token }) return response except Exception as error: response_message = jsonify({ 'message': str(error), 'status_code': 500 }) return response_message else: response_message = jsonify({ 'response_message': 'Email not registered', 'status_code': 406 }) return response_message
def options(self, gid): args = request.get_json(cache=False, force=True) if not checkParams(['pairs'], args): return {"ERROR": "One or more parameters are missing !"}, 400 pairs = args["pairs"] group = getGroup(gid=gid) if group is None: return {"ERROR": "This group does not exists !"}, 405 for p in pairs: try: stud = getUser(uid=p[0]) if stud is None: return { "ERROR": "The user with id " + str(p[0]) + " does not exists !" }, 400 elif stud['role'] != str(Roles.etudiant): return { "ERROR": "A student must have the 'student' role !" }, 400 tutor = getUser(uid=p[1]) if tutor is None: return { "ERROR": "The user with id " + str(p[1]) + " does not exists !" }, 400 elif tutor['role'] == str(Roles.etudiant): return {"ERROR": "A student can't be a tutor !"}, 400 elif "3" not in tutor['role'].split('-'): role = tutor['role'] + "-" + str(Roles.tuteur_univ) query = USER.update().values(role=role).where( USER.c.id == p[1]) query.execute() except IndexError: return {"ERROR": "Pairs are incorrectly formed !"}, 409 query = TUTORSHIP.insert().values(group_id=gid, student_id=p[0], ptutor_id=p[1]) query.execute() query = USER.select(USER.c.id == stud["id"]) rows = query.execute() res = rows.first() if res.hash is not None and len(res.hash) > 0: mail = mailsModels.getMailContent( "NEW_STUD_OF_GROUP", { "GROUP": group["name"], "URL": getParam('OLA_URL') + "registration/" + res.hash }) else: mail = mailsModels.getMailContent("STUD_OF_GROUP", { "GROUP": group["name"], "URL": getParam('OLA_URL') }) send_mail(mail[0], stud["email"], mail[1]) return {"RESULT": "Pairs added successfully"}, 200
def post(self): args = request.get_json(cache=False, force=True) if not checkParams([ 'name', 'year', 'class_short', 'class_long', 'department', 'resp_id', 'sec_id' ], args): return {"ERROR": "One or more parameters are missing !"}, 400 name = args['name'] year = args['year'] class_short = args['class_short'] class_long = args['class_long'] department = args['department'] resp_id = args['resp_id'] sec_id = args['sec_id'] res_dir = getParam('BASE_DIRECTORY') + name + "/" mails = [] group = getGroup(name=name) if group is not None: return {"GID": group["id"]}, 200 user = getUser(uid=resp_id) if user is None: return { "ERROR": "The user with id " + str(resp_id) + " does not exists !" }, 400 else: query = USER.select(USER.c.id == user["id"]) rows = query.execute() res = rows.first() if res.hash is not None and len(res.hash) > 0: mail = mailsModels.getMailContent( "NEW_RESP_OF_GROUP", { "GROUP": name, "URL": getParam('OLA_URL') + "registration/" + res.hash }) else: mail = mailsModels.getMailContent("RESP_OF_GROUP", { "GROUP": name, "URL": getParam('OLA_URL') }) mails.append((user["email"], mail)) if str(Roles.resp_formation) not in user['role'].split('-'): role = user['role'] + "-" + str(Roles.resp_formation) query = USER.update().values(role=role).where( USER.c.id == resp_id) query.execute() user = getUser(uid=sec_id) if user is None: return { "ERROR": "The user with id " + str(sec_id) + " does not exists !" }, 400 else: query = USER.select(USER.c.id == user["id"]) rows = query.execute() res = rows.first() if res.hash is not None and len(res.hash) > 0: mail = mailsModels.getMailContent( "NEW_SEC_OF_GROUP", { "GROUP": name, "URL": getParam('OLA_URL') + "registration/" + res.hash }) else: mail = mailsModels.getMailContent("SEC_OF_GROUP", { "GROUP": name, "URL": getParam('OLA_URL') }) mails.append((user["email"], mail)) if str(Roles.secretaire) not in user['role'].split('-'): role = user['role'] + "-" + str(Roles.secretaire) query = USER.update().values(role=role).where( USER.c.id == sec_id) query.execute() query = GROUP.insert().values(name=name, year=year, class_short=class_short, class_long=class_long, department=department, resp_id=resp_id, sec_id=sec_id, ressources_dir=res_dir) res = query.execute() os.mkdir(res_dir) for m in mails: addr = m[0] mail = m[1] send_mail(mail[0], addr, mail[1]) return {"GID": res.lastrowid}, 201
def catch_xss(flavor, uid): """Catches an XSS""" client = Client.query.filter_by(uid=uid).first() parameters = None if client == None: return jsonify({"status": "OK"}), 200 if flavor == "r": xss_type = "reflected" else: xss_type = "stored" if "X-Forwarded-For" in request.headers: ip_addr = request.headers["X-Forwarded-For"].split(", ")[0] else: ip_addr = request.remote_addr if request.method == "GET": parameters = request.args.to_dict() elif request.method == "POST": parameters = request.get_json() headers = [] for header in request.headers: headers.append({header[0]: header[1]}) data = {} for param, value in parameters.items(): if param == "cookies": if value != "": if "cookies" not in data.keys(): data["cookies"] = [] cookies_list = value.split("; ") for cookie in cookies_list: cookie_array = cookie.split("=") cookie_name = cookie_array[0] cookie_value = "".join(cookie_array[1:]) data["cookies"].append({cookie_name: cookie_value}) elif param == "local_storage": if value != "" and value != "{}": if "local_storage" not in data.keys(): data["local_storage"] = [] local_storage = json.loads(value) for element in local_storage.items(): data["local_storage"].append({element[0]: element[1]}) elif param == "session_storage": if value != "" and value != "{}": if "session_storage" not in data.keys(): data["session_storage"] = [] session_storage = json.loads(value) for element in session_storage.items(): data["session_storage"].append({element[0]: element[1]}) else: if value != "" and value != "{}": if param == "fingerprint": data["fingerprint"] = json.loads(value) if param == "dom": data["dom"] = "<html>\n{}\n</html>".format(value) else: data[param] = value xss = XSS(headers=json.dumps(headers), ip_addr=ip_addr, client_id=client.id, xss_type=xss_type, data=json.dumps(data), timestamp=int(time.time())) db.session.add(xss) db.session.commit() settings = Settings.query.first() if xss.client.mail_to != None and settings.smtp_host != None: try: send_mail(xss=xss) settings.smtp_status = True db.session.commit() except: settings.smtp_status = False db.session.commit() return jsonify({"status": "OK"}), 200