Skip to content

Commit

Permalink
start working on making banned page work
Browse files Browse the repository at this point in the history
  • Loading branch information
singharaj-usai committed Oct 9, 2024
1 parent 4c7fed3 commit df38e06
Show file tree
Hide file tree
Showing 5 changed files with 71 additions and 42 deletions.
2 changes: 1 addition & 1 deletion client/html/pages/banned/banned.html
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ <h4 class="alert-heading">Your account has been banned</h4>
<script>
$(document).ready(function() {
$.ajax({
url: '/api/users/check-ban',
url: '/api/auth/check-ban',
method: 'GET',
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`
Expand Down
43 changes: 25 additions & 18 deletions server/functions/api/middleware/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,33 @@ const User = require('../models/User');

const isAuthenticated = async (req, res, next) => {
try {
const token = req.headers.authorization?.split(' ')[1];

if (!token) {
return res.status(401).json({ message: 'Authentication required' });
}

const decoded = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(decoded.userId);

if (!user) {
return res.status(401).json({ message: 'User not found' });
}

req.user = user;
next();
const token = req.headers.authorization?.split(' ')[1];

if (!token) {
return res.status(401).json({ message: 'Authentication required' });
}

const decoded = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(decoded.userId);

if (!user) {
return res.status(401).json({ message: 'User not found' });
}

if (user.isBanned) {
return res.status(403).json({
message: 'Your account has been banned',
banReason: user.banReason
});
}

req.user = user;
next();
} catch (error) {
console.error('Authentication error:', error);
res.status(401).json({ message: 'Invalid or expired token' });
console.error('Authentication error:', error);
res.status(401).json({ message: 'Invalid or expired token' });
}
};
};

const isNotAuthenticated = (req, res, next) => {
if (req.session.userId) {
Expand Down
48 changes: 26 additions & 22 deletions server/functions/api/routes/admin.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const ForumPost = require('../models/ForumPost');
const Reply = require('../models/Reply');
const isAdmin = require('../middleware/adminAuth');
const { isAuthenticated } = require('../middleware/auth');
const authenticateToken = require('../middleware/authenticateToken');

// Apply isAuthenticated middleware to all admin routes
router.use(isAuthenticated);
Expand All @@ -17,7 +18,7 @@ router.get('/check-auth', (req, res) => {
});

// Promote user to admin
router.post('/promote-admin/:id', async (req, res) => {
router.post('/promote-admin/:id', authenticateToken, async (req, res) => {
try {
const userToPromote = await User.findById(req.params.id);
if (!userToPromote) {
Expand All @@ -38,7 +39,7 @@ router.post('/promote-admin/:id', async (req, res) => {
}
});

router.post('/demote-admin/:id', async (req, res) => {
router.post('/demote-admin/:id', authenticateToken, async (req, res) => {
try {
const userToDemote = await User.findById(req.params.id);
if (!userToDemote) {
Expand All @@ -65,7 +66,7 @@ router.post('/demote-admin/:id', async (req, res) => {

// Get all forum posts
// Get all forum posts
router.get('/forum-posts', async (req, res) => {
router.get('/forum-posts', authenticateToken, async (req, res) => {
try {
const posts = await ForumPost.find()
.populate('author', 'username')
Expand All @@ -81,7 +82,7 @@ router.get('/forum-posts', async (req, res) => {
}
});

router.post('/forum-posts/:id/toggle-pin', async (req, res) => {
router.post('/forum-posts/:id/toggle-pin', authenticateToken, async (req, res) => {
try {
const post = await ForumPost.findById(req.params.id);
if (!post) {
Expand All @@ -100,7 +101,7 @@ router.post('/forum-posts/:id/toggle-pin', async (req, res) => {
});

// Delete a forum post
router.delete('/forum-posts/:id', async (req, res) => {
router.delete('/forum-posts/:id', authenticateToken, async (req, res) => {
try {
const post = await ForumPost.findById(req.params.id);
if (!post) {
Expand All @@ -122,7 +123,7 @@ router.delete('/forum-posts/:id', async (req, res) => {
}
});
// Delete a forum reply
router.delete('/forum-replies/:id', async (req, res) => {
router.delete('/forum-replies/:id', authenticateToken, async (req, res) => {
try {
const reply = await Replies.findById(req.params.id);
if (!reply) {
Expand All @@ -145,38 +146,41 @@ router.delete('/forum-replies/:id', async (req, res) => {
}
});

// Get all users
router.get('/users', async (req, res) => {
// Get all users
router.get('/users', authenticateToken, async (req, res) => {
try {
const users = await User.find({}, '-password');
res.json(users);
const users = await User.find({}, '-password');
res.json(users);
} catch (error) {
res.status(500).json({ error: 'Error fetching users' });
console.error('Error fetching users:', error);
res.status(500).json({ error: 'Internal server error' });
}
});

router.post('/users/:userId/ban', async (req, res) => {
router.post('/users/:userId/ban', authenticateToken, async (req, res) => {
try {
const user = await User.findById(req.params.userId);
const { userId } = req.params;
const { ban, banReason } = req.body;

const user = await User.findById(userId);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}

user.isBanned = req.body.ban;
if (req.body.ban) {
user.banReason = req.body.banReason;
} else {
user.banReason = null;
}

user.isBanned = ban;
user.banReason = ban ? banReason : null;
await user.save();

res.json({ message: req.body.ban ? 'User banned successfully' : 'User unbanned successfully' });
res.json({ message: ban ? 'User banned successfully' : 'User unbanned successfully' });
} catch (error) {
res.status(500).json({ error: 'Error updating user ban status' });
console.error('Error banning/unbanning user:', error);
res.status(500).json({ error: 'Internal server error' });
}
});




// Get all games
router.get('/games', async (req, res) => {
try {
Expand Down
19 changes: 18 additions & 1 deletion server/functions/api/routes/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,21 @@ router.get("/validate-session", async (req, res) => {
}
});


// Check if user is banned
router.get("/check-ban", authenticateToken, async (req, res) => {
try {
const user = await User.findById(req.user.userId);
if (!user) {
return res.status(404).json({ error: "User not found" });
}
res.json({ isBanned: user.isBanned, banReason: user.banReason });
} catch (error) {
console.error("Error checking ban status:", error);
res.status(500).json({ error: "Internal server error" });
}
});

// Login endpoint
router.post("/login", async (req, res) => {
try {
Expand Down Expand Up @@ -298,7 +313,9 @@ router.post("/login", async (req, res) => {
username: user.username,
userId: user.userId,
signupDate: user.signupDate,
lastLoggedIn: user.lastLoggedIn
lastLoggedIn: user.lastLoggedIn,
isBanned: user.isBanned,
banReason: user.banReason
});
} catch (error) {
console.error("Login error:", error);
Expand Down
1 change: 1 addition & 0 deletions server/functions/api/routes/pages.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ router.get("/register", (req, res) => sendHtmlFile(res, "pages/authentication/re
router.get("/auth/verify-email/:token", (req, res) => sendHtmlFile(res, "pages/authentication/email-verified.html"));


router.get("/banned", (req, res) => sendHtmlFile(res, "pages/banned/banned.html"));


// User-related pages
Expand Down

0 comments on commit df38e06

Please sign in to comment.