generated from ruszkipista/ci11-todo-celeb-sandwich
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrun.py
308 lines (247 loc) · 10.8 KB
/
run.py
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
import os
from flask import Flask, render_template, request, redirect, flash, send_file, session, url_for
from io import BytesIO
import utilities
import formdb
# envWS.py should exist only in Development
if os.path.exists("envWS.py"):
import envWS
app = Flask(__name__)
# take app configuration from OS environment variables
app.secret_key = os.environ.get(
"FLASK_SECRET_KEY") # => Heroku Config Vars
app.config["FLASK_IP"] = os.environ.get("FLASK_IP", "0.0.0.0")
# the source 'PORT' name is mandated by Heroku app deployment
app.config["FLASK_PORT"] = int(os.environ.get("PORT"))
app.config["FLASK_DEBUG"] = os.environ.get("FLASK_DEBUG", "False").lower() in {
'1', 'true', 't', 'yes', 'y'}
# App routes
# ==============
@app.route("/") # trigger point through webserver: "/"= root directory
def index():
cars = None
# is logged in user valid?
loggedin_user = get_loggedin_user()
if loggedin_user:
cars = formdb.get_db_cars_for_user()
if not cars:
flash(f"You have no car assigned, ask the administrator for one!", 'info')
return render_template(
"index.html",
collection_name=formdb.get_db_coll_name_cars(),
records=cars
)
@app.route("/register", methods=['GET', 'POST'])
def register():
if request.method == "GET":
return render_template("reglog.html", register=True)
# request.method == POST
username_entered = formdb.get_form_reglog_field_username(request)
# check if username already exists in db
user_old = formdb.get_db_user_by_name(username_entered)
if user_old:
flash(f"Username already exists", 'danger')
return redirect(url_for("register"))
password_entered = formdb.get_form_reglog_field_password(request)
user_new = formdb.insert_db_user(username_entered, password_entered)
# put the new user_id into 'session' cookie
formdb.login_db_user(user_new)
flash("Registration Successful!", "success")
return redirect(url_for("index"))
@app.route("/login", methods=['GET', 'POST'])
def login():
if request.method == "GET":
return render_template("reglog.html", register=False)
# request.method == POST
username_entered = formdb.get_form_reglog_field_username(request)
password_entered = formdb.get_form_reglog_field_password(request)
user_old = formdb.get_db_user_by_name(username_entered)
if user_old:
password_stored = formdb.get_db_user_password(user_old)
# check if username does not exist in db
# or stored and entered passwords differ
if not user_old or not utilities.is_password_hash_correct(password_stored, password_entered):
flash(f"Incorrect Username and/or Password", 'danger')
return redirect(url_for("login"))
# put the User ID / Car IDs into session cookie
formdb.login_db_user(user_old)
flash(f"Welcome, {username_entered}", "success")
return redirect(url_for("index"))
@app.route("/logout")
def logout():
# is a user logged in?
loggedin_user_id = formdb.get_db_user_id()
if loggedin_user_id:
formdb.logout_db_user()
flash("You have been logged out", "info")
return redirect(url_for("login"))
@app.route("/profile", methods=['GET', 'POST'])
def profile():
loggedin_user = get_loggedin_user()
if not loggedin_user:
return redirect(url_for("login"))
if request.method == "GET":
return render_template("profile.html", user=loggedin_user)
# request.method == POST
password_old = formdb.get_form_profile_field_password_old(request)
password_stored = formdb.get_db_user_password(loggedin_user)
if not utilities.is_password_hash_correct(password_stored, password_old):
flash("Wrong old password", 'danger')
return redirect(url_for("profile"))
password_new = formdb.get_form_profile_field_password_new(request)
if utilities.is_password_hash_correct(password_stored, password_new):
flash("Old and New passwords are the same, not changed!", "warning")
return redirect(url_for("profile"))
# update password in DB
is_update_ok = formdb.set_db_user_password(
formdb.get_db_user_id(), password_new)
if is_update_ok:
flash("Your password has been changed", "success")
return render_template("profile.html", user=loggedin_user)
def get_loggedin_user():
loggedin_user = {}
# is a user logged in?
loggedin_user_id = formdb.get_db_user_id()
if loggedin_user_id:
# get user record from DB
loggedin_user = formdb.get_db_user_by_id(loggedin_user_id)
if not loggedin_user:
formdb.logout_db_user()
flash("Invalid logged in user has been logged out!", 'danger')
return loggedin_user
@app.route("/maintain/<collection_name>", methods=['GET', 'POST'])
def maintain(collection_name):
# validate logged in user
loggedin_user = get_loggedin_user()
if not loggedin_user:
return redirect(url_for("login"))
# is collection maintanable by admin only and user is not logged in as admin?
if formdb.get_db_is_admin_maintainable(collection_name) and not formdb.get_db_user_is_admin():
return redirect(url_for("index"))
cars = formdb.get_db_cars_for_user()
if not cars:
return redirect(url_for("index"))
# create an empty record
record = {}
if request.method == 'POST':
result = formdb.save_record_to_db(request, collection_name, record)
for m in result.messages:
flash(*m)
if not result.record:
return redirect(url_for('maintain', collection_name=collection_name))
records = formdb.get_db_all_records(collection_name)
if not records:
flash("There are no records. Create one below!", 'info')
return render_template(
"maintain.html",
collection_name=collection_name,
records=records,
last_record=record
)
@app.route("/update/<collection_name>/<record_id>", methods=['GET', 'POST'])
def update_record(collection_name, record_id):
# validate logged in user
loggedin_user = get_loggedin_user()
if not loggedin_user:
return redirect(url_for("login"))
# is collection maintanable by admin only and user is not logged in as admin?
if formdb.get_db_is_admin_maintainable(collection_name) and not formdb.get_db_user_is_admin():
return redirect(url_for("index"))
record = formdb.get_db_record_by_id(collection_name, record_id)
if not record:
entity_name = formdb.get_db_entity_name(collection_name)
flash(f"{entity_name} {record_id} does not exist", "danger")
return redirect(url_for('maintain', collection_name=collection_name))
if request.method == 'POST':
result = formdb.save_record_to_db(request, collection_name, record)
print(*result.messages[0])
for m in result.messages:
flash(*m)
# if record is empty, then the update was successful
if not result.record:
return redirect(url_for('maintain', collection_name=collection_name))
return render_template(
"maintain.html",
collection_name=collection_name,
records=[],
last_record=record
)
@app.route("/delete/<collection_name>/<record_id>", methods=['POST'])
def delete_record(collection_name, record_id):
# validate logged in user
loggedin_user = get_loggedin_user()
if not loggedin_user:
return redirect(url_for("login"))
# is collection maintanable by admin only and user is not logged in as admin?
if formdb.get_db_is_admin_maintainable(collection_name) and not formdb.get_db_user_is_admin():
return redirect(url_for("index"))
record = formdb.get_db_record_by_id(collection_name, record_id)
if not record:
flash(f"Record {record_id} does not exist", "danger")
else:
# delete record
formdb.delete_db_record(collection_name, record)
entity_name = formdb.get_db_entity_name(collection_name)
flash(f"Deleted one {entity_name} record", "info")
return redirect(url_for('maintain', collection_name=collection_name))
@app.route("/serve/image/<image_id>")
def serve_image(image_id):
# validate logged in user
loggedin_user = get_loggedin_user()
if not loggedin_user:
return redirect(url_for("login"))
image = formdb.get_db_image_by_id(image_id)
if image:
return send_file(BytesIO(image['image']), mimetype='application/octet-stream')
# inspired by https://stackoverflow.com/questions/4830535/how-do-i-format-a-date-in-jinja2
@app.template_filter('datetime_to_str')
def _jinja2_filter_datetime_to_str(dt, format):
if dt:
return dt.strftime(format)
else:
return str()
# learnt about calling functions from jinja template from here https://stackoverflow.com/a/22966127/8634389
@app.context_processor
def context_variables():
return dict(
fieldcatalog=formdb.get_db_fieldcatalog(),
buffer={coll: formdb.get_db_records(coll)
for coll in formdb.get_db_buffered_collections()}
)
@app.template_filter('filter_records')
def _jinja2_filter_filter_records(records: dict, field_details: dict):
return formdb.filter_db_records(records, field_details)
@app.template_filter('create_data_attributes')
def _jinja2_filter_create_data_attributes(coll_fieldcat: dict, record: dict, filter_postfix: str):
return formdb.create_form_data_attributes(coll_fieldcat, record, filter_postfix)
@app.template_filter('get_entity_select_field')
def _jinja2_filter_get_entity_select_field(entity_id, collection_name):
return formdb.get_db_entity_select_field(entity_id, collection_name)
@app.template_filter('ObjectId')
def _jinja2_filter_objectid(id: str):
field_name = "id"
record = {field_name: id}
formdb.translate_db_external_to_internal(
field_name, "ObjectId", None, record)
return record[field_name]
@app.template_filter('unix_time_ago')
def _jinja2_filter_time_ago(unix_timestamp: int):
return utilities.translate_unix_timestamp_to_time_ago_text(unix_timestamp)
# Flask pattern from https://flask.palletsprojects.com/en/1.1.x/patterns/sqlite3/
@app.teardown_appcontext
def close_db_connection(exception):
formdb.close_db_connection(exception)
@app.errorhandler(404)
def page_not_found(e):
return redirect(url_for("index"))
# Run the App
# =================
if __name__ == "__main__":
with app.app_context():
formdb.init_db()
app.run(
host=app.config["FLASK_IP"],
port=app.config["FLASK_PORT"],
debug=app.config["FLASK_DEBUG"],
use_reloader=False
)