KindAlien commited on
Commit
3388cfb
·
verified ·
1 Parent(s): 49aba67

Update db.py

Browse files
Files changed (1) hide show
  1. db.py +43 -0
db.py CHANGED
@@ -3,6 +3,7 @@ import json
3
  import os
4
  import time
5
  from dotenv import load_dotenv
 
6
 
7
  load_dotenv(override=True)
8
 
@@ -60,6 +61,17 @@ def init_db():
60
  timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
61
  )
62
  ''')
 
 
 
 
 
 
 
 
 
 
 
63
  conn.commit()
64
  conn.close()
65
  except Exception as e:
@@ -294,3 +306,34 @@ def clear_database():
294
  except Exception as e:
295
  print(f"[DB ERROR] Failed to clear database: {e}")
296
  return False, str(e)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  import os
4
  import time
5
  from dotenv import load_dotenv
6
+ from werkzeug.security import generate_password_hash, check_password_hash
7
 
8
  load_dotenv(override=True)
9
 
 
61
  timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
62
  )
63
  ''')
64
+ cursor.execute('''
65
+ CREATE TABLE IF NOT EXISTS users (
66
+ id INT AUTO_INCREMENT PRIMARY KEY,
67
+ name VARCHAR(255) NOT NULL,
68
+ college VARCHAR(255) NOT NULL,
69
+ email VARCHAR(255) UNIQUE NOT NULL,
70
+ phone VARCHAR(50),
71
+ password_hash VARCHAR(255) NOT NULL,
72
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
73
+ )
74
+ ''')
75
  conn.commit()
76
  conn.close()
77
  except Exception as e:
 
306
  except Exception as e:
307
  print(f"[DB ERROR] Failed to clear database: {e}")
308
  return False, str(e)
309
+
310
+ # --- Auth Logic ---
311
+ def create_user(name, college, email, phone, password):
312
+ try:
313
+ conn = get_db_connection()
314
+ password_hash = generate_password_hash(password)
315
+ with conn.cursor() as cursor:
316
+ cursor.execute(
317
+ "INSERT INTO users (name, college, email, phone, password_hash) VALUES (%s, %s, %s, %s, %s)",
318
+ (name, college, email, phone, password_hash)
319
+ )
320
+ conn.commit()
321
+ conn.close()
322
+ return True, "User created successfully"
323
+ except pymysql.err.IntegrityError:
324
+ return False, "Email already exists"
325
+ except Exception as e:
326
+ print(f"[DB ERROR] Failed to create user: {e}")
327
+ return False, str(e)
328
+
329
+ def get_user_by_email(email):
330
+ try:
331
+ conn = get_db_connection()
332
+ with conn.cursor() as cursor:
333
+ cursor.execute("SELECT * FROM users WHERE email = %s", (email,))
334
+ user = cursor.fetchone()
335
+ conn.close()
336
+ return user
337
+ except Exception as e:
338
+ print(f"[DB ERROR] Failed to get user: {e}")
339
+ return None