-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1482 lines (1248 loc) · 52 KB
/
app.py
File metadata and controls
1482 lines (1248 loc) · 52 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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import mysql.connector
import configparser
from flask import Flask, request, jsonify, render_template, send_file, send_from_directory
from flask_cors import CORS
import mysql.connector
import configparser
import hashlib
import secrets
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import xml.etree.ElementTree as ET
import json
import uuid
import base64
import sys
import uuid
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
import io
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
encryption_key = sys.argv[1]
password = encryption_key
salt = ""
# Modifier la fonction de vérification du hash
def check_password_hash(stored_hash, password_hash):
"""
Check if the provided password hash matches the stored hash with salt.
Args:
stored_hash (str): The stored salted hash in the database
password_hash (str): The SHA256 hash from client side
Returns:
bool: True if the password matches, False otherwise
"""
# Add server-side salt and hash again
salted_hash = hashlib.sha256((password_hash + salt).encode()).hexdigest()
return salted_hash == stored_hash
def pad_binary_data(data, length):
"""
Pads the binary data to the specified length with null bytes.
Args:
data (bytes): The binary data to pad.
length (int): The desired length of the padded data.
Returns:
bytes: The padded binary data.
"""
if len(data) < length:
data += b'\x00' * (length - len(data))
return data
def parse_answers(answers):
"""
Parses the answers if they are in string format.
Args:
answers (str or list): The answers to parse.
Returns:
list: The parsed answers.
"""
if isinstance(answers, str):
try:
return json.loads(answers)
except json.JSONDecodeError:
return []
return answers
# Path to the configuration file
CONFIG_FILE = 'config.ini'
app = Flask(__name__)
CORS(app)
app.config['UPLOAD_FOLDER'] = os.path.join(os.path.dirname(__file__), 'quizFiles')
# Function to read encrypted configuration
def read_encrypted_config(encryption_key):
"""
Reads and decrypts the configuration file.
Args:
encryption_key (str): The key used to decrypt the configuration
Returns:
configparser.ConfigParser: The decrypted configuration
"""
try:
with open(CONFIG_FILE, 'rb') as f:
data = f.read()
# Extract IV and encrypted data
iv = data[:AES.block_size]
encrypted_data = data[AES.block_size:]
# Prepare key for decryption
key_bytes = hashlib.sha256(encryption_key.encode()).digest()[:16]
cipher = AES.new(key_bytes, AES.MODE_CBC, iv)
# Decrypt data
decrypted_data = unpad(cipher.decrypt(encrypted_data), AES.block_size)
# Parse decrypted configuration
config = configparser.ConfigParser()
config.read_string(decrypted_data.decode())
return config
except Exception as e:
print(f"Error reading encrypted configuration: {e}")
return None
# Function to write encrypted configuration
def write_encrypted_config(config, encryption_key):
"""
Encrypts and writes the configuration to file.
Args:
config (configparser.ConfigParser): The configuration to encrypt
encryption_key (str): The key to use for encryption
"""
try:
# Convert config to string
config_string = io.StringIO()
config.write(config_string)
config_content = config_string.getvalue()
config_string.close()
# Prepare encryption
key_bytes = hashlib.sha256(encryption_key.encode()).digest()[:16]
iv = os.urandom(AES.block_size)
cipher = AES.new(key_bytes, AES.MODE_CBC, iv)
# Encrypt the content
from Crypto.Util.Padding import pad
encrypted_data = cipher.encrypt(pad(config_content.encode(), AES.block_size))
# Write to file
with open(CONFIG_FILE, 'wb') as f:
f.write(iv + encrypted_data)
except Exception as e:
print(f"Error writing encrypted configuration: {e}")
# Function to read connection information
def get_mysql_config(encryption_key=None):
"""
Gets MySQL connection information from the encrypted configuration file.
Args:
encryption_key (str, optional): The key to decrypt the configuration
Returns:
dict: MySQL connection parameters
"""
if os.path.exists(CONFIG_FILE) and encryption_key:
config = read_encrypted_config(encryption_key)
if config and 'Database' in config:
return {
'host': config.get('Database', 'host', fallback='127.0.0.1'),
'user': config.get('Database', 'user'),
'password': config.get('Database', 'password'),
'database': config.get('Database', 'database')
}
# Fallback to manual configuration if file doesn't exist or can't be decrypted
host = input("MySQL Host (default: 127.0.0.1): ") or '127.0.0.1'
user = input("MySQL Username: ")
password = input("MySQL Password: ")
database = input("Database Name: ")
# If we have an encryption key, save the new config encrypted
if encryption_key:
config = configparser.ConfigParser()
config.add_section('Database')
config.set('Database', 'host', host)
config.set('Database', 'user', user)
config.set('Database', 'password', password)
config.set('Database', 'database', database)
write_encrypted_config(config, encryption_key)
return {
'host': host,
'user': user,
'password': password,
'database': database
}
# Function to establish a MySQL connection
def get_db_connection():
"""
Establishes a connection to the MySQL database using the configuration file.
Returns:
mysql.connector.connection.MySQLConnection: The MySQL database connection.
"""
config = get_mysql_config(encryption_key)
return mysql.connector.connect(
host=config['host'],
user=config['user'],
password=config['password'],
database=config['database']
)
# Existing code to get MySQL configuration
config = get_mysql_config(encryption_key)
try:
# Connect to the MySQL database
connection = get_db_connection()
cursor = connection.cursor()
# Create tables
cursor.execute("""
CREATE TABLE IF NOT EXISTS accounts (
id_acc INT AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(255),
password_hash VARCHAR(64)
);
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS user_infos (
id_acc INT PRIMARY KEY,
name VARCHAR(255),
academy VARCHAR(255),
FOREIGN KEY (id_acc) REFERENCES accounts(id_acc) ON DELETE CASCADE
);
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS connexions (
id_acc INT PRIMARY KEY,
token BINARY(32) NOT NULL,
FOREIGN KEY (id_acc) REFERENCES accounts(id_acc) ON DELETE CASCADE
);
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS verifications (
id_acc INT PRIMARY KEY,
token BINARY(32) NOT NULL,
type VARCHAR(255) NOT NULL,
FOREIGN KEY (id_acc) REFERENCES accounts(id_acc) ON DELETE CASCADE
);
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS waiting_passwords (
id_acc INT PRIMARY KEY,
password_hash VARCHAR(64) NOT NULL,
FOREIGN KEY (id_acc) REFERENCES accounts(id_acc) ON DELETE CASCADE
);
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS quiz (
id_file INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
id_acc INT,
subject VARCHAR(255),
language VARCHAR(255),
FOREIGN KEY (id_acc) REFERENCES accounts(id_acc) ON DELETE CASCADE
);
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS question_posts (
id_question INT AUTO_INCREMENT PRIMARY KEY,
id_acc INT,
subject VARCHAR(255),
language VARCHAR(255),
FOREIGN KEY (id_acc) REFERENCES accounts(id_acc) ON DELETE CASCADE
);
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS question_contents (
id_question INT PRIMARY KEY,
title VARCHAR(255),
shown_answers TEXT,
correct_answers TEXT,
duration INT,
type VARCHAR(255),
FOREIGN KEY (id_question) REFERENCES question_posts(id_question) ON DELETE CASCADE
);
""")
print("Successfully connected to the MySQL database")
except mysql.connector.Error as err:
print(f"Error: {err}")
def is_hex(s):
"""
Checks if the given string is a valid hexadecimal string.
Args:
s (str): The string to check.
Returns:
bool: True if the string is a valid hexadecimal string, False otherwise.
"""
try:
bytes.fromhex(s)
return True
except ValueError:
return False
def is_valid_token(token):
"""
Checks if the given token is valid by querying the database.
Args:
token (str): The token to check.
Returns:
bool: True if the token is valid, False otherwise.
"""
conn = get_db_connection()
cursor = conn.cursor()
# Retrieving data for verification
cursor.execute("SELECT * FROM connexions")
rows = cursor.fetchall()
# Comparing binary data
cursor.execute("SELECT * FROM connexions WHERE token = %s", (pad_binary_data(bytes.fromhex(token), 32),))
rows = cursor.fetchall()
cursor.close()
conn.close()
return len(rows) > 0
@app.route('/quiz', methods=['GET'])
def get_quiz():
"""
Retrieves all quizzes from the database based on provided parameters.
Returns:
Response: A JSON response containing the quizzes or an error message.
"""
token = request.args.get('token')
params = request.args.to_dict(flat=False)
params.pop('token', None)
if not token:
return jsonify({'error': 'Invalid data structure'}), 400
if not isinstance(token, str):
return jsonify({'error': 'Invalid data types'}), 400
if not is_hex(token):
return jsonify({'error': 'Token not hexadecimal'}), 401
if not is_valid_token(token):
return jsonify({'error': 'Invalid token'}), 401
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
# Build the SQL query dynamically based on the provided parameters
query = """
SELECT q.*, ui.name AS username, ui.academy AS user_academy
FROM quiz q
JOIN user_infos ui ON q.id_acc = ui.id_acc
WHERE 1=1
"""
query_params = []
for key, value in params.items():
if value:
if key == "id_acc":
value = [v for v in value if v.isdigit()]
if value != []:
query += f" AND q.id_acc = %s"
query_params.append(int(value[0]))
elif key == "id_question":
value = [v for v in value if v.isdigit()]
if value != []:
query += f" AND id_question = %s"
query_params.append(int(value[0]))
else:
query += f" AND {key} LIKE %s"
if value != []:
query_params.append(f"%{value[0]}%")
try:
cursor.execute(query, query_params)
except mysql.connector.Error as err:
return jsonify({'error': f"{err}"}), 500
rows = cursor.fetchall()
cursor.close()
conn.close()
return jsonify(rows), 200
@app.route('/questions', methods=['GET'])
def get_questions():
"""
Retrieves all questions from the database.
Returns:
Response: A JSON response containing the questions or an error message.
"""
token = request.args.get('token')
params = request.args.to_dict(flat=False)
params.pop('token', None)
if not token:
return jsonify({'error': 'Invalid data structure'}), 400
if not isinstance(token, str):
return jsonify({'error': 'Invalid data types'}), 400
if not is_hex(token):
return jsonify({'error': 'Token not hexadecimal'}), 401
if not is_valid_token(token):
return jsonify({'error': 'Invalid token'}), 401
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
# Build the SQL query dynamically based on the provided parameters
query = """
SELECT qp.*, qc.title, qc.correct_answers, qc.shown_answers, qc.duration, qc.type, ui.name AS username, ui.academy AS user_academy
FROM question_posts qp
JOIN question_contents qc ON qp.id_question = qc.id_question
JOIN user_infos ui ON qp.id_acc = ui.id_acc
WHERE 1=1
"""
query_params = []
for key, value in params.items():
if value:
if key in ["id_question", "id_acc"]:
value = [v for v in value if v.isdigit()]
if value != []:
query += f" AND qp.{key} = %s"
query_params.append(int(value[0]))
else:
query += f" AND {key} LIKE %s"
if value != []:
query_params.append(f"%{value[0]}%")
try:
cursor.execute(query, query_params)
except mysql.connector.Error as err:
return jsonify({'error': f"{err}"}), 500
except:
raise RuntimeError("Curious error")
rows = cursor.fetchall()
for row in rows:
if 'shown_answers' in row:
row['shown_answers'] = parse_answers(row['shown_answers'])
if 'correct_answers' in row:
row['correct_answers'] = parse_answers(row['correct_answers'])
cursor.close()
conn.close()
return jsonify(rows), 200
@app.route('/question-content', methods=['GET'])
def get_question_content():
"""
Retrieves the content of a specific question from the database.
Returns:
Response: A JSON response containing the question content or an error message.
"""
token = request.args.get('token')
id_question = request.args.get('id_question')
if not token:
return jsonify({'error': 'Invalid data structure'}), 400
if not isinstance(token, str) or not id_question.isdigit():
return jsonify({'error': 'Invalid data types'}), 400
if not is_hex(token):
return jsonify({'error': 'Token not hexadecimal'}), 401
if not is_valid_token(token):
return jsonify({'error': 'Invalid token'}), 401
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
cursor.execute("SELECT * FROM question_contents WHERE id_question = %s", (id_question,))
rows = cursor.fetchall()
for row in rows:
row['shown_answers'] = parse_answers(row['shown_answers'])
row['correct_answers'] = parse_answers(row['correct_answers'])
cursor.close()
conn.close()
return jsonify(rows), 200
@app.route('/myposts', methods=['GET'])
def get_myposts():
"""
Retrieves all posts by the user based on the provided token.
Returns:
Response: A JSON response containing the posts or an error message.
"""
token = request.args.get('token')
if not token:
return jsonify({'error': 'Invalid data structure'}), 400
if not isinstance(token, str):
return jsonify({'error': 'Invalid data type for token'}), 400
if not is_hex(token):
return jsonify({'error': 'Token not hexadecimal'}), 401
if not is_valid_token(token):
return jsonify({'error': 'Invalid token'}), 401
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
cursor.execute("SELECT qp.*, qc.* FROM question_posts qp JOIN question_contents qc ON qp.id_question = qc.id_question WHERE id_acc IN (SELECT id_acc FROM connexions WHERE token = %s)", (pad_binary_data(bytes.fromhex(token), 32),))
questions = cursor.fetchall()
cursor.execute("SELECT * FROM quiz WHERE id_acc IN (SELECT id_acc FROM connexions WHERE token = %s)", (pad_binary_data(bytes.fromhex(token), 32),))
quizzes = cursor.fetchall()
for question in questions:
question['shown_answers'] = parse_answers(question['shown_answers'])
question['correct_answers'] = parse_answers(question['correct_answers'])
cursor.close()
conn.close()
return jsonify({'questions': questions, 'quizzes': quizzes}), 200
def verify_xml_structure(xml_file) -> bool:
try:
tree = ET.parse(xml_file)
root = tree.getroot()
if root.tag != 'quiz':
return False
questions_sections = root.findall('questions')
if not questions_sections:
return False
for questions in questions_sections:
question_list = questions.findall('question')
for question in question_list:
if 'type' not in question.attrib or 'duration' not in question.attrib:
return False
if question.find('title') is None or \
question.find('shown_answers') is None or \
question.find('correct_answers') is None:
return False
return True
except ET.ParseError:
print('ET.ParseError')
return False
def get_quiz_subject_and_language(xml_file):
try:
tree = ET.parse(xml_file)
root = tree.getroot()
subject = root.find('subject').text
language = root.find('language').text
return (subject, language)
except:
return (None, None)
@app.route('/quiz', methods=['POST'])
def post_quiz():
"""
Uploads a new quiz file and saves its information to the database.
Returns:
Response: A JSON response indicating success or an error message.
"""
token = request.form.get('token')
filename = request.form.get('filename')
file = request.files.get('file')
if not token or not filename or not file:
return jsonify({'error': 'Invalid data structure'}), 400
if not isinstance(token, str) or not isinstance(filename, str):
return jsonify({'error': 'Invalid data types'}), 400
if not is_hex(token):
return jsonify({'error': 'Token not hexadecimal'}), 401
if not is_valid_token(token):
return jsonify({'error': 'Invalid token'}), 401
conn = get_db_connection()
cursor = conn.cursor()
# Save the file
cursor.execute("SELECT MAX(id_file) FROM quiz")
max_id_file = cursor.fetchone()[0] or 0
file_path = os.path.join(app.config['UPLOAD_FOLDER'], str(max_id_file + 1))
file.save(file_path)
conn.commit()
cursor.close()
conn.close()
# Verify the XML structure and get the quiz subject and language
with open(file_path, 'r') as f:
if not verify_xml_structure(f):
return jsonify({'error': 'Invalid XML structure'}), 400
with open(file_path, 'r') as f:
subject, language = get_quiz_subject_and_language(f)
if subject is None or language is None:
os.remove(file_path)
return jsonify({'error': 'Missing subject or language'}), 400
conn = get_db_connection()
cursor = conn.cursor()
# Save file data to the database
cursor.execute("INSERT INTO quiz (id_file, name, id_acc, subject, language) VALUES (%s, %s, (SELECT id_acc FROM connexions WHERE token = %s), %s, %s)", (max_id_file + 1, filename, pad_binary_data(bytes.fromhex(token), 32), subject, language))
conn.commit()
cursor.close()
conn.close()
return jsonify({'message': 'Quiz uploaded successfully'}), 200
@app.route('/question', methods=['POST'])
def post_question():
"""
Uploads a new question and saves its information to the database.
Returns:
Response: A JSON response indicating success or an error message.
"""
data = request.get_json()
token = data.get('token')
question = data.get('question')
if not token or not question:
return jsonify({'error': 'Invalid data structure'}), 400
if not isinstance(token, str):
return jsonify({'error': 'Invalid data type for token'}), 400
if not isinstance(question, dict):
return jsonify({'error': 'Invalid data type for question'}), 400
# Convert shown_answers and correct_answers to lists
shown_answers = parse_answers(question['shown_answers'])
correct_answers = parse_answers(question['correct_answers'])
if isinstance(shown_answers, dict) and "answer" in shown_answers:
shown_answers = shown_answers["answer"]
if isinstance(correct_answers, dict) and "answer" in correct_answers:
correct_answers = correct_answers["answer"]
question['shown_answers'] = str(shown_answers)
question['correct_answers'] = str(correct_answers)
required_fields = ['subject', 'language', 'title', 'shown_answers', 'correct_answers', 'duration', 'type']
for field in required_fields:
if field not in question:
return jsonify({'error': f'Missing field: {field}'}), 400
if field == 'duration' and not isinstance(question[field], int):
return jsonify({'error': f'Invalid data type for {field}'}), 400
elif field != 'duration' and not isinstance(question[field], str):
return jsonify({'error': f'Invalid data type for {field}'}), 400
if not is_hex(token):
return jsonify({'error': 'Token not hexadecimal'}), 401
if not is_valid_token(token):
return jsonify({'error': 'Invalid token'}), 401
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute("INSERT INTO question_posts (id_acc, subject, language) VALUES ((SELECT id_acc FROM connexions WHERE token = %s), %s, %s)", (pad_binary_data(bytes.fromhex(token), 32), question['subject'], question['language'],))
cursor.execute("INSERT INTO question_contents (id_question, title, shown_answers, correct_answers, duration, type) VALUES (LAST_INSERT_ID(), %s, %s, %s, %s, %s)", (question['title'], json.dumps(shown_answers), json.dumps(correct_answers), question['duration'], question['type'],))
conn.commit()
cursor.close()
conn.close()
return jsonify({'message': 'Question uploaded successfully'}), 200
@app.route('/login', methods=['POST'])
def post_login():
"""Handles user login with token management"""
data = request.get_json()
email = data.get('email')
password_hash = data.get('password_hash')
if not email or not password_hash:
return jsonify({'error': 'Invalid data structure'}), 400
conn = get_db_connection()
cursor = conn.cursor()
# Verify credentials
cursor.execute("SELECT * FROM accounts WHERE email = %s", (email,))
account = cursor.fetchone()
if not account or not check_password_hash(account[2], password_hash):
return jsonify({'error': 'Invalid email or password'}), 401
# Generate new token
new_token = secrets.token_bytes(32)
# Update or insert token
cursor.execute("SELECT token FROM connexions WHERE id_acc = %s", (account[0],))
existing_token = cursor.fetchone()
if existing_token:
# Update existing token entry
cursor.execute("UPDATE connexions SET token = %s WHERE id_acc = %s",
(new_token, account[0]))
else:
# Create new token entry
cursor.execute("INSERT INTO connexions (id_acc, token) VALUES (%s, %s)",
(account[0], new_token))
conn.commit()
cursor.close()
conn.close()
return jsonify({'token': new_token.hex()}), 200
# Remplacer la fonction get_email_config existante par celle-ci:
def get_email_config(encryption_key=None):
"""
Gets email configuration from the encrypted configuration file.
Args:
encryption_key (str, optional): The key to decrypt the configuration
Returns:
dict: Email configuration parameters
"""
if os.path.exists(CONFIG_FILE) and encryption_key:
config = read_encrypted_config(encryption_key)
if config and 'Email' in config and 'SMTP' in config:
return {
'sender': config.get('Email', 'email'),
'password': config.get('Email', 'password'),
'smtp_server': config.get('SMTP', 'server'),
'smtp_port': config.getint('SMTP', 'port')
}
# Fallback to manual configuration if file doesn't exist or can't be decrypted
email = input("Email: ")
password = input("Email Password: ")
smtp_server = input("SMTP Server: ")
smtp_port = int(input("SMTP Port: "))
# If we have an encryption key, save the new config encrypted
if encryption_key:
config = configparser.ConfigParser()
if os.path.exists(CONFIG_FILE):
config = read_encrypted_config(encryption_key) or config
if 'Email' not in config:
config.add_section('Email')
if 'SMTP' not in config:
config.add_section('SMTP')
config.set('Email', 'email', email)
config.set('Email', 'password', password)
config.set('SMTP', 'server', smtp_server)
config.set('SMTP', 'port', str(smtp_port))
write_encrypted_config(config, encryption_key)
return {
'sender': email,
'password': password,
'smtp_server': smtp_server,
'smtp_port': smtp_port
}
# Modifier l'initialisation email_config
# Remplacer cette ligne:
# email_config = get_email_config()
# Par celle-ci:
email_config = get_email_config(encryption_key)
def send_email(subject, message, recipient):
sender = email_config['sender']
password = email_config['password']
smtp_server = email_config['smtp_server']
smtp_port = email_config['smtp_port']
# SMTP server configuration
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls() # Pour activer TLS
# Login to the server
server.login(sender, password)
# Create the email
email = MIMEMultipart()
email["From"] = sender
email["To"] = recipient
email["Subject"] = subject
# Attach the HTML message body
email.attach(MIMEText(message, "html"))
# Send the email
server.send_message(email)
# Disconnect
server.quit()
def is_authorized_email(email):
with open('authorized_emails.json', 'r') as f:
authorized_emails = json.load(f)
for e in authorized_emails:
if e in email:
return True
return False
@app.route('/signup', methods=['POST'])
def post_signup():
"""
Registers a new user by saving their email and password hash to the database.
Returns:
Response: A JSON response indicating success or an error message.
"""
data = request.get_json()
email = data.get('email')
password_hash = data.get('password_hash') # Hash from client
language = data.get('language')
if password_hash == "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855":
return jsonify({'error': "Password can't be empty"}), 400
if not email or not password_hash:
return jsonify({'error': 'Invalid data structure'}), 400
if not isinstance(email, str):
return jsonify({'error': 'Invalid data type for email'}), 400
if not is_authorized_email(email):
return jsonify({'error': 'Unauthorized email'}), 401
if not isinstance(password_hash, str):
return jsonify({'error': 'Invalid data type for password_hash'}), 400
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute("SELECT * FROM accounts WHERE email = %s", (email,))
rows = cursor.fetchall()
if len(rows) > 0:
return jsonify({'error': 'Email already in use'}), 409
# Add salt and hash again for storage
salted_hash = hashlib.sha256((password_hash + salt).encode()).hexdigest()
cursor.execute("INSERT INTO accounts (email, password_hash) VALUES (%s, %s)",
(email, salted_hash))
cursor.execute("INSERT INTO user_infos (id_acc, name, academy) VALUES ((SELECT id_acc FROM accounts WHERE email = %s), %s, %s)",
(email, "", ""))
token = secrets.token_bytes(32)
cursor.execute("INSERT INTO verifications (id_acc, token, type) VALUES ((SELECT id_acc FROM accounts WHERE email = %s), %s, %s)",
(email, token, 'signup'))
local_glossary = {
"en": {
"thank_you": "Thank you for signing up!",
"excited": "We are excited to have you on board.",
"verify_prompt": "Click the button below to verify your account and get started:",
"verify_button": "Verify Your Account",
"footer_note": "If you did not sign up for this account, please ignore this email.",
"header_title": "You're almost a member of the kahain-db!",
"email_subject": "Account Verification"
},
"fr": {
"thank_you": "Merci de vous être inscrit!",
"excited": "Nous sommes ravis de vous avoir parmi nous.",
"verify_prompt": "Cliquez sur le bouton ci-dessous pour vérifier votre compte et commencer :",
"verify_button": "Vérifiez Votre Compte",
"footer_note": "Si vous ne vous êtes pas inscrit pour ce compte, veuillez ignorer cet email.",
"header_title": "Vous êtes presque membre de la kahain-db!",
"email_subject": "Vérification du Compte"
},
"es": {
"thank_you": "¡Gracias por registrarte!",
"excited": "Estamos emocionados de tenerte a bordo.",
"verify_prompt": "Haz clic en el botón de abajo para verificar tu cuenta y comenzar:",
"verify_button": "Verifica Tu Cuenta",
"footer_note": "Si no te registraste para esta cuenta, por favor ignora este correo electrónico.",
"header_title": "¡Casi eres miembro de la kahain-db!",
"email_subject": "Verificación de Cuenta"
},
"it": {
"thank_you": "Grazie per esserti iscritto!",
"excited": "Siamo entusiasti di averti con noi.",
"verify_prompt": "Clicca sul pulsante sottostante per verificare il tuo account e iniziare:",
"verify_button": "Verifica il Tuo Account",
"footer_note": "Se non ti sei registrato per questo account, ignora questa email.",
"header_title": "Sei quasi un membro di kahain-db!",
"email_subject": "Verifica Account"
},
"de": {
"thank_you": "Vielen Dank für Ihre Anmeldung!",
"excited": "Wir freuen uns, Sie an Bord zu haben.",
"verify_prompt": "Klicken Sie auf die Schaltfläche unten, um Ihr Konto zu verifizieren und zu starten:",
"verify_button": "Verifizieren Sie Ihr Konto",
"footer_note": "Wenn Sie sich nicht für dieses Konto registriert haben, ignorieren Sie bitte diese E-Mail.",
"header_title": "Sie sind fast Mitglied der kahain-db!",
"email_subject": "Kontoverifizierung"
}
}
html_message = f"""
<html>
<head>
<style>
body {{
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
}}
.container {{
width: 100%;
background-color: #ffffff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}}
.header {{
background-color: #424242;
color: white;
text-align: center;
padding-top: 10px;
padding-bottom: 10px;
}}
.content {{
padding: 20px;
}}
.content h1 {{
color: #333333;
}}
.content p {{
color: #666666;
line-height: 1.5;
}}
.button {{
display: inline-block;
padding: 10px 20px;
margin: 20px 0;
background-color: #424242;
color: white;
text-decoration: none;
border-radius: 5px;
}}
.footer {{
text-align: center;
padding: 10px;
color: #999999;
font-size: 12px;
}}
img {{
width: 200px;
height: 200px;
}}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>{local_glossary.get(language, local_glossary["en"])["header_title"]}</h1>
</div>
<div class="content">
<h1>{local_glossary.get(language, local_glossary["en"])["thank_you"]}</h1>
<p>{local_glossary.get(language, local_glossary["en"])["excited"]}</p>
<p>{local_glossary.get(language, local_glossary["en"])["verify_prompt"]}</p>
<a href="http://127.0.0.1:5000/verif?token={token.hex()}&language={language}" class="button" style="color:white;">{local_glossary.get(language, local_glossary["en"])["verify_button"]}</a>
</div>
<div class="footer">
<p>{local_glossary.get(language, local_glossary["en"])["footer_note"]}</p>
</div>
</div>
</body>
</html>
"""
send_email(local_glossary.get(language, local_glossary["en"])["email_subject"], html_message, email)
conn.commit()
cursor.close()
conn.close()
return jsonify({'message': 'Email sent successfully'}), 200
@app.route('/reset-password', methods=['POST'])