From 49c9a5a7925891a4f260ee861d78ad50919aab84 Mon Sep 17 00:00:00 2001
From: LilleBRG <lillebrgmc@gmail.com>
Date: Tue, 1 Apr 2025 10:30:59 +0200
Subject: [PATCH] profile update and password update fixed

---
 backend/Api/BusinessLogic/UserLogic.cs     |   4 +-
 backend/Api/Controllers/UserController.cs  |  19 +++-
 backend/Api/DBAccess/DBAccess.cs           |  13 ++-
 frontend/profile/index.html                |   6 +-
 frontend/scripts/profile.js                | 123 ++++++++++++---------
 frontend/scripts/services/users.service.js |   4 +-
 6 files changed, 100 insertions(+), 69 deletions(-)

diff --git a/backend/Api/BusinessLogic/UserLogic.cs b/backend/Api/BusinessLogic/UserLogic.cs
index 4743cdd..cddf2bf 100644
--- a/backend/Api/BusinessLogic/UserLogic.cs
+++ b/backend/Api/BusinessLogic/UserLogic.cs
@@ -100,9 +100,9 @@ namespace Api.BusinessLogic
         /// <param name="user">Contains the updated user info</param>
         /// <param name="userId">Has the id for the user that is to be updated</param>
         /// <returns>returns the updated user in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
-        public async Task<IActionResult> EditProfile(User user, int userId)
+        public async Task<IActionResult> EditProfile(EditUserRequest userRequest, int userId)
         {
-            return await _dbAccess.UpdateUser(user, userId);
+            return await _dbAccess.UpdateUser(userRequest, userId);
         }
 
         public async Task<IActionResult> changePassword(ChangePasswordRequest passwordRequest, int userId)
diff --git a/backend/Api/Controllers/UserController.cs b/backend/Api/Controllers/UserController.cs
index bec64c0..42c940d 100644
--- a/backend/Api/Controllers/UserController.cs
+++ b/backend/Api/Controllers/UserController.cs
@@ -41,15 +41,26 @@ namespace Api.Controllers
             return await _userLogic.RegisterUser(user);
         }
 
-        // Sends the user and userId to userLogic
         [Authorize]
-        [HttpPut("Edit")]
-        public async Task<IActionResult> EditUser([FromBody] User user)
+        [HttpPut("change-password")]
+        public async Task<IActionResult> changePassword([FromBody] ChangePasswordRequest passwordRequest)
         {
             var claims = HttpContext.User.Claims;
             string userIdString = claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;
             int userId = Convert.ToInt32(userIdString);
-            return await _userLogic.EditProfile(user, userId);
+            return await _userLogic.changePassword(passwordRequest, userId);
+        }
+
+
+        // Sends the user and userId to userLogic
+        [Authorize]
+        [HttpPut("Update")]
+        public async Task<IActionResult> EditUser([FromBody] EditUserRequest userRequest)
+        {
+            var claims = HttpContext.User.Claims;
+            string userIdString = claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;
+            int userId = Convert.ToInt32(userIdString);
+            return await _userLogic.EditProfile(userRequest, userId);
         }
 
         // Sends the userId to userLogic
diff --git a/backend/Api/DBAccess/DBAccess.cs b/backend/Api/DBAccess/DBAccess.cs
index 90baaf0..c98e194 100644
--- a/backend/Api/DBAccess/DBAccess.cs
+++ b/backend/Api/DBAccess/DBAccess.cs
@@ -99,7 +99,7 @@ namespace Api.DBAccess
         /// <param name="user">Contains the updated user info</param>
         /// <param name="userId">Has the id for the user that is to be updated</param>
         /// <returns>returns the updated user in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
-        public async Task<IActionResult> UpdateUser(User user, int userId)
+        public async Task<IActionResult> UpdateUser(EditUserRequest user, int userId)
         {
             var profile = await _context.Users.FirstOrDefaultAsync(u => u.Id == userId);
             var users = await _context.Users.ToListAsync();
@@ -119,11 +119,14 @@ namespace Api.DBAccess
                 }
             }
 
-            if(user.Email != "" && user.Email != null)
-                profile.Email = user.Email;
+            if(user.Email == "" || user.Email == null)
+                return new ConflictObjectResult(new { message = "Please enter an email" });
 
-            if (user.UserName != "" && user.UserName != null)
-                profile.UserName = user.UserName;
+            if (user.UserName == "" || user.UserName == null)
+                return new ConflictObjectResult(new { message = "Please enter a username" });
+
+            profile.Email = user.Email;
+            profile.UserName = user.UserName;
 
 
 
diff --git a/frontend/profile/index.html b/frontend/profile/index.html
index dcd8af7..98ff11b 100644
--- a/frontend/profile/index.html
+++ b/frontend/profile/index.html
@@ -38,12 +38,12 @@
                 <form id="editForm">
                     <div class="form-container">
                         <label for="email"><b>Email</b></label>
-                        <input type="email" placeholder="Enter email "id="email">
-        
+                        <input type="text" placeholder="Enter email "id="email">
+         
                         <label for="uname"><b>Username</b></label>
                         <input type="text" placeholder="Enter username" id="uname">
         
-                        <button type="submit">Save Changes</button>
+                        <button id="submitEditBtn" type="submit">Save Changes</button>
         
                     </div>
                 </form>
diff --git a/frontend/scripts/profile.js b/frontend/scripts/profile.js
index 995ec6d..1f824d6 100644
--- a/frontend/scripts/profile.js
+++ b/frontend/scripts/profile.js
@@ -4,76 +4,95 @@ import { get } from "./services/users.service.js";
 import { update } from "./services/users.service.js";
 import { updatePassword } from "./services/users.service.js";
 
-let id = localStorage.getItem("id");
+var username;
+var email;
 
-get(id).then(res => {
-    var table = document.getElementById(`profileCard`);
-table.innerHTML += `
+get().then((res) => {
+  username = res.userName;
+  email = res.email;
+  var table = document.getElementById(`profileCard`);
+  table.innerHTML += `
     <div class="pfp">
         <img style="width:200px; height:200px" src="${profileData.pfp}">
     </div>
     <div class="userData">
-        <h2>${res.userName}</h2>
-        <h2>${res.email}</h2>
+        <h2>${username}</h2>
+        <h2>${email}</h2>
     </div>
 </div>`;
-})
-
+});
 
+const checkForChanges = () => {
+    if (emailInput.value !== email || usernameInput.value !== username) {
+        submitBtn.disabled = false; // Enable button if changes were made
+    } else {
+        submitBtn.disabled = true; // Disable button if no changes
+    }
+};
 
+const emailInput = document.getElementById("email");
+const usernameInput = document.getElementById("uname");
+const submitBtn = document.getElementById("submitEditBtn");
 var pswModal = document.getElementById("PasswordModal");
 var editModal = document.getElementById("editModal");
 var editIconbtn = document.getElementById("openEditModal");
 var passwordBtn = document.getElementById("openPasswordModal");
 
+emailInput.addEventListener("input", checkForChanges);
+usernameInput.addEventListener("input", checkForChanges);
+
 // Open modals
-editIconbtn.onclick = () => (editModal.style.display = "block");
+editIconbtn.onclick = () => {
+  document.getElementById("uname").value = username;
+  document.getElementById("email").value = email;
+  submitBtn.disabled = true;
+  editModal.style.display = "block";
+};
 passwordBtn.onclick = () => (pswModal.style.display = "block");
 
 // Close modals when clicking on any close button
-document.querySelectorAll(".close").forEach(closeBtn => {
-    closeBtn.onclick = () => {
-        pswModal.style.display = "none";
-        editModal.style.display = "none";
-        document.getElementById("form-error").innerText = "";
-        document.getElementById("form-error").style.display = "none";
-    };
+document.querySelectorAll(".close").forEach((closeBtn) => {
+  closeBtn.onclick = () => {
+    pswModal.style.display = "none";
+    editModal.style.display = "none";
+    document.getElementById("form-error").innerText = "";
+    document.getElementById("form-error").style.display = "none";
+  };
 });
 
 // Close modals when clicking outside
 window.onclick = (event) => {
-    if (event.target == pswModal || event.target == editModal) {
-        pswModal.style.display = "none";
-        editModal.style.display = "none";
-        document.getElementById("form-error").innerText = "";
-        document.getElementById("form-error").style.display = "none";
-    }
+  if (event.target == pswModal || event.target == editModal) {
+    pswModal.style.display = "none";
+    editModal.style.display = "none";
+    document.getElementById("form-error").innerText = "";
+    document.getElementById("form-error").style.display = "none";
+  }
 };
 
-document.getElementById("editForm").addEventListener("submit", function(event) {
+document
+  .getElementById("editForm")
+  .addEventListener("submit", function (event) {
     event.preventDefault(); // Prevents default form submission
 
     document.getElementById("form-error").style.display = "none";
 
-    // Get form values
-    const email = document.getElementById("email").value;
-    const username = document.getElementById("uname").value;
-
     // Call function with form values
-    update(email, username, id)
-        .then(response => {
-            if (response?.error) {
-                document.getElementById("form-error").innerText = response.error;
-                document.getElementById("form-error").style.display = "block";
+    update(emailInput.value, usernameInput.value).then((response) => {
+      if (response?.error) {
+        document.getElementById("form-error").innerText = response.error;
+        document.getElementById("form-error").style.display = "block";
 
-                return;
-            }
+        return;
+      }
 
-            location.href = "/profile";
-        });
-});
+      location.href = "/profile";
+    });
+  });
 
-document.getElementById("PasswordForm").addEventListener("submit", function(event) {
+document
+  .getElementById("PasswordForm")
+  .addEventListener("submit", function (event) {
     event.preventDefault(); // Prevents default form submission
 
     document.getElementById("form-error").style.display = "none";
@@ -83,22 +102,20 @@ document.getElementById("PasswordForm").addEventListener("submit", function(even
     const repeatPassword = document.getElementById("rpsw").value;
 
     if (newPassword !== repeatPassword) {
-        let errorDiv = document.getElementById("form-error");
-        errorDiv.style.display = "block"; 
-        errorDiv.innerText = "Passwords do not match!";
-        return;
+      let errorDiv = document.getElementById("form-error");
+      errorDiv.style.display = "block";
+      errorDiv.innerText = "Passwords do not match!";
+      return;
     }
 
-    updatePassword(oldPassword, newPassword, id)
-        .then(response => {
-            //error messages do not work
-            if (response.error) {
-                document.getElementById("form-error").innerText = response.message;
-                document.getElementById("form-error").style.display = "block";
-                return;
-            }
-        });
-});
+    updatePassword(oldPassword, newPassword).then((response) => {
+      //error messages do not work
+      if (response.error) {
+        document.getElementById("form-error").innerText = response.message;
+        document.getElementById("form-error").style.display = "block";
+        return;
+      }
+    });
+  });
 
 document.querySelector(".logout-container").addEventListener("click", logout);
-
diff --git a/frontend/scripts/services/users.service.js b/frontend/scripts/services/users.service.js
index 7ab71d8..fb49213 100644
--- a/frontend/scripts/services/users.service.js
+++ b/frontend/scripts/services/users.service.js
@@ -22,14 +22,14 @@ export function create(email, username, password, repeatPassword){
 }
 
 export function update(email, username){
-    return request("PATCH", "/user/update", {
+    return request("PUT", "/user/update", {
         email,
         username,
     });
 }
 
 export function updatePassword(oldPassword, newPassword){
-    return request("PATCH", "/user/update-password", {
+    return request("PUT", "/user/update-password", {
         oldPassword,
         newPassword,
     });