Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update functionality for Admin profile #931

Merged
merged 8 commits into from
May 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions backend/app/models/Admin.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ const adminSchema = new Schema(
trim: true,
unique: true,
},
image: {
type: String,
trim: true,
},
},
{ timestamps: { createdAt: 'createdAt', updatedAt: 'updatedAt' } }
);
Expand Down
1 change: 1 addition & 0 deletions backend/app/routes/admin/getAdmins.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const getAdminsAggregate = (match, page) => {
email: 1,
contact: 1,
isSuperAdmin: 1,
image:1
},
},
{ $skip: constants.PAGINATION_LIMIT.GET_ADMINS * (Number(page) - 1) },
Expand Down
17 changes: 15 additions & 2 deletions backend/app/routes/admin/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
const router = require('express').Router({ mergeParams: true });
const multer = require('multer');
const { nanoid } = require('nanoid');
const path = require('path');
const validationMiddleware = require('../../../helpers/middlewares/validation');
const { authMiddleware } = require('../../../helpers/middlewares/auth');

const {
postSuperAdminSchema,
getAdminsSchema,
Expand All @@ -23,6 +25,17 @@
const updateAdmin = require('./updateAdmin');
const deleteAdmin = require('./deleteAdmin');



const store = multer.diskStorage({
destination: 'uploads/Admin/',
filename: (req, file, cb) => {
const uniqueFilename = nanoid() + path.extname(file.originalname);
cb(null, uniqueFilename);
},
});
const upload = multer({ storage: store });

router.get('/', validationMiddleware(getAdminsSchema, 'query'), authMiddleware, getAdmins);
router.get('/createSuperAdmin', createSuperAdmin);

Expand All @@ -33,7 +46,7 @@
router.post('/resetpassword/:token', validationMiddleware(resetPasswordSchema), resetPassword);

router.put('/password', validationMiddleware(passwordChangeSchema), authMiddleware, changePassword);
router.put('/:id/:token', validationMiddleware(updateAdminSchema), updateAdmin);
router.put('/:id/:token', validationMiddleware(updateAdminSchema),upload.single('image') ,updateAdmin);

Check failure

Code scanning / CodeQL

Missing rate limiting High

This route handler performs
a database access
, but is not rate-limited.
This route handler performs
a file system access
, but is not rate-limited.
This route handler performs
a file system access
, but is not rate-limited.
This route handler performs
a database access
, but is not rate-limited.

router.delete('/deleteAdmin', validationMiddleware(deleteAdminSchema), authMiddleware, deleteAdmin);

Expand Down
42 changes: 33 additions & 9 deletions backend/app/routes/admin/updateAdmin.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,42 @@
const Admin = require('../../models/Admin');
const fs = require('fs');
const path = require('path');

module.exports =async (req, res) => {
const admin = await Admin.findById(req.params.id);

if (!admin) {
return res.status(404).json({ error: 'Admin not found' });
}

// Delete previous image if it exists
if (admin.image && admin.image!=="undefined" && req.file?.path) {
if (fs.existsSync(path.join(__dirname,'..' ,'..','..', admin.image))) {
fs.unlinkSync(path.join(__dirname,'..' ,'..','..', admin.image));
}
}

try {
const updatedAdmin = await Admin.findByIdAndUpdate(
req.params.id,
{
$set: req.body,
},
{ new: true }
);
res.status(200).json(updatedAdmin);
const updateFields = {
firstName:req.body.firstName,
lastName:req.body.lastName,
contact:req.body.contact,
username:req.body.username
};
if (req.file?.path) {
updateFields.image = req.file.path;
}else{
updateFields.image = admin.image;
}
const updatedAdmin = await Admin.findByIdAndUpdate(
req.params.id,
{ $set: updateFields },
Fixed Show fixed Hide fixed
{ new: true }
);
return res.status(200).json({"Req.Body":updateFields,"updatedDoc":updatedAdmin});
} catch (err) {
res.status(500).json(err);
return res.status(500).json(err);
}

res.send('Done');
Kajol-Kumari marked this conversation as resolved.
Show resolved Hide resolved
};
23 changes: 17 additions & 6 deletions frontend/src/pages/Admin/Admin.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,13 @@ export const Admin = (props) => {
const toggleNav = () => setIsMenuOpen(!isMenuOpen);
const closeMobileMenu = () => setIsMenuOpen(false);
const dispatch = useDispatch();
const firstName = localStorage.getItem("firstName");
const [update,setUpdate]=useState(true);
const [qId,setQId] = useState("")
const [adminData, setAdminData] = useState({});
const [image,setImage]=useState('./images/admin.png');
const FetchAdminData = async () => {
try {
const baseUrl = `${END_POINT}/admin`;
const baseUrl = `${END_POINT}/admin/`;
const params = {
type: "self",
email: localStorage.getItem("email"),
Expand All @@ -47,8 +48,18 @@ export const Admin = (props) => {
"Content-Type": "application/json",
Authorization: `Bearer ${localStorage.getItem("token")}`,
};
// Make the GET request using Axios

const response = await axios.get(baseUrl, { params, headers });
let formattedPath = response.data[0].image?.replace(/\\/g, "/");
if (formattedPath?.startsWith("uploads/")) {
formattedPath = formattedPath.replace("uploads/", "");
if (formattedPath && formattedPath !=="undefined") {
formattedPath = `${END_POINT}/${formattedPath}`;
}
}
if(formattedPath!=="undefined" && formattedPath){
setImage(formattedPath);
}
setAdminData(response.data[0]);
} catch (error) {
console.error("There was a problem with the fetch operation:", error);
Expand All @@ -68,15 +79,15 @@ export const Admin = (props) => {
logout(dispatch);
}
return true;
}, [dispatch]);
}, [dispatch,update]);

return (
<div style={{ minHeight: "100vh" }}>
<div className={style["dashing"]}>
<div className={style["left"]}>
<div className={style["welcome-section"]} onClick={() => setTab(0)}>
<img
src="./images/admin.png"
src={image}
className={style["img-admin"]}
alt="admin_img"
/>
Expand Down Expand Up @@ -212,7 +223,7 @@ export const Admin = (props) => {
</div>
<div className={style["right"]}>
{tab === 0 ? (
<Profile adminData={adminData} />
<Profile adminData={{...adminData,image}} update={()=>{setUpdate(!update)}} />
) : tab === 1 ? (
<Dashboard setTab={setTab} />
) : tab === 2 ? (
Expand Down
Loading
Loading