Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
executable file
·400 lines (300 loc) · 14.9 KB
/
Copy pathapp.py
File metadata and controls
executable file
·400 lines (300 loc) · 14.9 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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
"""
Charlie Team, CMSC 495 Section 7381, Spring 2024
John Leckie, Shara Belton, Sirish Tadepalli, and Thomas Memmo
Mark Munoz, Professor
Astronomy Web App
This is a Flask web application for a simple astronomy website. Frontend elements were mockup
forms with no backend functionality.
For our team's project, a database was added. The users (Astronomy professors working for the
school) can now schedule a time slot for either telescope usage or instructing students using
the planetarium. These actions will test interoperability between the frontend and backend
elements of the application.
"""
import hashlib # Required for password hashing
from datetime import datetime,timedelta
import logging
import mysql.connector
from flask import Flask, render_template, request, redirect, url_for, flash, session, jsonify
app = Flask(__name__)
app.secret_key = '86753093212135889'
# Connect to the MySQL database
db = mysql.connector.connect(
host="13.58.228.75",
user="cmsc495",
password="CMSC4952024",
database="cmsc495_astro"
)
#make a cursor for writing queries
cursor = db.cursor()
# Configure logging to write to security_log.txt
security_logger = logging.getLogger("security")
security_logger.setLevel(logging.INFO)
# File handler for security log
security_handler = logging.FileHandler("security_log.txt")
security_handler.setLevel(logging.INFO)
# Formatter for the log messages
security_formatter = logging.Formatter('%(asctime)s - %(message)s')
security_handler.setFormatter(security_formatter)
# Add the handler to the security logger
security_logger.addHandler(security_handler)
# Store user data in a file
SECURITY_DATA_FILE = 'security_log.txt'
# Logger for failed login attempts
failed_login_logger = logging.getLogger
@app.route('/register', methods=['GET', 'POST'])
def register():
"""
Register users and store their information in a database after validation.
Returns:
rendered template for the registration page with flash messages
"""
flash('', 'error') # Clears existing flash messages for the session, if any
if request.method == 'POST':
username = request.form['username'] #retrieves the values for username etc from the form that got submitted
name = request.form['name']
password = request.form['password']
confirm_password = request.form['confirm_password']
# Check if password and confirm_password match
if password != confirm_password:
flash('Password and confirm password do not match. Please try again.',
'error')
else:
# Check if the username already exists in the database
cursor.execute("SELECT * FROM Users WHERE username = %s", (username,))
results = cursor.fetchall()
if results:
flash('Username already exists. Choose another username or return to Login via below link.', 'error')
return render_template('register.html')
# Validate password complexity
if not (len(password) >= 12 and any(c.isupper() for c in password)
and any(c.islower() for c in password)
and any(c.isdigit() for c in password)
and any(not c.isalnum() for c in password)):
flash('Password does not meet complexity requirements', 'error')
# Check for spaces in username and password
elif ' ' in username or ' ' in password:
flash('Username and password cannot contain spaces.', 'error')
else:
# Hash the password before storing it (for security)
hashed_password = hashlib.sha256(password.encode()).hexdigest()
# add username and hashed password to database
cursor.execute("INSERT INTO Users (name, username, password) VALUES (%s, %s, %s)", (name, username, hashed_password))
#commit db and display success message
db.commit()
flash('Registration successful!', 'success')
page_name = 'register'
return render_template('register.html', page_name=page_name)
@app.route('/login', methods=['POST', 'GET'])
def login():
"""
Authenticate users and log them in if valid credentials are provided.
Returns:
rendered template for login page with flash messages
"""
flash('', 'error') # Clears existing flash messages for the session, if any
reg_message = session.pop('reg_message', None)
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
cursor.execute("SELECT password FROM Users WHERE username = %s", (username,))
row = cursor.fetchone()
db_password = row[0]
#if that password, and therefore account, exists
if db_password:
# Hash the provided password for comparison
hashed_password = hashlib.sha256(password.encode()).hexdigest()
if db_password == hashed_password:
session['logged_in'] = True
session['username'] = username
return redirect(url_for("home")) # Redirect to the home page after successful login
else:
# Log the failed login attempt
failed_login_message = (f'Failed login attempt for username: {username} from '
f'IP: {request.remote_addr}')
security_logger.info(failed_login_message)
flash('Invalid username or password', 'error')
#if there is no resulting_row, meaning that account doesn't exist
else:
# Log the failed login attempt
failed_login_message = ('Account not found '
f'IP: {request.remote_addr}')
security_logger.info(failed_login_message)
flash('Account not found', 'error')
page_name = 'login'
return render_template('login.html', reg_message=reg_message, page_name=page_name)
def get_available_time_slots(week_date):
cursor.execute("SELECT time FROM Telescope WHERE date = %s AND UserID IS NULL", (week_date,))
available_time_slots = [slot[0] for slot in cursor.fetchall()]
return available_time_slots
@app.route('/telescope_time', methods=['POST', 'GET'])
def telescope_time():
"""
Render the telescope time sign-up page.
Returns:
rendered template for telescope time page
"""
# Check if the user is logged in, if not, redirect to the login page
if not session.get('logged_in'):
return redirect(url_for('login'))
if request.method == 'POST':
dataGet = request.json
if dataGet.get('type') == 'calendar':
selected_date = dataGet.get('date')
#Do what is needed with the data
print(selected_date)
# Convert the date string to a datetime object
date = datetime.strptime(selected_date, '%Y-%m-%d')
# Find the Monday of the week
monday = date - timedelta(days=date.weekday())
week_dates = []
# Iterate from Monday to Sunday and add each date to the list
for i in range(7):
week_dates.append((monday + timedelta(days=i)).strftime('%Y-%m-%d'))
print(week_dates)
dates_and_times_dict = {}
for date in week_dates:
time_slots = get_available_time_slots(date)
dates_and_times_dict.update({date: time_slots})
print(dates_and_times_dict)
# convert timedelta objects to strings
for key, value in dates_and_times_dict.items():
dates_and_times_dict[key] = [str(slot) for slot in value]
print(dates_and_times_dict)
return jsonify(dates_and_times_dict)
# return data after getting it
# FOR FORM SUBMISSION
else:
date = dataGet['date']
time = dataGet['time']
time = convert_to_24_hour(time)
print(time)
username = session['username']
#first get the userID associated with that name from the Users table
cursor.execute("SELECT userID FROM Users WHERE username = %s", (username,))
row = cursor.fetchone()
userID = row[0]
#fill that userID into the row with that date and time which are formatted into strings
cursor.execute("UPDATE Telescope SET userID = %s WHERE date = %s AND time = %s", (userID, str(date), str(time)))
db.commit()
print('Successfully reserved');
return jsonify({'message': 'Reservation successful'})
page_name = 'telescope-time'
return render_template('telescope_time.html', page_name=page_name)
def convert_to_24_hour(time_str):
# Parse the time string using strptime
time_obj = datetime.strptime(time_str, '%I:%M %p') # %I for 12-hour format, %p for AM/PM indicator
# Convert the time object to 24-hour format using strftime
time_24_hour = time_obj.strftime('%H:%M') # %H for 24-hour format, %M for minutes
return time_24_hour
@app.route('/update_password', methods=['GET', 'POST'])
def update_password():
"""
If the user is logged in, it verifies the current password, runs the same checks on the
candidate new one, and updates the user's password in the file if all checks pass.
Returns:
Updates database with user's new password, once candidate passwords pass checks.
"""
# Check if the user is logged in, if not, redirect to the login page
if not session.get('logged_in'):
return redirect(url_for('login'))
flash('', 'error') # Clears existing flash messages for the session, if any
if request.method == 'POST':
current_password = request.form['current_password']
new_password = request.form['new_password']
confirm_new_password = request.form['confirm_new_password']
username = session.get("username")
hashed_current_password = hashlib.sha256(current_password.encode()).hexdigest()
cursor.execute("SELECT password FROM Users WHERE username = %s", (username,))
row = cursor.fetchone()
db_password = row[0]
# Ensure current password and database password are a match
if db_password != hashed_current_password:
# Log the failed password change attempt
failed_change_password_message = (f'Failed password change attempt for username: {username} from '
f'IP: {request.remote_addr}')
security_logger.info(failed_change_password_message)
flash('Invalid password', 'error')
return redirect(url_for("update_password"))
# Check for spaces in username and password
if " " in new_password:
flash("Password cannot contain spaces.",
"error")
return redirect(url_for("update_password"))
# Check if the new password and confirm password match
if new_password != confirm_new_password:
flash("New password and confirm password do not match. Try again.",
"error")
return redirect(url_for("update_password"))
# Password complexity validation (same as registration)
if not (len(new_password) >= 12
and any(c.isupper() for c in new_password)
and any(c.islower() for c in new_password)
and any(c.isdigit() for c in new_password)
and any(not c.isalnum() for c in new_password)):
flash("New password does not meet complexity requirements",
"error")
return redirect(url_for("update_password"))
# Check if the new password is in CommonPasswords.txt.
with open("static/CommonPasswords.txt", "r",
encoding="utf-8") as common_passwords_file:
print("Debug: Comparing COMMON PASSWORD LIST")
common_passwords = [line.strip() for line in common_passwords_file]
if new_password in common_passwords:
flash("New password is commonly used. Choose a different password.",
"error")
return redirect(url_for("update_password"))
# Hash the new password before storing it (for security)
hashed_new_password = hashlib.sha256(new_password.encode()).hexdigest()
# Update the user's password in the database
cursor.execute("UPDATE Users SET password = %s WHERE username = %s", (hashed_new_password, username))
db.commit()
flash("Password updated successfully", "success")
return redirect(url_for("home"))
page_name = 'update-password'
return render_template('update_password.html')
@app.route('/')
def home():
if 'logged_in' in session:
current_time = datetime.now()
page_name = 'Home'
return render_template('index.html', current_time=current_time, page_name=page_name)
else:
page_name = 'Login'
return redirect(url_for('login'))
@app.route('/planetarium', methods=['POST', 'GET'])
def planetarium():
"""
Render the planetarium volunteer page.
Returns:
rendered template for planetarium volunteer page
"""
# Check if the user is logged in, if not, redirect to the login page
if not session.get('logged_in'):
return redirect(url_for('login'))
if request.method == 'POST':
date = request.form['date']
time = request.form['time']
username = session['username']
#first get the userID associated with that name from the Users table
cursor.execute("SELECT userID FROM Users WHERE username = %s", (username,))
row = cursor.fetchone()
userID = row[0]
#fill that userID into the row with that date and time which are formatted into strings
cursor.execute("INSERT INTO Planetarium (userID, date, time) VALUES (%s, %s, %s)", (userID, date, time))
db.commit()
flash('Thank you! We will confirm shortly..', 'success')
page_name = 'Planetarium'
return render_template('planetarium.html', page_name=page_name)
@app.route('/logout')
def logout():
"""
Log users out by clearing their session data.
Returns:
Redirects to the login page with a logout flash message
"""
# Clear the user's session data to log them out
session.clear()
flash('Logout Successful - See you next time!', 'success')
return redirect(url_for('login'))
if __name__ == '__main__':
app.run()