-
Notifications
You must be signed in to change notification settings - Fork 228
Expand file tree
/
Copy pathapp.py
More file actions
1672 lines (1351 loc) · 58.8 KB
/
Copy pathapp.py
File metadata and controls
1672 lines (1351 loc) · 58.8 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
from http import HTTPStatus
from flask import Flask, render_template, request, redirect, url_for, session, jsonify, flash
import sqlite3
import os
import secrets
from werkzeug.utils import secure_filename
from werkzeug.security import generate_password_hash, check_password_hash
import datetime
from datetime import timedelta
from services.certificate_service import process_certificate
from flask_wtf import CSRFProtect
try:
from dotenv import load_dotenv
load_dotenv()
except ImportError:
pass
app = Flask(__name__)
app.secret_key = os.environ.get("SECRET_KEY", secrets.token_hex(16))
app.permanent_session_lifetime = timedelta(days=30)
# Session security configuration
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(hours=2)
app.config['SESSION_COOKIE_SECURE'] = os.environ.get('FLASK_ENV') == 'production'
@app.before_request
def make_session_permanent():
session.permanent = True
# csrf = CSRFProtect(app)
# ✅ Portable DB path (works on Windows/Linux/Vercel)
DB_PATH = os.path.join(os.path.dirname(__file__), "ams.db")
# Define upload folder path for certificates
UPLOAD_FOLDER = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static", "uploads")
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
def ensure_achievements_schema(connection):
cursor = connection.cursor()
cursor.execute("PRAGMA table_info(achievements)")
columns = cursor.fetchall()
column_names = [c[1] for c in columns]
# Add teacher_id if missing
if "teacher_id" not in column_names:
cursor.execute("ALTER TABLE achievements ADD COLUMN teacher_id TEXT DEFAULT 'unknown'")
# Add created_at if missing
if "created_at" not in column_names:
cursor.execute("ALTER TABLE achievements ADD COLUMN created_at TEXT")
cursor.execute("UPDATE achievements SET created_at = CURRENT_TIMESTAMP WHERE created_at IS NULL")
# Add certificate_hash if missing
if "certificate_hash" not in column_names:
cursor.execute("ALTER TABLE achievements ADD COLUMN certificate_hash TEXT")
# This works even if the column was added via ALTER TABLE earlier
cursor.execute("CREATE UNIQUE INDEX IF NOT EXISTS idx_cert_hash ON achievements (certificate_hash)")
connection.commit()
def add_profile_picture_column():
"""
Add profile_picture column to student table if it doesn't exist
"""
try:
connection = sqlite3.connect(DB_PATH)
cursor = connection.cursor()
# Check if profile_picture column exists in student table
cursor.execute("PRAGMA table_info(student)")
columns = cursor.fetchall()
column_names = [column[1] for column in columns]
if "profile_picture" not in column_names:
print("Adding profile_picture column to student table...")
cursor.execute(
"ALTER TABLE student ADD COLUMN profile_picture TEXT"
)
connection.commit()
print("profile_picture column added successfully!")
else:
print("profile_picture column already exists in student table")
connection.close()
except sqlite3.Error as e:
print(f"Error adding profile_picture column: {e}")
# Define a function to check allowed file extensions
def allowed_file(filename):
ALLOWED_EXTENSIONS = {"pdf", "png", "jpg", "jpeg"}
return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
# Initialize database on startup
# Initialize database on startup
def init_db():
connection = sqlite3.connect(DB_PATH)
cursor = connection.cursor()
# Student table
cursor.execute("""
CREATE TABLE IF NOT EXISTS student (
student_name TEXT NOT NULL,
student_id TEXT PRIMARY KEY,
email TEXT UNIQUE NOT NULL,
phone_number TEXT,
password TEXT NOT NULL,
student_gender TEXT,
student_dept TEXT,
is_approved BOOLEAN DEFAULT 1,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
# Teacher table
cursor.execute("""
CREATE TABLE IF NOT EXISTS teacher (
teacher_name TEXT NOT NULL,
teacher_id TEXT PRIMARY KEY,
email TEXT UNIQUE NOT NULL,
phone_number TEXT,
password TEXT NOT NULL,
teacher_gender TEXT,
teacher_dept TEXT,
is_approved BOOLEAN DEFAULT 1,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
# Admin table
cursor.execute("""
CREATE TABLE IF NOT EXISTS admin (
admin_name TEXT NOT NULL,
admin_id TEXT PRIMARY KEY,
email TEXT UNIQUE NOT NULL,
password TEXT NOT NULL,
is_superuser BOOLEAN DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
# Departments table for admin management
cursor.execute("""
CREATE TABLE IF NOT EXISTS departments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
dept_code TEXT UNIQUE NOT NULL,
dept_name TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
# Achievement categories table
cursor.execute("""
CREATE TABLE IF NOT EXISTS achievement_categories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
category_code TEXT UNIQUE NOT NULL,
category_name TEXT NOT NULL,
description TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
# Achievements table
cursor.execute("""
CREATE TABLE IF NOT EXISTS achievements (
id INTEGER PRIMARY KEY AUTOINCREMENT,
teacher_id TEXT NOT NULL,
student_id TEXT NOT NULL,
achievement_type TEXT NOT NULL,
event_name TEXT NOT NULL,
achievement_date DATE NOT NULL,
organizer TEXT NOT NULL,
position TEXT NOT NULL,
achievement_description TEXT,
certificate_path TEXT,
symposium_theme TEXT,
programming_language TEXT,
coding_platform TEXT,
paper_title TEXT,
journal_name TEXT,
conference_level TEXT,
conference_role TEXT,
team_size INTEGER,
project_title TEXT,
database_type TEXT,
difficulty_level TEXT,
other_description TEXT,
certificate_hash TEXT UNIQUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (student_id) REFERENCES student(student_id),
FOREIGN KEY (teacher_id) REFERENCES teacher(teacher_id)
)
""")
# Feedback table
cursor.execute("""
CREATE TABLE IF NOT EXISTS feedback (
id INTEGER PRIMARY KEY AUTOINCREMENT,
role TEXT NOT NULL,
name TEXT,
email TEXT,
feedback_type TEXT NOT NULL,
message TEXT NOT NULL,
rating INTEGER,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
# Insert default super admin if not exists
cursor.execute("SELECT COUNT(*) FROM admin WHERE admin_id = 'superadmin'")
if cursor.fetchone()[0] == 0:
default_password = generate_password_hash("admin123")
cursor.execute("""
INSERT INTO admin (admin_name, admin_id, email, password, is_superuser)
VALUES (?, ?, ?, ?, ?)
""", ("Super Administrator", "superadmin", "admin@system.com", default_password, 1))
# Insert default departments if not exists
default_departments = [
("CSE", "Computer Science and Engineering"),
("ECE", "Electronics and Communication Engineering"),
("EEE", "Electrical and Electronics Engineering"),
("MECH", "Mechanical Engineering"),
("CIVIL", "Civil Engineering"),
("IT", "Information Technology")
]
for dept_code, dept_name in default_departments:
cursor.execute("SELECT COUNT(*) FROM departments WHERE dept_code = ?", (dept_code,))
if cursor.fetchone()[0] == 0:
cursor.execute("INSERT INTO departments (dept_code, dept_name) VALUES (?, ?)", (dept_code, dept_name))
# Insert default achievement categories if not exists
default_categories = [
("CODING", "Coding Competition", "Programming and coding competitions"),
("HACKATHON", "Hackathon", "Hackathon events"),
("PAPER", "Paper Presentation", "Research paper presentations"),
("PROJECT", "Project Exhibition", "Project exhibitions and demos"),
("SPORTS", "Sports Achievement", "Sports and athletic achievements"),
("CULTURAL", "Cultural Event", "Cultural and arts events"),
("INTERNSHIP", "Internship", "Internship completions"),
("CERTIFICATION", "Certification", "Professional certifications")
]
for cat_code, cat_name, description in default_categories:
cursor.execute("SELECT COUNT(*) FROM achievement_categories WHERE category_code = ?", (cat_code,))
if cursor.fetchone()[0] == 0:
cursor.execute("INSERT INTO achievement_categories (category_code, category_name, description) VALUES (?, ?, ?)",
(cat_code, cat_name, description))
connection.commit()
connection.close()
print("Database initialized successfully")
# Call initialization function
init_db()
# Permission decorators for RBAC
def login_required(f):
"""Decorator to check if user is logged in"""
from functools import wraps
@wraps(f)
def decorated_function(*args, **kwargs):
if not session.get("logged_in"):
return redirect(url_for("home"))
return f(*args, **kwargs)
return decorated_function
def admin_required(f):
"""Decorator to check if user is admin"""
from functools import wraps
@wraps(f)
def decorated_function(*args, **kwargs):
if not session.get("logged_in") or not session.get("admin_id"):
return redirect(url_for("home"))
return f(*args, **kwargs)
return decorated_function
def superadmin_required(f):
"""Decorator to check if user is super admin"""
from functools import wraps
@wraps(f)
def decorated_function(*args, **kwargs):
if not session.get("logged_in") or not session.get("admin_id") or not session.get("is_superuser"):
return redirect(url_for("admin_dashboard"))
return f(*args, **kwargs)
return decorated_function
def student_required(f):
"""Decorator to check if user is student"""
from functools import wraps
@wraps(f)
def decorated_function(*args, **kwargs):
if not session.get("logged_in") or not session.get("student_id"):
return redirect(url_for("student"))
return f(*args, **kwargs)
return decorated_function
def teacher_required(f):
"""Decorator to check if user is teacher"""
from functools import wraps
@wraps(f)
def decorated_function(*args, **kwargs):
if not session.get("logged_in") or not session.get("teacher_id"):
return redirect(url_for("teacher"))
return f(*args, **kwargs)
return decorated_function
@app.context_processor
def inject_csrf():
"""Provide csrf_token() for templates that expect it (e.g. tests)."""
return {"csrf_token": lambda: ""}
# Permission decorators for RBAC
def login_required(f):
"""Decorator to check if user is logged in"""
from functools import wraps
@wraps(f)
def decorated_function(*args, **kwargs):
if not session.get("logged_in"):
return redirect(url_for("home"))
return f(*args, **kwargs)
return decorated_function
def admin_required(f):
"""Decorator to check if user is admin"""
from functools import wraps
@wraps(f)
def decorated_function(*args, **kwargs):
if not session.get("logged_in") or not session.get("admin_id"):
return redirect(url_for("home"))
return f(*args, **kwargs)
return decorated_function
def superadmin_required(f):
"""Decorator to check if user is super admin"""
from functools import wraps
@wraps(f)
def decorated_function(*args, **kwargs):
if not session.get("logged_in") or not session.get("admin_id") or not session.get("is_superuser"):
return redirect(url_for("admin_dashboard"))
return f(*args, **kwargs)
return decorated_function
def student_required(f):
"""Decorator to check if user is student"""
from functools import wraps
@wraps(f)
def decorated_function(*args, **kwargs):
if not session.get("logged_in") or not session.get("student_id"):
return redirect(url_for("student"))
return f(*args, **kwargs)
return decorated_function
def teacher_required(f):
"""Decorator to check if user is teacher"""
from functools import wraps
@wraps(f)
def decorated_function(*args, **kwargs):
if not session.get("logged_in") or not session.get("teacher_id"):
return redirect(url_for("teacher"))
return f(*args, **kwargs)
return decorated_function
# Custom 404 Error Handler
@app.errorhandler(HTTPStatus.NOT_FOUND)
def page_not_found(error):
"""Handle 404 errors with custom template"""
return render_template('404.html'), HTTPStatus.NOT_FOUND
@app.route("/")
def home():
return render_template("home.html")
@app.route("/terms")
def terms():
return render_template("terms.html")
@app.route("/privacy-policy")
def privacy_policy():
return render_template("privacy-policy.html")
@app.route("/teacher-achievements", endpoint="teacher-achievements")
def teacher_achievements():
return render_template("teacher_achievements_2.html")
@app.route("/submit_achievements", methods=["GET", "POST"])
@teacher_required
def submit_achievements():
teacher_id = session.get("teacher_id")
if request.method == "POST":
try:
import hashlib
# Extract standard form data
student_id = request.form.get("student_id")
achievement_type = request.form.get("achievement_type")
event_name = request.form.get("event_name")
achievement_date = request.form.get("achievement_date")
organizer = request.form.get("organizer")
position = request.form.get("position")
achievement_description = request.form.get("achievement_description")
# Handle numeric fields
team_size = request.form.get("team_size")
team_size = int(team_size) if team_size and team_size.strip() else None
# Optional detail fields
details = {
"symposium_theme": request.form.get("symposium_theme"),
"programming_language": request.form.get("programming_language"),
"coding_platform": request.form.get("coding_platform"),
"paper_title": request.form.get("paper_title"),
"journal_name": request.form.get("journal_name"),
"conference_level": request.form.get("conference_level"),
"conference_role": request.form.get("conference_role"),
"project_title": request.form.get("project_title"),
"database_type": request.form.get("database_type"),
"difficulty_level": request.form.get("difficulty_level"),
"other_description": request.form.get("other_description")
}
certificate_path = None
certificate_hash = None
# -----------------------------
# FILE & HASH HANDLING
# -----------------------------
if "certificate" in request.files:
file = request.files["certificate"]
if file and file.filename != "":
if not allowed_file(file.filename):
return render_template("submit_achievements.html", error="Invalid file type.")
# 1. Read bytes for hashing
file.seek(0)
file_bytes = file.read()
certificate_hash = hashlib.sha256(file_bytes).hexdigest()
file.seek(0) # 2. Reset pointer so we can save it later
# 3. DB Check for existing Hash
with sqlite3.connect(DB_PATH) as check_conn:
cursor = check_conn.cursor()
cursor.execute("SELECT id FROM achievements WHERE certificate_hash = ?", (certificate_hash,))
if cursor.fetchone():
return render_template("submit_achievements.html",
error="Duplicate detected! This certificate is already registered.")
# 4. Save File if check passed
timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
secure_name = f"{timestamp}_{secure_filename(file.filename)}"
file_path = os.path.join(UPLOAD_FOLDER, secure_name)
file.save(file_path)
certificate_path = f"uploads/{secure_name}"
# 5. Optional OCR
try:
res = process_certificate(file_path)
parsed = res.get("parsed_data", {})
event_name = event_name or parsed.get("event_name")
achievement_date = achievement_date or parsed.get("achievement_date")
except Exception as ocr_err:
print(f"OCR failed: {ocr_err}")
# -----------------------------
# DATABASE INSERT
# -----------------------------
with sqlite3.connect(DB_PATH) as connection:
cursor = connection.cursor()
ensure_achievements_schema(connection)
# Validate Student
cursor.execute("SELECT student_name FROM student WHERE student_id = ?", (student_id,))
student_row = cursor.fetchone()
if not student_row:
return render_template("submit_achievements.html", error="Student ID not found.")
student_name = student_row[0]
query = """
INSERT INTO achievements (
student_id, teacher_id, achievement_type, event_name, achievement_date,
organizer, position, achievement_description, certificate_path,
symposium_theme, programming_language, coding_platform, paper_title,
journal_name, conference_level, conference_role, team_size,
project_title, database_type, difficulty_level, other_description,
certificate_hash
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
"""
params = (
student_id, teacher_id, achievement_type, event_name, achievement_date,
organizer, position, achievement_description, certificate_path,
details["symposium_theme"], details["programming_language"],
details["coding_platform"], details["paper_title"], details["journal_name"],
details["conference_level"], details["conference_role"], team_size,
details["project_title"], details["database_type"],
details["difficulty_level"], details["other_description"], certificate_hash
)
cursor.execute(query, params)
connection.commit()
return render_template("submit_achievements.html",
success=f"Success! Achievement for {student_name} recorded.")
except sqlite3.IntegrityError:
return render_template("submit_achievements.html", error="Database error: Duplicate certificate hash.")
except Exception as e:
return render_template("submit_achievements.html", error=f"Error: {str(e)}")
return render_template("submit_achievements.html")
@app.route("/student-achievements", endpoint="student-achievements")
@student_required
def student_achievements():
student_data = {
"id": session.get("student_id"),
"name": session.get("student_name"),
"dept": session.get("student_dept"),
}
return render_template("student_achievements_1.html", student=student_data)
@app.route("/student-dashboard", endpoint="student-dashboard")
@student_required
def student_dashboard():
student_data = {
"id": session.get("student_id"),
"name": session.get("student_name"),
"dept": session.get("student_dept"),
}
return render_template("student_dashboard.html", student=student_data)
@app.route("/student/profile", endpoint="student-profile")
@student_required
def student_profile():
# Get student ID from session
student_id = session.get('student_id')
# Connect to database
connection = sqlite3.connect(DB_PATH)
connection.row_factory = sqlite3.Row
cursor = connection.cursor()
# Get student data from database
cursor.execute("SELECT * FROM student WHERE student_id = ?", (student_id,))
student = cursor.fetchone()
connection.close()
if not student:
# Student not found in database (should not happen)
session.clear()
return redirect(url_for('student'))
# Convert row to dict for easier template access
student_dict = dict(student)
# Build profile picture URL if exists
profile_picture_url = None
if student_dict.get('profile_picture'):
profile_picture_url = url_for('static', filename=student_dict['profile_picture'])
return render_template("student_profile.html",
student=student_dict,
profile_picture_url=profile_picture_url)
@app.route("/student/profile/edit", endpoint="student_profile_edit", methods=["POST"])
@student_required
def student_profile_edit():
student_id = session.get('student_id')
try:
# Get form data
student_name = request.form.get('student_name')
email = request.form.get('email')
phone_number = request.form.get('phone_number')
student_gender = request.form.get('student_gender')
student_dept = request.form.get('student_dept')
current_password = request.form.get('current_password')
new_password = request.form.get('new_password')
confirm_password = request.form.get('confirm_password')
# Connect to database
connection = sqlite3.connect(DB_PATH)
cursor = connection.cursor()
# Get current student data
cursor.execute("SELECT * FROM student WHERE student_id = ?", (student_id,))
student = cursor.fetchone()
if not student:
connection.close()
session.clear()
return redirect(url_for('student'))
# Handle password change if requested
if current_password and new_password and confirm_password:
# Verify current password
if not check_password_hash(student[4], current_password):
connection.close()
flash('Current password is incorrect', 'danger')
return redirect(url_for('student-profile'))
# Verify new passwords match
if new_password != confirm_password:
connection.close()
flash('New passwords do not match', 'danger')
return redirect(url_for('student-profile'))
# Verify password length
if len(new_password) < 6:
connection.close()
flash('New password must be at least 6 characters long', 'danger')
return redirect(url_for('student-profile'))
# Hash new password
hashed_password = generate_password_hash(new_password)
else:
# Keep existing password
hashed_password = student[4]
# Handle profile picture upload
profile_picture_path = None
if 'profile_picture' in request.files:
file = request.files['profile_picture']
if file and file.filename != '':
if allowed_file(file.filename):
# Create a secure filename with timestamp to prevent duplicates
timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
secure_name = f"profile_{student_id}_{timestamp}_{secure_filename(file.filename)}"
# Create profiles subdirectory if it doesn't exist
profiles_dir = os.path.join(UPLOAD_FOLDER, 'profiles')
os.makedirs(profiles_dir, exist_ok=True)
file_path = os.path.join(profiles_dir, secure_name)
file.save(file_path)
profile_picture_path = f"uploads/profiles/{secure_name}"
# Delete old profile picture if exists
if student[7]: # profile_picture is at index 7
old_picture_path = os.path.join('static', student[7])
if os.path.exists(old_picture_path):
try:
os.remove(old_picture_path)
except:
pass # Ignore error if file doesn't exist
else:
connection.close()
flash('Invalid file type. Please upload JPG, JPEG, or PNG files.', 'danger')
return redirect(url_for('student-profile'))
# Update student data in database
if profile_picture_path:
cursor.execute("""
UPDATE student
SET student_name = ?, email = ?, phone_number = ?,
student_gender = ?, student_dept = ?, password = ?,
profile_picture = ?
WHERE student_id = ?
""", (student_name, email, phone_number, student_gender,
student_dept, hashed_password, profile_picture_path, student_id))
else:
cursor.execute("""
UPDATE student
SET student_name = ?, email = ?, phone_number = ?,
student_gender = ?, student_dept = ?, password = ?
WHERE student_id = ?
""", (student_name, email, phone_number, student_gender,
student_dept, hashed_password, student_id))
connection.commit()
connection.close()
# Update session data
session['student_name'] = student_name
session['student_dept'] = student_dept
flash('Profile updated successfully!', 'success')
return redirect(url_for('student-profile'))
except Exception as e:
print(f"Error updating profile: {e}")
flash(f'Error updating profile: {str(e)}', 'danger')
return redirect(url_for('student-profile'))
@app.route("/teacher-dashboard", endpoint="teacher-dashboard")
@teacher_required
def teacher_dashboard():
teacher_id = session.get("teacher_id")
teacher_data = {
"id": teacher_id,
"name": session.get("teacher_name"),
"dept": session.get("teacher_dept"),
}
connection = sqlite3.connect(DB_PATH)
connection.row_factory = sqlite3.Row
cursor = connection.cursor()
# ✅ Ensure schema exists so query never crashes
ensure_achievements_schema(connection)
cursor.execute("SELECT COUNT(*) FROM achievements WHERE teacher_id = ?", (teacher_id,))
total_achievements = cursor.fetchone()[0]
cursor.execute("SELECT COUNT(DISTINCT student_id) FROM achievements WHERE teacher_id = ?", (teacher_id,))
students_managed = cursor.fetchone()[0]
one_week_ago = (datetime.datetime.now() - datetime.timedelta(days=7)).strftime("%Y-%m-%d")
cursor.execute("SELECT COUNT(*) FROM achievements WHERE teacher_id = ? AND achievement_date >= ?",
(teacher_id, one_week_ago))
this_week_count = cursor.fetchone()[0]
cursor.execute("""
SELECT a.id, a.student_id, s.student_name, a.achievement_type,
a.event_name, a.achievement_date
FROM achievements a
JOIN student s ON a.student_id = s.student_id
WHERE a.teacher_id = ?
ORDER BY a.created_at DESC
LIMIT 5
""", (teacher_id,))
recent_entries = cursor.fetchall()
# ===============================
# BASIC STATS (required for dashboard)
# ===============================
stats = {
"total_achievements": total_achievements,
"students_managed": students_managed,
"this_week": this_week_count,
}
# ===============================
# 📊 PERFORMANCE ANALYTICS COUNTS
# ===============================
cursor.execute("""
SELECT student_id, COUNT(*) as total
FROM achievements
WHERE teacher_id = ?
GROUP BY student_id
""", (teacher_id,))
rows = cursor.fetchall()
top_students = []
avg_students = []
low_students = []
for r in rows:
sid = r["student_id"]
total = r["total"]
cursor.execute("SELECT student_name FROM student WHERE student_id = ?", (sid,))
name_row = cursor.fetchone()
name = name_row["student_name"] if name_row else sid
if total >= 5:
top_students.append((name, total))
elif total >= 2:
avg_students.append((name, total))
else:
low_students.append((name, total))
# counts for chart
top_count = len(top_students)
avg_count = len(avg_students)
low_count = len(low_students)
return render_template(
"teacher_dashboard.html",
teacher=teacher_data,
stats=stats,
recent_entries=recent_entries,
top_students=top_students,
avg_students=avg_students,
low_students=low_students,
top_count=top_count,
avg_count=avg_count,
low_count=low_count
)
@app.route("/all-achievements", endpoint="all-achievements")
@teacher_required
def all_achievements():
teacher_id = session.get("teacher_id")
connection = sqlite3.connect(DB_PATH)
connection.row_factory = sqlite3.Row
cursor = connection.cursor()
cursor.execute("""
SELECT a.id, a.student_id, s.student_name, a.achievement_type,
a.event_name, a.achievement_date, a.position, a.organizer,
a.certificate_path
FROM achievements a
JOIN student s ON a.student_id = s.student_id
WHERE a.teacher_id = ?
ORDER BY a.achievement_date DESC
""", (teacher_id,))
achievements = cursor.fetchall()
connection.close()
return render_template("all_achievements.html", achievements=achievements)
# ==================== ADMIN ROUTES ====================
@app.route("/admin", methods=["GET", "POST"])
def admin_login():
"""Admin login page"""
if request.method == "POST":
admin_id = request.form.get("admin_id")
password = request.form.get("password")
connection = sqlite3.connect(DB_PATH)
cursor = connection.cursor()
cursor.execute("SELECT * FROM admin WHERE admin_id = ?", (admin_id,))
admin_data = cursor.fetchone()
connection.close()
if admin_data and check_password_hash(admin_data[3], password):
session["logged_in"] = True
session["admin_id"] = admin_data[1]
session["admin_name"] = admin_data[0]
session["is_superuser"] = bool(admin_data[4])
return redirect(url_for("admin_dashboard"))
else:
return render_template("admin_login.html", error="Invalid credentials. Please try again.")
return render_template("admin_login.html")
@app.route("/admin/dashboard")
@admin_required
def admin_dashboard():
"""Admin dashboard with system statistics"""
connection = sqlite3.connect(DB_PATH)
connection.row_factory = sqlite3.Row
cursor = connection.cursor()
# System statistics
cursor.execute("SELECT COUNT(*) FROM student")
total_students = cursor.fetchone()[0]
cursor.execute("SELECT COUNT(*) FROM teacher")
total_teachers = cursor.fetchone()[0]
cursor.execute("SELECT COUNT(*) FROM achievements")
total_achievements = cursor.fetchone()[0]
cursor.execute("SELECT COUNT(*) FROM student WHERE is_approved = 0")
pending_student_approvals = cursor.fetchone()[0]
cursor.execute("SELECT COUNT(*) FROM teacher WHERE is_approved = 0")
pending_teacher_approvals = cursor.fetchone()[0]
# Recent activities
cursor.execute("""
SELECT type, name, id, is_approved, created_at FROM (
SELECT 'student' as type, student_name as name, student_id as id, is_approved, created_at
FROM student
ORDER BY created_at DESC
LIMIT 5
)
UNION ALL
SELECT type, name, id, is_approved, created_at FROM (
SELECT 'teacher' as type, teacher_name as name, teacher_id as id, is_approved, created_at
FROM teacher
ORDER BY created_at DESC
LIMIT 5
)
ORDER BY created_at DESC
LIMIT 10
""")
recent_activities = cursor.fetchall()
# Department statistics
cursor.execute("""
SELECT student_dept, COUNT(*) as count
FROM student
WHERE student_dept IS NOT NULL AND student_dept != ''
GROUP BY student_dept
ORDER BY count DESC
LIMIT 5
""")
dept_stats = cursor.fetchall()
connection.close()
stats = {
"total_students": total_students,
"total_teachers": total_teachers,
"total_achievements": total_achievements,
"pending_student_approvals": pending_student_approvals,
"pending_teacher_approvals": pending_teacher_approvals,
}
return render_template(
"admin_dashboard.html",
stats=stats,
recent_activities=recent_activities,
dept_stats=dept_stats,
admin_name=session.get("admin_name"),
is_superuser=session.get("is_superuser", False)
)
@app.route("/admin/users")
@admin_required
def admin_users():
"""Manage users (students and teachers)"""
user_type = request.args.get("type", "students")
status = request.args.get("status", "all")
connection = sqlite3.connect(DB_PATH)
connection.row_factory = sqlite3.Row
cursor = connection.cursor()
if user_type == "students":
query = "SELECT * FROM student WHERE 1=1"
params = []
if status == "pending":
query += " AND is_approved = 0"
elif status == "approved":
query += " AND is_approved = 1"
query += " ORDER BY created_at DESC"
cursor.execute(query, params)
users = cursor.fetchall()
user_type_name = "Students"
else:
query = "SELECT * FROM teacher WHERE 1=1"
params = []
if status == "pending":
query += " AND is_approved = 0"
elif status == "approved":
query += " AND is_approved = 1"
query += " ORDER BY created_at DESC"
cursor.execute(query, params)
users = cursor.fetchall()
user_type_name = "Teachers"
connection.close()
return render_template(
"admin_users.html",
users=users,
user_type=user_type,
user_type_name=user_type_name,