-
-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathuserStateController.js
More file actions
362 lines (301 loc) · 11.1 KB
/
Copy pathuserStateController.js
File metadata and controls
362 lines (301 loc) · 11.1 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
const mongoose = require('mongoose');
const UserStateCatalog = require('../models/userStateCatalog');
const UserStateSelection = require('../models/userStateSelection');
const ALLOWED_COLORS = [
'#3498db',
'#27ae60',
'#9b59b6',
'#e67e22',
'#e74c3c',
'#16a085',
'#2c3e50',
'#e91e8c',
'#f1c40f',
'#3f51b5',
'#00bcd4',
'#795548',
'#8bc34a',
'#673ab7',
'#607d8b',
];
const slugify = (s) =>
s
.replace(/[\p{Emoji_Presentation}\p{Extended_Pictographic}]/gu, '')
.toLowerCase()
.replaceAll(/[^a-z0-9\s]+/gu, '')
.trim()
.replaceAll(/\s+/gu, '-');
const generateKey = (label) => {
const base = slugify(label);
const suffix = Math.random().toString(36).slice(2, 6);
return base ? `${base}-${suffix}` : suffix;
};
function checkManage(req) {
const requestor = req.body?.requestor || {};
return (
requestor.role === 'Owner' ||
requestor.role === 'Administrator' ||
(Array.isArray(requestor.permissions) &&
requestor.permissions.includes('manage_user_state_indicator'))
);
}
// Fix: validate userId as a real MongoDB ObjectId — SonarCloud safe
function parseUserId(id) {
if (!mongoose.Types.ObjectId.isValid(id)) return null;
return new mongoose.Types.ObjectId(id);
}
// Fix: whitelist-based key sanitization
function sanitizeKey(key) {
if (typeof key !== 'string') return null;
const clean = key.replaceAll(/[^a-z0-9-]/gu, '');
return clean || null;
}
// Fix: escape user input before using in regex
function escapeRegex(str) {
return str.replaceAll(/[$()*+.?[\\\]^{|}]/gu, String.raw`\$&`);
}
const listCatalog = async (req, res) => {
try {
const items = await UserStateCatalog.find({ isActive: true }).sort({ order: 1 }).lean();
return res.json({ items });
} catch (listError) {
return res.status(500).json({ error: 'db error', details: listError.message });
}
};
function sanitizeEmoji(emoji) {
if (typeof emoji !== 'string') return null;
return [...emoji]
.filter((c) => /\p{Emoji_Presentation}|\p{Extended_Pictographic}/u.test(c))
.join('')
.slice(0, 2);
}
const createCatalog = async (req, res) => {
if (!checkManage(req)) return res.status(403).json({ error: 'Forbidden' });
try {
const { label, color, emoji } = req.body || {};
if (!label || typeof label !== 'string') {
return res.status(400).json({ error: 'label is required' });
}
if (label.length > 30) {
return res.status(400).json({ error: 'label must be ≤ 30 chars' });
}
const key = generateKey(label);
const max = await UserStateCatalog.findOne().sort({ order: -1 }).lean();
const nextOrder = max ? max.order + 1 : 0;
const safeLabel = [...label]
.filter((c) => c.codePointAt(0) >= 32 && c.codePointAt(0) !== 127)
.join('')
.slice(0, 30);
const safeColor = ALLOWED_COLORS.includes(color)
? color
: ALLOWED_COLORS[nextOrder % ALLOWED_COLORS.length];
const safeEmoji = sanitizeEmoji(emoji) ?? '';
const escapedLabel = escapeRegex(safeLabel);
const clash = await UserStateCatalog.findOne({
label: { $regex: `^${escapedLabel}$`, $options: 'i' },
emoji: safeEmoji,
isActive: true,
}).lean();
if (clash) {
return res.status(409).json({ error: 'A state with this label and emoji already exists' });
}
const item = await UserStateCatalog.create({
key: String(key),
label: String(safeLabel),
emoji: String(safeEmoji),
color: String(safeColor),
order: Number(nextOrder),
isActive: true,
});
return res.status(201).json({ item });
} catch (createError) {
return res.status(500).json({ error: 'db error', details: createError.message });
}
};
const reorderCatalog = async (req, res) => {
if (!checkManage(req)) return res.status(403).json({ error: 'Forbidden' });
const { orderedKeys } = req.body || {};
if (!Array.isArray(orderedKeys)) {
return res.status(400).json({ error: 'orderedKeys must be array' });
}
try {
const count = await UserStateCatalog.countDocuments({ isActive: true });
if (orderedKeys.length !== count) {
return res.status(400).json({ error: 'orderedKeys must match catalog keys' });
}
const docs = await UserStateCatalog.find({ isActive: true }, 'key').lean();
const existing = new Set(docs.map((d) => d.key));
if (!orderedKeys.every((k) => existing.has(k))) {
return res.status(400).json({ error: 'orderedKeys must match catalog keys' });
}
const sanitizedKeys = orderedKeys.map((k) => sanitizeKey(k)).filter(Boolean);
await UserStateCatalog.bulkWrite(
sanitizedKeys.map((k, i) => ({
updateOne: { filter: { key: { $eq: k } }, update: { $set: { order: i } } },
})),
);
const items = await UserStateCatalog.find({ isActive: true }).sort({ order: 1 }).lean();
return res.json({ items });
} catch (reorderError) {
return res.status(500).json({ error: 'db error', details: reorderError.message });
}
};
async function checkLabelClash(trimmed, itemId, resolvedEmoji) {
const escapedTrimmed = escapeRegex(trimmed);
return UserStateCatalog.findOne({
_id: { $ne: itemId },
label: { $regex: `^${escapedTrimmed}$`, $options: 'i' },
emoji: resolvedEmoji,
isActive: true,
}).lean();
}
async function handleIsActive(item, isActive, key) {
item.isActive = isActive;
if (isActive === false) {
await UserStateSelection.updateMany(
{ 'stateIndicators.key': key },
{ $pull: { stateIndicators: { key } } },
);
}
}
const updateCatalog = async (req, res) => {
if (!checkManage(req)) return res.status(403).json({ error: 'Forbidden' });
const key = sanitizeKey(req.params.key);
if (!key) return res.status(400).json({ error: 'invalid key' });
const { label, color, emoji, isActive } = req.body || {};
const safeEmoji = sanitizeEmoji(emoji);
try {
const item = await UserStateCatalog.findOne({ key: { $eq: String(key) } });
if (!item) return res.status(404).json({ error: 'not found' });
if (typeof label === 'string') {
const trimmed = label.trim();
if (!trimmed) return res.status(400).json({ error: 'label cannot be empty' });
if (trimmed.length > 30) return res.status(400).json({ error: 'label must be ≤ 30 chars' });
const resolvedEmoji = safeEmoji === null ? item.emoji : safeEmoji;
const clash = await checkLabelClash(trimmed, item._id, resolvedEmoji);
if (clash)
return res.status(409).json({ error: 'A state with this label and emoji already exists' });
item.label = trimmed;
}
if (typeof color === 'string' && ALLOWED_COLORS.includes(color)) {
item.color = color;
}
if (typeof emoji === 'string') {
item.emoji = safeEmoji;
}
if (typeof isActive === 'boolean') {
await handleIsActive(item, isActive, key);
}
await item.save();
return res.json({ item });
} catch (updateError) {
return res.status(500).json({ error: 'db error', details: updateError.message });
}
};
const getCatalogItemUsage = async (req, res) => {
if (!checkManage(req)) return res.status(403).json({ error: 'Forbidden' });
const { key } = req.params;
if (!key) return res.status(400).json({ error: 'key is required' });
try {
const count = await UserStateSelection.countDocuments({
'stateIndicators.key': key,
});
return res.json({ key, count });
} catch (err) {
return res.status(500).json({ error: 'db error', details: err.message });
}
};
const getUserSelections = async (req, res) => {
// Fix L172: validate userId as ObjectId — SonarCloud safe
const userId = parseUserId(req.params.userId);
if (!userId) return res.status(400).json({ error: 'invalid userId' });
try {
const doc = await UserStateSelection.findOne({ userId: { $eq: userId } }).lean();
return res.json({ userId, stateIndicators: doc?.stateIndicators || [] });
} catch (getError) {
return res.status(500).json({ error: 'db error', details: getError.message });
}
};
const setUserSelections = async (req, res) => {
if (!checkManage(req)) return res.status(403).json({ error: 'Forbidden' });
// Fix L205, L218: validate userId as ObjectId — SonarCloud safe
const userId = parseUserId(req.params.userId);
if (!userId) return res.status(400).json({ error: 'invalid userId' });
const { selectedKeys } = req.body || {};
if (!Array.isArray(selectedKeys)) {
return res.status(400).json({ error: 'selectedKeys must be array' });
}
try {
const active = await UserStateCatalog.find({ isActive: true }, 'key order').lean();
const activeByKey = new Map(active.map((c) => [c.key, c]));
for (const k of selectedKeys) {
if (!activeByKey.has(k)) {
return res.status(400).json({ error: `invalid or inactive key: ${k}` });
}
}
if (selectedKeys.length > 10) {
return res.status(400).json({ error: 'too many selections (max 10)' });
}
const existing = await UserStateSelection.findOne({ userId: { $eq: userId } }).lean();
const existingMap = new Map(
(existing?.stateIndicators || []).map((s) => [s.key, s.selectedAt]),
);
const normalized = active
.sort((a, b) => a.order - b.order)
.filter((c) => selectedKeys.includes(c.key))
.map((c) => ({
key: c.key,
selectedAt: existingMap.get(c.key) || new Date(),
}));
const doc = await UserStateSelection.findOneAndUpdate(
{ userId: { $eq: userId } },
{ $set: { stateIndicators: normalized } },
{ new: true, upsert: true },
).lean();
return res.json({ userId, stateIndicators: doc.stateIndicators });
} catch (setError) {
return res.status(500).json({ error: 'db error', details: setError.message });
}
};
const getBatchUserSelections = async (req, res) => {
const { userIds } = req.body || {};
if (!Array.isArray(userIds) || userIds.length === 0) {
return res.status(400).json({ error: 'userIds must be a non-empty array' });
}
// Most users (managers, mentors) have small teams (10-50 members) so this is fast.
// Owners/Admins may have 1000+ users — pagination should be implemented for that case - will handle later on
if (userIds.length > 3000) {
return res
.status(400)
.json({ error: `too many userIds (max 300), received: ${userIds.length}` });
}
// Validate each as a proper ObjectId before hitting the DB
const validIds = userIds.map((id) => parseUserId(id)).filter(Boolean);
if (validIds.length === 0) {
return res.status(400).json({ error: 'no valid userIds provided' });
}
try {
const docs = await UserStateSelection.find(
{ userId: { $in: validIds } },
'userId stateIndicators',
).lean();
// Shape into { [userId]: stateIndicators[] } for easy lookup on the frontend
const selections = {};
for (const doc of docs) {
selections[String(doc.userId)] = doc.stateIndicators || [];
}
return res.json({ selections });
} catch (batchError) {
return res.status(500).json({ error: 'db error', details: batchError.message });
}
};
module.exports = {
listCatalog,
createCatalog,
reorderCatalog,
updateCatalog,
getCatalogItemUsage,
getUserSelections,
setUserSelections,
getBatchUserSelections,
};