From 788bd077df05ca2483f52f2f1b27fdd4ae8d0162 Mon Sep 17 00:00:00 2001 From: Gisli Nielsen <gislion@stud.ntnu.no> Date: Tue, 7 May 2024 16:27:42 +0200 Subject: [PATCH] Changed to use userId in cookie --- Backend/routes/login.py | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/Backend/routes/login.py b/Backend/routes/login.py index 93eb4a6..39d1388 100644 --- a/Backend/routes/login.py +++ b/Backend/routes/login.py @@ -16,26 +16,32 @@ def post_login(): # Check if user exists and/or password exists cur = mysql.connection.cursor() - cur.execute('''SELECT user.email, user.hash, user.salt FROM user WHERE user.email = %s''', (email,)) + cur.execute('''SELECT user.user_id, user.email, user.hash, user.salt FROM user WHERE user.email = %s''', (email,)) dbData = cur.fetchall() cur.close() + if len(dbData) <= 0: + return jsonify({"message": "Incorrect login information."}), 400 + + # Deconstruct dbData[0] + userId, email, hash, salt = dbData[0] + # Check if user exists if len(dbData) <= 0: return jsonify({"message": "Incorrect login information."}), 400 - salt = dbData[0][2].encode("utf-8") - hash = hash_function(password, salt) + # Retrieve the password and hash the password to check with DB hash + salt = salt.encode("utf-8") + new_hash = hash_function(password, salt) # Password check - if hash.decode("utf-8") != dbData[0][1]: + if new_hash.decode("utf-8") != hash: return jsonify({"message": "Incorrect login information."}), 400 - # Set cookie + # Set cookie and make it last 24 hours response = make_response(jsonify({"message": "Login successful"})) - - # Cookie lasts 24 hours - response.set_cookie('logged_in', email, max_age=60*60*24) + userId = str(userId) + response.set_cookie('logged_in', userId, max_age=60*60*24) return response, 200 def post_register(): @@ -61,6 +67,7 @@ def post_register(): if len(data) > 0: return jsonify({"message": "Email already exists"}), 400 + # Instert the user information into the DB cur = mysql.connection.cursor() cur.execute('''INSERT INTO user_details (email, first_name, last_name, address) VALUES (%s, %s, %s, %s)''', (email, firstname, lastname, address)) cur.execute('''INSERT INTO user (email, hash, salt) VALUES (%s, %s, %s)''', (email, password, salt)) @@ -72,6 +79,7 @@ def post_register(): def hash_function(password, salt): password = password.encode("utf-8") + # Hash the password and return the hashed value hashed = bcrypt.hashpw(password, salt) return hashed -- GitLab