Notif system

This commit is contained in:
Mr Swift
2024-09-28 23:00:10 +03:30
parent 8f63b82236
commit b1f792f493
8 changed files with 130 additions and 0 deletions
@@ -0,0 +1,19 @@
const Notification = require('../../models/GPS.Notif')
module.exports.notifyGPS = async (type, gps_id) => {
try {
const io = global._io
const gps = io.of('/gps')
const data = { type }
if (type === 'updateGPSInbox') {
const gpsInbox = await Notification.find({ userID:gps_id, seen: false }).sort({updated_at: -1})
data.gpsInbox = gpsInbox
}
gps.to(gps_id.toString()).emit(`GPS:notify`, data)
} catch (e) {
console.log(e)
}
}
@@ -1,5 +1,6 @@
const jwt = require('jsonwebtoken')
const User = require('../../models/User')
const UserGPS = require('../../models/GPS.User')
const authentication = require('../../authentication')
module.exports.isAdmin = async (socket, next) => {
@@ -65,3 +66,23 @@ module.exports.isAgent = async (socket, next) => {
next(new Error(e))
}
}
module.exports.isGPS = async (socket, next) => {
try {
const token = socket.handshake?.auth?.token
if (!token) throw new Error('unauthenticated')
// verifies secret and checks if the token is expired
const decodedToken = await jwt.verify(token.replace(/^Bearer\s/, ''), authentication.secretKey)
if (!decodedToken) throw new Error('unauthorized')
// find user
const user = await UserGPS.findById(decodedToken._id)
if (!user || !user.active) throw new Error('unauthorized')
socket.userId = decodedToken._id.toString()
return next()
} catch (e) {
next(new Error(e))
}
}
@@ -0,0 +1,25 @@
const { isGPS } = require('../middlewares/ws_authentication')
const gpsEventsController = require('../controllers/GPS_EventsController')
module.exports.gpsNamespace = () => {
const io = global._io
const gps = io.of('/gps')
// gpss middlewares
gps.use(isGPS)
// attach events
gps.on('connection', socket => {
socket.join(socket.gpsId)
gpsEventsController.getAllNotifs(socket)
/// /////////////////////////////////////////////////////// handle connection error
socket.on('connect_error', err => {
console.log(err.message)
})
/// ////////////////////////////////////////////////////// events
socket.on('gps:fetchAnnouncements', data => gpsEventsController.fetchAnnouncements(socket))
socket.on('gps:updateAnnouncement', data => gpsEventsController.updateAnnouncement(socket, data))
})
}
+2
View File
@@ -4,6 +4,7 @@ function init(server) {
const { userNamespace } = require('./namespaces/user_NameSpace')
const { agentNamespace } = require('./namespaces/agent_NameSpace')
const { adminNamespace } = require('./namespaces/admin_NameSpace')
const { gpsNamespace } = require('./namespaces/GPS_NameSpace')
const { Server } = require('socket.io')
const socketIO = require('socket.io')
@@ -18,6 +19,7 @@ function init(server) {
userNamespace()
agentNamespace()
adminNamespace()
gpsNamespace()
}
module.exports = init