ability to ban and unban users
This commit is contained in:
@@ -33,6 +33,14 @@ const authenticateToken = async (req, res, next) => {
|
||||
});
|
||||
}
|
||||
|
||||
// Check if user is banned
|
||||
if (user.isBanned) {
|
||||
return res.status(403).json({
|
||||
error: "Your account has been suspended. Please contact support for more information.",
|
||||
code: "USER_BANNED",
|
||||
});
|
||||
}
|
||||
|
||||
// Validate JWT version to invalidate old tokens after password change
|
||||
if (decoded.jwtVersion !== user.jwtVersion) {
|
||||
return res.status(401).json({
|
||||
@@ -93,6 +101,12 @@ const optionalAuth = async (req, res, next) => {
|
||||
return next();
|
||||
}
|
||||
|
||||
// Banned users are treated as unauthenticated for optional auth
|
||||
if (user.isBanned) {
|
||||
req.user = null;
|
||||
return next();
|
||||
}
|
||||
|
||||
// Validate JWT version to invalidate old tokens after password change
|
||||
if (decoded.jwtVersion !== user.jwtVersion) {
|
||||
req.user = null;
|
||||
|
||||
41
backend/migrations/20260106000001-add-user-ban-fields.js
Normal file
41
backend/migrations/20260106000001-add-user-ban-fields.js
Normal file
@@ -0,0 +1,41 @@
|
||||
"use strict";
|
||||
|
||||
module.exports = {
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
// isBanned - boolean flag indicating if user is banned
|
||||
await queryInterface.addColumn("Users", "isBanned", {
|
||||
type: Sequelize.BOOLEAN,
|
||||
defaultValue: false,
|
||||
allowNull: false,
|
||||
});
|
||||
|
||||
// bannedAt - timestamp when ban was applied
|
||||
await queryInterface.addColumn("Users", "bannedAt", {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: true,
|
||||
});
|
||||
|
||||
// bannedBy - UUID of admin who applied the ban
|
||||
await queryInterface.addColumn("Users", "bannedBy", {
|
||||
type: Sequelize.UUID,
|
||||
allowNull: true,
|
||||
references: {
|
||||
model: "Users",
|
||||
key: "id",
|
||||
},
|
||||
});
|
||||
|
||||
// banReason - reason provided by admin for the ban
|
||||
await queryInterface.addColumn("Users", "banReason", {
|
||||
type: Sequelize.TEXT,
|
||||
allowNull: true,
|
||||
});
|
||||
},
|
||||
|
||||
down: async (queryInterface, Sequelize) => {
|
||||
await queryInterface.removeColumn("Users", "banReason");
|
||||
await queryInterface.removeColumn("Users", "bannedBy");
|
||||
await queryInterface.removeColumn("Users", "bannedAt");
|
||||
await queryInterface.removeColumn("Users", "isBanned");
|
||||
},
|
||||
};
|
||||
@@ -142,6 +142,23 @@ const User = sequelize.define(
|
||||
defaultValue: "user",
|
||||
allowNull: false,
|
||||
},
|
||||
isBanned: {
|
||||
type: DataTypes.BOOLEAN,
|
||||
defaultValue: false,
|
||||
allowNull: false,
|
||||
},
|
||||
bannedAt: {
|
||||
type: DataTypes.DATE,
|
||||
allowNull: true,
|
||||
},
|
||||
bannedBy: {
|
||||
type: DataTypes.UUID,
|
||||
allowNull: true,
|
||||
},
|
||||
banReason: {
|
||||
type: DataTypes.TEXT,
|
||||
allowNull: true,
|
||||
},
|
||||
itemRequestNotificationRadius: {
|
||||
type: DataTypes.INTEGER,
|
||||
defaultValue: 10,
|
||||
@@ -343,4 +360,27 @@ User.prototype.resetPassword = async function (newPassword) {
|
||||
});
|
||||
};
|
||||
|
||||
// Ban user method - sets ban fields and invalidates all sessions
|
||||
User.prototype.banUser = async function (adminId, reason) {
|
||||
return this.update({
|
||||
isBanned: true,
|
||||
bannedAt: new Date(),
|
||||
bannedBy: adminId,
|
||||
banReason: reason,
|
||||
// Increment JWT version to immediately invalidate all sessions
|
||||
jwtVersion: this.jwtVersion + 1,
|
||||
});
|
||||
};
|
||||
|
||||
// Unban user method - clears ban fields
|
||||
User.prototype.unbanUser = async function () {
|
||||
return this.update({
|
||||
isBanned: false,
|
||||
bannedAt: null,
|
||||
bannedBy: null,
|
||||
banReason: null,
|
||||
// Note: We don't increment jwtVersion on unban - user will need to log in fresh
|
||||
});
|
||||
};
|
||||
|
||||
module.exports = User;
|
||||
|
||||
@@ -219,6 +219,14 @@ router.post(
|
||||
});
|
||||
}
|
||||
|
||||
// Check if user is banned
|
||||
if (user.isBanned) {
|
||||
return res.status(403).json({
|
||||
error: "Your account has been suspended. Please contact support for more information.",
|
||||
code: "USER_BANNED",
|
||||
});
|
||||
}
|
||||
|
||||
// Verify password
|
||||
const isPasswordValid = await user.comparePassword(password);
|
||||
|
||||
|
||||
@@ -137,6 +137,10 @@ router.get("/", async (req, res, next) => {
|
||||
model: User,
|
||||
as: "owner",
|
||||
attributes: ["id", "firstName", "lastName", "imageFilename"],
|
||||
where: {
|
||||
isBanned: { [Op.ne]: true }
|
||||
},
|
||||
required: true,
|
||||
},
|
||||
],
|
||||
limit: parseInt(limit),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
const express = require('express');
|
||||
const { User, UserAddress } = require('../models'); // Import from models/index.js to get models with associations
|
||||
const { authenticateToken } = require('../middleware/auth');
|
||||
const { authenticateToken, optionalAuth, requireAdmin } = require('../middleware/auth');
|
||||
const logger = require('../utils/logger');
|
||||
const userService = require('../services/UserService');
|
||||
const { validateS3Keys } = require('../utils/s3KeyValidator');
|
||||
@@ -210,10 +210,20 @@ router.put('/availability', authenticateToken, async (req, res, next) => {
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/:id', async (req, res, next) => {
|
||||
router.get('/:id', optionalAuth, async (req, res, next) => {
|
||||
try {
|
||||
const isAdmin = req.user?.role === 'admin';
|
||||
|
||||
// Base attributes to exclude
|
||||
const excludedAttributes = ['password', 'email', 'phone', 'address', 'verificationToken', 'passwordResetToken'];
|
||||
|
||||
// If not admin, also exclude ban-related fields
|
||||
if (!isAdmin) {
|
||||
excludedAttributes.push('isBanned', 'bannedAt', 'bannedBy', 'banReason');
|
||||
}
|
||||
|
||||
const user = await User.findByPk(req.params.id, {
|
||||
attributes: { exclude: ['password', 'email', 'phone', 'address'] }
|
||||
attributes: { exclude: excludedAttributes }
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
@@ -222,7 +232,8 @@ router.get('/:id', async (req, res, next) => {
|
||||
|
||||
const reqLogger = logger.withRequestId(req.id);
|
||||
reqLogger.info("Public user profile fetched", {
|
||||
requestedUserId: req.params.id
|
||||
requestedUserId: req.params.id,
|
||||
viewerIsAdmin: isAdmin
|
||||
});
|
||||
|
||||
res.json(user);
|
||||
@@ -263,4 +274,137 @@ router.put('/profile', authenticateToken, async (req, res, next) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Admin: Ban a user
|
||||
router.post('/admin/:id/ban', authenticateToken, requireAdmin, async (req, res, next) => {
|
||||
try {
|
||||
const { reason } = req.body;
|
||||
const targetUserId = req.params.id;
|
||||
|
||||
// Validate reason is provided
|
||||
if (!reason || !reason.trim()) {
|
||||
return res.status(400).json({ error: "Ban reason is required" });
|
||||
}
|
||||
|
||||
// Prevent banning yourself
|
||||
if (targetUserId === req.user.id) {
|
||||
return res.status(400).json({ error: "You cannot ban yourself" });
|
||||
}
|
||||
|
||||
const targetUser = await User.findByPk(targetUserId);
|
||||
|
||||
if (!targetUser) {
|
||||
return res.status(404).json({ error: "User not found" });
|
||||
}
|
||||
|
||||
// Prevent banning other admins
|
||||
if (targetUser.role === 'admin') {
|
||||
return res.status(403).json({ error: "Cannot ban admin users" });
|
||||
}
|
||||
|
||||
// Check if already banned
|
||||
if (targetUser.isBanned) {
|
||||
return res.status(400).json({ error: "User is already banned" });
|
||||
}
|
||||
|
||||
// Ban the user (this also invalidates sessions via jwtVersion increment)
|
||||
await targetUser.banUser(req.user.id, reason.trim());
|
||||
|
||||
// Send ban notification email
|
||||
try {
|
||||
const emailServices = require("../services/email");
|
||||
await emailServices.userEngagement.sendUserBannedNotification(
|
||||
targetUser,
|
||||
req.user,
|
||||
reason.trim()
|
||||
);
|
||||
const reqLogger = logger.withRequestId(req.id);
|
||||
reqLogger.info("User ban notification email sent", {
|
||||
bannedUserId: targetUserId,
|
||||
adminId: req.user.id
|
||||
});
|
||||
} catch (emailError) {
|
||||
// Log but don't fail the ban operation
|
||||
const reqLogger = logger.withRequestId(req.id);
|
||||
reqLogger.error('Failed to send user ban notification email', {
|
||||
error: emailError.message,
|
||||
stack: emailError.stack,
|
||||
bannedUserId: targetUserId,
|
||||
adminId: req.user.id
|
||||
});
|
||||
}
|
||||
|
||||
const reqLogger = logger.withRequestId(req.id);
|
||||
reqLogger.info("User banned by admin", {
|
||||
targetUserId,
|
||||
adminId: req.user.id,
|
||||
reason: reason.trim()
|
||||
});
|
||||
|
||||
// Return updated user data (excluding sensitive fields)
|
||||
const updatedUser = await User.findByPk(targetUserId, {
|
||||
attributes: { exclude: ['password', 'verificationToken', 'passwordResetToken'] }
|
||||
});
|
||||
|
||||
res.json({
|
||||
message: "User has been banned successfully",
|
||||
user: updatedUser
|
||||
});
|
||||
} catch (error) {
|
||||
const reqLogger = logger.withRequestId(req.id);
|
||||
reqLogger.error("Admin ban user failed", {
|
||||
error: error.message,
|
||||
stack: error.stack,
|
||||
targetUserId: req.params.id,
|
||||
adminId: req.user.id
|
||||
});
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
// Admin: Unban a user
|
||||
router.post('/admin/:id/unban', authenticateToken, requireAdmin, async (req, res, next) => {
|
||||
try {
|
||||
const targetUserId = req.params.id;
|
||||
|
||||
const targetUser = await User.findByPk(targetUserId);
|
||||
|
||||
if (!targetUser) {
|
||||
return res.status(404).json({ error: "User not found" });
|
||||
}
|
||||
|
||||
// Check if user is actually banned
|
||||
if (!targetUser.isBanned) {
|
||||
return res.status(400).json({ error: "User is not banned" });
|
||||
}
|
||||
|
||||
// Unban the user
|
||||
await targetUser.unbanUser();
|
||||
|
||||
const reqLogger = logger.withRequestId(req.id);
|
||||
reqLogger.info("User unbanned by admin", {
|
||||
targetUserId,
|
||||
adminId: req.user.id
|
||||
});
|
||||
|
||||
// Return updated user data (excluding sensitive fields)
|
||||
const updatedUser = await User.findByPk(targetUserId, {
|
||||
attributes: { exclude: ['password', 'verificationToken', 'passwordResetToken'] }
|
||||
});
|
||||
|
||||
res.json({
|
||||
message: "User has been unbanned successfully",
|
||||
user: updatedUser
|
||||
});
|
||||
} catch (error) {
|
||||
const reqLogger = logger.withRequestId(req.id);
|
||||
reqLogger.error("Admin unban user failed", {
|
||||
error: error.message,
|
||||
stack: error.stack,
|
||||
targetUserId: req.params.id,
|
||||
adminId: req.user.id
|
||||
});
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -104,6 +104,7 @@ class TemplateManager {
|
||||
"forumCommentDeletionToAuthor.html",
|
||||
"paymentDeclinedToRenter.html",
|
||||
"paymentMethodUpdatedToOwner.html",
|
||||
"userBannedNotification.html",
|
||||
];
|
||||
|
||||
const failedTemplates = [];
|
||||
@@ -526,6 +527,21 @@ class TemplateManager {
|
||||
<p style="text-align: center;"><a href="{{approvalUrl}}" class="button">Review & Approve Rental</a></p>
|
||||
`
|
||||
),
|
||||
|
||||
userBannedNotification: baseTemplate.replace(
|
||||
"{{content}}",
|
||||
`
|
||||
<p>Hi {{userName}},</p>
|
||||
<h2>Your Account Has Been Suspended</h2>
|
||||
<p>Your Village Share account has been suspended by our moderation team.</p>
|
||||
<div style="background-color: #f8d7da; border-left: 4px solid #dc3545; padding: 20px; margin: 20px 0;">
|
||||
<p><strong>Reason for Suspension:</strong></p>
|
||||
<p>{{banReason}}</p>
|
||||
</div>
|
||||
<p>You have been logged out of all devices and cannot log in to your account.</p>
|
||||
<p>If you believe this suspension was made in error, please contact <a href="mailto:{{supportEmail}}">{{supportEmail}}</a>.</p>
|
||||
`
|
||||
),
|
||||
};
|
||||
|
||||
return (
|
||||
|
||||
@@ -118,6 +118,57 @@ class UserEngagementEmailService {
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send notification when a user's account is banned
|
||||
* @param {Object} bannedUser - User who was banned
|
||||
* @param {string} bannedUser.firstName - Banned user's first name
|
||||
* @param {string} bannedUser.email - Banned user's email
|
||||
* @param {Object} admin - Admin who performed the ban
|
||||
* @param {string} admin.firstName - Admin's first name
|
||||
* @param {string} admin.lastName - Admin's last name
|
||||
* @param {string} banReason - Reason for the ban
|
||||
* @returns {Promise<{success: boolean, messageId?: string, error?: string}>}
|
||||
*/
|
||||
async sendUserBannedNotification(bannedUser, admin, banReason) {
|
||||
if (!this.initialized) {
|
||||
await this.initialize();
|
||||
}
|
||||
|
||||
try {
|
||||
const supportEmail = process.env.SUPPORT_EMAIL;
|
||||
|
||||
const variables = {
|
||||
userName: bannedUser.firstName || "there",
|
||||
banReason: banReason,
|
||||
supportEmail: supportEmail,
|
||||
};
|
||||
|
||||
const htmlContent = await this.templateManager.renderTemplate(
|
||||
"userBannedNotification",
|
||||
variables
|
||||
);
|
||||
|
||||
const subject = "Important: Your Village Share Account Has Been Suspended";
|
||||
|
||||
const result = await this.emailClient.sendEmail(
|
||||
bannedUser.email,
|
||||
subject,
|
||||
htmlContent
|
||||
);
|
||||
|
||||
if (result.success) {
|
||||
console.log(
|
||||
`User banned notification email sent to ${bannedUser.email}`
|
||||
);
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.error("Failed to send user banned notification email:", error);
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = UserEngagementEmailService;
|
||||
|
||||
277
backend/templates/emails/userBannedNotification.html
Normal file
277
backend/templates/emails/userBannedNotification.html
Normal file
@@ -0,0 +1,277 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
|
||||
<title>Account Suspended</title>
|
||||
<style>
|
||||
/* Reset styles */
|
||||
body,
|
||||
table,
|
||||
td,
|
||||
p,
|
||||
a,
|
||||
li,
|
||||
blockquote {
|
||||
-webkit-text-size-adjust: 100%;
|
||||
-ms-text-size-adjust: 100%;
|
||||
}
|
||||
table,
|
||||
td {
|
||||
mso-table-lspace: 0pt;
|
||||
mso-table-rspace: 0pt;
|
||||
}
|
||||
img {
|
||||
-ms-interpolation-mode: bicubic;
|
||||
}
|
||||
|
||||
/* Base styles */
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
width: 100% !important;
|
||||
min-width: 100%;
|
||||
height: 100%;
|
||||
background-color: #f8f9fa;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
|
||||
Oxygen, Ubuntu, Cantarell, sans-serif;
|
||||
line-height: 1.6;
|
||||
color: #212529;
|
||||
}
|
||||
|
||||
/* Container */
|
||||
.email-container {
|
||||
max-width: 600px;
|
||||
margin: 0 auto;
|
||||
background-color: #ffffff;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
/* Header - Warning red gradient */
|
||||
.header {
|
||||
background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
|
||||
padding: 40px 30px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.logo {
|
||||
font-size: 32px;
|
||||
font-weight: 700;
|
||||
color: #ffffff;
|
||||
text-decoration: none;
|
||||
letter-spacing: -1px;
|
||||
}
|
||||
|
||||
.tagline {
|
||||
color: #f8d7da;
|
||||
font-size: 16px;
|
||||
margin-top: 8px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* Content */
|
||||
.content {
|
||||
padding: 40px 30px;
|
||||
}
|
||||
|
||||
.content h1 {
|
||||
font-size: 28px;
|
||||
font-weight: 600;
|
||||
margin: 0 0 20px 0;
|
||||
color: #212529;
|
||||
}
|
||||
|
||||
.content h2 {
|
||||
font-size: 22px;
|
||||
font-weight: 600;
|
||||
margin: 30px 0 15px 0;
|
||||
color: #495057;
|
||||
}
|
||||
|
||||
.content p {
|
||||
margin: 0 0 16px 0;
|
||||
color: #6c757d;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.content strong {
|
||||
color: #495057;
|
||||
}
|
||||
|
||||
/* Alert box */
|
||||
.alert-box {
|
||||
background-color: #f8d7da;
|
||||
border-left: 4px solid #dc3545;
|
||||
padding: 20px;
|
||||
margin: 20px 0;
|
||||
border-radius: 0 6px 6px 0;
|
||||
}
|
||||
|
||||
.alert-box p {
|
||||
margin: 0 0 10px 0;
|
||||
color: #721c24;
|
||||
}
|
||||
|
||||
.alert-box p:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
/* Info box */
|
||||
.info-box {
|
||||
background-color: #e7f3ff;
|
||||
border-left: 4px solid #667eea;
|
||||
padding: 20px;
|
||||
margin: 20px 0;
|
||||
border-radius: 0 6px 6px 0;
|
||||
}
|
||||
|
||||
.info-box p {
|
||||
margin: 0 0 10px 0;
|
||||
color: #004085;
|
||||
}
|
||||
|
||||
.info-box p:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
/* Button */
|
||||
.button {
|
||||
display: inline-block;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: #ffffff !important;
|
||||
text-decoration: none;
|
||||
padding: 16px 32px;
|
||||
border-radius: 6px;
|
||||
font-weight: 600;
|
||||
margin: 20px 0;
|
||||
text-align: center;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.button:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
|
||||
}
|
||||
|
||||
/* Footer */
|
||||
.footer {
|
||||
background-color: #f8f9fa;
|
||||
padding: 30px;
|
||||
text-align: center;
|
||||
border-top: 1px solid #e9ecef;
|
||||
}
|
||||
|
||||
.footer p {
|
||||
margin: 0 0 10px 0;
|
||||
font-size: 14px;
|
||||
color: #6c757d;
|
||||
}
|
||||
|
||||
.footer a {
|
||||
color: #667eea;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.footer a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
/* Responsive */
|
||||
@media only screen and (max-width: 600px) {
|
||||
.email-container {
|
||||
margin: 0;
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
.header,
|
||||
.content,
|
||||
.footer {
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.logo {
|
||||
font-size: 28px;
|
||||
}
|
||||
|
||||
.content h1 {
|
||||
font-size: 24px;
|
||||
}
|
||||
|
||||
.content h2 {
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
.button {
|
||||
display: block;
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="email-container">
|
||||
<div class="header">
|
||||
<div class="logo">Village Share</div>
|
||||
<div class="tagline">Important Account Notice</div>
|
||||
</div>
|
||||
|
||||
<div class="content">
|
||||
<p>Hi {{userName}},</p>
|
||||
|
||||
<h1>Your Account Has Been Suspended</h1>
|
||||
|
||||
<p>
|
||||
We're writing to inform you that your Village Share account has been
|
||||
suspended by our moderation team.
|
||||
</p>
|
||||
|
||||
<div class="alert-box">
|
||||
<p><strong>Reason for Suspension:</strong></p>
|
||||
<p>{{banReason}}</p>
|
||||
</div>
|
||||
|
||||
<div class="info-box">
|
||||
<p><strong>What this means:</strong></p>
|
||||
<ul style="margin: 10px 0; padding-left: 20px; color: #004085">
|
||||
<li>You have been logged out of all devices</li>
|
||||
<li>You cannot log in to your account</li>
|
||||
<li>Your listings are no longer visible to other users</li>
|
||||
<li>Any pending rental requests have been affected</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<h2>Need Help or Have Questions?</h2>
|
||||
<p>
|
||||
If you believe this suspension was made in error or if you would like
|
||||
to appeal this decision, please contact our support team:
|
||||
</p>
|
||||
|
||||
<p style="text-align: center">
|
||||
<a href="mailto:{{supportEmail}}" class="button">Contact Support</a>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<strong>Best regards,</strong><br />
|
||||
The Village Share Team
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="footer">
|
||||
<p><strong>Village Share</strong></p>
|
||||
<p>Building a community of sharing and trust</p>
|
||||
<p>
|
||||
This email was sent because your account status has changed.
|
||||
</p>
|
||||
<p>
|
||||
If you have questions, please contact
|
||||
<a href="mailto:{{supportEmail}}">{{supportEmail}}</a>
|
||||
</p>
|
||||
<p>© 2025 Village Share. All rights reserved.</p>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
215
frontend/src/components/BanUserModal.tsx
Normal file
215
frontend/src/components/BanUserModal.tsx
Normal file
@@ -0,0 +1,215 @@
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { userAPI } from "../services/api";
|
||||
import { User } from "../types";
|
||||
|
||||
interface BanUserModalProps {
|
||||
show: boolean;
|
||||
onHide: () => void;
|
||||
user: User;
|
||||
onBanComplete: (updatedUser: User) => void;
|
||||
}
|
||||
|
||||
const BanUserModal: React.FC<BanUserModalProps> = ({
|
||||
show,
|
||||
onHide,
|
||||
user,
|
||||
onBanComplete,
|
||||
}) => {
|
||||
const [processing, setProcessing] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [reason, setReason] = useState("");
|
||||
const [success, setSuccess] = useState(false);
|
||||
const [updatedUser, setUpdatedUser] = useState<User | null>(null);
|
||||
|
||||
const handleBan = async () => {
|
||||
if (!reason.trim()) {
|
||||
setError("Please provide a reason for banning this user");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setProcessing(true);
|
||||
setError(null);
|
||||
|
||||
const response = await userAPI.adminBanUser(user.id, reason.trim());
|
||||
|
||||
// Store updated user data for later callback
|
||||
setUpdatedUser(response.data.user);
|
||||
|
||||
// Show success confirmation
|
||||
setSuccess(true);
|
||||
} catch (error: any) {
|
||||
setError(error.response?.data?.error || "Failed to ban user");
|
||||
} finally {
|
||||
setProcessing(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
// Call parent callback with updated user data if we have it
|
||||
if (updatedUser) {
|
||||
onBanComplete(updatedUser);
|
||||
}
|
||||
|
||||
// Reset all states when closing
|
||||
setProcessing(false);
|
||||
setError(null);
|
||||
setReason("");
|
||||
setSuccess(false);
|
||||
setUpdatedUser(null);
|
||||
onHide();
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (show) {
|
||||
document.body.style.overflow = "hidden";
|
||||
} else {
|
||||
document.body.style.overflow = "unset";
|
||||
}
|
||||
|
||||
return () => {
|
||||
document.body.style.overflow = "unset";
|
||||
};
|
||||
}, [show]);
|
||||
|
||||
if (!show) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
className="modal d-block"
|
||||
style={{ backgroundColor: "rgba(0,0,0,0.5)" }}
|
||||
>
|
||||
<div className="modal-dialog modal-dialog-centered">
|
||||
<div className="modal-content">
|
||||
<div className="modal-header">
|
||||
<h5 className="modal-title">
|
||||
{success
|
||||
? "User Banned"
|
||||
: `Ban User ${user.firstName} ${user.lastName}`}
|
||||
</h5>
|
||||
<button
|
||||
type="button"
|
||||
className="btn-close"
|
||||
onClick={handleClose}
|
||||
disabled={processing}
|
||||
aria-label="Close"
|
||||
></button>
|
||||
</div>
|
||||
<div className="modal-body">
|
||||
{success ? (
|
||||
<div className="text-center py-4">
|
||||
<div className="mb-4">
|
||||
<i
|
||||
className="bi bi-check-circle-fill text-success"
|
||||
style={{ fontSize: "4rem" }}
|
||||
></i>
|
||||
</div>
|
||||
<h3 className="text-success mb-3">User Banned</h3>
|
||||
<div className="alert alert-info">
|
||||
<p className="mb-0">
|
||||
{user.firstName} {user.lastName} has been banned and logged
|
||||
out of all sessions. If they had listings, they are no
|
||||
longer available. They have been notified via email.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{error && (
|
||||
<div className="alert alert-danger mb-3" role="alert">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
handleBan();
|
||||
}}
|
||||
>
|
||||
<div className="mb-3">
|
||||
<label className="form-label">
|
||||
Reason for Ban <span className="text-danger">*</span>
|
||||
</label>
|
||||
<textarea
|
||||
className="form-control"
|
||||
rows={4}
|
||||
value={reason}
|
||||
onChange={(e) => {
|
||||
setReason(e.target.value);
|
||||
setError(null);
|
||||
}}
|
||||
placeholder="Please explain why this user is being banned..."
|
||||
maxLength={1000}
|
||||
required
|
||||
disabled={processing}
|
||||
/>
|
||||
<div className="form-text text-muted">
|
||||
{reason.length}/1000 characters (Required)
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="alert alert-warning">
|
||||
<i className="bi bi-exclamation-triangle-fill me-2"></i>
|
||||
<strong>Warning:</strong> Banning this user will:
|
||||
<ul className="mb-0 mt-2">
|
||||
<li>Immediately log them out of all sessions</li>
|
||||
<li>Prevent them from logging back in</li>
|
||||
<li>
|
||||
Send them an email notification with the ban reason
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="modal-footer">
|
||||
{success ? (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
onClick={handleClose}
|
||||
>
|
||||
Done
|
||||
</button>
|
||||
) : (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
onClick={handleClose}
|
||||
disabled={processing}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-danger"
|
||||
onClick={handleBan}
|
||||
disabled={processing || !reason.trim()}
|
||||
>
|
||||
{processing ? (
|
||||
<>
|
||||
<div
|
||||
className="spinner-border spinner-border-sm me-2"
|
||||
role="status"
|
||||
>
|
||||
<span className="visually-hidden">Loading...</span>
|
||||
</div>
|
||||
Banning...
|
||||
</>
|
||||
) : (
|
||||
"Ban User"
|
||||
)}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default BanUserModal;
|
||||
@@ -6,6 +6,8 @@ import { getImageUrl } from '../services/uploadService';
|
||||
import { useAuth } from '../contexts/AuthContext';
|
||||
import ChatWindow from '../components/ChatWindow';
|
||||
import Avatar from '../components/Avatar';
|
||||
import BanUserModal from '../components/BanUserModal';
|
||||
import ConfirmationModal from '../components/ConfirmationModal';
|
||||
|
||||
const PublicProfile: React.FC = () => {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
@@ -16,6 +18,9 @@ const PublicProfile: React.FC = () => {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [showChat, setShowChat] = useState(false);
|
||||
const [showBanModal, setShowBanModal] = useState(false);
|
||||
const [showUnbanModal, setShowUnbanModal] = useState(false);
|
||||
const [unbanning, setUnbanning] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
fetchUserProfile();
|
||||
@@ -44,6 +49,28 @@ const PublicProfile: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const handleBanComplete = (updatedUser: User) => {
|
||||
setUser(updatedUser);
|
||||
};
|
||||
|
||||
const handleUnban = async () => {
|
||||
if (!user) return;
|
||||
|
||||
try {
|
||||
setUnbanning(true);
|
||||
const response = await userAPI.adminUnbanUser(user.id);
|
||||
setUser(response.data.user);
|
||||
setShowUnbanModal(false);
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.error || 'Failed to unban user');
|
||||
} finally {
|
||||
setUnbanning(false);
|
||||
}
|
||||
};
|
||||
|
||||
const isAdmin = currentUser?.role === 'admin';
|
||||
const canBanUser = isAdmin && user && currentUser?.id !== user.id && user.role !== 'admin';
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="container mt-5">
|
||||
@@ -75,7 +102,21 @@ const PublicProfile: React.FC = () => {
|
||||
<div className="text-center mb-4">
|
||||
<Avatar user={user} size="xxxl" className="mb-3 mx-auto" />
|
||||
<h3>{user.firstName} {user.lastName}</h3>
|
||||
{currentUser && currentUser.id !== user.id && (
|
||||
|
||||
{/* Show ban status badge for admins */}
|
||||
{isAdmin && user.isBanned && (
|
||||
<div className="mt-2">
|
||||
<span className="badge bg-danger">Banned</span>
|
||||
{user.bannedAt && (
|
||||
<small className="text-muted d-block mt-1">
|
||||
Banned on {new Date(user.bannedAt).toLocaleDateString()}
|
||||
</small>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Message button - hide for banned users */}
|
||||
{currentUser && currentUser.id !== user.id && !user.isBanned && (
|
||||
<button
|
||||
className="btn btn-primary mt-3"
|
||||
onClick={() => setShowChat(true)}
|
||||
@@ -83,6 +124,35 @@ const PublicProfile: React.FC = () => {
|
||||
<i className="bi bi-chat-dots-fill me-2"></i>Message
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Admin Ban/Unban buttons */}
|
||||
{canBanUser && (
|
||||
<div className="mt-3">
|
||||
{user.isBanned ? (
|
||||
<button
|
||||
className="btn btn-success"
|
||||
onClick={() => setShowUnbanModal(true)}
|
||||
>
|
||||
<i className="bi bi-person-check me-2"></i>Unban User
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
className="btn btn-danger"
|
||||
onClick={() => setShowBanModal(true)}
|
||||
>
|
||||
<i className="bi bi-person-x me-2"></i>Ban User
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Show ban reason for admins */}
|
||||
{isAdmin && user.isBanned && user.banReason && (
|
||||
<div className="alert alert-warning mt-3 text-start">
|
||||
<strong>Ban Reason:</strong>
|
||||
<p className="mb-0 mt-1">{user.banReason}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -153,6 +223,31 @@ const PublicProfile: React.FC = () => {
|
||||
recipient={user}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* BanUserModal */}
|
||||
{user && (
|
||||
<BanUserModal
|
||||
show={showBanModal}
|
||||
onHide={() => setShowBanModal(false)}
|
||||
user={user}
|
||||
onBanComplete={handleBanComplete}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* UnbanModal */}
|
||||
{user && (
|
||||
<ConfirmationModal
|
||||
show={showUnbanModal}
|
||||
onClose={() => setShowUnbanModal(false)}
|
||||
onConfirm={handleUnban}
|
||||
title={`Unban ${user.firstName} ${user.lastName}`}
|
||||
message="Are you sure you want to unban this user? They will be able to log in and use the platform again."
|
||||
confirmText="Unban User"
|
||||
cancelText="Cancel"
|
||||
confirmButtonClass="btn-success"
|
||||
loading={unbanning}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -184,6 +184,10 @@ export const userAPI = {
|
||||
getPublicProfile: (id: string) => api.get(`/users/${id}`),
|
||||
getAvailability: () => api.get("/users/availability"),
|
||||
updateAvailability: (data: any) => api.put("/users/availability", data),
|
||||
// Admin endpoints
|
||||
adminBanUser: (id: string, reason: string) =>
|
||||
api.post(`/users/admin/${id}/ban`, { reason }),
|
||||
adminUnbanUser: (id: string) => api.post(`/users/admin/${id}/unban`),
|
||||
};
|
||||
|
||||
export const addressAPI = {
|
||||
|
||||
@@ -33,6 +33,11 @@ export interface User {
|
||||
stripeConnectedAccountId?: string;
|
||||
addresses?: Address[];
|
||||
itemRequestNotificationRadius?: number;
|
||||
// Ban-related fields (only visible to admins)
|
||||
isBanned?: boolean;
|
||||
bannedAt?: string;
|
||||
bannedBy?: string;
|
||||
banReason?: string;
|
||||
}
|
||||
|
||||
export interface Message {
|
||||
|
||||
Reference in New Issue
Block a user