diff --git a/app.js b/app.js index e445617..b2a7b39 100644 --- a/app.js +++ b/app.js @@ -44,12 +44,12 @@ app.use(express.static(path.join(__dirname, 'uploads'))); app.use(cors()); // Require APIs -const userRoutes = require('./src/routes/auth.route'); -const eventRoutes = require('./src/routes/event.route'); +const authRoutes = require('./src/routes/auth.route'); +const userRoutes = require('./src/routes/user.route'); // local APIs +app.use('/v1/api', authRoutes); app.use('/v1/api', userRoutes); -app.use('/v1/api', eventRoutes); // API for uploads file (photo, galleries) app.get('/uploads/:id', (req, res) => { diff --git a/src/controllers/event.controller.js b/src/controllers/event.controller.js deleted file mode 100644 index 8c6f727..0000000 --- a/src/controllers/event.controller.js +++ /dev/null @@ -1,317 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* Dependencies */ -/* -------------------------------------------------------------------------- */ -// Packages -const fs = require('fs'); -const { default: mongoose } = require('mongoose'); - -// Models -const Event = require('../models/event.model'); - -// helpers -const { getfilteredArrayOfObject, firebaseAdmin } = require('../utils/helpers'); - -/* -------------------------------------------------------------------------- */ -/* Events Controller */ -/* -------------------------------------------------------------------------- */ - -/** - * Create a new event - * @param {Object} req - The request object - * @param {Object} res - The response object - */ -const createEvent = async (req, res) => { - let newEvent = new Event(); - // in common - newEvent.gallery = - req.files?.gallery === undefined - ? [] - : req.files?.gallery.map((g) => g.path.replace('\\', '/')); - newEvent.photo = - req.files?.photo === undefined - ? '' - : (req.files?.photo[0].path).replace('\\', '/'); - newEvent.link = req.body.link; - newEvent.isEvent = req.body.isEvent; - newEvent.start_at = req.body.start_at; - newEvent.end_at = req.body.end_at; - newEvent.coordinates.latitude = req.body.latitude; - newEvent.coordinates.longitude = req.body.longitude; - newEvent.createdAt = new Date(); - // for arabic language - newEvent.ar.event_name = req.body.event_name_ar; - newEvent.ar.description = req.body.description_ar; - newEvent.ar.event_location = req.body.event_location_ar; - // for french language - newEvent.fr.event_name = req.body.event_name_fr; - newEvent.fr.description = req.body.description_fr; - newEvent.fr.event_location = req.body.event_location_fr; - - await newEvent - .save() - .then((data) => { - // send notificaiton - var message = { - notification: { - title: `${ - data.isEvent === true - ? 'Un événement a été ajouté' - : 'Une actualité a été ajoutée' - }`, - body: data.fr.event_name, - }, - // data must only contain string values - data: { - type: data.isEvent === true ? 'event' : 'news', - title: data.fr.event_name, - body: data.fr.description, - eventId: `${data._id}`, - }, - topic: 'event', - }; - // Send a message to devices subscribed to the provided topic. - firebaseAdmin - .messaging() - .send(message) - .then((response) => { - // Response is a message ID string. - console.log('Notification envoyé avec succès :', response); - }) - .catch((error) => { - console.log("Erreur lors de l'envoi de la notification :", error); - }); - - // response - res.status(200).json({ - status: true, - message: 'Nouvelle evenement créée avec succès', - HelpRequest: newEvent, - }); - }) - .catch((error) => { - res.status(500).json({ - success: false, - message: error.message, - }); - }); -}; - -/** - * Retrieves all events - * @param {Object} res - The response object - */ -const getAllEvents = async (req, res) => { - try { - let lang = req.headers.lang; - // Return events depending on the selected language (arabic or french) - let events = await Event.aggregate([ - { - $project: - lang !== undefined - ? lang === 'ar' - ? { fr: 0 } - : { ar: 0 } - : { __v: 0 }, - }, - ]).exec(); - - const eventsSortByDate = events?.sort((a, b) => b.createdAt - a.createdAt); - - res.json({ - success: true, - events: lang - ? getfilteredArrayOfObject(eventsSortByDate, lang) - : eventsSortByDate, - }); - } catch (error) { - res.status(500).json({ - success: false, - message: error.message, - }); - } -}; - -/** - * Retrieves an event by ID - * @param {Object} req - The request object - * @param {Object} res - The response object - */ -const getEventById = async (req, res) => { - try { - let lang = req.headers.lang; - - // Return event depending on the selected language (arabic or french) - let event = await Event.aggregate([ - { $match: { _id: mongoose.Types.ObjectId(req.params.id) } }, - { - $project: - lang !== undefined - ? lang === 'ar' - ? { fr: 0 } - : { ar: 0 } - : { __v: 0 }, - }, - ]).exec(); - res.json({ - success: true, - event: lang ? getfilteredArrayOfObject(event, lang)[0] : event[0], - }); - } catch (error) { - res.status(500).json({ - success: false, - message: error.message, - }); - } -}; - -/** - * Update an event by ID - * @param {Object} req - The request object - * @param {Object} res - The response object - */ -const updateEvent = async (req, res) => { - try { - let CurrentEvent = await Event.findOne({ _id: req.params.id }); - - const updateImages = {}; - - if (req.files?.photo) { - // delete photo - // check if we got files object - if (req.files?.photo !== undefined) { - // check if the user didn't have photo - if (CurrentEvent.photo !== '') { - fs.unlinkSync(`${CurrentEvent.photo}`); - } - } - // then update - updateImages.photo = (req.files?.photo[0].path).replace('\\', '/'); - } - - if (req.files?.gallery) { - // delete gallery - // check if we got files object - if (CurrentEvent.gallery != '' || CurrentEvent.gallery.length > 1) { - // check if the request didn't gallery images - CurrentEvent.gallery.map((gr) => { - try { - try { - fs.unlinkSync(`${gr}`); - } catch (error) { - console.log(error); - } - } catch (error) { - console.log(error); - } - }); - } - // then update - updateImages.gallery = req.files?.gallery.map((g) => - g.path.replace('\\', '/'), - ); - } - - let event = await Event.findOneAndUpdate( - { _id: req.params.id }, - { - $set: { - // in common - ...updateImages, - start_at: req.body.start_at - ? req.body.start_at - : CurrentEvent.start_at, - isEvent: req.body.isEvent ? req.body.isEvent : CurrentEvent.isEvent, - end_at: req.body.end_at ? req.body.end_at : CurrentEvent.end_at, - link: req.body.link ?? req.body.link, - 'coordinates.latitude': req.body.latitude - ? req.body.latitude - : CurrentEvent.coordinates.latitude, - 'coordinates.longitude': req.body.longitude - ? req.body.longitude - : CurrentEvent.coordinates.longitude, - // for arabic language - 'ar.event_name': req.body.event_name_ar - ? req.body.event_name_ar - : CurrentEvent.ar.event_name, - 'ar.description': req.body.description_ar - ? req.body.description_ar - : CurrentEvent.ar.description, - 'ar.event_location': req.body.event_location_ar - ? req.body.event_location_ar - : CurrentEvent.ar.event_location, - // for french language - 'fr.event_name': req.body.event_name_fr - ? req.body.event_name_fr - : CurrentEvent.fr.event_name, - 'fr.description': req.body.description_fr - ? req.body.description_fr - : CurrentEvent.fr.description, - 'fr.event_location': req.body.event_location_fr - ? req.body.event_location_fr - : CurrentEvent.fr.event_location, - }, - }, - { new: true }, - ); - - res.status(200).json({ - success: true, - message: "L'article a bien été mis à jour", - updatedEvent: event, - }); - } catch (error) { - res.status(500).json({ - success: false, - message: error.message, - }); - } -}; - -/** - * Delete an event by ID - * @param {Object} req - The request object - * @param {Object} res - The response object - */ -const deleteEvent = async (req, res) => { - try { - let imagesToDelete = await Event.findOne({ _id: req.params.id }); - if (imagesToDelete.photo !== '') { - fs.unlinkSync(`${imagesToDelete.photo}`); - } - - // delete gallery - if (imagesToDelete.gallery != '' || imagesToDelete.gallery > 1) { - imagesToDelete.gallery.map((gr) => { - try { - fs.unlinkSync(`${gr}`); - } catch (error) { - console.log(error); - } - }); - } - - // Delete Event object - let deletedEvent = await Event.findOneAndDelete({ _id: req.params.id }); - - if (deletedEvent) { - res.status(200).json({ - status: true, - message: 'Article supprimé avec succès', - }); - } - } catch (error) { - res.status(500).json({ - success: false, - message: error.message, - }); - } -}; - -// export module -module.exports = { - createEvent, - getAllEvents, - getEventById, - updateEvent, - deleteEvent, -}; diff --git a/src/controllers/user.controller.js b/src/controllers/user.controller.js new file mode 100644 index 0000000..2364b20 --- /dev/null +++ b/src/controllers/user.controller.js @@ -0,0 +1,139 @@ +/* -------------------------------------------------------------------------- */ +/* Dependencies */ +/* -------------------------------------------------------------------------- */ +const fs = require('fs'); +const User = require('../models/user.model'); + +/* -------------------------------------------------------------------------- */ +/* User Controller */ +/* -------------------------------------------------------------------------- */ + +/** + * Check if the email exists in the database + * @param {Object} req - The request object + * @param {Object} res - The response object + */ +const checkExistEmail = async (req, res) => { + try { + const foundUser = await User.findOne({ email: req.body.email }); + const message = foundUser ? 'Email existe déjà' : ''; + res.status(foundUser ? 403 : 200).json({ success: !foundUser, message }); + } catch (error) { + res.status(500).json({ success: false, message: error.message }); + } +}; + +/** + * Retrieves the current user object + * @param {Object} req - The request object + * @param {Object} res - The response object + */ +const getCurrentUser = async (req, res) => { + try { + const foundUser = await User.findById(req.decoded._id); + res + .status(foundUser ? 200 : 404) + .json({ success: !!foundUser, user: foundUser }); + } catch (error) { + res.status(500).json({ success: false, message: error.message }); + } +}; + +/** + * Retrieves a user by ID + * @param {Object} req - The request object + * @param {Object} res - The response object + */ +const getUserById = async (req, res) => { + try { + const foundUser = await User.findById(req.params.id); + res + .status(foundUser ? 200 : 404) + .json({ success: !!foundUser, user: foundUser }); + } catch (error) { + res.status(500).json({ success: false, message: error.message }); + } +}; + +/** + * Update a user by ID + * @param {Object} req - The request object + * @param {Object} res - The response object + */ +const updateUserById = async (req, res) => { + try { + const { id } = req.params; + let foundUser = await User.findById(id); + + const updateImages = {}; + if (req.files?.photo) { + if (foundUser.photo !== '') fs.unlinkSync(foundUser.photo); + updateImages.photo = req.files.photo[0].path.replace('\\', '/'); + } + + const updatedUser = await User.findByIdAndUpdate( + id, + { + ...updateImages, + ...req.body, + updated_at: Date.now(), + }, + { new: true }, + ); + + res.status(updatedUser ? 200 : 404).json({ + success: !!updatedUser, + message: updatedUser + ? "Mise à jour réussie de l'utilisateur" + : 'Utilisateur non trouvé', + updatedUser, + }); + } catch (error) { + res.status(500).json({ success: false, message: error.message }); + } +}; + +/** + * Retrieves all users + * @param {Object} req - The request object + * @param {Object} res - The response object + */ +const getAllUsers = async (req, res) => { + try { + const users = await User.find(); + res.status(200).json({ success: true, users }); + } catch (error) { + res.status(500).json({ success: false, message: error.message }); + } +}; + +/** + * Deletes a user by ID + * @param {Object} req - The request object + * @param {Object} res - The response object + */ +const deleteUser = async (req, res) => { + try { + const { id } = req.params; + const user = await User.findById(id); + if (user.photo !== '') fs.unlinkSync(user.photo); + const deletedUser = await User.findByIdAndDelete(id); + res.status(deletedUser ? 200 : 404).json({ + success: !!deletedUser, + message: deletedUser + ? "L'utilisateur a été supprimée avec succès" + : 'Utilisateur non trouvé', + }); + } catch (error) { + res.status(500).json({ success: false, message: error.message }); + } +}; + +module.exports = { + checkExistEmail, + getCurrentUser, + getUserById, + updateUserById, + getAllUsers, + deleteUser, +}; diff --git a/src/models/event.model.js b/src/models/event.model.js deleted file mode 100644 index 5c25ec8..0000000 --- a/src/models/event.model.js +++ /dev/null @@ -1,43 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* Dependencies */ -/* -------------------------------------------------------------------------- */ -const mongoose = require('mongoose'); -const Schema = mongoose.Schema; - -/* -------------------------------------------------------------------------- */ -/* Event Schema */ -/* -------------------------------------------------------------------------- */ -const EventSchema = new Schema( - { - gallery: [String], - photo: String, - title: { type: String, required: true }, - description: { - type: String, - required: true, - }, - date: { - type: Date, - required: true, - }, - location: { - type: String, - required: true, - }, - attendees: [ - { - type: mongoose.Schema.Types.ObjectId, - ref: 'User', - }, - ], - creator: { - type: mongoose.Schema.Types.ObjectId, - ref: 'User', - required: true, - }, - }, - { timestamps: true }, -); - -// export Event Schema -module.exports = mongoose.model('Event', EventSchema); diff --git a/src/routes/event.route.js b/src/routes/event.route.js deleted file mode 100644 index 94becda..0000000 --- a/src/routes/event.route.js +++ /dev/null @@ -1,33 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* Dependencies */ -/* -------------------------------------------------------------------------- */ -// Packages -const router = require('express').Router(); - -// Middlewares -const { fileUpload } = require('../middlewares/multer'); -const verifyToken = require('../middlewares/verify-token'); - -// controllers -const eventController = require('../controllers/event.controller'); - -/* -------------------------------------------------------------------------- */ -/* Event Route */ -/* -------------------------------------------------------------------------- */ - -// POST request - create a new event -router.post('/event', fileUpload, verifyToken, eventController.createEvent); - -// GET request - get all events -router.get('/events', eventController.getAllEvents); - -// GET request - get a single event -router.get('/events/:id', eventController.getEventById); - -// PUT request - Update a single event -router.put('/events/:id', fileUpload, verifyToken, eventController.updateEvent); - -// DELETE request - delete a single event -router.delete('/events/:id', verifyToken, eventController.deleteEvent); - -module.exports = router; diff --git a/src/routes/user.route.js b/src/routes/user.route.js new file mode 100644 index 0000000..b2c1daf --- /dev/null +++ b/src/routes/user.route.js @@ -0,0 +1,41 @@ +/* -------------------------------------------------------------------------- */ +/* Dependencies */ +/* -------------------------------------------------------------------------- */ +// Packages +const router = require('express').Router(); + +// Middlewares +const verifyToken = require('../middlewares/verify-token'); +const { fileUpload } = require('../middlewares/multer'); + +// controllers +const userController = require('../controllers/user.controller'); + +/* -------------------------------------------------------------------------- */ +/* User Route */ +/* -------------------------------------------------------------------------- */ + +// Get reqyest - check if email exist or not +router.post('/users/check-email', userController.checkExistEmail); + +// GET request - Get all users +router.get('/users', verifyToken, userController.getAllUsers); + +// GET request - Get current user +router.get('/users/me', verifyToken, userController.getCurrentUser); + +// GET request - Get usser by Id +router.get('/users/:id', userController.getUserById); + +// PUT request - Update user by id +router.put( + '/users/:id', + verifyToken, + fileUpload, + userController.updateUserById, +); + +// DELETE request - delete user +router.delete('/users/:id', verifyToken, userController.deleteUser); + +module.exports = router;