91 lines
2.7 KiB
Python
91 lines
2.7 KiB
Python
|
import bcrypt
|
||
|
from db import get_db_connection
|
||
|
|
||
|
def register_user(email, display_name, password):
|
||
|
hashed_password = bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()
|
||
|
conn = get_db_connection()
|
||
|
cursor = conn.cursor()
|
||
|
try:
|
||
|
cursor.execute(
|
||
|
"INSERT INTO users (email, display_name, password_hash) VALUES (%s, %s, %s) RETURNING uid;",
|
||
|
(email, display_name, hashed_password)
|
||
|
)
|
||
|
uid = cursor.fetchone()["uid"]
|
||
|
conn.commit()
|
||
|
return uid
|
||
|
except Exception as e:
|
||
|
conn.rollback()
|
||
|
raise e
|
||
|
finally:
|
||
|
cursor.close()
|
||
|
conn.close()
|
||
|
|
||
|
def authenticate_user(email, password):
|
||
|
conn = get_db_connection()
|
||
|
cursor = conn.cursor()
|
||
|
try:
|
||
|
cursor.execute("SELECT uid, password_hash FROM users WHERE email = %s;", (email,))
|
||
|
user = cursor.fetchone()
|
||
|
if user and bcrypt.checkpw(password.encode(), user["password_hash"].encode()):
|
||
|
return user["uid"]
|
||
|
return None
|
||
|
finally:
|
||
|
cursor.close()
|
||
|
conn.close()
|
||
|
|
||
|
def add_friend(user_uid, friend_uid):
|
||
|
conn = get_db_connection()
|
||
|
cursor = conn.cursor()
|
||
|
try:
|
||
|
cursor.execute("SELECT friend_list FROM users WHERE uid = %s;", (user_uid,))
|
||
|
friends = cursor.fetchone()["friend_list"]
|
||
|
if friend_uid not in friends:
|
||
|
friends.append(friend_uid)
|
||
|
cursor.execute(
|
||
|
"UPDATE users SET friend_list = %s WHERE uid = %s;",
|
||
|
(friends, user_uid)
|
||
|
)
|
||
|
conn.commit()
|
||
|
return True
|
||
|
except Exception as e:
|
||
|
conn.rollback()
|
||
|
raise e
|
||
|
finally:
|
||
|
cursor.close()
|
||
|
conn.close()
|
||
|
|
||
|
def send_match_invite(sender_uid, receiver_uid):
|
||
|
conn = get_db_connection()
|
||
|
cursor = conn.cursor()
|
||
|
try:
|
||
|
cursor.execute(
|
||
|
"INSERT INTO matches (player1_uid, player2_uid) VALUES (%s, %s) RETURNING match_id;",
|
||
|
(sender_uid, receiver_uid)
|
||
|
)
|
||
|
match_id = cursor.fetchone()["match_id"]
|
||
|
conn.commit()
|
||
|
return match_id
|
||
|
except Exception as e:
|
||
|
conn.rollback()
|
||
|
raise e
|
||
|
finally:
|
||
|
cursor.close()
|
||
|
conn.close()
|
||
|
|
||
|
def accept_match_invite(match_id, player2_uid):
|
||
|
conn = get_db_connection()
|
||
|
cursor = conn.cursor()
|
||
|
try:
|
||
|
cursor.execute(
|
||
|
"UPDATE matches SET match_date = CURRENT_TIMESTAMP WHERE match_id = %s AND player2_uid = %s;",
|
||
|
(match_id, player2_uid)
|
||
|
)
|
||
|
conn.commit()
|
||
|
return True
|
||
|
except Exception as e:
|
||
|
conn.rollback()
|
||
|
raise e
|
||
|
finally:
|
||
|
cursor.close()
|
||
|
conn.close()
|