somewhere

This commit is contained in:
Swift
2023-08-17 13:05:51 +03:30
parent 30c7eb0e7b
commit 53843207cc
429 changed files with 117489 additions and 1 deletions
@@ -0,0 +1,67 @@
const jwt = require('jsonwebtoken')
const User = require('../../models/User')
const authentication = require('../../authentication')
module.exports.isAdmin = 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 User.findById(decodedToken._id)
if (!user || !user.scope.includes('admin')) throw new Error('unauthorized')
socket.userId = decodedToken._id.toString()
return next()
} catch (e) {
// console.log('ws user middleware error --- ', e)
next(new Error(e))
}
}
module.exports.isUser = 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 User.findById(decodedToken._id)
if (!user || !user.scope.includes('user')) throw new Error('unauthorized')
socket.userId = decodedToken._id.toString()
return next()
} catch (e) {
// console.log('ws user middleware error --- ', e)
next(new Error(e))
}
}
module.exports.isAgent = 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 User.findById(decodedToken._id)
if (!user || !user.scope.includes('user')) throw new Error('unauthorized')
if (!user.isAgent) throw new Error('شما نماینده نیستید')
socket.userId = decodedToken._id.toString()
socket.agentId = user.representation_id.toString()
return next()
} catch (e) {
next(new Error(e))
}
}