-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
383 lines (291 loc) · 12 KB
/
app.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
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
from flask import Flask, request, render_template, send_from_directory, jsonify, redirect, url_for, flash, session
import MySQLdb
import os
import json
from datetime import datetime
import uuid
import subprocess
import bcrypt
ip = '192.168.241.64'
app = Flask(__name__)
app.secret_key = 'test'
db = MySQLdb.connect(host=ip, user="mario", passwd="toor", db="bacOS")
cursor = db.cursor()
def datetimeformat(value, format='%Y-%m-%dT%H:%M'):
if isinstance(value, str):
dt = datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
return dt.strftime(format)
return value
app.jinja_env.filters['datetimeformat'] = datetimeformat
@app.route('/upload-api', methods=['POST'])
def upload():
files = request.files.getlist('files')
user = request.form.get('user')
event = request.form.get('event')
for file in files:
file_path = os.path.join('rezolvari', user, file.filename)
if not os.path.isdir(os.path.dirname(file_path)):
os.makedirs(os.path.dirname(file_path))
file.save(file_path)
file_path = r'C:\Users\m3m0r\Projects\bacOS\rezolvari\tests.py'
user_path = rf'C:\Users\m3m0r\Projects\bacOS\rezolvari\{user}'
print(user)
subprocess.run(['python3', file_path, event, user_path])
return ' ', 200
@app.route('/')
def home():
return redirect(url_for('events'))
@app.route('/logout')
def logout():
session.pop('logged_in', None)
flash('You have been logged out', 'success')
return redirect(url_for('login'))
import bcrypt
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
username = request.form.get('username')
email = request.form.get('email')
password = request.form.get('password').encode('utf-8') # Encode the password to bytes
type = request.form.get('type')
# Generate a salt and hash the password
hashed_password = bcrypt.hashpw(password, bcrypt.gensalt())
if type == 'on':
type = 'asteapta aprobare'
else:
type = 'elev'
user_uuid = uuid.uuid4()
query = "INSERT INTO users (username, email, password, account_type, UUID) VALUES (%s, %s, %s, %s, %s)"
cursor.execute(query, (username, email, hashed_password, type, user_uuid))
db.commit()
flash('Account created successfully', 'success')
session['mail'] = email
session['logged_in'] = True
session['uuid'] = user_uuid
session['type'] = type
print("user: ", session['uuid'], "with type: ", session['type'])
return redirect(url_for('events'))
return render_template('login.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
email = request.form.get('email')
password = request.form.get('password').encode('utf-8')
query = "SELECT * FROM users WHERE email = %s"
cursor.execute(query, (email,))
result = cursor.fetchone()
if result and bcrypt.checkpw(password, result[2].encode('utf-8')):
session['logged_in'] = True
session['uuid'] = result[5]
session['mail'] = email
session['type'] = result[3]
print("user: ", session['uuid'], "with type: ", session['type'])
return redirect(url_for('events'))
else:
flash('Invalid credentials', 'error')
return redirect(url_for('login'))
return render_template('login.html')
@app.route('/creare', methods=['GET', 'POST'])
def creare():
#modifica doar pt profesori
if 'logged_in' in session and session['logged_in'] and session['type'] == 'profesor':
if request.method == 'POST':
nume = request.form.get('nume')
startdatetime = request.form.get('startdatetime')
durata = request.form.get('durata')
compiler = request.form.get('compiler')
if compiler == 'on':
compiler = True
else:
compiler = False
cursor.execute(f"INSERT INTO events (nume, startdatetime, durata, compiler) VALUES ('{nume}', '{startdatetime}', {durata}, {compiler})")
db.commit()
id = str(cursor.lastrowid)
os.makedirs("events\\" + id)
subiecte = request.files.getlist('subiecte')
for file in subiecte:
if file:
file.save(os.path.join("events\\" + id, file.filename))
test = request.files.get('teste')
if test:
test.save(os.path.join(id, test.filename))
return render_template('creare.html')
else:
return render_template('blocked.html')
@app.route('/loginapi', methods=['POST'])
def loginapi():
email = request.form.get('email')
password = request.form.get('password').encode('utf-8')
query = "SELECT * FROM users WHERE email = %s"
cursor.execute(query, (email,))
result = cursor.fetchone()
if result and bcrypt.checkpw(password, result[2].encode('utf-8')):
return jsonify({'OK': 'user found'}), 200
else:
return jsonify({'error': 'user not found'}), 401
@app.route('/api/event/<int:id>', methods=['GET'])
def api_event(id):
cursor.execute("SELECT * FROM events WHERE id = %s", (id,))
event = cursor.fetchone()
if event:
event_data = {
'id': event[0],
'nume': event[1],
'startdatetime': event[3],
'durata': event[4],
'compiler': event[5],
'subiecte': os.listdir(f"events\\{id}")
}
return jsonify(event_data)
else:
return jsonify({'error': 'Event not found'}), 404
@app.route('/subiecte/<int:id>', methods=['GET'])
def subiecte(id):
return jsonify(os.listdir(f"events\\{id}"))
@app.route('/durata/<int:id>', methods=['GET'])
def durata(id):
cursor.execute("SELECT durata FROM events WHERE id = %s", (id,))
durata = cursor.fetchone()
return jsonify(durata[0])
@app.route('/compiler/<int:id>', methods=['GET'])
def compiler(id):
cursor.execute("SELECT compiler FROM events WHERE id = %s", (id,))
compiler = cursor.fetchone()
return jsonify(compiler[0])
@app.route('/tests/<int:id>', methods=['GET'])
def tests(id):
cursor.execute("SELECT teste FROM events WHERE id = %s", (id,))
tests = cursor.fetchone()
return jsonify(tests[0])
@app.route('/startdatetime/<int:id>', methods=['GET'])
def startdatetime(id):
cursor.execute("SELECT startdatetime FROM events WHERE id = %s", (id,))
result = cursor.fetchone()
if result:
startdatetime = result[0] # This should be a datetime object
# Format datetime as 'YYYY-MM-DD HH:MM:SS'
formatted_startdatetime = startdatetime.strftime('%Y-%m-%d %H:%M:%S')
return jsonify(formatted_startdatetime)
@app.route('/gentest/<int:id>', methods=['GET', 'POST'])
def gentest(id):
#doar pentru profesori
if 'logged_in' in session and session['logged_in']:
if request.method == 'POST':
subiect = request.form.get('subiect')
input = request.form.get('input')
expected_output = request.form.get('expected_output')
punctaj = request.form.get('punctaj')
cursor.execute("SELECT teste FROM events WHERE id = %s", (id,))
existing_json = cursor.fetchone()[0]
print(id)
try:
existing_data = json.loads(existing_json)
if not isinstance(existing_data, list):
existing_data = []
except (json.JSONDecodeError, TypeError):
existing_data = []
test_data = {
'id': subiect,
'input': input,
'expected_output': expected_output,
'punctaj': punctaj
}
existing_data.append(test_data)
updated_json = json.dumps(existing_data)
cursor.execute("UPDATE events SET teste = %s WHERE id = %s", (updated_json, id))
db.commit()
return redirect(url_for('event', id=id))
if request.method == 'GET':
return render_template('gentest.html', id = id)
else:
return redirect(url_for('login'))
@app.route('/events', methods=['GET'])
def events():
if 'logged_in' in session and session['logged_in']:
cursor.execute("SELECT username FROM users WHERE UUID = %s", (session['uuid'],))
user = cursor.fetchone()
if user:
username = user[0]
else:
username = None
cursor.execute("SELECT id, nume FROM events")
events = cursor.fetchall()
events_with_ids = [(event[1], event[0]) for event in events]
return render_template('events.html', events_with_ids=events_with_ids )
@app.route('/event/<id>', methods=['GET', 'POST'])
def event(id):
print(session['mail'])
cursor.execute("SELECT punctaj FROM punctaj WHERE event_id = %s AND username = %s", (id, session['mail']))
punctaj = cursor.fetchone()
print(punctaj)
cursor.execute("SELECT * FROM events WHERE id = %s", (id,))
event = cursor.fetchone()
event_data = {
'id': event[0],
'nume': event[1],
'startdatetime': event[3],
'durata': event[4],
'compiler': event[5],
'subiecte': os.listdir(f"events\\{id}")
}
#sa fie pt profesori if ul ca sa fie else ul pt elevi
if 'logged_in' in session and session['logged_in'] and session['type'] == 'profesor':
return render_template('event.html', event_data=event_data)
else:
return render_template('event_uneditable.html', event_data=event_data, readonly=True, punctaj=punctaj)
@app.route('/event/<int:id>/<path:file_path>')
def download_file(id, file_path):
directory = os.path.join("events", str(id))
return send_from_directory(directory, file_path, as_attachment=True)
@app.route('/event/<int:id>/edit', methods=['POST'])
def edit_event(id):
if 'logged_in' in session and session['logged_in']:
nume = request.form.get('nume')
startdatetime = request.form.get('startdatetime').replace('T', ' ')
durata = request.form.get('durata')
compiler = request.form.get('compiler')
compiler = True if compiler == 'on' else False
query = """
UPDATE events
SET nume = %s, startdatetime = %s, durata = %s, compiler = %s
WHERE id = %s
"""
cursor.execute(query, (nume, startdatetime, durata, compiler, id))
db.commit()
flash('Event updated successfully', 'success')
return redirect(url_for('events'))
else:
return redirect(url_for('login'))
@app.route('/user/<username>', methods=['GET', 'POST'])
def edit_user(username):
if 'logged_in' in session and session['logged_in']:
if request.method == 'POST':
new_username = request.form.get('username')
new_email = request.form.get('email')
new_password = request.form.get('password')
query = """
UPDATE users
SET username = %s, email = %s, password = %s
WHERE username = %s
"""
cursor.execute(query, (new_username, new_email, new_password, username))
db.commit()
flash('User details updated successfully', 'success')
return redirect(url_for('edit_user', username=new_username))
query = "SELECT username, email, password FROM users WHERE username = %s"
cursor.execute(query, (username,))
user = cursor.fetchone()
if not user:
flash('User not found', 'error')
return redirect(url_for('events'))
user_data = {
'username': user[0],
'email': user[1],
'password': user[2]
}
return render_template('user.html', user_data=user_data)
@app.route('/despre', methods=['GET'])
def despre():
return render_template('despre.html')
if __name__ == '__main__':
app.run(host = ip, port=80, debug=True)