-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
369 lines (303 loc) · 13.1 KB
/
app.py
File metadata and controls
369 lines (303 loc) · 13.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
# import os module, env variables, Flask modules needed.
import os
from flask import (
Flask, flash, render_template,
redirect, request, session, url_for)
from flask_mail import Mail, Message
from flask_wtf import FlaskForm
from wtforms.fields.html5 import DateField
from wtforms.validators import DataRequired
from wtforms import validators, SubmitField
from flask_pymongo import PyMongo
from bson.objectid import ObjectId
from werkzeug.security import generate_password_hash, check_password_hash
if os.path.exists("env.py"):
import env
# create instance of Flask
app = Flask(__name__)
# create object of class
class DateForm(FlaskForm):
startdate = DateField('Start Date', format='%Y-%m-%d',
validators=(validators.DataRequired(),))
enddate = DateField('End Date', format='%Y-%m-%d',
validators=(validators.DataRequired(),))
submit = SubmitField('Submit')
# additional configuration
app.config["MONGO_DBNAME"] = os.environ.get("MONGO_DBNAME") # grabs DB name
app.config["MONGO_URI"] = os.environ.get("MONGO_URI") # connection string
app.secret_key = os.environ.get("SECRET_KEY") # required for flask security
# create instance of pymongo and pass it the flask app
mongo = PyMongo(app)
# route for main index page of app
@app.route("/")
@app.route("/index")
def index():
return render_template("index.html")
# route for registration page of app
@app.route("/register", methods=["GET", "POST"])
def register():
if request.method == "POST":
is_admin = "on" if request.form.get("is_admin") else "off"
existing_user = mongo.db.users.find_one(
{"email": request.form.get("inputEmail").lower()})
if existing_user:
flash("User already exists")
return redirect(url_for("register"))
ent_base = {
"email": request.form.get("inputEmail").lower(),
"title": "Title",
"salary": "0",
"holidays": "20",
"bonus": "0"
}
register = {
"email": request.form.get("inputEmail").lower(),
"password": generate_password_hash(
request.form.get("inputPassword")),
"firstName": request.form.get("inputFirstName").lower(),
"lastName": request.form.get("inputLastName").lower(),
"is_admin": is_admin,
"user_name": request.form.get("uname").lower(),
"address": request.form.get("inputAddress").lower(),
"city": request.form.get("inputCity").lower(),
"country": request.form.get("inputCountry").lower(),
"post_code": request.form.get("postCode").lower()
}
mongo.db.users.insert_one(register)
mongo.db.position.insert_one(ent_base)
session["user"] = request.form.get("inputEmail")
if register["is_admin"] == "on":
session["admin"] = True
return redirect(url_for("profile", username=session["user"]))
return render_template("register.html")
# route for edit profile page of app
@app.route("/update_profile/<id>", methods=["GET", "POST"])
def update_profile(id):
if request.method == "POST":
is_admin = "on" if request.form.get("is_admin") else "off"
existing_user = mongo.db.users.find_one(
{"email": request.form.get("inputEmail").lower()})
if existing_user:
edited = {
"email": request.form.get("inputEmail").lower(),
"password": generate_password_hash(
request.form.get("inputPassword")),
"firstName": request.form.get("inputFirstName").lower(),
"lastName": request.form.get("inputLastName").lower(),
"is_admin": is_admin,
"user_name": request.form.get("uname").lower(),
"address": request.form.get("inputAddress").lower(),
"city": request.form.get("inputCity").lower(),
"country": request.form.get("inputCountry").lower(),
"post_code": request.form.get("postCode").lower()
}
mongo.db.users.update({"_id": ObjectId(id)}, edited)
flash("Update Successful!")
return_edit = mongo.db.users.find_one({"_id": ObjectId(id)})
return render_template(
"update_profile.html", return_edit=return_edit)
# route for login page of app
@app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
existing_user = mongo.db.users.find_one(
{"email": request.form.get("inputEmail").lower()})
if existing_user:
if check_password_hash(
existing_user["password"],
request.form.get("inputPassword")):
session["user"] = request.form.get("inputEmail").lower()
if existing_user["is_admin"] == "on":
session["admin"] = True
return redirect(
url_for("profile", username=session["user"]))
else:
flash("Incorrect Username and/or Password")
return redirect(url_for("login"))
else:
flash("Incorrect Username and/or Password")
return redirect(url_for("login"))
return render_template("login.html")
# route for profile page of app
@app.route("/profile/<username>", methods=["GET", "POST"])
def profile(username):
cur_hols = mongo.db.position.find_one({"email": session["user"]})
new_entitlements = mongo.db.position.find_one({"email": session["user"]})
tasks = list(mongo.db.tasks.find())
ents_base = mongo.db.position.find_one({"email": session["user"]})
return_edit = mongo.db.users.find_one(
{"email": session["user"]})
if session["user"]:
return render_template(
"profile.html",
tasks=tasks,
return_edit=return_edit,
cur_hols=cur_hols,
new_entitlements=new_entitlements,
ents_base=ents_base
)
return redirect(url_for("login"))
# route for logout function of app
@app.route("/logout")
def logout():
flash("You have successfully logged out")
session.clear()
return redirect(url_for("login"))
# route for add task page and function of app
@app.route("/add_task", methods=["GET", "POST"])
def add_task():
if request.method == "POST":
is_urgent = "on" if request.form.get("is_urgent") else "off"
task = {
"category_name": request.form.get("category_name"),
"task_name": request.form.get("task_name"),
"task_description": request.form.get("task_description"),
"is_urgent": is_urgent,
"due_date": request.form.get("due_date"),
"task_assign": request.form.get("task_assign"),
"created_by": session["user"]
}
mongo.db.tasks.insert_one(task)
flash("Task successfully added")
return redirect(url_for("add_task"))
categories = mongo.db.categories.find().sort("category_name", 1)
return render_template("add_task.html", categories=categories)
# route for edit task fucntion and page of app
@app.route("/edit_task/<task_id>", methods=["GET", "POST"])
def edit_task(task_id):
if request.method == "POST":
is_urgent = "on" if request.form.get("is_urgent") else "off"
submit = {
"category_name": request.form.get("category_name"),
"task_name": request.form.get("task_name"),
"task_description": request.form.get("task_description"),
"is_urgent": is_urgent,
"due_date": request.form.get("due_date"),
"task_assign": request.form.get("task_assign"),
"created_by": session["user"]
}
mongo.db.tasks.update({"_id": ObjectId(task_id)}, submit)
flash("Task Successfully updated")
task = mongo.db.tasks.find_one({"_id": ObjectId(task_id)})
categories = mongo.db.categories.find().sort("category_name", 1)
return render_template("edit_task.html", task=task, categories=categories)
# route for delete task function of app
@app.route("/delete_task/<task_id>")
def delete_task(task_id):
mongo.db.tasks.remove({"_id": ObjectId(task_id)})
return redirect(url_for("profile", username=session["user"]))
# route for info page of app
@app.route("/info")
def info():
return render_template("info.html")
# getting and setting the vars for the mail settings
mail_settings = {
"MAIL_SERVER": os.environ.get(
'MAIL_SERVER'), "MAIL_PORT": os.environ.get('MAIL_PORT'),
"MAIL_USE_TLS": False,
"MAIL_USE_SSL": os.environ.get('MAIL_USE_SSL'),
"MAIL_USERNAME": os.environ.get('MAIL_USERNAME'),
"MAIL_PASSWORD": os.environ.get('MAIL_PASSWORD'),
"SECURITY_EMAIL_SENDER": os.environ.get("SECURITY_EMAIL_SENDER")
}
# updating the mail settings vars to app config
app.config.update(mail_settings)
# creating instance of Mail and passing the app
mail = Mail(app)
# route for handling mail on main index page of app
@app.route("/index", methods=["GET", "POST"])
def contact():
if request.method == "POST":
with app.app_context():
msg = Message("Hello from HIVE")
msg.sender = os.environ.get('MAIL_USERNAME')
msg.recipients = [request.form.get("email")]
msg.body = f"Email From: {msg.sender}"
msg.html = '<b>Hello, thanks for signing up!</b> \
welcome to the HIVE, check us out: \
<a href="https://hive-human-resources.herokuapp.com/info"> \
HIVE</a>.'
mail.send(msg)
flash("Email sent!")
return redirect(url_for('index'))
return render_template("index.html")
# route for handling mail on info page of app
@app.route("/info", methods=["GET", "POST"])
def info_contact():
if request.method == "POST":
with app.app_context():
msg = Message("Hello from HIVE")
msg.sender = os.environ.get('MAIL_USERNAME')
msg.recipients = [request.form.get("email")]
msg.body = f"Email From: {msg.sender}"
msg.html = '<b>Hello, thanks for signing up!</b> \
welcome to the HIVE, check us out: \
<a href="https://hive-human-resources.herokuapp.com/info"> \
HIVE</a>.'
mail.send(msg)
flash("Email sent!")
return redirect(url_for('info'))
return render_template("info.html")
# route for handling annual leave page of app
@app.route("/annual_leave/<hol_id>", methods=["GET", "POST"])
def annual_leave(hol_id):
form = DateForm(meta={'csrf': False})
if request.method == "POST":
get_hols = mongo.db.position.find_one({"email": session["user"]})
print(get_hols)
if get_hols is None:
print("None")
elif int(get_hols["holidays"]) <= 0:
flash(
"You have no Holidays available to take, \
contact your HR department.")
elif form.validate_on_submit():
session['startdate'] = form.startdate.data
session['enddate'] = form.enddate.data
delta = session['enddate'] - session['startdate']
delta = delta.days
new_hols = int(get_hols["holidays"]) - delta
print(new_hols)
hol_update = {"$set": {"holidays": new_hols}}
mongo.db.position.update_one({"_id": ObjectId(hol_id)}, hol_update)
flash(f"You have booked {delta} day(s) off!")
cur_hols = mongo.db.position.find_one({"_id": ObjectId(hol_id)})
print(cur_hols["email"])
return render_template(
'annual_leave.html', form=form, cur_hols=cur_hols)
# route for handling edit entitlements page and function
@app.route("/edit_entitlements/<entitlement_id>", methods=["GET", "POST"])
def edit_entitlements(entitlement_id):
if request.method == "POST":
user_entitled = mongo.db.users.find_one(
{"email": request.form.get("inputEmail").lower()})
if user_entitled:
entitlement = {
"email": request.form.get("inputEmail").lower(),
"title": request.form.get("inputTitle").lower(),
"salary": request.form.get("inputSalary").lower(),
"holidays": request.form.get("inputHolidays").lower(),
"bonus": request.form.get("inputBonus").lower()
}
mongo.db.position.update_one(
{"email": request.form.get("inputEmail").lower()},
{"$set": entitlement})
flash('Profile updated')
name = mongo.db.users.find_one({"email": session["user"]})
new_entitlements = mongo.db.position.find_one(
{"_id": ObjectId(entitlement_id)})
return render_template(
"edit_entitlements.html", new_entitlements=new_entitlements, name=name)
# route for error handling - URL was not found
@app.errorhandler(404)
def not_found(e):
return render_template('404.html'), 404
# route for error handling - Internal server error
@app.errorhandler(500)
def server_error(error):
return render_template('500.html'), 500
# tell the app where and when to run the app. IP & PORT Vars hidden in env.py
if __name__ == "__main__":
app.run(host=os.environ.get("IP"),
port=int(os.environ.get("PORT")),
debug=False)