UnderCover/undercover/routes.py

191 lines
5.5 KiB
Python
Raw Normal View History

# Copyright Sage Vaillancourt 2021
import os
2022-09-22 15:43:36 -04:00
import subprocess
import threading
import urllib.parse
from flask import (Blueprint, render_template, request, make_response, session, redirect, jsonify)
from wtforms import Form, StringField, TextAreaField, validators
from email_validator import validate_email, EmailNotValidError
2021-07-23 23:09:08 -04:00
import undercover.db as db
from undercover.pdf_builder import CLData
writing_blueprint = Blueprint('writing', __name__,)
class CLForm(Form):
username = StringField(
'Username:',
[validators.Length(min=4, max=99)],
default="Sage"
)
company = StringField(
'Company:',
[validators.Length(min=2, max=99)],
default="BananaCorp"
)
jobAndPronoun = StringField(
'Job and Pronoun (a/an):',
[validators.Length(min=4, max=99)],
2021-07-24 01:08:18 -04:00
default="a banana stocker"
)
skillTypes = StringField(
'Skill Type:',
[validators.Length(min=2, max=99)],
default="practical"
)
mySkills = StringField(
'My Skills:',
[validators.Length(min=2, max=99)],
2021-07-24 01:08:18 -04:00
default="stocking bananas"
)
closingText = TextAreaField(
'Closing Text:',
[validators.Length(min=2, max=99)],
default="I look forward to hearing from you"
)
body = TextAreaField(
'Body:',
[validators.Length(min=4, max=9999)],
2022-09-22 15:47:51 -04:00
default=(
"My name is {\\username}. I'm excited for the opportunity to work as "
"{\\jobAndPronoun} with your company. I think my {\\skillTypes} knowledge "
2022-09-22 16:58:12 -04:00
"of {\\mySkills} could contribute well to your team.\n\n"
2022-09-22 15:47:51 -04:00
"I am passionate about what I do, and I think we would work well together.\n\n"
"Thank you for your consideration."
)
)
@writing_blueprint.route('/login', methods=['POST', 'GET'])
def login():
if request.method == 'POST':
2022-09-23 15:14:24 -04:00
username = request.form['login']
if db.login(username, request.form['password']):
session['username'] = username
return redirect('/')
return make_response("", 401)
return '''
<form method="post">
<p><input type=text name=username></p>
<p><input type=password name=password></p>
<p><input type=submit value=Login></p>
</form>
'''
2022-09-23 15:12:07 -04:00
@writing_blueprint.route('/logout', methods=['POST', 'GET'])
def logout():
session.pop('username', None)
return redirect('/')
@writing_blueprint.route('/', methods=['GET'])
def index_get():
return render_template(
'writing.jinja2',
form=CLForm(),
2022-09-23 15:12:07 -04:00
username=session.get('username')
)
2022-09-23 18:59:42 -04:00
@writing_blueprint.route('/create_account', methods=['GET'])
2022-09-23 19:40:07 -04:00
def create_account_page():
2022-09-23 18:59:42 -04:00
return render_template('create_account.jinja2')
2022-09-23 19:40:07 -04:00
@writing_blueprint.route('/create_account', methods=['POST'])
def create_account():
email = request.form['login']
try:
validate_email(email, check_deliverability=True)
except EmailNotValidError as e:
form = CLForm(request.form)
return make_response(render_template('writing.jinja2', form=form, error=str(e)), 401)
if db.get_user(email):
2022-09-23 19:40:07 -04:00
return make_response("A user with that email already exists!", 401)
2022-09-23 19:40:07 -04:00
db.add_user(email, request.form['password'])
session['username'] = email
return redirect('/')
@writing_blueprint.route('/dbtest', methods=['GET'])
def db_test_get():
response = make_response(db.get_user_letters(1)[0].contents, 200)
response.mimetype = "text/plain"
return response
@writing_blueprint.route('/update', methods=['POST'])
def update_get():
expected_token = os.environ['GITLAB_HOOK_TOKEN']
given_token = request.headers['X-Gitlab-Token']
event_type = request.headers['X-Gitlab-Event']
if expected_token == given_token and event_type == "Push Hook":
print("Update notification received.")
response = make_response("", 200)
response.mimetype = "text/plain"
2022-09-22 15:43:36 -04:00
threading.Timer(5, git_update, []).start()
return response
else:
return make_response("", 404)
2022-09-22 15:43:36 -04:00
def git_update():
script = os.environ['UPDATE_SCRIPT_PATH']
if not script:
return
subprocess.run(['bash', '-c', "test -f " + script + " && " + script])
@writing_blueprint.route('/', methods=['POST'])
def index_post():
form = CLForm(request.form)
if form.validate():
2021-07-23 23:09:08 -04:00
data = CLData(
username=form.username.data,
company=form.company.data,
jobAndPronoun=form.jobAndPronoun.data,
skillTypes=form.skillTypes.data,
mySkills=form.mySkills.data,
closingText=form.closingText.data,
2021-07-23 23:09:08 -04:00
body=form.body.data,
)
email = session.get('login')
if email:
user = db.get_user(email)
letters = db.get_user_letters(user.id)
if True: # len(letters) == 0:
db.add_letter(user.id, 'LETTER_TITLE', jsonify(data).get_data(True))
else:
print("TODO: Add letter editing!")
# db.edit_letter()
(resp, errors) = data.generate_pdf()
if errors:
resp = make_response(render_template(
'writing.jinja2',
form=form,
letter_errors=errors,
))
# Save entered data as cookies on user's machine
for pair in data.get_pairs():
resp.set_cookie(pair[0], urllib.parse.quote(pair[1]))
return resp
return render_template(
'writing.jinja2',
form=form,
)