diff --git a/package-lock.json b/package-lock.json index c4278e0..9476a83 100644 --- a/package-lock.json +++ b/package-lock.json @@ -41,6 +41,7 @@ "nuxt-leaflet": "^0.0.27", "read-excel-file": "^5.2.2", "socket.io": "^4.4.1", + "socket.io-client": "^4.8.0", "validator": "^13.12.0", "vue-persian-datetime-picker": "^2.10.3" }, @@ -8774,6 +8775,18 @@ "node": ">=10.2.0" } }, + "node_modules/engine.io-client": { + "version": "6.6.1", + "resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-6.6.1.tgz", + "integrity": "sha512-aYuoak7I+R83M/BBPIOs2to51BmFIpC1wZe6zZzMrT2llVsHy5cvcmdsJgP2Qz6smHu+sD9oexiSUAVd8OfBPw==", + "dependencies": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.3.1", + "engine.io-parser": "~5.2.1", + "ws": "~8.17.1", + "xmlhttprequest-ssl": "~2.1.1" + } + }, "node_modules/engine.io-parser": { "version": "5.2.3", "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.3.tgz", @@ -18688,6 +18701,20 @@ "ws": "~8.17.1" } }, + "node_modules/socket.io-client": { + "version": "4.8.0", + "resolved": "https://registry.npmjs.org/socket.io-client/-/socket.io-client-4.8.0.tgz", + "integrity": "sha512-C0jdhD5yQahMws9alf/yvtsMGTaIDBnZ8Rb5HU56svyq0l5LIrGzIDZZD5pHQlmzxLuU91Gz+VpQMKgCTNYtkw==", + "dependencies": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.3.2", + "engine.io-client": "~6.6.1", + "socket.io-parser": "~4.2.4" + }, + "engines": { + "node": ">=10.0.0" + } + }, "node_modules/socket.io-parser": { "version": "4.2.4", "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.4.tgz", @@ -22292,6 +22319,14 @@ "node": ">=4.0" } }, + "node_modules/xmlhttprequest-ssl": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/xmlhttprequest-ssl/-/xmlhttprequest-ssl-2.1.1.tgz", + "integrity": "sha512-ptjR8YSJIXoA3Mbv5po7RtSYHO6mZr8s7i5VGmEk7QY2pQWyT1o0N+W1gKbOyJPUCGXGnuw0wqe8f0L6Y0ny7g==", + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/xtend": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", diff --git a/package.json b/package.json index eceb62b..8f0964c 100644 --- a/package.json +++ b/package.json @@ -48,6 +48,7 @@ "nuxt-leaflet": "^0.0.27", "read-excel-file": "^5.2.2", "socket.io": "^4.4.1", + "socket.io-client": "^4.8.0", "validator": "^13.12.0", "vue-persian-datetime-picker": "^2.10.3" }, diff --git a/server/WebSocket/controllers/GPS_EventsController.js b/server/WebSocket/controllers/GPS_EventsController.js new file mode 100644 index 0000000..4f1c5b1 --- /dev/null +++ b/server/WebSocket/controllers/GPS_EventsController.js @@ -0,0 +1,48 @@ +const Notification = require('../../models/GPS.Notif') + +module.exports.getAllNotifs = async socket => { + try { + console.log('4'); + + const notif = await Notification.find({ userID: socket.userId, read: false }).sort({ updated_at: -1 }) +console.log(notif); + + + + socket.emit(`gps:allNotifs`, notif) + } catch (e) { + console.log(e) + } +} + +module.exports.notifyGPS = async (type, userId) => { + try { + const io = global._io + const gps = io.of('/gps') + const data = { type } + + if (type === 'updateGPSInbox') { + const gpsInbox = await Notification.find({ userID: userId, read: false }).sort({ updated_at: -1 }) + data.gpsInbox = gpsInbox + } + + gps.to(userId.toString()).emit(`gps:notify`, data) + } catch (e) { + console.log(e) + } +} + + + +module.exports.fetchNotifications = async (socket) => { + try { + console.log('5'); + + const notif = await Notification.find({ userID: socket.userId, read: false }).sort({ updated_at: -1 }) + console.log(notif); + + socket.emit('gps:notifications', notif) + } catch (e) { + console.log(e) + } +} diff --git a/server/WebSocket/middlewares/ws_authentication.js b/server/WebSocket/middlewares/ws_authentication.js index dad95ea..d7613f9 100644 --- a/server/WebSocket/middlewares/ws_authentication.js +++ b/server/WebSocket/middlewares/ws_authentication.js @@ -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,33 @@ module.exports.isAgent = async (socket, next) => { next(new Error(e)) } } + +module.exports.isGPS = async (socket, next) => { + try { + console.log('1'); + + const token = socket.handshake?.auth?.token + if (!token) { + console.log('unauthorized 1'); + throw new Error('unauthorized') + } + // verifies secret and checks if the token is expired + const decodedToken = await jwt.verify(token.replace(/^Bearer\s/, ''), authentication.secretKey) + if (!decodedToken) { + console.log('unauthorized 2'); + throw new Error('unauthorized') + } + + // find user + const user = await UserGPS.findById(decodedToken._id) + if (!user || !user.active) { + console.log('unauthorized 3'); + throw new Error('unauthorized') + } + + socket.userId = decodedToken._id.toString() + return next() + } catch (e) { + next(new Error(e)) + } +} diff --git a/server/WebSocket/namespaces/GPS_NameSpace.js b/server/WebSocket/namespaces/GPS_NameSpace.js new file mode 100644 index 0000000..faa0c68 --- /dev/null +++ b/server/WebSocket/namespaces/GPS_NameSpace.js @@ -0,0 +1,26 @@ +const { isGPS } = require('../middlewares/ws_authentication') +const gpsEventsController = require('../controllers/GPS_EventsController') + +module.exports.gpsNamespace = () => { + const io = global._io + const gps = io.of('/gps') + console.log('2'); + + // gpss middlewares + gps.use(isGPS) + console.log('3'); + + // attach events + gps.on('connection', socket => { + socket.join(socket.userId) + gpsEventsController.getAllNotifs(socket) + + /// /////////////////////////////////////////////////////// handle connection error + socket.on('connect_error', err => { + console.log(err.message) + }) + + /// ////////////////////////////////////////////////////// events + socket.on('gps:fetchNotifications', data => gpsEventsController.fetchNotifications(socket)) + }) +} diff --git a/server/WebSocket/wss.js b/server/WebSocket/wss.js index 35aed73..00cb545 100644 --- a/server/WebSocket/wss.js +++ b/server/WebSocket/wss.js @@ -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 diff --git a/server/controllers/GPS.Auth.js b/server/controllers/GPS.Auth.js index c8bbf0b..b553951 100644 --- a/server/controllers/GPS.Auth.js +++ b/server/controllers/GPS.Auth.js @@ -7,6 +7,8 @@ const { checkValidations } = require('../plugins/controllersHelperFunctions') const UserGPS = require('../models/GPS.User') const { generateRandomDigits } = require('../plugins/controllersHelperFunctions') +const Notification = require('../models/GPS.Notif') + module.exports.login_with_pass = [ [ body('username') @@ -55,6 +57,10 @@ module.exports.login_with_pass = [ }) user.token = token await user.save() + await Notification.create({ + userID:user._id, + content:"test" + }) return res.status(200).json({ token }) } catch (err) { return res.status(422).json({ @@ -90,6 +96,10 @@ module.exports.login_with_otp = [ }) user.otp = generateRandomDigits(6) user.save() + await Notification.create({ + userID:user._id, + content:"test" + }) return res.status(200).json({ token }) } diff --git a/server/controllers/GPS.Notif.js b/server/controllers/GPS.Notif.js new file mode 100644 index 0000000..07216b6 --- /dev/null +++ b/server/controllers/GPS.Notif.js @@ -0,0 +1,30 @@ +const { param, validationResult } = require('express-validator') +const { _sr } = require('../plugins/serverResponses') +const { checkValidations } = require('../plugins/controllersHelperFunctions') +const Notification = require('../models/GPS.Notif') + + +module.exports.setSeen = [ + [ + param('id').notEmpty().isMongoId().withMessage('ایدی را وارد یا تصحیح کنید') + ], + checkValidations(validationResult), + async (req, res) => { + const notif = await Notification.findById(req.params.id) + if (!notif || notif.userID !== req.userID) { + res.status(404).json({ msg: _sr.fa.not_found.item_id }) + } else { + notif.read = true; + notif.save() + } + } +] + +module.exports.setSeenAll = [ + async (req, res) => { + await Notification.updateMany( + { userID: req.userID }, + { seen: true } + ) + } +] \ No newline at end of file diff --git a/server/database.js b/server/database.js index d59a6d9..0f6c099 100644 --- a/server/database.js +++ b/server/database.js @@ -5,7 +5,7 @@ const inHostUrl = 'mongodb://root:KPTt76tImNBBMm4Kor8QA9gB@asan-service:27017/as const outHostUrl = 'mongodb://root:KPTt76tImNBBMm4Kor8QA9gB@hotaka.liara.cloud:33794/asanserv_database?authSource=admin' const init = ()=>{ try { - mongoose.connect(outHostUrl, { + mongoose.connect(inHostUrl, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, diff --git a/server/models/GPS.Notif.js b/server/models/GPS.Notif.js new file mode 100644 index 0000000..02eaa46 --- /dev/null +++ b/server/models/GPS.Notif.js @@ -0,0 +1,17 @@ +const mongoose = require("mongoose"); + +const notificationSchema = new mongoose.Schema( + { + userID: { + type: String, + ref: 'UserGPS' + }, + content: String, + read: { + type: Boolean, + default: false, + }, + } +); + +module.exports = mongoose.model("Notification", notificationSchema); diff --git a/server/routes/gps.js b/server/routes/gps.js index 62dcf76..0cc7cf5 100644 --- a/server/routes/gps.js +++ b/server/routes/gps.js @@ -8,6 +8,12 @@ const award = require('../controllers/GPS.Award') const awardRequest = require('../controllers/GPS.AwardRequest') const overview = require('../controllers/GPS.Overview') const userGPS = require('../controllers/GPS.User') +const notif = require('../controllers/GPS.Notif') + +/// /////////////// Notification +router.get('/notif/:id', notif.setSeen) +router.get('/notif', notif.setSeenAll) + /// /////////////// User router.get('/user/me', userGPS.getCurrent) diff --git a/test.js b/test.js index bbf13ad..660ec6b 100644 --- a/test.js +++ b/test.js @@ -1,59 +1,129 @@ -const nodemailer = require('nodemailer') +const { io } = require("socket.io-client"); -function sendConfirmationEmail() { - return new Promise(async (resolve, reject) => { - try { +const init = ()=>{ + const socket = io(`ws://127.0.0.1:5000/gps`, { + reconnectionDelay: 20000, + reconnectionDelayMax: 20000, + auth: { + token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2NmM2ZmYyY2NkMDJiNTNkMzRkMjNiYTYiLCJpYXQiOjE3MjczNTQ3OTYsImV4cCI6MTcyOTk0Njc5Nn0.7W3ZsjZbW-fbbZWCX1wxJ8Wfmdro5wM7ow-b7xwE4Fk" + } + }) + // eslint-disable-next-line node/handle-callback-err + socket.on('connect_error', err => {}) + + /// /////////////////////////////////////////// events + socket.on('connect', () => { + // console.log('**************** You have access to agent notifications') + socket.emit('gps:fetchNotifications') + }) + + socket.on(`gps:allNotifs`, data => { + console.log(data); + + }) + socket.on(`gps:notifications`, data => { + + console.log(data); + + }) + + socket.on(`gps:notify`, data => { + if (data.type === 'updateAgentInbox') { + // update store + console.log(data); + } + + if (data.type === 'newAgentInbox') { + + console.log(data); + + } + }) + + + +} +init() + + + + + + + + + + + + + + + + + + + + + + + + +// const nodemailer = require('nodemailer') + +// function sendConfirmationEmail() { +// return new Promise(async (resolve, reject) => { +// try { - /// //// email configs - // const hostURL = 'www.asan-service.com' - const transporter = nodemailer.createTransport({ - host: 'smtp.c1.liara.email', - port: 587, - secure: false, // true for 465, false for other ports - auth: { - user: 'awesome_bell_ncc1hi', - pass: '509f8938-db95-4b8d-83e7-9ea8eccfd28b' - }, - tls: { - rejectUnauthorized: false - } - }) +// /// //// email configs +// // const hostURL = 'www.asan-service.com' +// const transporter = nodemailer.createTransport({ +// host: 'smtp.c1.liara.email', +// port: 587, +// secure: false, // true for 465, false for other ports +// auth: { +// user: 'awesome_bell_ncc1hi', +// pass: '509f8938-db95-4b8d-83e7-9ea8eccfd28b' +// }, +// tls: { +// rejectUnauthorized: false +// } +// }) - const emailHTMLTemplate = ` -
- ` +// const emailHTMLTemplate = ` +// +// ` - // send mail with defined transport object - await transporter.sendMail({ - from: '"AsanService"