better profile photo update logic

This commit is contained in:
Daniel 2023-06-08 17:09:22 +03:30
parent 39abb09002
commit dcdef77387
5 changed files with 31 additions and 53 deletions

View File

@ -10,6 +10,7 @@ import Modal from ".";
import ChangePassword from "./ChangePassword";
import { faPenToSquare } from "@fortawesome/free-regular-svg-icons";
import SubmitButton from "../SubmitButton";
import ProfilePhoto from "../ProfilePhoto";
type Props = {
toggleSettingsModal: Function;
@ -141,37 +142,29 @@ export default function UserSettings({ toggleSettingsModal }: Props) {
Profile Photo
</p>
<div className="w-28 h-28 flex items-center justify-center border border-sky-100 rounded-full relative">
{user.profilePic && user.profilePic !== "DELETE" ? (
<div>
<img
alt="Profile Photo"
className="rounded-full object-cover h-28 w-28 border-[3px] border-sky-100 border-opacity-0"
src={user.profilePic}
/>
<div
onClick={() =>
setUser({
...user,
profilePic: "DELETE",
})
}
className="absolute top-1 left-1 w-5 h-5 flex items-center justify-center border p-1 bg-white border-sky-100 rounded-full text-gray-500 hover:text-red-500 duration-100 cursor-pointer"
>
<FontAwesomeIcon icon={faClose} className="w-3 h-3" />
</div>
<ProfilePhoto
src={user.profilePic}
className="h-28 w-28 border-[1px]"
/>
{user.profilePic && (
<div
onClick={() =>
setUser({
...user,
profilePic: "",
})
}
className="absolute top-1 left-1 w-5 h-5 flex items-center justify-center border p-1 bg-white border-slate-200 rounded-full text-gray-500 hover:text-red-500 duration-100 cursor-pointer"
>
<FontAwesomeIcon icon={faClose} className="w-3 h-3" />
</div>
) : (
<FontAwesomeIcon
icon={faUser}
className="w-10 h-10 text-sky-400"
/>
)}
<div className="absolute -bottom-2 left-0 right-0 mx-auto w-fit text-center">
<label
htmlFor="upload-photo"
title="PNG or JPG (Max: 3MB)"
className="border border-sky-100 rounded-md bg-white px-2 text-center select-none cursor-pointer text-sky-900 duration-100 hover:border-sky-500"
className="border border-slate-200 rounded-md bg-white px-2 text-center select-none cursor-pointer text-sky-900 duration-100 hover:border-sky-500"
>
Browse...
<input

View File

@ -11,14 +11,14 @@ export default function ProfilePhoto({ src, className }: Props) {
const [error, setError] = useState(false);
useEffect(() => {
console.log(src);
}, []);
setError(false);
}, [src]);
return error || !src ? (
<div
className={`bg-sky-500 text-white h-10 w-10 shadow rounded-full border-[3px] border-slate-200 flex items-center justify-center ${className}`}
>
<FontAwesomeIcon icon={faUser} className="w-5 h-5" />
<FontAwesomeIcon icon={faUser} className="w-1/2 h-1/2" />
</div>
) : (
<img

View File

@ -7,8 +7,8 @@ import bcrypt from "bcrypt";
export default async function (user: AccountSettings, userId: number) {
const profilePic = user.profilePic;
if (profilePic?.startsWith("data:image/jpeg;base64")) {
if ((user?.profilePic?.length as number) < 1572864) {
if (profilePic.startsWith("data:image/jpeg;base64")) {
if (user.profilePic.length < 1572864) {
try {
const filePath = path.join(
process.cwd(),
@ -26,7 +26,7 @@ export default async function (user: AccountSettings, userId: number) {
} else {
console.log("A file larger than 1.5MB was uploaded.");
}
} else if (profilePic === "DELETE") {
} else if (profilePic == "") {
fs.unlink(`data/uploads/avatar/${userId}.jpg`, (err) => {
if (err) console.log(err);
});
@ -47,12 +47,6 @@ export default async function (user: AccountSettings, userId: number) {
if (user.newPassword && user.oldPassword) {
const saltRounds = 10;
const requestOldHashedPassword = bcrypt.hashSync(
user.oldPassword,
saltRounds
);
console.log(requestOldHashedPassword);
if (bcrypt.compareSync(user.oldPassword, updatedUser.password)) {
const newHashedPassword = bcrypt.hashSync(user.newPassword, saltRounds);
@ -71,5 +65,10 @@ export default async function (user: AccountSettings, userId: number) {
const { password, ...userInfo } = updatedUser;
return { response: userInfo, status: 200 };
const response: Omit<AccountSettings, "password"> = {
...userInfo,
profilePic: `/api/avatar/${userInfo.id}?${Date.now()}`,
};
return { response, status: 200 };
}

View File

@ -1,4 +0,0 @@
export default async function avatarExists(fileUrl: string): Promise<boolean> {
const response = await fetch(fileUrl, { method: "HEAD" });
return !(response.headers.get("content-type") === "text/plain");
}

View File

@ -1,6 +1,5 @@
import { create } from "zustand";
import { AccountSettings } from "@/types/global";
import avatarExists from "@/lib/client/avatarExists";
type AccountStore = {
account: AccountSettings;
@ -8,13 +7,6 @@ type AccountStore = {
updateAccount: (user: AccountSettings) => Promise<boolean>;
};
const determineProfilePicSource = async (data: any) => {
const path = `/api/avatar/${data.response.id}`;
const imageExists = await avatarExists(path);
if (imageExists) return path + "?" + Date.now();
else return null;
};
const useAccountStore = create<AccountStore>()((set) => ({
account: {} as AccountSettings,
setAccount: async (email) => {
@ -22,7 +14,7 @@ const useAccountStore = create<AccountStore>()((set) => ({
const data = await response.json();
const profilePic = await determineProfilePicSource(data);
const profilePic = `/api/avatar/${data.response.id}?${Date.now()}`;
if (response.ok) set({ account: { ...data.response, profilePic } });
},
@ -39,9 +31,7 @@ const useAccountStore = create<AccountStore>()((set) => ({
console.log(data);
const profilePic = await determineProfilePicSource(data);
if (response.ok) set({ account: { ...data.response, profilePic } });
if (response.ok) set({ account: { ...data.response } });
return response.ok;
},