Skip to content
Open
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
2 changes: 1 addition & 1 deletion admin/css/adminPanel.css
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ main {
}

/* bg color for input */
#name, #date, #description, #time {
#name, #date, #description, #timeInput {
background-color: #595959;
color: white;
}
6 changes: 3 additions & 3 deletions admin/html/admin.html
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,14 @@ <h1 class="title">Admin Panel</h1>
<option value="create">Create New Event</option>
<option value="edit">Edit Event</option>
</select>
<div id="create">
<div id="create" class="hidden">
<form class="form" id="event_form" action="/admin/submit" method="post" enctype="multipart/form-data">
<label>Event Title</label>
<input type="text" id="name" name="name" placeholder="Event Name">
<label>Event Date</label>
<input type="date" id="date" name="date" placeholder="Event Date">
<label>Event Time</label>
<input type="time" id="time" name="time" placeholder="Event Time">
<input type="time" id="timeInput" name="time" placeholder="Event Time">
<label>Event Description</label>
<textarea id="description" name="description" placeholder="Description"></textarea>
<label>Event Image</label>
Expand Down Expand Up @@ -53,7 +53,7 @@ <h1>Are you sure you want to delete this event?</h1>
Do you still want to proceed?
</p>
<div id="confirmButtons">
<button id="yesBtn">Yes</button>
<button id="yesBtn" onclick = "delEvent()">Yes</button>
<button id="noBtn" onclick="closeModal('delete')">No</button>
</div>
</div>
Expand Down
51 changes: 47 additions & 4 deletions admin/js/editScript.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,64 @@ let deleteModal = document.getElementById('deleteModal');
// Set up span elements for edit and delete modals
let editSpan = document.getElementById("editClose");
let deleteSpan = document.getElementById("deleteClose");
let currentEventId = null;
let currentEventName = null;
let currentEventDelId = null;


// Function to open the modals
function openModal(modalType) {
function openModal(modalType, elementName, elementDelId) {
if(modalType === 'edit') {
console.log("Edit Button clicked!");

editModal.style.display = "block";
} else if(modalType === 'delete') {
} else if (modalType === 'delete') {
console.log("Delete button clicked!");
console.log(elementName);
currentEventName = elementName;
currentEventDelId = elementDelId;
deleteModal.style.display = "block";
}
}


function delEvent() {
if (!currentEventName) {
console.error('No event ID to delete.');
return;
}

console.log(currentEventName);
fetch(`http://localhost:3000/admin/delete?eventName=${currentEventName}`, {
method: 'DELETE',
})
.then((res) => {
if (res.ok) {
// Remove the event card from UI
const eventCard = document.getElementById(currentEventDelId);
if (eventCard) {
eventCard.remove();
}
closeModal('delete');
} else {
throw 'Failed to delete event';
}
})
.catch((error) => {
console.error('Error deleting event:', error);
alert('Failed to delete event. Please try again.');
})
.finally(() => {
currentEventId = null; // Reset the currentEventId after deletion
});
}

// Function to close the modals
function closeModal(modalType) {
if(modalType === 'edit') {
editModal.style.display = "none";
} else if (modalType === 'delete') {
deleteModal.style.display = "none";
currentEventId = null;
}
}

Expand Down Expand Up @@ -67,6 +106,10 @@ function toggleDiv() {
}
}

window.onload = () => {
document.addEventListener('DOMContentLoaded', function() {
toggleDiv();
});

window.onload = function() {
toggleDiv();
}
25 changes: 20 additions & 5 deletions admin/js/eventParse.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ window.onload = displayEvents();
let editContainer = document.getElementById('itemContainer');

function displayEvents() {

fetch('api/fetch/events').then((res) => { return res.json() }).then((data) => {
data.message.forEach(element => {
addElement(element);
Expand All @@ -20,21 +21,35 @@ function searchElement() {
});
}

function randNum(max) {
return Math.floor(Math.random() * max) + 1;
}

function addElement(element) {
let time = convertTime(element.time);
let id = randNum(100000);
let container = `
<div class="editItem">
<img src="/js/acm.jpg" alt="acm" height="100" class="editImage" />
<div class="editItem" id="${id}">
<img src="http://localhost:3000/api/fetch/images/${element.imageName}" alt="acm" height="100" class="editImage" />
<div class="editText">
<h2>${element.name}</h2>
<p>${element.description}</p>
<p><b>${element.date}</b></p>
<button class="editBtn" onclick="openModal('edit')" >Edit</button>
<button class="editBtn deleteBtn" onclick="openModal('delete')" >Delete</button>
<p><b>${element.date}</b> at <b>${time}</b></p>
<button class="editBtn" onclick="openModal('edit', '${element.name}', '${id}')" >Edit</button>
<button class="editBtn deleteBtn" onclick="openModal('delete', '${element.name}', '${id}')" >Delete</button>
</div>
</div>
`;
editContainer.innerHTML += container;
}

function convertTime(time24) {
const [hours, minutes] = time24.split(':').map(Number);
const period = hours < 12 ? 'AM' : 'PM';
const hours12 = hours % 12 || 12;

return `${hours12}:${minutes.toString().padStart(2, '0')} ${period}`;
}

const search = document.getElementById('search');
search.addEventListener('input', searchElement);
4 changes: 3 additions & 1 deletion admin/js/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@ function submitEvent(e) {
let name = document.getElementById("name").value.trim();
let date = document.getElementById("date").value;
let description = document.getElementById("description").value.trim();
let time = document.getElementById("timeInput").value;
let imageInput = document.getElementById("image");
let imageFile = imageInput.files[0]; // Get the selected image file

// Check for empty fields
if (!name || !date || !description) {
if (!name || !date || !description || !time) {
alert("Please fill out all fields before submitting!");
return;
}
Expand All @@ -21,6 +22,7 @@ function submitEvent(e) {
formData.append("name", name);
formData.append("date", date);
formData.append("description", description);
formData.append("time", time);
formData.append("image", imageFile);

alert("Event Added!");
Expand Down
37 changes: 26 additions & 11 deletions controllers/adminController.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const mongo_utils = require('../utils/mongo_utils');
const path = require('path');


// Stuff for gridfsbucket, also set up multer as to use req.file.originalname
const multer = require("multer");
const { GridFSBucket, ObjectID } = require('mongodb');
Expand Down Expand Up @@ -35,7 +36,7 @@ exports.login = async (req,res)=>{
// Encrypt cookie
const auth = cookieCrypt.encrypt((new Date()).toString());
// Set cookie
res.cookie('auth',auth,{httpOnly:true});
res.cookie('auth', auth, { httpOnly: true });

return res.redirect('/admin');
}
Expand All @@ -47,9 +48,10 @@ exports.create = async (req, res)=>{
const name = req.body.name.trim();
const date = req.body.date;
const desc = req.body.description.trim();
const time = req.body.time;
const imageName = req.file.originalname;

if (!req.body.name || !req.body.date || !req.body.description) {
if (!req.body.name || !req.body.date || !req.body.description || !req.body.time) {
res.status(400).redirect("/admin");
return;
}
Expand All @@ -58,6 +60,7 @@ exports.create = async (req, res)=>{
name:name,
date:date,
description:desc,
time:time,
imageName: imageName
};

Expand Down Expand Up @@ -86,27 +89,39 @@ exports.create = async (req, res)=>{

// Delete event by name
exports.deleteEvent = async (req,res)=>{
const eventName = req.query.name; // Specify the name of the event to delete

console.log(`Deleting event with name: ${eventName}`);
const eventName = req.query.eventName; // Specify the name of the event to delete
const currentEventImgName = req.query.imgName;
// console.log(req.query.eventName);
// console.log(req.query.imgName);
// console.log(`Deleting event with name: ${eventName}`);

try {
const db = mongo_utils.get_client().db();

const imgCollection = db.collection('images.files')
const imgId = await imgCollection.findOne({filename : currentEventImgName});
const imgResult = await imgCollection.deleteOne({ filename : currentEventImgName });

const chunksCollection = db.collection('images.chunks')
const chunksResult = await chunksCollection.deleteMany({ files_id : imgId._id });

const collection = db.collection('events');
const result = await collection.deleteOne({ name : eventName });

// Delete the event by name
const result = await collection.deleteOne({ name: eventName });
console.log(result);
console.log(imgResult);
console.log(chunksResult);

if (result.deletedCount === 1) {
// Event successfully deleted
if (result.deletedCount >= 1 && imgResult.deletedCount >= 1 && chunksResult.deletedCount >= 1){
res.status(200).json({ message: 'Event deleted successfully' });
return;
} else {
// Event not found
res.status(404).json({ message: 'Event not found' });
res.status(404).json({ message: ':(' });
return;
}
} catch (err) {
// Error handling
res.status(500).json({ message: err.message });
return;
}
}
3 changes: 2 additions & 1 deletion controllers/apiController.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ exports.fetchEvent = async(req, res)=>{
const getName = req.query.name;
const getType = req.query.type;
const getDate = req.query.date;


const query = {};
if(getName) {
Expand All @@ -25,7 +26,7 @@ exports.fetchEvent = async(req, res)=>{
const db = mongo_utils.get_client().db();
const collection = db.collection('events');

const result = await collection.find(query, { projection: { _id : 0 } }).toArray();
const result = await collection.find(query).toArray();

res.send({
message: result,
Expand Down
24 changes: 24 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"mongodb": "^6.5.0",
"mongoose": "^7.6.2",
"multer": "^1.4.5-lts.1",
"nodeman": "^1.1.2",
"nodemon": "^3.1.0"
},
"devDependencies": {
Expand Down
8 changes: 4 additions & 4 deletions routes/adminRouter.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const express = require("express");
const router = express.Router();
const { cookieAuthCheck } = require("../utils/secureCookie.js");
const { render, create, deleteEvent,login,loginRender } = require('../controllers/adminController.js');
const { render, create, deleteEvent, login, loginRender } = require('../controllers/adminController.js');
const bodyParser = require("body-parser");
const file_utils = require("../utils/file_utils.js");

Expand All @@ -10,9 +10,9 @@ console.log(__dirname);

router.use('/submit', file_utils.upload.single('image'));

router.get('/', cookieAuthCheck,render);
router.get('/login',loginRender)
router.post('/login',login)
router.get('/', cookieAuthCheck, render);
router.get('/login', loginRender)
router.post('/login', login)
router.post('/submit', cookieAuthCheck, create);
router.post('/delete', /*cookieAuthCheck,*/ deleteEvent);

Expand Down
14 changes: 7 additions & 7 deletions routes/rootRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ const router = express.Router();
const routes = require('../controllers/rootController');


router.get('/',routes.homePage);
router.get('/workshops',routes.workshopPage);
router.get('/', routes.homePage);
router.get('/workshops', routes.workshopPage);
router.get('/events', routes.eventPage);
router.get('/calendar',routes.calenderPage);
router.get('/important-links',routes.importantLinkPage);
router.get('/leadership',routes.leadershipPage);
router.get('/merchandise',routes.merchandisePage);
router.get('/projects',routes.projectPage);
router.get('/calendar', routes.calenderPage);
router.get('/important-links', routes.importantLinkPage);
router.get('/leadership', routes.leadershipPage);
router.get('/merchandise', routes.merchandisePage);
router.get('/projects', routes.projectPage);

module.exports = router;