diff --git a/client/src/components/DashProfile.jsx b/client/src/components/DashProfile.jsx index 73c439c..4fd34d3 100644 --- a/client/src/components/DashProfile.jsx +++ b/client/src/components/DashProfile.jsx @@ -2,12 +2,7 @@ import { Alert, Button, Modal, ModalBody, TextInput } from "flowbite-react"; import { useEffect, useRef, useState } from "react"; import { useSelector } from "react-redux"; import { Link } from "react-router-dom"; -import { - getDownloadURL, - getStorage, - ref, - uploadBytesResumable, -} from "firebase/storage"; +import { getDownloadURL, getStorage, ref, uploadBytesResumable } from "firebase/storage"; import { app } from "../firebase"; import { CircularProgressbar } from "react-circular-progressbar"; import "react-circular-progressbar/dist/styles.css"; @@ -34,6 +29,8 @@ export default function DashProfile() { const [updateUserSuccess, setUpdateUserSuccess] = useState(null); const [updateUserError, setUpdateUserError] = useState(null); const [showModal, setShowModal] = useState(false); + const [authModalVisible, setAuthModalVisible] = useState(false); + const [authPassword, setAuthPassword] = useState(""); const filePickerRef = useRef(null); const dispatch = useDispatch(); @@ -53,33 +50,25 @@ export default function DashProfile() { }, [imageFile]); const uploadImage = async () => { - setImageFileUploading(true); - setImageFileUploadError(null); const storage = getStorage(app); - const fileName = new Date().getTime() + imageFile.name; - const storageRef = ref(storage, fileName); + const storageRef = ref(storage, `profileImages/${currentUser._id}`); const uploadTask = uploadBytesResumable(storageRef, imageFile); + uploadTask.on( "state_changed", (snapshot) => { - const progress = - (snapshot.bytesTransferred / snapshot.totalBytes) * 100; - setImageFileUploadProgress(progress.toFixed(0)); + const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100; + setImageFileUploadProgress(progress); + if (progress === 100) { + setImageFileUploading(false); + } }, (error) => { - setImageFileUploadError( - "Could not upload image (File must be less than 2MB)" - ); - setImageFileUploadProgress(null); - setImageFile(null); - setImageFileUrl(null); - setImageFileUploading(false); + setImageFileUploadError("Image upload failed, please try again."); }, () => { getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => { - setImageFileUrl(downloadURL); - setFormData({ ...formData, profilePicture: downloadURL }); - setImageFileUploading(false); + setFormData((prevData) => ({ ...prevData, profilePicture: downloadURL })); }); } ); @@ -89,43 +78,87 @@ export default function DashProfile() { setFormData({ ...formData, [e.target.id]: e.target.value.trim() }); }; - const handleSubmit = async (e) => { + const handleAuthSubmit = async (e) => { e.preventDefault(); - setUpdateUserError(null); - setUpdateUserSuccess(null); - if (Object.keys(formData).length === 0) { - setUpdateUserError("No changes made"); - return; - } - if (imageFileUploading) { - setUpdateUserError("Please wait until image is uploaded"); - return; - } try { - dispatch(updateStart()); - const res = await fetch(`/api/user/update/${currentUser._id}`, { - method: "PUT", + const res = await fetch(`/api/auth/signin`, { + method: "POST", headers: { "Content-Type": "application/json", }, - body: JSON.stringify(formData), + body: JSON.stringify({ + email: currentUser.email, + password: authPassword, + }), }); const data = await res.json(); - if (!res.ok) { - dispatch(updateFailure(data.message)); - setUpdateUserError(data.message); + if (res.ok) { + setAuthModalVisible(false); + try { + dispatch(updateStart()); + const res = await fetch(`/api/user/update/${currentUser._id}`, { + method: "PUT", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify(formData), + }); + + const data = await res.json(); + + // Check the response from the server + console.log("Update response:", data); + + if (!res.ok) { + dispatch(updateFailure(data.message)); + setUpdateUserError(data.message); + } else { + dispatch(updateSuccess(data)); + setUpdateUserSuccess("User's profile updated successfully"); + setFormData({}); + } + } catch (error) { + dispatch(updateFailure(error.message)); + setUpdateUserError(error.message); + } } else { - dispatch(updateSuccess(data)); - setUpdateUserSuccess("User's profile updated successfully"); + setUpdateUserError("Authentication failed, please try again."); } } catch (error) { - dispatch(updateFailure(error.message)); - setUpdateUserError(error.message); + setUpdateUserError("Error authenticating, please try again."); + } + }; + + const handleSubmit = async (e) => { + e.preventDefault(); + setUpdateUserError(null); + setUpdateUserSuccess(null); + + // Check if formData is set correctly + console.log("Submitting form data:", formData); + + // Make sure to send the form data only if there's anything to update + if (Object.keys(formData).length === 0 && !imageFile) { + setUpdateUserError("No changes made"); + return; } + + // Handle image upload + if (imageFileUploading) { + setUpdateUserError("Please wait until the image is uploaded"); + return; + } + + // Check if any sensitive fields are being updated + if (formData.username || formData.email || formData.password) { + setAuthModalVisible(true); // Open authentication modal + return; + } + + // If no sensitive fields, proceed with update }; const handleDeleteUser = async () => { - setShowModal(false); try { dispatch(deleteUserStart()); const res = await fetch(`/api/user/delete/${currentUser._id}`, { @@ -143,19 +176,7 @@ export default function DashProfile() { }; const handleSignOut = async () => { - try { - const res = await fetch("/api/user/signout", { - method: "POST", - }); - const data = await res.json(); - if (!res.ok) { - console.log(data.message); - } else { - dispatch(signOutSuccess()); - } - } catch (error) { - console.log(error.message); - } + dispatch(signOutSuccess()); }; return ( @@ -170,7 +191,7 @@ export default function DashProfile() { hidden >