From c8cdcd88a61698d102bddf218e7aa88e11fedf3b Mon Sep 17 00:00:00 2001 From: terryjung0244 Date: Mon, 1 Jul 2024 22:30:57 -0400 Subject: [PATCH 01/31] Issue 225: Add basic structure for Incidents Component --- Client/src/Pages/Incidents/index.css | 13 +++++++++++++ Client/src/Pages/Incidents/index.jsx | 21 +++++++++++++++------ Client/src/Pages/Status/index.jsx | 10 ++++------ 3 files changed, 32 insertions(+), 12 deletions(-) diff --git a/Client/src/Pages/Incidents/index.css b/Client/src/Pages/Incidents/index.css index e69de29bb..9886428f3 100644 --- a/Client/src/Pages/Incidents/index.css +++ b/Client/src/Pages/Incidents/index.css @@ -0,0 +1,13 @@ +.maintenance-checklist-card { + max-width: 314; + margin: auto; + padding: 2; + box-shadow: 3; +} + +.maintenance-checklist-box { + height: 100; + background-color: grey; + border-radius: 1px; + margin-bottom: 2px; +} diff --git a/Client/src/Pages/Incidents/index.jsx b/Client/src/Pages/Incidents/index.jsx index e1aa44740..a6f305498 100644 --- a/Client/src/Pages/Incidents/index.jsx +++ b/Client/src/Pages/Incidents/index.jsx @@ -1,9 +1,18 @@ -import React from 'react' +import React from "react"; +import { Card, CardContent, Box, Typography, Button } from "@mui/material"; const Incidents = () => { - return ( -
Incidents
- ) -} + return ( + + + + Create a maintenance window to + + + + + + ); +}; -export default Incidents \ No newline at end of file +export default Incidents; diff --git a/Client/src/Pages/Status/index.jsx b/Client/src/Pages/Status/index.jsx index 33729f7e1..f0cf82b60 100644 --- a/Client/src/Pages/Status/index.jsx +++ b/Client/src/Pages/Status/index.jsx @@ -1,9 +1,7 @@ -import React from 'react' +import React from "react"; const Status = () => { - return ( -
Status
- ) -} + return
Status
; +}; -export default Status \ No newline at end of file +export default Status; From 5cd7e362e959fd51d229e4e6c1bce0cb49641cd7 Mon Sep 17 00:00:00 2001 From: terryjung0244 Date: Tue, 2 Jul 2024 13:41:59 -0400 Subject: [PATCH 02/31] Define an array of maintenance item and Map maintenance items array to ListItem components with icons --- Client/src/Pages/Incidents/index.jsx | 38 ++++++++++++++++++++++++++-- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/Client/src/Pages/Incidents/index.jsx b/Client/src/Pages/Incidents/index.jsx index a6f305498..70659aabc 100644 --- a/Client/src/Pages/Incidents/index.jsx +++ b/Client/src/Pages/Incidents/index.jsx @@ -1,15 +1,49 @@ import React from "react"; -import { Card, CardContent, Box, Typography, Button } from "@mui/material"; +import "./index.css"; +import { + Card, + CardContent, + Box, + Typography, + Button, + List, + ListItem, + ListItemIcon, + ListItemText, +} from "@mui/material"; +import CheckCircleOutlineIcon from "@mui/icons-material/CheckCircleOutline"; const Incidents = () => { + const maintenanceItems = [ + "Mark your maintenance periods", + "Eliminate any misunderstandings", + "Stop sending alerts in maintenance windows", + ]; + return ( Create a maintenance window to + + {maintenanceItems.map((item, index) => { + + + + + + ; + })} + - + ); From 7d27a72f628394b4b1f484471714a7c9f3bbb545 Mon Sep 17 00:00:00 2001 From: terryjung0244 Date: Tue, 2 Jul 2024 21:44:03 -0400 Subject: [PATCH 03/31] Issue 225: update maintenance checklist component structure --- Client/src/Pages/Incidents/index.css | 38 +++++++++++++---- Client/src/Pages/Incidents/index.jsx | 64 +++++++++++----------------- 2 files changed, 54 insertions(+), 48 deletions(-) diff --git a/Client/src/Pages/Incidents/index.css b/Client/src/Pages/Incidents/index.css index 9886428f3..77ec42814 100644 --- a/Client/src/Pages/Incidents/index.css +++ b/Client/src/Pages/Incidents/index.css @@ -1,13 +1,33 @@ -.maintenance-checklist-card { - max-width: 314; +.maintenance-checklist-main { + max-width: 350px; + min-height: 390px; margin: auto; - padding: 2; - box-shadow: 3; + padding: 5px; } -.maintenance-checklist-box { - height: 100; - background-color: grey; - border-radius: 1px; - margin-bottom: 2px; +.maintenance-image { + width: 280px; + height: 150px; + background-color: whitesmoke; + border-radius: 10px; +} + +.maintenance-title { + font-size: 20px; + font-weight: bold; + margin-top: 40px; + margin-bottom: 30px; +} + +.checklist-item { + display: flex; + margin-bottom: 10px; +} + +.checklist-item-text { + margin-left: 10px; +} + +.maintenance-checklist-main .maintenance-checklist-button { + margin-top: 30px; } diff --git a/Client/src/Pages/Incidents/index.jsx b/Client/src/Pages/Incidents/index.jsx index 70659aabc..888584ee5 100644 --- a/Client/src/Pages/Incidents/index.jsx +++ b/Client/src/Pages/Incidents/index.jsx @@ -1,51 +1,37 @@ import React from "react"; import "./index.css"; -import { - Card, - CardContent, - Box, - Typography, - Button, - List, - ListItem, - ListItemIcon, - ListItemText, -} from "@mui/material"; +import { Button } from "@mui/material"; import CheckCircleOutlineIcon from "@mui/icons-material/CheckCircleOutline"; const Incidents = () => { const maintenanceItems = [ - "Mark your maintenance periods", - "Eliminate any misunderstandings", - "Stop sending alerts in maintenance windows", + { id: 1, text: "Mark your maintenance periods" }, + { id: 2, text: "Eliminate any misunderstandings" }, + { id: 3, text: "Stop sending alerts in maintenance windows" }, ]; return ( - - - - Create a maintenance window to - - {maintenanceItems.map((item, index) => { - - - - - - ; - })} - - - - - - +
+
+
Create a maintenance window to
+
+ {maintenanceItems.map((item) => ( +
+ +
{item.text}
+
+ ))} +
+ + +
); }; From c1d0c24f785a3506339aad3b0868b90ff4db9214 Mon Sep 17 00:00:00 2001 From: Daniel Cojocea Date: Wed, 3 Jul 2024 13:04:46 -0400 Subject: [PATCH 04/31] Refactored code and hooked up picture to localState --- Client/src/Components/ProgressBars/index.css | 3 +- Client/src/Components/ProgressBars/index.jsx | 3 + .../TabPanels/Account/ProfilePanel.jsx | 200 ++++++++++-------- .../src/Components/TextFields/Image/index.jsx | 5 +- Client/src/Utils/fileUtils.js | 21 ++ 5 files changed, 135 insertions(+), 97 deletions(-) create mode 100644 Client/src/Utils/fileUtils.js diff --git a/Client/src/Components/ProgressBars/index.css b/Client/src/Components/ProgressBars/index.css index 8bd3fc966..5ba1939da 100644 --- a/Client/src/Components/ProgressBars/index.css +++ b/Client/src/Components/ProgressBars/index.css @@ -17,7 +17,8 @@ padding-left: 2px; } .progress-bar-container:has(p.input-error){ - border-color: var(--env-var-color-24); + border-color: var(--env-var-color-19); + background-color: var(--env-var-color-21); padding: 8px var(--env-var-spacing-1-plus); } .progress-bar-container p.input-error{ diff --git a/Client/src/Components/ProgressBars/index.jsx b/Client/src/Components/ProgressBars/index.jsx index 2d60683ef..40e1a5a2c 100644 --- a/Client/src/Components/ProgressBars/index.jsx +++ b/Client/src/Components/ProgressBars/index.jsx @@ -94,6 +94,9 @@ const ProgressUpload = ({ } : { ml: "auto", + "&:focus": { + outline: "none", + }, } } > diff --git a/Client/src/Components/TabPanels/Account/ProfilePanel.jsx b/Client/src/Components/TabPanels/Account/ProfilePanel.jsx index 2208fd646..a9d5a5c81 100644 --- a/Client/src/Components/TabPanels/Account/ProfilePanel.jsx +++ b/Client/src/Components/TabPanels/Account/ProfilePanel.jsx @@ -1,5 +1,5 @@ import { useTheme } from "@emotion/react"; -import { useState } from "react"; +import { useRef, useState } from "react"; import TabPanel from "@mui/lab/TabPanel"; import { Box, Divider, Modal, Stack, Typography } from "@mui/material"; import ButtonSpinner from "../../ButtonSpinner"; @@ -16,6 +16,7 @@ import { update } from "../../../Features/Auth/authSlice"; import ImageField from "../../TextFields/Image"; import ImageIcon from "@mui/icons-material/Image"; import ProgressUpload from "../../ProgressBars"; +import { bytesToUrl, checkImage, formatBytes } from "../../../Utils/fileUtils"; /** * ProfilePanel component displays a form for editing user profile information @@ -42,12 +43,18 @@ const ProfilePanel = () => { //Disabled for now, will revisit in the future // email: user.email, //TODO - upload picture - profilePicUrl: "placeholder", + profilePicUrl: { src: user.profilePicUrl }, }); const [errors, setErrors] = useState({}); + const clearError = (err) => { + setErrors((prev) => { + const updatedErrors = { ...prev }; + if (updatedErrors[err]) delete updatedErrors[err]; + return updatedErrors; + }); + }; const [isOpen, setIsOpen] = useState(""); const isModalOpen = (name) => isOpen === name; - const [loading, setLoading] = useState(false); const handleChange = (event) => { const { value, id } = event.target; @@ -73,90 +80,84 @@ const ProfilePanel = () => { return updatedErrors; }); }; - - //TODO - add setPicture state to localData - const [picture, setPicture] = useState(); - const [uploadProgress, setUploadProgress] = useState(0); - const [isUploading, setIsUploading] = useState(false); + const [progress, setProgress] = useState({ value: 0, isLoading: false }); + const intervalRef = useRef(null); const handlePicture = (event) => { - clearError("picture"); const pic = event.target.files[0]; - console.log(pic); - //TODO - add setPicture state to localData - setPicture({ name: pic.name, type: pic.type, size: formatBytes(pic.size) }); - setIsUploading(true); + //reset errors if any + clearError("picture"); + if (pic) { + setProgress((prev) => ({ ...prev, isLoading: true })); + setLocalData((prev) => ({ + ...prev, + profilePicUrl: { + name: pic.name, + type: pic.type, + size: formatBytes(pic.size), + src: "", + }, + })); - const { error } = imageValidation.validate( - { - type: pic.type, - size: pic.size, - }, - { abortEarly: false } - ); + const { error } = imageValidation.validate( + { + type: pic.type, + size: pic.size, + }, + { abortEarly: false } + ); - if (error) { - setErrors((prev) => { - const updatedErrors = { ...prev }; - updatedErrors["picture"] = error.details[0].message; - return updatedErrors; - }); - return; - } - - setTimeout(() => { - //TODO - add setPicture state to localData - setPicture((prev) => ({ ...prev, src: URL.createObjectURL(pic) })); - }, 1500); - - let progress = 0; - const interval = setInterval(() => { - progress += 10; - setUploadProgress(progress); - if (progress >= 100) { - clearInterval(interval); + if (error) { + setErrors((prev) => ({ + ...prev, + ["picture"]: error.details[0].message, + })); + return; } - }, 150); - }; - const formatBytes = (bytes) => { - if (bytes === 0) return "0 Bytes"; - const megabytes = bytes / (1024 * 1024); - return megabytes.toFixed(2) + " MB"; - }; - const clearError = (err) => { - setErrors((prev) => { - const updatedErrors = { ...prev }; - if (updatedErrors[err]) delete updatedErrors[err]; - return updatedErrors; - }); - }; - const handleCancelUpload = () => { - //TODO - add setPicture state to localData - setPicture(); - setUploadProgress(0); - setIsUploading(false); - clearError("picture"); - }; - const handleClosePictureModal = () => { - setIsOpen(""); - setUploadProgress(0); - setIsUploading(false); - clearError("picture"); - }; - //TODO - revisit once localData is set up properly - const handleDeletePicture = () => { - setLoading(true); - setTimeout(() => { - //TODO - add setPicture state to localData - setPicture(null); - setLoading(false); - }, 2000); + const reader = new FileReader(); + reader.onloadend = () => { + const arrayBuffer = reader.result; + const bytes = new Uint8Array(arrayBuffer); + setLocalData((prev) => ({ + ...prev, + profilePicUrl: { + ...prev.profilePicUrl, + src: bytes, + }, + })); + + //TODO - potentitally remove once image compression functions are implemented above + intervalRef.current = setInterval(() => { + const buffer = 8; + setProgress((prev) => { + if (prev.value + buffer >= 100) { + clearInterval(intervalRef.current); + return { value: 100, isLoading: false }; + } + return { ...prev, value: prev.value + buffer }; + }); + }, 150); + }; + reader.readAsArrayBuffer(pic); + } }; - //TODO - implement update profile function - const handleUpdatePicture = () => { + const removePicture = () => { + clearError("picture"); + setLocalData((prev) => ({ + ...prev, + profilePicUrl: { src: user.profilePicUrl }, + })); + //interrupt interval if modal closes prior to completing the process + clearInterval(intervalRef.current); + setProgress({ value: 0, isLoading: false }); + }; + const closePictureModal = () => { + removePicture(); + setIsOpen(""); + }; + const handleUpdatePicture = () => { + setProgress({ value: 0, isLoading: false }); setIsOpen(""); - setUploadProgress(0); - setIsUploading(false); }; //TODO - implement delete account function const handleDeleteAccount = () => {}; @@ -261,7 +262,11 @@ const ProfilePanel = () => { { mr: "8px", }} /> - - - ); + return
Incidents
; }; export default Incidents; diff --git a/Client/src/Pages/Maintenance/index.css b/Client/src/Pages/Maintenance/index.css new file mode 100644 index 000000000..f26a48767 --- /dev/null +++ b/Client/src/Pages/Maintenance/index.css @@ -0,0 +1,36 @@ +.maintenance-checklist-main { + max-width: 350px; + min-height: 390px; + margin: auto; + padding: 5px; +} + +.maintenance-image { + width: 280px; + height: 150px; + background-color: whitesmoke; + border-radius: 10px; +} + +.maintenance-title { + color: var(--env-var-color-2); + font-size: 16px; + font-weight: bold; + margin-top: 40px; + margin-bottom: 30px; +} + +.checklist-item { + font-size: 13px; + color: var(--env-var-color-2); + display: flex; + margin-bottom: 10px; +} + +.checklist-item-text { + margin-left: 10px; +} + +.maintenance-checklist-main .maintenance-checklist-button { + margin-top: 30px; +} diff --git a/Client/src/Pages/Maintenance/index.jsx b/Client/src/Pages/Maintenance/index.jsx new file mode 100644 index 000000000..4cf77b025 --- /dev/null +++ b/Client/src/Pages/Maintenance/index.jsx @@ -0,0 +1,39 @@ +import React from "react"; +import "./index.css"; +import WindowFrame from "./../../assets/Images/maintenance_window_frame.svg"; +import { Button } from "@mui/material"; +import CheckCircleOutlineIcon from "@mui/icons-material/CheckCircleOutline"; + +const Maintenance = () => { + const maintenanceItems = [ + { id: 1, text: "Mark your maintenance periods" }, + { id: 2, text: "Eliminate any misunderstandings" }, + { id: 3, text: "Stop sending alerts in maintenance windows" }, + ]; + + return ( +
+ WindowFrame +
Create a maintenance window to
+
+ {maintenanceItems.map((item) => ( +
+ +
{item.text}
+
+ ))} +
+ + +
+ ); +}; + +export default Maintenance; diff --git a/Client/src/Utils/PathMap.js b/Client/src/Utils/PathMap.js index 2a86c17f7..a14aafe63 100644 --- a/Client/src/Utils/PathMap.js +++ b/Client/src/Utils/PathMap.js @@ -1,9 +1,10 @@ const pathMap = { - "/monitors": "Monitors", - "/incidents": "Incidents", - "/status" : "Status Pages", - "/integrations": "Integrations", - "/settings" : "Settings" -} + "/monitors": "Monitors", + "/incidents": "Incidents", + "/status": "Status Pages", + "/integrations": "Integrations", + "/maintenance": "maintenance", + "/settings": "Settings", +}; -export default pathMap; \ No newline at end of file +export default pathMap; From 31c16e8d3d89f93b93c5d7844f844e5cfd198ece Mon Sep 17 00:00:00 2001 From: terryjung0244 Date: Sun, 7 Jul 2024 22:18:57 -0400 Subject: [PATCH 19/31] 1.Added Icon-maintenance-gray.png to assets/images. 2.Imported and used MaintenanceIcon in DashboardMenuButton for the maintenance page button. --- Client/src/Components/DashboardMenu/index.jsx | 3 ++- .../src/assets/Images/Icon-maintenance-gray.png | Bin 0 -> 744 bytes 2 files changed, 2 insertions(+), 1 deletion(-) create mode 100644 Client/src/assets/Images/Icon-maintenance-gray.png diff --git a/Client/src/Components/DashboardMenu/index.jsx b/Client/src/Components/DashboardMenu/index.jsx index 0730ea643..a88274c5d 100644 --- a/Client/src/Components/DashboardMenu/index.jsx +++ b/Client/src/Components/DashboardMenu/index.jsx @@ -5,6 +5,7 @@ import Monitors from "../../assets/Images/Icon-monitor-gray.png"; import Incidents from "../../assets/Images/Icon-warning-gray.png"; import SensorsIcon from "../../assets/Images/Icon-signal-gray.png"; import AllInclusiveIcon from "../../assets/Images/Icon-link-gray.png"; +import MaintenanceIcon from "../../assets/Images/Icon-maintenance-gray.png"; import SettingsIcon from "../../assets/Images/Icon-setting-gray.png"; import React, { useState, useEffect } from "react"; import { useNavigate, useLocation } from "react-router-dom"; @@ -63,7 +64,7 @@ function DashboardMenu() { () => handleClick(pathMap["/integrations"], "/integrations") )} {DashboardMenuButton( - AllInclusiveIcon, + MaintenanceIcon, "Maintenance", "/maintenance", activeButton === "/maintenance", diff --git a/Client/src/assets/Images/Icon-maintenance-gray.png b/Client/src/assets/Images/Icon-maintenance-gray.png new file mode 100644 index 0000000000000000000000000000000000000000..c2c203d762cb335da8ada629280951221090729b GIT binary patch literal 744 zcmVP)f-wFA^a*ZY zz;?8pyRtze%a$N_#@^M{>g?IwbI&sEh$nj3B&K`HP%|cSB*#QE!xU7^{Nk-Qh_-#p zdC8uB**2tHL)2cSA|?|_#}GHrG?P9BXb#8T@w5;aEIlNj3s_9XU(({t_Xe}{n2vt! z)F^HbrQ3z!#A^(nx)5B5HoAFT70zXOJSVG5T0 zv3GJb4JSV{lj^&z`>n6xWth%ig_o1P)&nqPz1MowxC%dgl)PFkU-rxu&~xu(kjJb- zW*-yp=e>JpzhMt6)m@y=A7K2A&_vrn%fy_12{;Z}xfZjBgRrO1ai4Aw$$7*+R@Igr zP}dyW<;~4~mZts=v6qd6HAl+CP1$1z-W19zA;L~iyUy-02Kr}5 zQOPi5F3_MD>ffH};rpTq1UM2VR1lC9ibma*Lcp&h6Lj^d-XuT`;LTLbBz5j|wA&~G z_r0S?s%t#~Gn@2#Q5c%0m{hf9XtKmpm1^P-rF1M4pgG9qudRO&E#Q3W4V(!Nfgy5-V;hIoxQol;f1@79FAgr6fZ5UKS$t%nSw3H||d1)6xx zc=X~!LN*m^+syOVywKRX?^L(0n6*vboIUYZbR+Q(g;LL6K?3-L>R2+1cRS+WkmF%` zOzzcWO@zz{*HC+vnu5_R`GB1S%oa^RtYrBcK9dW)4toW`q@Y&F$gC8Dl4Ugo>Ll;3 aTgPukNgD_r569mC0000 Date: Mon, 8 Jul 2024 10:26:56 -0700 Subject: [PATCH 20/31] Generate avatar image on register or update if an image is included --- Server/controllers/authController.js | 38 +- Server/db/MongoDB.js | 15 +- Server/models/user.js | 3 + Server/package-lock.json | 532 +++++++++++++++++++++++++++ Server/package.json | 1 + Server/utils/imageProcessing.js | 27 ++ 6 files changed, 594 insertions(+), 22 deletions(-) create mode 100644 Server/utils/imageProcessing.js diff --git a/Server/controllers/authController.js b/Server/controllers/authController.js index 757d8f78b..b64b7f764 100644 --- a/Server/controllers/authController.js +++ b/Server/controllers/authController.js @@ -7,7 +7,7 @@ const { recoveryValidation, recoveryTokenValidation, newPasswordValidation, - deleteUserParamValidation + deleteUserParamValidation, } = require("../validation/joi"); const logger = require("../utils/logger"); require("dotenv").config(); @@ -59,6 +59,7 @@ const registerController = async (req, res, next) => { const userForToken = { ...newUser._doc }; delete userForToken.profileImage; + delete userForToken.avatarImage; const token = issueToken(userForToken); @@ -274,21 +275,23 @@ const resetPasswordController = async (req, res, next) => { */ const deleteUserController = async (req, res, next) => { try { - const token = req.headers.authorization.split(' ')[1]; - const decodedToken = jwt.decode(token) + const token = req.headers.authorization.split(" ")[1]; + const decodedToken = jwt.decode(token); const { _id, email } = decodedToken; const decodedTokenCastedAsRequest = { params: { - userId: _id + userId: _id, }, body: { - email - } - } + email, + }, + }; // Validate user - await deleteUserParamValidation.validateAsync(decodedTokenCastedAsRequest.body); + await deleteUserParamValidation.validateAsync( + decodedTokenCastedAsRequest.body + ); // Check if the user exists const user = await req.db.getUserByEmail(decodedTokenCastedAsRequest); @@ -297,45 +300,42 @@ const deleteUserController = async (req, res, next) => { } // 1. Find all the monitors associated with the user id - const monitors = await req.db.getMonitorsByUserId(decodedTokenCastedAsRequest); - + const monitors = await req.db.getMonitorsByUserId( + decodedTokenCastedAsRequest + ); + if (monitors) { // 2. Delete jobs associated with each monitor for (const monitor of monitors) { await req.jobQueue.deleteJob(monitor); } - + // 3. Delete all checks associated with each monitor for (const monitor of monitors) { await req.db.deleteChecks(monitor._id); } - + // 4. Delete all alerts associated with each monitor for (const monitor of monitors) { await req.db.deleteAlertByMonitorId(monitor._id); } - + // 5. Delete each monitor await req.db.deleteMonitorsByUserId(user._id); - + // 6. Delete the user by id await req.db.deleteUser(decodedTokenCastedAsRequest); - return res.status(200).json({ success: true, msg: successMessages.AUTH_DELETE_USER, }); - } else { - return res.status(404).json({ success: false, msg: errorMessages.MONITOR_GET_BY_USER_ID, }); - } - } catch (error) { error.service = SERVICE_NAME; next(error); diff --git a/Server/db/MongoDB.js b/Server/db/MongoDB.js index 738708696..1f46b63a6 100644 --- a/Server/db/MongoDB.js +++ b/Server/db/MongoDB.js @@ -8,6 +8,7 @@ const crypto = require("crypto"); const DUPLICATE_KEY_CODE = 11000; // MongoDB error code for duplicate key const { errorMessages, successMessages } = require("../utils/messages"); const { error } = require("console"); +const { GenerateAvatarImage } = require("../utils/imageProcessing"); const connect = async () => { try { await mongoose.connect(process.env.DB_CONNECTION_STRING); @@ -33,12 +34,16 @@ const connect = async () => { const insertUser = async (req, res) => { try { const userData = { ...req.body }; - console.log(req.file); if (req.file) { + // 1. Save the full size image userData.profileImage = { data: req.file.buffer, contentType: req.file.mimetype, }; + + // 2. Get the avatar sized image + const avatar = await GenerateAvatarImage(req.file); + userData.avatarImage = avatar; } const newUser = new UserModel(userData); await newUser.save(); @@ -96,10 +101,15 @@ const updateUser = async (req, res) => { try { const candidateUser = { ...req.body }; if (req.file) { + // 1. Save the full size image candidateUser.profileImage = { data: req.file.buffer, contentType: req.file.mimetype, }; + + // 2. Get the avaatar sized image + const avatar = await GenerateAvatarImage(req.file); + candidateUser.avatarImage = avatar; } const updatedUser = await UserModel.findByIdAndUpdate( @@ -115,7 +125,6 @@ const updateUser = async (req, res) => { } }; - /** * Delete a user by ID * @async @@ -600,5 +609,5 @@ module.exports = { editAlert, deleteAlert, deleteAlertByMonitorId, - deleteMonitorsByUserId + deleteMonitorsByUserId, }; diff --git a/Server/models/user.js b/Server/models/user.js index 3ad3daad7..1a8135e33 100644 --- a/Server/models/user.js +++ b/Server/models/user.js @@ -20,6 +20,9 @@ const UserSchema = mongoose.Schema( type: String, required: true, }, + avatarImage: { + type: String, + }, profileImage: { data: Buffer, contentType: String, diff --git a/Server/package-lock.json b/Server/package-lock.json index ad6637c18..bf83f62ca 100644 --- a/Server/package-lock.json +++ b/Server/package-lock.json @@ -23,6 +23,7 @@ "mongoose": "^8.3.3", "multer": "1.4.5-lts.1", "ping": "0.4.4", + "sharp": "0.33.4", "winston": "^3.13.0" }, "devDependencies": { @@ -47,6 +48,16 @@ "kuler": "^2.0.0" } }, + "node_modules/@emnapi/runtime": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.2.0.tgz", + "integrity": "sha512-bV21/9LQmcQeCPEg3BDFtvwL6cwiTMksYNWQQ4KOxCZikEGalWtenoZ0wCiukJINlGCIi2KXx01g4FoH/LxpzQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, "node_modules/@hapi/hoek": { "version": "9.3.0", "resolved": "https://registry.npmjs.org/@hapi/hoek/-/hoek-9.3.0.tgz", @@ -60,6 +71,456 @@ "@hapi/hoek": "^9.0.0" } }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.33.4", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.33.4.tgz", + "integrity": "sha512-p0suNqXufJs9t3RqLBO6vvrgr5OhgbWp76s5gTRvdmxmuv9E1rcaqGUsl3l4mKVmXPkTkTErXediAui4x+8PSA==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "glibc": ">=2.26", + "node": "^18.17.0 || ^20.3.0 || >=21.0.0", + "npm": ">=9.6.5", + "pnpm": ">=7.1.0", + "yarn": ">=3.2.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.0.2" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.33.4", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.33.4.tgz", + "integrity": "sha512-0l7yRObwtTi82Z6ebVI2PnHT8EB2NxBgpK2MiKJZJ7cz32R4lxd001ecMhzzsZig3Yv9oclvqqdV93jo9hy+Dw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "glibc": ">=2.26", + "node": "^18.17.0 || ^20.3.0 || >=21.0.0", + "npm": ">=9.6.5", + "pnpm": ">=7.1.0", + "yarn": ">=3.2.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.0.2" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.0.2.tgz", + "integrity": "sha512-tcK/41Rq8IKlSaKRCCAuuY3lDJjQnYIW1UXU1kxcEKrfL8WR7N6+rzNoOxoQRJWTAECuKwgAHnPvqXGN8XfkHA==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "macos": ">=11", + "npm": ">=9.6.5", + "pnpm": ">=7.1.0", + "yarn": ">=3.2.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.0.2.tgz", + "integrity": "sha512-Ofw+7oaWa0HiiMiKWqqaZbaYV3/UGL2wAPeLuJTx+9cXpCRdvQhCLG0IH8YGwM0yGWGLpsF4Su9vM1o6aer+Fw==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "macos": ">=10.13", + "npm": ">=9.6.5", + "pnpm": ">=7.1.0", + "yarn": ">=3.2.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.0.2.tgz", + "integrity": "sha512-iLWCvrKgeFoglQxdEwzu1eQV04o8YeYGFXtfWU26Zr2wWT3q3MTzC+QTCO3ZQfWd3doKHT4Pm2kRmLbupT+sZw==", + "cpu": [ + "arm" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "glibc": ">=2.28", + "npm": ">=9.6.5", + "pnpm": ">=7.1.0", + "yarn": ">=3.2.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.0.2.tgz", + "integrity": "sha512-x7kCt3N00ofFmmkkdshwj3vGPCnmiDh7Gwnd4nUwZln2YjqPxV1NlTyZOvoDWdKQVDL911487HOueBvrpflagw==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "glibc": ">=2.26", + "npm": ">=9.6.5", + "pnpm": ">=7.1.0", + "yarn": ">=3.2.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.0.2.tgz", + "integrity": "sha512-cmhQ1J4qVhfmS6szYW7RT+gLJq9dH2i4maq+qyXayUSn9/3iY2ZeWpbAgSpSVbV2E1JUL2Gg7pwnYQ1h8rQIog==", + "cpu": [ + "s390x" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "glibc": ">=2.28", + "npm": ">=9.6.5", + "pnpm": ">=7.1.0", + "yarn": ">=3.2.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.0.2.tgz", + "integrity": "sha512-E441q4Qdb+7yuyiADVi5J+44x8ctlrqn8XgkDTwr4qPJzWkaHwD489iZ4nGDgcuya4iMN3ULV6NwbhRZJ9Z7SQ==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "glibc": ">=2.26", + "npm": ">=9.6.5", + "pnpm": ">=7.1.0", + "yarn": ">=3.2.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.0.2.tgz", + "integrity": "sha512-3CAkndNpYUrlDqkCM5qhksfE+qSIREVpyoeHIU6jd48SJZViAmznoQQLAv4hVXF7xyUB9zf+G++e2v1ABjCbEQ==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "musl": ">=1.2.2", + "npm": ">=9.6.5", + "pnpm": ">=7.1.0", + "yarn": ">=3.2.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.0.2.tgz", + "integrity": "sha512-VI94Q6khIHqHWNOh6LLdm9s2Ry4zdjWJwH56WoiJU7NTeDwyApdZZ8c+SADC8OH98KWNQXnE01UdJ9CSfZvwZw==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "musl": ">=1.2.2", + "npm": ">=9.6.5", + "pnpm": ">=7.1.0", + "yarn": ">=3.2.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.33.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.33.4.tgz", + "integrity": "sha512-RUgBD1c0+gCYZGCCe6mMdTiOFS0Zc/XrN0fYd6hISIKcDUbAW5NtSQW9g/powkrXYm6Vzwd6y+fqmExDuCdHNQ==", + "cpu": [ + "arm" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "glibc": ">=2.28", + "node": "^18.17.0 || ^20.3.0 || >=21.0.0", + "npm": ">=9.6.5", + "pnpm": ">=7.1.0", + "yarn": ">=3.2.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.0.2" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.33.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.33.4.tgz", + "integrity": "sha512-2800clwVg1ZQtxwSoTlHvtm9ObgAax7V6MTAB/hDT945Tfyy3hVkmiHpeLPCKYqYR1Gcmv1uDZ3a4OFwkdBL7Q==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "glibc": ">=2.26", + "node": "^18.17.0 || ^20.3.0 || >=21.0.0", + "npm": ">=9.6.5", + "pnpm": ">=7.1.0", + "yarn": ">=3.2.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.0.2" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.33.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.33.4.tgz", + "integrity": "sha512-h3RAL3siQoyzSoH36tUeS0PDmb5wINKGYzcLB5C6DIiAn2F3udeFAum+gj8IbA/82+8RGCTn7XW8WTFnqag4tQ==", + "cpu": [ + "s390x" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "glibc": ">=2.31", + "node": "^18.17.0 || ^20.3.0 || >=21.0.0", + "npm": ">=9.6.5", + "pnpm": ">=7.1.0", + "yarn": ">=3.2.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.0.2" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.33.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.33.4.tgz", + "integrity": "sha512-GoR++s0XW9DGVi8SUGQ/U4AeIzLdNjHka6jidVwapQ/JebGVQIpi52OdyxCNVRE++n1FCLzjDovJNozif7w/Aw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "glibc": ">=2.26", + "node": "^18.17.0 || ^20.3.0 || >=21.0.0", + "npm": ">=9.6.5", + "pnpm": ">=7.1.0", + "yarn": ">=3.2.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.0.2" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.33.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.33.4.tgz", + "integrity": "sha512-nhr1yC3BlVrKDTl6cO12gTpXMl4ITBUZieehFvMntlCXFzH2bvKG76tBL2Y/OqhupZt81pR7R+Q5YhJxW0rGgQ==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "musl": ">=1.2.2", + "node": "^18.17.0 || ^20.3.0 || >=21.0.0", + "npm": ">=9.6.5", + "pnpm": ">=7.1.0", + "yarn": ">=3.2.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.0.2" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.33.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.33.4.tgz", + "integrity": "sha512-uCPTku0zwqDmZEOi4ILyGdmW76tH7dm8kKlOIV1XC5cLyJ71ENAAqarOHQh0RLfpIpbV5KOpXzdU6XkJtS0daw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "musl": ">=1.2.2", + "node": "^18.17.0 || ^20.3.0 || >=21.0.0", + "npm": ">=9.6.5", + "pnpm": ">=7.1.0", + "yarn": ">=3.2.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.0.2" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.33.4", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.33.4.tgz", + "integrity": "sha512-Bmmauh4sXUsUqkleQahpdNXKvo+wa1V9KhT2pDA4VJGKwnKMJXiSTGphn0gnJrlooda0QxCtXc6RX1XAU6hMnQ==", + "cpu": [ + "wasm32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.1.1" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0", + "npm": ">=9.6.5", + "pnpm": ">=7.1.0", + "yarn": ">=3.2.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.33.4", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.33.4.tgz", + "integrity": "sha512-99SJ91XzUhYHbx7uhK3+9Lf7+LjwMGQZMDlO/E/YVJ7Nc3lyDFZPGhjwiYdctoH2BOzW9+TnfqcaMKt0jHLdqw==", + "cpu": [ + "ia32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0", + "npm": ">=9.6.5", + "pnpm": ">=7.1.0", + "yarn": ">=3.2.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.33.4", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.33.4.tgz", + "integrity": "sha512-3QLocdTRVIrFNye5YocZl+KKpYKP+fksi1QhmOArgx7GyhIbQp/WrJRu176jm8IxromS7RIkzMiMINVdBtC8Aw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0", + "npm": ">=9.6.5", + "pnpm": ">=7.1.0", + "yarn": ">=3.2.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, "node_modules/@ioredis/commands": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/@ioredis/commands/-/commands-1.2.0.tgz", @@ -2385,6 +2846,77 @@ "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" }, + "node_modules/sharp": { + "version": "0.33.4", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.33.4.tgz", + "integrity": "sha512-7i/dt5kGl7qR4gwPRD2biwD2/SvBn3O04J77XKFgL2OnZtQw+AG9wnuS/csmu80nPRHLYE9E41fyEiG8nhH6/Q==", + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "color": "^4.2.3", + "detect-libc": "^2.0.3", + "semver": "^7.6.0" + }, + "engines": { + "libvips": ">=8.15.2", + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.33.4", + "@img/sharp-darwin-x64": "0.33.4", + "@img/sharp-libvips-darwin-arm64": "1.0.2", + "@img/sharp-libvips-darwin-x64": "1.0.2", + "@img/sharp-libvips-linux-arm": "1.0.2", + "@img/sharp-libvips-linux-arm64": "1.0.2", + "@img/sharp-libvips-linux-s390x": "1.0.2", + "@img/sharp-libvips-linux-x64": "1.0.2", + "@img/sharp-libvips-linuxmusl-arm64": "1.0.2", + "@img/sharp-libvips-linuxmusl-x64": "1.0.2", + "@img/sharp-linux-arm": "0.33.4", + "@img/sharp-linux-arm64": "0.33.4", + "@img/sharp-linux-s390x": "0.33.4", + "@img/sharp-linux-x64": "0.33.4", + "@img/sharp-linuxmusl-arm64": "0.33.4", + "@img/sharp-linuxmusl-x64": "0.33.4", + "@img/sharp-wasm32": "0.33.4", + "@img/sharp-win32-ia32": "0.33.4", + "@img/sharp-win32-x64": "0.33.4" + } + }, + "node_modules/sharp/node_modules/color": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/color/-/color-4.2.3.tgz", + "integrity": "sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1", + "color-string": "^1.9.0" + }, + "engines": { + "node": ">=12.5.0" + } + }, + "node_modules/sharp/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/sharp/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT" + }, "node_modules/side-channel": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", diff --git a/Server/package.json b/Server/package.json index 2133afd4d..778a89acf 100644 --- a/Server/package.json +++ b/Server/package.json @@ -25,6 +25,7 @@ "mongoose": "^8.3.3", "multer": "1.4.5-lts.1", "ping": "0.4.4", + "sharp": "0.33.4", "winston": "^3.13.0" }, "devDependencies": { diff --git a/Server/utils/imageProcessing.js b/Server/utils/imageProcessing.js new file mode 100644 index 000000000..59793004f --- /dev/null +++ b/Server/utils/imageProcessing.js @@ -0,0 +1,27 @@ +const sharp = require("sharp"); +/** + * Generates a 64 * 64 pixel image from a given image + * @param {} file + */ +const GenerateAvatarImage = async (file) => { + try { + // Resize to target 64 * 64 + let resizedImageBuffer = await sharp(file.buffer) + .resize({ + width: 64, + height: 64, + fit: "cover", + }) + .toBuffer(); + + //Get b64 string + const base64Image = resizedImageBuffer.toString("base64"); + return base64Image; + } catch (error) { + throw error; + } +}; + +module.exports = { + GenerateAvatarImage, +}; From 475f7c69aed7779c10f7aba6c61b24868a64c6f6 Mon Sep 17 00:00:00 2001 From: Daniel Cojocea Date: Mon, 8 Jul 2024 13:42:45 -0400 Subject: [PATCH 21/31] Styling changes --- .../Charts/Servers/serverStatus.css | 2 +- Client/src/Components/MonitorTable/index.css | 69 +++++++++++++++---- Client/src/Components/MonitorTable/index.jsx | 20 ++++-- Client/src/Pages/Monitors/index.css | 3 +- Client/src/Pages/Monitors/index.jsx | 11 ++- Client/src/Pages/Monitors/monitors.css | 15 ++-- Client/src/assets/icons/open-in-new-page.svg | 3 + 7 files changed, 97 insertions(+), 26 deletions(-) create mode 100644 Client/src/assets/icons/open-in-new-page.svg diff --git a/Client/src/Components/Charts/Servers/serverStatus.css b/Client/src/Components/Charts/Servers/serverStatus.css index 541019107..97a4fec3f 100644 --- a/Client/src/Components/Charts/Servers/serverStatus.css +++ b/Client/src/Components/Charts/Servers/serverStatus.css @@ -12,7 +12,7 @@ } .server-status-tile { - min-width: 310px; + min-width: 250px; width: calc(100% - 310px); padding: var(--spacing-general-1); border: 1px solid var(--color-border-0); diff --git a/Client/src/Components/MonitorTable/index.css b/Client/src/Components/MonitorTable/index.css index 23b463f87..f2d24252e 100644 --- a/Client/src/Components/MonitorTable/index.css +++ b/Client/src/Components/MonitorTable/index.css @@ -3,30 +3,32 @@ align-items: center; } -.host-open-icon { +.host-row a { width: var(--env-var-img-width-2); height: var(--env-var-img-width-2); - margin-right: 8px; + color: var(--env-var-color-5); + margin-right: 10px; + margin-bottom: 2px; +} +.host-row a svg { + width: var(--env-var-font-size-large); + height: var(--env-var-font-size-large); +} +.host-row .host-percentage { + font-size: var(--env-var-font-size-small); } .host-name { - width: 100px; - font-size: var(--env-var-font-size-medium); - font-weight: bold; - margin-right: var(--env-var-spacing-1); + width: fit-content; + margin-right: 10px; + font-weight: 700; text-overflow: ellipsis; overflow: hidden; white-space: nowrap; } -.host-percentage { - font-size: var(--env-var-font-size-medium); -} - .host-status { - display: flex; - align-items: center; - height: 100%; + width: fit-content; } .host-status-details { @@ -47,3 +49,44 @@ border-radius: 50%; margin-right: calc(var(--env-var-spacing-1) / 2); } + +.monitors .MuiPaper-root:has(table.MuiTable-root) { + box-shadow: none; + border: solid 1px var(--env-var-color-16); + border-radius: var(--env-var-radius-1); +} +.monitors .MuiTableFooter-root .MuiTableCell-root { + border: none; +} +.monitors .MuiTableHead-root, +.monitors .MuiTableRow-root:hover { + background-color: var(--env-var-color-13); +} +.monitors .MuiTableHead-root .MuiTableCell-root, +.monitors .MuiTableBody-root .MuiTableCell-root { + font-size: var(--env-var-font-size-medium); +} +.monitors .MuiTableHead-root .MuiTableCell-root { + padding: var(--env-var-spacing-1) var(--env-var-spacing-2); + font-weight: 500; + color: var(--env-var-color-2); +} +.monitors .MuiTableHead-root span { + position: relative; + display: inline-block; + height: 14px; + width: 20px; + overflow: hidden; + margin-bottom: -3px; + margin-left: 2px; +} +.monitors .MuiTableHead-root span svg { + position: absolute; + width: 20px; + height: 20px; + bottom: 0; +} +.monitors .MuiTableBody-root .MuiTableCell-root { + color: var(--env-var-color-5); + padding: 6px var(--env-var-spacing-2); +} diff --git a/Client/src/Components/MonitorTable/index.jsx b/Client/src/Components/MonitorTable/index.jsx index 763a66c95..db1d90630 100644 --- a/Client/src/Components/MonitorTable/index.jsx +++ b/Client/src/Components/MonitorTable/index.jsx @@ -14,6 +14,8 @@ import { TablePagination, Paper, } from "@mui/material"; +import SouthRoundedIcon from "@mui/icons-material/SouthRounded"; +import OpenInNewPage from "../../assets/icons/open-in-new-page.svg?react" /** * Host component. @@ -31,7 +33,7 @@ const Host = ({ params }) => { return (
- OpenIt +
{params.title}
{ className="host-status-dot" style={{ backgroundColor: params.statusDotColor }} /> - {params.status} + + {params.status} +
); @@ -142,9 +149,14 @@ const MonitorTable = ({ monitors = [] }) => { Host - Status + + Status + + + + Response Time - Action + Actions {mappedRows} diff --git a/Client/src/Pages/Monitors/index.css b/Client/src/Pages/Monitors/index.css index 987bbd7cd..a21a3e125 100644 --- a/Client/src/Pages/Monitors/index.css +++ b/Client/src/Pages/Monitors/index.css @@ -1,7 +1,6 @@ .monitors, .new-monitor { width: 70vw; - padding: 4vw; } .monitors { @@ -9,13 +8,13 @@ } .monitors-bar { - margin-top: calc(2 * var(--env-var-spacing-2)); display: flex; justify-content: space-between; align-items: center; } .monitors-bar-title { + color: var(--env-var-color-1); font-size: 24px; font-weight: 700; } diff --git a/Client/src/Pages/Monitors/index.jsx b/Client/src/Pages/Monitors/index.jsx index a895ae47a..241ca4b10 100644 --- a/Client/src/Pages/Monitors/index.jsx +++ b/Client/src/Pages/Monitors/index.jsx @@ -8,8 +8,10 @@ import Button from "../../Components/Button"; import ServerStatus from "../../Components/Charts/Servers/ServerStatus"; import SearchTextField from "../../Components/TextFields/Search/SearchTextField"; import MonitorTable from "../../Components/MonitorTable"; +import { useTheme } from "@emotion/react"; const Monitors = () => { + const theme = useTheme(); const navigate = useNavigate(); const monitorState = useSelector((state) => state.monitors); const authState = useSelector((state) => state.auth); @@ -25,7 +27,12 @@ const Monitors = () => { const down = monitorState.monitors.length - up; return ( -
+
Hello, {authState.user.firstname} @@ -36,7 +43,7 @@ const Monitors = () => { onClick={() => { navigate("/monitors/create"); }} - sx={{ padding: "10px 20px", fontSize: "13px" }} + sx={{ padding: "6px 25px", fontSize: "13px" }} />
diff --git a/Client/src/Pages/Monitors/monitors.css b/Client/src/Pages/Monitors/monitors.css index 3a442aa42..05ae79709 100644 --- a/Client/src/Pages/Monitors/monitors.css +++ b/Client/src/Pages/Monitors/monitors.css @@ -7,6 +7,7 @@ .current-monitors-title-holder { display: flex; + align-items: center; } .current-monitors-bar { @@ -18,16 +19,22 @@ font-size: 1rem; font-weight: bold; margin-right: var(--env-var-spacing-1); + color: var(--env-var-color-1); } .current-monitors-counter { - width: var(--env-var-spacing-2); - height: var(--env-var-spacing-2); + display: inline-flex; + justify-content: center; + align-items: center; + padding: 2px; + min-width: 22px; + min-height: 22px; background-color: var(--env-var-color-15); border: 1px solid var(--env-var-color-6); border-radius: 50%; - text-align: center; - align-items: center; + font-size: var(--env-var-font-size-medium); + font-weight: 500; + color: var(--env-var-color-5); } .monitors-v-gaping { diff --git a/Client/src/assets/icons/open-in-new-page.svg b/Client/src/assets/icons/open-in-new-page.svg new file mode 100644 index 000000000..2bcb21c43 --- /dev/null +++ b/Client/src/assets/icons/open-in-new-page.svg @@ -0,0 +1,3 @@ + + + From 4668728cbefb42430df3b78fdea0869a008aba89 Mon Sep 17 00:00:00 2001 From: Daniel Cojocea Date: Mon, 8 Jul 2024 14:05:21 -0400 Subject: [PATCH 22/31] Fixed conflict --- Client/src/Pages/Demo/Demo.jsx | 4 ---- 1 file changed, 4 deletions(-) diff --git a/Client/src/Pages/Demo/Demo.jsx b/Client/src/Pages/Demo/Demo.jsx index 2aa9041d1..1df70651b 100644 --- a/Client/src/Pages/Demo/Demo.jsx +++ b/Client/src/Pages/Demo/Demo.jsx @@ -426,10 +426,6 @@ const Demo = () => { } label="image.jpg" size="2 MB" /> - - - -
); }; From 31e4c7b1107ce82fb12ff28a2721de1f516b60cb Mon Sep 17 00:00:00 2001 From: Daniel Cojocea Date: Mon, 8 Jul 2024 16:06:12 -0400 Subject: [PATCH 23/31] Fixed avatar image not displaying --- Client/src/Components/Avatar/index.jsx | 27 +++++-------------- .../TabPanels/Account/ProfilePanel.jsx | 2 -- Client/src/Features/Auth/authSlice.js | 2 +- 3 files changed, 7 insertions(+), 24 deletions(-) diff --git a/Client/src/Components/Avatar/index.jsx b/Client/src/Components/Avatar/index.jsx index ffe2934c6..99a6c1542 100644 --- a/Client/src/Components/Avatar/index.jsx +++ b/Client/src/Components/Avatar/index.jsx @@ -23,33 +23,18 @@ const Avatar = ({ src, small, sx }) => { const border = small ? 1 : 3; const [image, setImage] = useState(); - // useEffect(() => { - // const fetchData = async () => { - // try { - // if (user.profileImage.data && user.profileImage.contentType) { - // const url = await bufferToUrl(user.profileImage); - // setImage(url); - // } - // } catch (error) { - // console.error("Error converting buffer to URL: ", error); - // } - // }; - - // fetchData(); - // }, [user]); + useEffect(() => { + if (user.avatarImage) { + setImage(`data:image/png;base64,${user.avatarImage}`); + } + }, [user?.avatarImage]); return ( { // Resets picture-related states and clears interval const removePicture = () => { errors["picture"] && clearError("picture"); - setFile({ src: "placeholder" }); clearInterval(intervalRef.current); // interrupt interval if image upload is canceled prior to completing the process setProgress({ value: 0, isLoading: false }); }; @@ -154,7 +153,6 @@ const ProfilePanel = () => { // Removes current profile image from UI const handleDeletePicture = () => { - setFile({ src: "placeholder" }); // TODO - implement delete picture function }; diff --git a/Client/src/Features/Auth/authSlice.js b/Client/src/Features/Auth/authSlice.js index bfb2dfd27..bec0f3035 100644 --- a/Client/src/Features/Auth/authSlice.js +++ b/Client/src/Features/Auth/authSlice.js @@ -48,7 +48,7 @@ export const update = createAsyncThunk( await new Promise((resolve) => setTimeout(resolve, 1500)); const fd = new FormData(); - const imageResult = await axios.get(form.file); + const imageResult = await axios.get(form.file, { responseType: "blob" }); fd.append("firstname", form.firstname); fd.append("lastname", form.lastname); fd.append("profileImage", imageResult.data); From b94d1021c2926cb48218afb901188ee93b8266f3 Mon Sep 17 00:00:00 2001 From: Daniel Cojocea Date: Mon, 8 Jul 2024 16:26:08 -0400 Subject: [PATCH 24/31] Removed unused functions & fixed warning --- Client/src/Components/Avatar/index.jsx | 6 +++--- Client/src/Utils/fileUtils.js | 22 +--------------------- 2 files changed, 4 insertions(+), 24 deletions(-) diff --git a/Client/src/Components/Avatar/index.jsx b/Client/src/Components/Avatar/index.jsx index 99a6c1542..151914061 100644 --- a/Client/src/Components/Avatar/index.jsx +++ b/Client/src/Components/Avatar/index.jsx @@ -2,7 +2,6 @@ import { Avatar as MuiAvatar } from "@mui/material"; import PropTypes from "prop-types"; import { useSelector } from "react-redux"; import { useEffect, useState } from "react"; -import { bufferTo64, bufferToUrl } from "../../Utils/fileUtils"; /** * @component @@ -32,7 +31,6 @@ const Avatar = ({ src, small, sx }) => { return ( { ...style, ...sx, }} - /> + > + {user.firstname?.charAt(0)}{user.lastname?.charAt(0)} + ); }; diff --git a/Client/src/Utils/fileUtils.js b/Client/src/Utils/fileUtils.js index 7e33ba6b1..699832b47 100644 --- a/Client/src/Utils/fileUtils.js +++ b/Client/src/Utils/fileUtils.js @@ -8,24 +8,4 @@ export const checkImage = (url) => { const img = new Image(); img.src = url; return img.naturalWidth !== 0; -}; - -export const bufferTo64 = (bufferData) => { - const uint8Array = new Uint8Array(bufferData.data); - const blob = new Blob([uint8Array], { type: bufferData.contentType }); - return new Promise((resolve) => { - const reader = new FileReader(); - reader.onloadend = () => { - resolve(reader.result); - }; - reader.readAsDataURL(blob); - }); -}; - -export const bufferToUrl = (buffer) => { - console.log(buffer); - const blob = new Blob([buffer.data], { type: buffer.contentType }); - const url = URL.createObjectURL(blob); - - return url; -}; +}; \ No newline at end of file From f42facdea005089d64e19aabda021e022d83dcde Mon Sep 17 00:00:00 2001 From: Daniel Cojocea Date: Mon, 8 Jul 2024 19:51:21 -0400 Subject: [PATCH 25/31] Changed pagination to reflect Figma design --- Client/src/Components/MonitorTable/index.css | 55 ++++++++++-- Client/src/Components/MonitorTable/index.jsx | 92 +++++++++++--------- 2 files changed, 98 insertions(+), 49 deletions(-) diff --git a/Client/src/Components/MonitorTable/index.css b/Client/src/Components/MonitorTable/index.css index f2d24252e..360526fc4 100644 --- a/Client/src/Components/MonitorTable/index.css +++ b/Client/src/Components/MonitorTable/index.css @@ -55,7 +55,7 @@ border: solid 1px var(--env-var-color-16); border-radius: var(--env-var-radius-1); } -.monitors .MuiTableFooter-root .MuiTableCell-root { +.monitors .MuiTableBody-root .MuiTableRow-root:last-child .MuiTableCell-root { border: none; } .monitors .MuiTableHead-root, @@ -72,21 +72,64 @@ color: var(--env-var-color-2); } .monitors .MuiTableHead-root span { - position: relative; display: inline-block; - height: 14px; + height: 17px; width: 20px; overflow: hidden; - margin-bottom: -3px; + margin-bottom: -2px; margin-left: 2px; } .monitors .MuiTableHead-root span svg { - position: absolute; width: 20px; height: 20px; - bottom: 0; } .monitors .MuiTableBody-root .MuiTableCell-root { color: var(--env-var-color-5); padding: 6px var(--env-var-spacing-2); } + +.monitors .MuiPagination-root { + flex: 1; + margin-top: 35px; + border: solid 1px var(--env-var-color-16); + border-radius: var(--env-var-radius-1); + padding: var(--env-var-spacing-1-plus) var(--env-var-spacing-2); +} +.monitors .MuiPagination-root ul { + justify-content: center; +} +.monitors .MuiPagination-root ul li button { + font-size: var(--env-var-font-size-medium); + color: var(--env-var-color-5); + font-weight: 500; +} +.monitors .MuiPagination-root ul li:first-child { + margin-right: auto; +} +.monitors .MuiPagination-root ul li:last-child { + margin-left: auto; +} +.monitors .MuiPagination-root ul li:first-child button, +.monitors .MuiPagination-root ul li:last-child button { + border: solid 1px var(--env-var-color-16); + border-radius: var(--env-var-radius-1); +} +.monitors .MuiPagination-root ul li:first-child button { + padding: 0 var(--env-var-spacing-1) 0 var(--env-var-spacing-1-plus); +} +.monitors .MuiPagination-root ul li:last-child button { + padding: 0 var(--env-var-spacing-1-plus) 0 var(--env-var-spacing-1); +} +.monitors .MuiPagination-root ul li:first-child button::after, +.monitors .MuiPagination-root ul li:last-child button::before { + position: relative; + display: inline-block; +} +.monitors .MuiPagination-root ul li:first-child button::after { + content: "Previous"; + margin-left: 15px; +} +.monitors .MuiPagination-root ul li:last-child button::before { + content: "Next"; + margin-right: 15px; +} diff --git a/Client/src/Components/MonitorTable/index.jsx b/Client/src/Components/MonitorTable/index.jsx index db1d90630..bf24fe8b3 100644 --- a/Client/src/Components/MonitorTable/index.jsx +++ b/Client/src/Components/MonitorTable/index.jsx @@ -1,7 +1,6 @@ import "./index.css"; import { useState } from "react"; import PropTypes from "prop-types"; -import OpenIt from "../../assets/Images/Icon-open-in-tab-gray.png"; import ResponseTimeChart from "../Charts/ResponseTimeChart"; import { Table, @@ -10,12 +9,14 @@ import { TableContainer, TableHead, TableRow, - TableFooter, - TablePagination, Paper, + Pagination, + PaginationItem, } from "@mui/material"; -import SouthRoundedIcon from "@mui/icons-material/SouthRounded"; -import OpenInNewPage from "../../assets/icons/open-in-new-page.svg?react" +import ArrowDownwardRoundedIcon from "@mui/icons-material/ArrowDownwardRounded"; +import OpenInNewPage from "../../assets/icons/open-in-new-page.svg?react"; +import ArrowBackRoundedIcon from "@mui/icons-material/ArrowBackRounded"; +import ArrowForwardRoundedIcon from "@mui/icons-material/ArrowForwardRounded"; /** * Host component. @@ -93,20 +94,15 @@ const Status = ({ params }) => { * @returns {React.Component} Returns a table with the monitor data. */ const MonitorTable = ({ monitors = [] }) => { - const [page, setPage] = useState(0); - const [rowsPerPage, setRowsPerPage] = useState(5); + const [page, setPage] = useState(1); + const rowsPerPage = 5; const handleChangePage = (event, newPage) => { setPage(newPage); }; - const handleChangeRowsPerPage = (event) => { - setRowsPerPage(parseInt(event.target.value, 10)); - setPage(0); - }; - const mappedRows = monitors - .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) + .slice((page - 1) * rowsPerPage, page * rowsPerPage) .map((monitor) => { const params = { url: monitor.url, @@ -144,36 +140,46 @@ const MonitorTable = ({ monitors = [] }) => { }); return ( - - - - - Host - - Status - - - - - Response Time - Actions - - - {mappedRows} - - - - - -
-
+ <> + + + + + Host + + Status + + + + + Response Time + Actions + + + {mappedRows} +
+
+ ( + + )} + /> + ); }; From 30f7ecff82a6a40403ef44e212e8a52f97664044 Mon Sep 17 00:00:00 2001 From: Daniel Cojocea Date: Mon, 8 Jul 2024 20:03:27 -0400 Subject: [PATCH 26/31] Fixed gap issue & added search svg --- Client/src/Components/TextFields/Search/SearchTextField.jsx | 4 ++-- Client/src/Pages/Monitors/index.jsx | 1 - Client/src/assets/icons/search.svg | 3 +++ 3 files changed, 5 insertions(+), 3 deletions(-) create mode 100644 Client/src/assets/icons/search.svg diff --git a/Client/src/Components/TextFields/Search/SearchTextField.jsx b/Client/src/Components/TextFields/Search/SearchTextField.jsx index 934a19943..7f7264faa 100644 --- a/Client/src/Components/TextFields/Search/SearchTextField.jsx +++ b/Client/src/Components/TextFields/Search/SearchTextField.jsx @@ -1,11 +1,11 @@ import "./searchTextField.css"; import React from "react"; -import Search from "../../../assets/Images/Icon-search-gray.png"; +import SearchSvg from "../../../assets/icons/search.svg?react"; const SearchTextField = () => { return (
- Search +
); diff --git a/Client/src/Pages/Monitors/index.jsx b/Client/src/Pages/Monitors/index.jsx index 241ca4b10..a8f30623f 100644 --- a/Client/src/Pages/Monitors/index.jsx +++ b/Client/src/Pages/Monitors/index.jsx @@ -67,7 +67,6 @@ const Monitors = () => {
-
); diff --git a/Client/src/assets/icons/search.svg b/Client/src/assets/icons/search.svg new file mode 100644 index 000000000..a1bc74224 --- /dev/null +++ b/Client/src/assets/icons/search.svg @@ -0,0 +1,3 @@ + + + From 44465efd25e5d94f2bf694568342be72789a73a1 Mon Sep 17 00:00:00 2001 From: Daniel Cojocea Date: Tue, 9 Jul 2024 01:40:45 -0400 Subject: [PATCH 27/31] Added offset fix --- Client/src/Components/MonitorTable/index.jsx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Client/src/Components/MonitorTable/index.jsx b/Client/src/Components/MonitorTable/index.jsx index bf24fe8b3..977c6e918 100644 --- a/Client/src/Components/MonitorTable/index.jsx +++ b/Client/src/Components/MonitorTable/index.jsx @@ -94,7 +94,7 @@ const Status = ({ params }) => { * @returns {React.Component} Returns a table with the monitor data. */ const MonitorTable = ({ monitors = [] }) => { - const [page, setPage] = useState(1); + const [page, setPage] = useState(0); const rowsPerPage = 5; const handleChangePage = (event, newPage) => { @@ -102,7 +102,7 @@ const MonitorTable = ({ monitors = [] }) => { }; const mappedRows = monitors - .slice((page - 1) * rowsPerPage, page * rowsPerPage) + .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) .map((monitor) => { const params = { url: monitor.url, @@ -161,8 +161,8 @@ const MonitorTable = ({ monitors = [] }) => { handleChangePage(event, value - 1)} shape="rounded" renderItem={(item) => ( Date: Tue, 9 Jul 2024 10:23:22 -0700 Subject: [PATCH 28/31] Added delete image profile functionality to update user --- Server/controllers/authController.js | 5 +++++ Server/db/MongoDB.js | 15 +++++++++++++-- Server/utils/utils.js | 17 +++++++++++++++++ Server/validation/joi.js | 3 ++- 4 files changed, 37 insertions(+), 3 deletions(-) create mode 100644 Server/utils/utils.js diff --git a/Server/controllers/authController.js b/Server/controllers/authController.js index b64b7f764..e06c58eb9 100644 --- a/Server/controllers/authController.js +++ b/Server/controllers/authController.js @@ -108,9 +108,13 @@ const loginController = async (req, res, next) => { // Remove password from user object. Should this be abstracted to DB layer? const userWithoutPassword = { ...user._doc }; delete userWithoutPassword.password; + delete userWithoutPassword.avatarImage; // Happy path, return token const token = issueToken(userWithoutPassword); + // reset avatar image + userWithoutPassword.avatarImage = user.avatarImage; + return res.status(200).json({ success: true, msg: successMessages.AUTH_LOGIN_USER, @@ -135,6 +139,7 @@ const userEditController = async (req, res, next) => { return; } + // TODO is this neccessary any longer? Verify ownership middleware should handle this if (req.params.userId !== req.user._id.toString()) { const error = new Error(errorMessages.AUTH_UNAUTHORIZED); error.status = 401; diff --git a/Server/db/MongoDB.js b/Server/db/MongoDB.js index 1f46b63a6..4c9e19095 100644 --- a/Server/db/MongoDB.js +++ b/Server/db/MongoDB.js @@ -7,8 +7,8 @@ const RecoveryToken = require("../models/RecoveryToken"); const crypto = require("crypto"); const DUPLICATE_KEY_CODE = 11000; // MongoDB error code for duplicate key const { errorMessages, successMessages } = require("../utils/messages"); -const { error } = require("console"); const { GenerateAvatarImage } = require("../utils/imageProcessing"); +const { ParseBoolean } = require("../utils/utils"); const connect = async () => { try { await mongoose.connect(process.env.DB_CONNECTION_STRING); @@ -100,7 +100,14 @@ const updateUser = async (req, res) => { try { const candidateUser = { ...req.body }; - if (req.file) { + // ****************************************** + // Handle profile image + // ****************************************** + + if (ParseBoolean(candidateUser.deleteProfileImage) === true) { + candidateUser.profileImage = null; + candidateUser.avatarImage = null; + } else if (req.file) { // 1. Save the full size image candidateUser.profileImage = { data: req.file.buffer, @@ -112,6 +119,10 @@ const updateUser = async (req, res) => { candidateUser.avatarImage = avatar; } + // ****************************************** + // End handling profile image + // ****************************************** + const updatedUser = await UserModel.findByIdAndUpdate( candidateUserId, candidateUser, diff --git a/Server/utils/utils.js b/Server/utils/utils.js new file mode 100644 index 000000000..8893623b6 --- /dev/null +++ b/Server/utils/utils.js @@ -0,0 +1,17 @@ +/** + * Converts a request body parameter to a boolean. + * @param {string | boolean} value + * @returns {boolean} + */ +const ParseBoolean = (value) => { + if (value === true || value === "true") { + return true; + } else if (value === false || value === "false") { + return false; + } + throw new Error("Invalid boolean value"); +}; + +module.exports = { + ParseBoolean, +}; diff --git a/Server/validation/joi.js b/Server/validation/joi.js index 8864fb8bd..28973f2cf 100644 --- a/Server/validation/joi.js +++ b/Server/validation/joi.js @@ -26,6 +26,7 @@ const editUserBodyValidation = joi.object({ firstname: joi.string(), lastname: joi.string(), profileImage: joi.any(), + deleteProfileImage: joi.boolean(), role: joi.string(), }); @@ -165,5 +166,5 @@ module.exports = { createCheckBodyValidation, getChecksParamValidation, deleteChecksParamValidation, - deleteUserParamValidation + deleteUserParamValidation, }; From f2fc5bd984ecdd0769bc549afae509df41f6f709 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Tue, 9 Jul 2024 10:28:41 -0700 Subject: [PATCH 29/31] Changed parse boolean functionality to allow for undefined" --- Server/utils/utils.js | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Server/utils/utils.js b/Server/utils/utils.js index 8893623b6..f4aa5da62 100644 --- a/Server/utils/utils.js +++ b/Server/utils/utils.js @@ -6,10 +6,8 @@ const ParseBoolean = (value) => { if (value === true || value === "true") { return true; - } else if (value === false || value === "false") { - return false; } - throw new Error("Invalid boolean value"); + return false; }; module.exports = { From 15b7383c611359da6cc0e2af8868bc74ec3d81fa Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Tue, 9 Jul 2024 10:29:11 -0700 Subject: [PATCH 30/31] Changed ParseBoolean functionality to allow for undefined and null --- Server/utils/utils.js | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Server/utils/utils.js b/Server/utils/utils.js index f4aa5da62..934c99492 100644 --- a/Server/utils/utils.js +++ b/Server/utils/utils.js @@ -6,8 +6,14 @@ const ParseBoolean = (value) => { if (value === true || value === "true") { return true; + } else if ( + value === false || + value === "false" || + value === null || + value === undefined + ) { + return false; } - return false; }; module.exports = { From 10c8751c6ba464837b2f2d93dd0c1b0395d4cec3 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Tue, 9 Jul 2024 11:45:14 -0700 Subject: [PATCH 31/31] Added configured axios instance with 401 interceptor, refactored all requests to use axios instance --- Client/src/Features/Auth/authSlice.js | 13 ++++----- Client/src/Features/Monitors/monitorsSlice.js | 23 ++++++---------- Client/src/Pages/ForgotPassword/index.jsx | 6 ++--- Client/src/Pages/Login/index.jsx | 8 +++--- Client/src/Pages/Register/index.jsx | 9 +++---- Client/src/Pages/SetNewPassword/index.jsx | 7 +++-- Client/src/Utils/axiosConfig.js | 27 +++++++++++++++++++ Client/src/main.jsx | 3 +++ 8 files changed, 56 insertions(+), 40 deletions(-) create mode 100644 Client/src/Utils/axiosConfig.js diff --git a/Client/src/Features/Auth/authSlice.js b/Client/src/Features/Auth/authSlice.js index bec0f3035..bc75e53f7 100644 --- a/Client/src/Features/Auth/authSlice.js +++ b/Client/src/Features/Auth/authSlice.js @@ -1,7 +1,6 @@ -import axios from "axios"; +import axiosInstance from "../../Utils/axiosConfig"; import { createAsyncThunk, createSlice } from "@reduxjs/toolkit"; import { jwtDecode } from "jwt-decode"; -const BASE_URL = import.meta.env.VITE_APP_API_BASE_URL; const initialState = { isLoading: false, @@ -15,7 +14,7 @@ export const register = createAsyncThunk( "auth/register", async (form, thunkApi) => { try { - const res = await axios.post(`${BASE_URL}/auth/register`, form); + const res = await axiosInstance.post("/auth/register", form); return res.data; } catch (error) { if (error.response.data) { @@ -28,7 +27,7 @@ export const register = createAsyncThunk( export const login = createAsyncThunk("auth/login", async (form, thunkApi) => { try { - const res = await axios.post(`${BASE_URL}/auth/login`, form); + const res = await axiosInstance.post(`/auth/login`, form); return res.data; } catch (error) { if (error.response && error.response.data) { @@ -48,12 +47,14 @@ export const update = createAsyncThunk( await new Promise((resolve) => setTimeout(resolve, 1500)); const fd = new FormData(); - const imageResult = await axios.get(form.file, { responseType: "blob" }); + const imageResult = await axiosInstance.get(form.file, { + responseType: "blob", + }); fd.append("firstname", form.firstname); fd.append("lastname", form.lastname); fd.append("profileImage", imageResult.data); - const res = await axios.post(`${BASE_URL}/auth/user/${user._id}`, fd, { + const res = await axiosInstance.post(`/auth/user/${user._id}`, fd, { headers: { Authorization: `Bearer ${token}`, "Content-Type": "multipart/form-data", diff --git a/Client/src/Features/Monitors/monitorsSlice.js b/Client/src/Features/Monitors/monitorsSlice.js index c2a4ad044..d5c257021 100644 --- a/Client/src/Features/Monitors/monitorsSlice.js +++ b/Client/src/Features/Monitors/monitorsSlice.js @@ -1,8 +1,6 @@ -import axios from "axios"; import { createAsyncThunk, createSlice } from "@reduxjs/toolkit"; import { jwtDecode } from "jwt-decode"; -const BASE_URL = import.meta.env.VITE_APP_API_BASE_URL; - +import axiosInstance from "../../Utils/axiosConfig"; const initialState = { isLoading: false, monitors: [], @@ -16,7 +14,7 @@ export const createMonitor = createAsyncThunk( try { const { authToken, monitor } = data; - const res = await axios.post(`${BASE_URL}/monitors`, monitor, { + const res = await axiosInstance.post(`/monitors`, monitor, { headers: { Authorization: `Bearer ${authToken}`, "Content-Type": "application/json", @@ -36,9 +34,7 @@ export const getMonitors = createAsyncThunk( "monitors/getMonitors", async (token, thunkApi) => { try { - const res = await axios.get( - import.meta.env.VITE_APP_API_BASE_URL + "/monitors" - ); + const res = await axiosInstance.get("/monitors"); return res.data; } catch (error) { if (error.response && error.response.data) { @@ -54,14 +50,11 @@ export const getMonitorsByUserId = createAsyncThunk( async (token, thunkApi) => { const user = jwtDecode(token); try { - const res = await axios.get( - import.meta.env.VITE_APP_API_BASE_URL + "/monitors/user/" + user._id, - { - headers: { - Authorization: `Bearer ${token}`, - }, - } - ); + const res = await axiosInstance.get("/monitors/user/" + user._id, { + headers: { + Authorization: `Bearer ${token}`, + }, + }); return res.data; } catch (error) { if (error.response && error.response.data) { diff --git a/Client/src/Pages/ForgotPassword/index.jsx b/Client/src/Pages/ForgotPassword/index.jsx index c5dbb0de3..5012b9d67 100644 --- a/Client/src/Pages/ForgotPassword/index.jsx +++ b/Client/src/Pages/ForgotPassword/index.jsx @@ -7,11 +7,9 @@ import Button from "../../Components/Button"; import LeftArrow from "../../assets/Images/arrow-left.png"; import { useState, useEffect } from "react"; import { recoveryValidation } from "../../Validation/validation"; -import axios from "axios"; +import axiosInstance from "../../Utils/axiosConfig"; import { useNavigate } from "react-router-dom"; -const BASE_URL = import.meta.env.VITE_APP_API_BASE_URL; - const ForgotPassword = () => { const navigate = useNavigate(); @@ -50,7 +48,7 @@ const ForgotPassword = () => { if (error !== undefined) { throw error; } - await axios.post(`${BASE_URL}/auth/recovery/request`, form); + await axiosInstance.post(`/auth/recovery/request`, form); navigate("/check-email"); } catch (error) { //TODO display error (Toast?) diff --git a/Client/src/Pages/Login/index.jsx b/Client/src/Pages/Login/index.jsx index 4beb4d2c8..a9fcde0d5 100644 --- a/Client/src/Pages/Login/index.jsx +++ b/Client/src/Pages/Login/index.jsx @@ -9,12 +9,10 @@ import CheckBox from "../../Components/Checkbox/Checkbox"; import Button from "../../Components/Button"; import Google from "../../assets/Images/Google.png"; import PasswordTextField from "../../Components/TextFields/Password/PasswordTextField"; - +import axiosInstance from "../../Utils/axiosConfig"; import { loginValidation } from "../../Validation/validation"; import { login } from "../../Features/Auth/authSlice"; import { useDispatch } from "react-redux"; -import axios from "axios"; -const BASE_URL = import.meta.env.VITE_APP_API_BASE_URL; const Login = () => { const dispatch = useDispatch(); @@ -33,8 +31,8 @@ const Login = () => { }); useEffect(() => { - axios - .get(BASE_URL + "/auth/users/admin") + axiosInstance + .get("/auth/users/admin") .then((response) => { if (response.data.data === false) { navigate("/register"); diff --git a/Client/src/Pages/Register/index.jsx b/Client/src/Pages/Register/index.jsx index 1760a5be2..617e04edd 100644 --- a/Client/src/Pages/Register/index.jsx +++ b/Client/src/Pages/Register/index.jsx @@ -11,12 +11,9 @@ import Check from "../../Components/Check/Check"; import Button from "../../Components/Button"; import Google from "../../assets/Images/Google.png"; import { registerValidation } from "../../Validation/validation"; - +import axiosInstance from "../../Utils/axiosConfig"; import { useDispatch } from "react-redux"; import { register } from "../../Features/Auth/authSlice"; -import axios from "axios"; - -const BASE_URL = import.meta.env.VITE_APP_API_BASE_URL; const Register = () => { const dispatch = useDispatch(); @@ -41,8 +38,8 @@ const Register = () => { }); useEffect(() => { - axios - .get(BASE_URL + "/auth/users/admin") + axiosInstance + .get("/auth/users/admin") .then((response) => { if (response.data.data === true) { navigate("/login"); diff --git a/Client/src/Pages/SetNewPassword/index.jsx b/Client/src/Pages/SetNewPassword/index.jsx index d2360c7c5..d0b4242ee 100644 --- a/Client/src/Pages/SetNewPassword/index.jsx +++ b/Client/src/Pages/SetNewPassword/index.jsx @@ -8,8 +8,7 @@ import LeftArrow from "../../assets/Images/arrow-left.png"; import { useParams } from "react-router-dom"; import { useState, useEffect } from "react"; import { newPasswordValidation } from "../../Validation/validation"; -import axios from "axios"; -const BASE_URL = import.meta.env.VITE_APP_API_BASE_URL; +import axiosInstance from "../../Utils/axiosConfig"; import { useNavigate } from "react-router-dom"; const SetNewPassword = () => { @@ -33,10 +32,10 @@ const SetNewPassword = () => { // TODO show loading spinner setIsLoading(true); try { - await axios.post(`${BASE_URL}/auth/recovery/validate`, { + await axiosInstance.post("/auth/recovery/validate", { recoveryToken: token, }); - await axios.post(`${BASE_URL}/auth/recovery/reset`, { + await axiosInstance.post("/auth/recovery/reset", { ...form, recoveryToken: token, }); diff --git a/Client/src/Utils/axiosConfig.js b/Client/src/Utils/axiosConfig.js new file mode 100644 index 000000000..8d3040028 --- /dev/null +++ b/Client/src/Utils/axiosConfig.js @@ -0,0 +1,27 @@ +import axios from "axios"; +import { clearAuthState } from "../Features/Auth/authSlice"; +const BASE_URL = import.meta.env.VITE_APP_API_BASE_URL; + +let store; + +export const injectStore = (s) => { + store = s; +}; + +const axiosInstance = axios.create({ + baseURL: BASE_URL, +}); + +axiosInstance.interceptors.response.use( + (response) => response, + (error) => { + console.error(error); + if (error.response && error.response.status === 401) { + console.log("Invalid token revoked"); + store.dispatch(clearAuthState()); + } + return Promise.reject(error); + } +); + +export default axiosInstance; diff --git a/Client/src/main.jsx b/Client/src/main.jsx index 601dab68d..09754147d 100644 --- a/Client/src/main.jsx +++ b/Client/src/main.jsx @@ -8,6 +8,9 @@ import { ThemeProvider } from "@mui/material"; import { Provider } from "react-redux"; import { persistor, store } from "./store"; import { PersistGate } from "redux-persist/integration/react"; +import { injectStore } from "./Utils/axiosConfig.js"; + +injectStore(store); ReactDOM.createRoot(document.getElementById("root")).render(