|
| 1 | +// backend/middlewares/isEventContact.js |
| 2 | +const { Event } = require("../models/schema"); |
| 3 | + |
| 4 | +module.exports = async function isEventContact(req, res, next) { |
| 5 | + console.log("🚀 isEventContact MIDDLEWARE CALLED"); |
| 6 | + console.log("req.params:", req.params); |
| 7 | + console.log("req.user:", req.user); |
| 8 | + |
| 9 | + try { |
| 10 | + const eventId = req.params.eventId || req.params.id || req.body.eventId; |
| 11 | + console.log("Extracted eventId:", eventId); |
| 12 | + |
| 13 | + if (!eventId) { |
| 14 | + console.log("❌ No eventId found"); |
| 15 | + return res.status(400).json({ message: "Missing event id parameter" }); |
| 16 | + } |
| 17 | + |
| 18 | + const event = await Event.findById(eventId).populate("organizing_unit_id"); |
| 19 | + console.log("Event found:", event ? "YES" : "NO"); |
| 20 | + |
| 21 | + if (!event) { |
| 22 | + console.log("❌ Event not found in database"); |
| 23 | + return res.status(404).json({ message: "Event not found" }); |
| 24 | + } |
| 25 | + |
| 26 | + const unit = event.organizing_unit_id; |
| 27 | + console.log("Unit populated:", unit); |
| 28 | + |
| 29 | + const unitEmail = String( |
| 30 | + (unit && unit.contact_info && unit.contact_info.email) || "", |
| 31 | + ) |
| 32 | + .trim() |
| 33 | + .toLowerCase(); |
| 34 | + |
| 35 | + const userEmail = String( |
| 36 | + (req.user && |
| 37 | + (req.user.username || |
| 38 | + (req.user.personal_info && req.user.personal_info.email))) || |
| 39 | + "", |
| 40 | + ) |
| 41 | + .trim() |
| 42 | + .toLowerCase(); |
| 43 | + |
| 44 | + console.log("=== EMAIL COMPARISON ==="); |
| 45 | + console.log("Unit Email:", unitEmail); |
| 46 | + console.log("User Email:", userEmail); |
| 47 | + console.log("Match:", unitEmail === userEmail); |
| 48 | + console.log("========================"); |
| 49 | + |
| 50 | + if (!unitEmail) { |
| 51 | + console.log("❌ No unit email found"); |
| 52 | + return res |
| 53 | + .status(404) |
| 54 | + .json({ message: "Organizing unit contact email not found" }); |
| 55 | + } |
| 56 | + |
| 57 | + if (unitEmail && userEmail && unitEmail === userEmail) { |
| 58 | + console.log("✅ Access granted - user is unit contact"); |
| 59 | + req.isUnitContact = true; |
| 60 | + return next(); |
| 61 | + } |
| 62 | + |
| 63 | + console.log("❌ Access denied - user is NOT unit contact"); |
| 64 | + return res.status(403).json({ message: "Forbidden: not the unit contact" }); |
| 65 | + } catch (err) { |
| 66 | + console.error("❌ isEventContact error:", err); |
| 67 | + return res.status(500).json({ message: "Server error" }); |
| 68 | + } |
| 69 | +}; |
0 commit comments