54 lines
1.5 KiB
JavaScript
54 lines
1.5 KiB
JavaScript
const mongoose = require('mongoose')
|
|
const UserModel = require('../models/UserModel')
|
|
const {
|
|
viewerBlockedUser,
|
|
userBlockedViewer
|
|
} = require('../utils/blockVisibility')
|
|
|
|
function isChatBlockedBetween(userDoc, otherUserId) {
|
|
if (!userDoc || !otherUserId) return false
|
|
const otherId = String(otherUserId)
|
|
return (
|
|
viewerBlockedUser(userDoc, otherId) ||
|
|
userBlockedViewer(userDoc, otherId)
|
|
)
|
|
}
|
|
|
|
module.exports = async (req, res, next) => {
|
|
try {
|
|
const userId = String(req.user._id)
|
|
const receiverId = String(
|
|
req.body?.receiverId || req.query?.receiverId || ''
|
|
).trim()
|
|
|
|
if (!receiverId || !mongoose.Types.ObjectId.isValid(receiverId)) {
|
|
return next()
|
|
}
|
|
|
|
if (receiverId === userId) {
|
|
return res.status(400).json({ message: 'امکان ارسال پیام به خود وجود ندارد' })
|
|
}
|
|
|
|
const [currentUser, peer] = await Promise.all([
|
|
UserModel.findById(userId).select('blocked_by blocked_users'),
|
|
UserModel.findById(receiverId).select('blocked_by blocked_users')
|
|
])
|
|
|
|
if (!peer) {
|
|
return res.status(404).json({ message: 'کاربر یافت نشد' })
|
|
}
|
|
|
|
if (
|
|
isChatBlockedBetween(currentUser, receiverId) ||
|
|
isChatBlockedBetween(peer, userId)
|
|
) {
|
|
return res.status(403).json({ message: 'امکان ارسال پیام وجود ندارد' })
|
|
}
|
|
|
|
next()
|
|
} catch (error) {
|
|
console.error('chatPeerBlock error:', error)
|
|
res.status(500).json({ error: 'Server error' })
|
|
}
|
|
}
|