Merge pull request #10 from Danakcorp/Zarei | Final test WS

Add WS for notif system
This commit is contained in:
Mr Swift
2024-09-30 12:58:57 +03:30
committed by GitHub
12 changed files with 329 additions and 53 deletions
+35
View File
@@ -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",
+1
View File
@@ -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"
},
@@ -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)
}
}
@@ -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))
}
}
@@ -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))
})
}
+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
+10
View File
@@ -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 })
}
+30
View File
@@ -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 }
)
}
]
+1 -1
View File
@@ -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,
+17
View File
@@ -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);
+6
View File
@@ -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)
+122 -52
View File
@@ -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 = `
<div style="direction: rtl;background-color: #065495;overflow: hidden;">
<div
style="width: 70%;border-radius: 10px;margin: 150px auto;background: #fff;text-align: center;padding: 20px;box-shadow: 0 15px 30px #000;"
>
<h1 style="color: #000;font-size: 25px;margin-bottom: 20px;">
<span> این ایمیل در وبسایت</span>
<strong style="color: #065495"> آسان سرویس </strong>
<span> ثبت شده است. </span>
</h1>
<p style="color: #000;">کد تایید آدرس ایمیل شما:</p>
<div style="text-align: center;margin-top: 5px;">
<p style="color: #065495;text-align: center;font-weight: bold;font-size: 20px;direction: ltr;">
${54534}
</p>
</div>
</div>
</div>
`
// const emailHTMLTemplate = `
// <div style="direction: rtl;background-color: #065495;overflow: hidden;">
// <div
// style="width: 70%;border-radius: 10px;margin: 150px auto;background: #fff;text-align: center;padding: 20px;box-shadow: 0 15px 30px #000;"
// >
// <h1 style="color: #000;font-size: 25px;margin-bottom: 20px;">
// <span> این ایمیل در وبسایت</span>
// <strong style="color: #065495"> آسان سرویس </strong>
// <span> ثبت شده است. </span>
// </h1>
// <p style="color: #000;">کد تایید آدرس ایمیل شما:</p>
// <div style="text-align: center;margin-top: 5px;">
// <p style="color: #065495;text-align: center;font-weight: bold;font-size: 20px;direction: ltr;">
// ${54534}
// </p>
// </div>
// </div>
// </div>
// `
// send mail with defined transport object
await transporter.sendMail({
from: '"AsanService" <confirmation@asan-service.com>', // sender address
to: "www.amir.com007@gmail.com", // list of receivers
subject: 'تایید ایمیل',
text: emailHTMLTemplate,
html: emailHTMLTemplate
})
// // send mail with defined transport object
// await transporter.sendMail({
// from: '"AsanService" <confirmation@asan-service.com>', // sender address
// to: "www.amir.com007@gmail.com", // list of receivers
// subject: 'تایید ایمیل',
// text: emailHTMLTemplate,
// html: emailHTMLTemplate
// })
resolve()
} catch (err) {
reject(err)
}
})
}
// resolve()
// } catch (err) {
// reject(err)
// }
// })
// }
sendConfirmationEmail()
// sendConfirmationEmail()