| const router = require('express').Router(); |
| const Notification = require('../models/Notification'); |
| const User = require('../models/User'); |
| const verify = require('../utils/verifyToken'); |
| const webpush = require('web-push'); |
|
|
| const verifyAdmin = async (req, res, next) => { |
| const user = await User.findById(req.user._id); |
| if (user.role !== 'admin') return res.status(403).send("ACCESS DENIED"); |
| next(); |
| }; |
|
|
|
|
| |
| webpush.setVapidDetails( |
| process.env.VAPID_EMAIL, |
| process.env.VAPID_PUBLIC_KEY, |
| process.env.VAPID_PRIVATE_KEY |
| ); |
|
|
| |
| router.get('/', verify, async (req, res) => { |
| try { |
| const notes = await Notification.find({ |
| $or: [ |
| { target_user_id: null }, |
| { target_user_id: req.user._id } |
| ] |
| }).sort({ created_at: -1 }).limit(20); |
| |
| res.json(notes); |
| } catch (err) { |
| res.status(500).send("Error fetching notifications"); |
| } |
| }); |
|
|
| |
| router.post('/subscribe', verify, async (req, res) => { |
| const subscription = req.body; |
| |
| await User.findByIdAndUpdate(req.user._id, { pushSubscription: subscription }); |
| res.status(201).json({}); |
| }); |
|
|
| |
| router.post('/send', verify, verifyAdmin, async (req, res) => { |
| const { title, message, url, targetUserId } = req.body; |
| const payload = JSON.stringify({ title, body: message, url }); |
|
|
| try { |
| if (targetUserId) { |
| |
| const user = await User.findById(targetUserId); |
| if (user?.pushSubscription) { |
| await webpush.sendNotification(user.pushSubscription, payload); |
| } |
| } else { |
| |
| |
| const users = await User.find({ pushSubscription: { $exists: true } }); |
| |
| const promises = users.map(user => |
| webpush.sendNotification(user.pushSubscription, payload).catch(err => { |
| if (err.statusCode === 410) { |
| |
| User.findByIdAndUpdate(user._id, { $unset: { pushSubscription: "" } }); |
| } |
| }) |
| ); |
| await Promise.all(promises); |
| } |
| |
| res.json({ success: true }); |
| } catch (err) { |
| res.status(500).json({ error: "Push Failed" }); |
| } |
| }); |
|
|
| module.exports = router; |