Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import sqlite3 | |
| import os | |
| from passlib.context import CryptContext | |
| from jose import jwt, JWTError | |
| from datetime import datetime, timedelta | |
| from groq import Groq | |
| # ---------------- CONFIG ---------------- | |
| SECRET_KEY = "supersecretkey123" # change in production | |
| ALGORITHM = "HS256" | |
| ACCESS_TOKEN_EXPIRE_MINUTES = 60 | |
| COLLEGE_EMAIL_DOMAIN = "@college.edu" # change to your real domain | |
| GROQ_API_KEY = os.getenv("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") | |
| groq_client = Groq(api_key=GROQ_API_KEY) | |
| pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") | |
| # ---------------- DATABASE SETUP ---------------- | |
| def get_db(): | |
| conn = sqlite3.connect("database.db", check_same_thread=False) | |
| return conn | |
| def init_db(): | |
| conn = get_db() | |
| cur = conn.cursor() | |
| cur.execute(""" | |
| CREATE TABLE IF NOT EXISTS users ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| full_name TEXT, | |
| email TEXT UNIQUE, | |
| password TEXT, | |
| role TEXT, | |
| status TEXT, | |
| created_at TEXT | |
| ) | |
| """) | |
| conn.commit() | |
| conn.close() | |
| init_db() | |
| # ---------------- SECURITY ---------------- | |
| def hash_password(password: str) -> str: | |
| return pwd_context.hash(password) | |
| def verify_password(password: str, hashed: str) -> bool: | |
| return pwd_context.verify(password, hashed) | |
| def create_access_token(data: dict, expires_delta: timedelta | None = None): | |
| to_encode = data.copy() | |
| expire = datetime.utcnow() + (expires_delta or timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)) | |
| to_encode.update({"exp": expire}) | |
| return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) | |
| # ---------------- AUTH LOGIC ---------------- | |
| def register_user(full_name, email, password, role): | |
| if not email.endswith(COLLEGE_EMAIL_DOMAIN): | |
| return "β Only college email addresses are allowed." | |
| if role not in ["student", "teacher"]: | |
| return "β Role must be student or teacher." | |
| conn = get_db() | |
| cur = conn.cursor() | |
| try: | |
| cur.execute(""" | |
| INSERT INTO users (full_name, email, password, role, status, created_at) | |
| VALUES (?, ?, ?, ?, ?, ?) | |
| """, (full_name, email, hash_password(password), role, "pending", datetime.utcnow().isoformat())) | |
| conn.commit() | |
| return "β Registration successful! Please wait for admin approval." | |
| except sqlite3.IntegrityError: | |
| return "β Email already registered." | |
| finally: | |
| conn.close() | |
| def login_user(email, password): | |
| conn = get_db() | |
| cur = conn.cursor() | |
| cur.execute("SELECT id, password, role, status FROM users WHERE email=?", (email,)) | |
| user = cur.fetchone() | |
| conn.close() | |
| if not user: | |
| return "β Invalid email or password.", None | |
| user_id, hashed_pw, role, status = user | |
| if not verify_password(password, hashed_pw): | |
| return "β Invalid email or password.", None | |
| if status != "approved": | |
| return "β³ Your account is not approved yet.", None | |
| token = create_access_token({"sub": email, "role": role}) | |
| return f"β Login successful! Role: {role}", {"email": email, "role": role, "token": token} | |
| # ---------------- ADMIN LOGIC ---------------- | |
| def get_pending_users(): | |
| conn = get_db() | |
| cur = conn.cursor() | |
| cur.execute("SELECT id, full_name, email, role, status FROM users WHERE status='pending'") | |
| users = cur.fetchall() | |
| conn.close() | |
| return users | |
| def approve_user(user_id): | |
| conn = get_db() | |
| cur = conn.cursor() | |
| cur.execute("UPDATE users SET status='approved' WHERE id=?", (user_id,)) | |
| conn.commit() | |
| conn.close() | |
| return "β User approved successfully." | |
| def reject_user(user_id): | |
| conn = get_db() | |
| cur = conn.cursor() | |
| cur.execute("DELETE FROM users WHERE id=?", (user_id,)) | |
| conn.commit() | |
| conn.close() | |
| return "β User rejected and removed." | |
| # ---------------- DASHBOARDS ---------------- | |
| def student_dashboard(): | |
| return "π Welcome Student! Your dashboard will be built next." | |
| def teacher_dashboard(): | |
| return "π©βπ« Welcome Teacher! Your dashboard will be built next." | |
| def admin_dashboard(): | |
| users = get_pending_users() | |
| if not users: | |
| return "No pending users." | |
| output = "π Pending Users:\n\n" | |
| for u in users: | |
| output += f"ID: {u[0]} | {u[1]} | {u[2]} | {u[3]} | {u[4]}\n" | |
| output += "\nUse the approve/reject section below." | |
| return output | |
| # ---------------- GROQ AI FEATURE (Optional Assistant) ---------------- | |
| def ai_assistant(query): | |
| if not GROQ_API_KEY: | |
| return "β GROQ_API_KEY not set." | |
| completion = groq_client.chat.completions.create( | |
| model="llama3-8b-8192", | |
| messages=[{"role": "user", "content": query}] | |
| ) | |
| return completion.choices[0].message.content | |
| # ---------------- UI (GRADIO) ---------------- | |
| with gr.Blocks(title="Secure College Platform") as app: | |
| gr.Markdown("## π Secure College Platform (Students & Teachers Only)") | |
| with gr.Tabs(): | |
| # ---------------- REGISTER TAB ---------------- | |
| with gr.Tab("π Register"): | |
| full_name = gr.Textbox(label="Full Name") | |
| email = gr.Textbox(label="College Email") | |
| password = gr.Textbox(label="Password", type="password") | |
| role = gr.Radio(["student", "teacher"], label="Select Role") | |
| register_btn = gr.Button("Register") | |
| register_output = gr.Textbox(label="Status") | |
| register_btn.click(register_user, inputs=[full_name, email, password, role], outputs=register_output) | |
| # ---------------- LOGIN TAB ---------------- | |
| with gr.Tab("π Login"): | |
| login_email = gr.Textbox(label="Email") | |
| login_password = gr.Textbox(label="Password", type="password") | |
| login_btn = gr.Button("Login") | |
| login_output = gr.Textbox(label="Login Status") | |
| session_state = gr.State() | |
| def login_and_route(email, password): | |
| msg, session = login_user(email, password) | |
| return msg, session | |
| login_btn.click(login_and_route, inputs=[login_email, login_password], outputs=[login_output, session_state]) | |
| # ---------------- STUDENT DASHBOARD ---------------- | |
| with gr.Tab("π Student Dashboard"): | |
| student_output = gr.Textbox(label="Student Panel") | |
| gr.Button("Load Dashboard").click(lambda: student_dashboard(), outputs=student_output) | |
| # ---------------- TEACHER DASHBOARD ---------------- | |
| with gr.Tab("π©βπ« Teacher Dashboard"): | |
| teacher_output = gr.Textbox(label="Teacher Panel") | |
| gr.Button("Load Dashboard").click(lambda: teacher_dashboard(), outputs=teacher_output) | |
| # ---------------- ADMIN PANEL ---------------- | |
| with gr.Tab("π Admin Panel"): | |
| admin_output = gr.Textbox(label="Pending Users", lines=10) | |
| gr.Button("Refresh Pending Users").click(lambda: admin_dashboard(), outputs=admin_output) | |
| gr.Markdown("### Approve or Reject User") | |
| user_id_input = gr.Number(label="User ID", precision=0) | |
| approve_btn = gr.Button("Approve") | |
| reject_btn = gr.Button("Reject") | |
| admin_action_output = gr.Textbox(label="Action Status") | |
| approve_btn.click(approve_user, inputs=user_id_input, outputs=admin_action_output) | |
| reject_btn.click(reject_user, inputs=user_id_input, outputs=admin_action_output) | |
| # ---------------- AI ASSISTANT ---------------- | |
| with gr.Tab("π€ AI Assistant"): | |
| ai_query = gr.Textbox(label="Ask anything about college system") | |
| ai_btn = gr.Button("Ask AI") | |
| ai_output = gr.Textbox(label="AI Response", lines=5) | |
| ai_btn.click(ai_assistant, inputs=ai_query, outputs=ai_output) | |
| app.launch() | |