-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathboardPermissionCheck.js
More file actions
86 lines (72 loc) · 2.69 KB
/
boardPermissionCheck.js
File metadata and controls
86 lines (72 loc) · 2.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
const boardModel = require("../models/boardModel");
const dashboardModel = require("../models/dashboardModel");
/**
* Middleware to check if user has required role for a board's dashboard
* Extracts dashboardId from the board and checks permissions
* @param {Array<string>} allowedRoles - Array of roles that can access (e.g., ['Admin', 'Editor'])
*/
function checkBoardPermission(allowedRoles) {
return async (req, res, next) => {
try {
const userId = req.user.userId || req.user.id;
const boardId = parseInt(req.params.boardId || req.body.boardId);
if (!boardId) {
return res.status(400).json({ error: "Board ID is required" });
}
// Get the board to find its dashboard
const board = await boardModel.getBoard(boardId);
if (!board) {
return res.status(404).json({ error: "Board not found" });
}
const dashboardId = board.DashboardId;
const userRole = await dashboardModel.getUserRole(userId, dashboardId);
if (!userRole) {
return res.status(403).json({ error: "You do not have access to this dashboard" });
}
if (!allowedRoles.includes(userRole)) {
return res.status(403).json({
error: `Access denied. Required role: ${allowedRoles.join(" or ")}. Your role: ${userRole}`
});
}
req.userRole = userRole;
req.dashboardId = dashboardId;
next();
} catch (error) {
console.error("Board permission check error:", error);
res.status(500).json({ error: "Internal server error" });
}
};
}
/**
* Middleware for checking permissions when creating a board (dashboardId in params)
*/
function checkDashboardForBoardCreation(allowedRoles) {
return async (req, res, next) => {
try {
const userId = req.user.userId || req.user.id;
const dashboardId = parseInt(req.params.dashboardId || req.body.dashboardId);
if (!dashboardId) {
return res.status(400).json({ error: "Dashboard ID is required" });
}
const userRole = await dashboardModel.getUserRole(userId, dashboardId);
if (!userRole) {
return res.status(403).json({ error: "You do not have access to this dashboard" });
}
if (!allowedRoles.includes(userRole)) {
return res.status(403).json({
error: `Access denied. Required role: ${allowedRoles.join(" or ")}. Your role: ${userRole}`
});
}
req.userRole = userRole;
req.dashboardId = dashboardId;
next();
} catch (error) {
console.error("Dashboard permission check error:", error);
res.status(500).json({ error: "Internal server error" });
}
};
}
module.exports = {
checkBoardPermission,
checkDashboardForBoardCreation
};