powr-sdk-api 4.10.2 → 4.10.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +4 -0
- package/dist/middleware/serviceKey.js +44 -0
- package/dist/middleware/serviceKey.test.js +50 -0
- package/dist/routes/index.js +5 -2
- package/dist/routes/profiles.js +55 -8
- package/dist/routes/users.js +192 -62
- package/dist/utils/usersQuery.js +96 -0
- package/dist/utils/usersQuery.test.js +53 -0
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -27,6 +27,9 @@ const {
|
|
|
27
27
|
const {
|
|
28
28
|
verifyToken
|
|
29
29
|
} = require("./middleware/jwtToken");
|
|
30
|
+
const {
|
|
31
|
+
verifyTokenOrServiceKey
|
|
32
|
+
} = require("./middleware/serviceKey");
|
|
30
33
|
const {
|
|
31
34
|
getDb: getPowrDb
|
|
32
35
|
} = require("./services/mongo");
|
|
@@ -41,6 +44,7 @@ module.exports = {
|
|
|
41
44
|
initializeFunctions,
|
|
42
45
|
initializeTools,
|
|
43
46
|
verifyToken,
|
|
47
|
+
verifyTokenOrServiceKey,
|
|
44
48
|
executeTasks,
|
|
45
49
|
executeTool,
|
|
46
50
|
createTask,
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const crypto = require("crypto");
|
|
4
|
+
const {
|
|
5
|
+
verifyToken
|
|
6
|
+
} = require("./jwtToken");
|
|
7
|
+
function serviceKeyFromEnv() {
|
|
8
|
+
return process.env.POWR_SERVICE_KEY || process.env.SERVICE_KEY || "";
|
|
9
|
+
}
|
|
10
|
+
function safeEqual(a, b) {
|
|
11
|
+
const left = crypto.createHash("sha256").update(String(a)).digest();
|
|
12
|
+
const right = crypto.createHash("sha256").update(String(b)).digest();
|
|
13
|
+
return crypto.timingSafeEqual(left, right);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Accept a user JWT or X-Service-Key (project-to-project).
|
|
18
|
+
* Service key is POWR_SERVICE_KEY (SERVICE_KEY alias). JWT path unchanged.
|
|
19
|
+
*/
|
|
20
|
+
const verifyTokenOrServiceKey = async (req, res, next) => {
|
|
21
|
+
const provided = req.get("X-Service-Key");
|
|
22
|
+
if (provided) {
|
|
23
|
+
const expected = serviceKeyFromEnv();
|
|
24
|
+
if (!expected) {
|
|
25
|
+
return res.status(503).json({
|
|
26
|
+
success: false,
|
|
27
|
+
message: "Service key is not configured."
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
if (!safeEqual(provided, expected)) {
|
|
31
|
+
return res.status(401).json({
|
|
32
|
+
success: false,
|
|
33
|
+
message: "Unauthorized: valid X-Service-Key required."
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
req.serviceCall = true;
|
|
37
|
+
return next();
|
|
38
|
+
}
|
|
39
|
+
return verifyToken(req, res, next);
|
|
40
|
+
};
|
|
41
|
+
module.exports = {
|
|
42
|
+
verifyTokenOrServiceKey,
|
|
43
|
+
serviceKeyFromEnv
|
|
44
|
+
};
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
jest.mock("./jwtToken", () => ({
|
|
4
|
+
verifyToken: jest.fn((req, res, next) => next())
|
|
5
|
+
}));
|
|
6
|
+
const {
|
|
7
|
+
verifyTokenOrServiceKey
|
|
8
|
+
} = require("./serviceKey");
|
|
9
|
+
function mockRes() {
|
|
10
|
+
const res = {};
|
|
11
|
+
res.status = jest.fn().mockReturnValue(res);
|
|
12
|
+
res.json = jest.fn().mockReturnValue(res);
|
|
13
|
+
return res;
|
|
14
|
+
}
|
|
15
|
+
describe("verifyTokenOrServiceKey", () => {
|
|
16
|
+
const previous = process.env.POWR_SERVICE_KEY;
|
|
17
|
+
afterEach(() => {
|
|
18
|
+
if (previous === undefined) delete process.env.POWR_SERVICE_KEY;else process.env.POWR_SERVICE_KEY = previous;
|
|
19
|
+
});
|
|
20
|
+
it("accepts a matching X-Service-Key", async () => {
|
|
21
|
+
process.env.POWR_SERVICE_KEY = "test-powr-service-key";
|
|
22
|
+
const req = {
|
|
23
|
+
get: name => name === "X-Service-Key" ? "test-powr-service-key" : undefined
|
|
24
|
+
};
|
|
25
|
+
const res = mockRes();
|
|
26
|
+
const next = jest.fn();
|
|
27
|
+
await verifyTokenOrServiceKey(req, res, next);
|
|
28
|
+
expect(next).toHaveBeenCalled();
|
|
29
|
+
expect(req.serviceCall).toBe(true);
|
|
30
|
+
});
|
|
31
|
+
it("rejects a wrong key", async () => {
|
|
32
|
+
process.env.POWR_SERVICE_KEY = "test-powr-service-key";
|
|
33
|
+
const req = {
|
|
34
|
+
get: () => "nope"
|
|
35
|
+
};
|
|
36
|
+
const res = mockRes();
|
|
37
|
+
await verifyTokenOrServiceKey(req, res, jest.fn());
|
|
38
|
+
expect(res.status).toHaveBeenCalledWith(401);
|
|
39
|
+
});
|
|
40
|
+
it("returns 503 when a key is sent but none is configured", async () => {
|
|
41
|
+
delete process.env.POWR_SERVICE_KEY;
|
|
42
|
+
delete process.env.SERVICE_KEY;
|
|
43
|
+
const req = {
|
|
44
|
+
get: () => "any"
|
|
45
|
+
};
|
|
46
|
+
const res = mockRes();
|
|
47
|
+
await verifyTokenOrServiceKey(req, res, jest.fn());
|
|
48
|
+
expect(res.status).toHaveBeenCalledWith(503);
|
|
49
|
+
});
|
|
50
|
+
});
|
package/dist/routes/index.js
CHANGED
|
@@ -7,6 +7,9 @@ const {
|
|
|
7
7
|
const {
|
|
8
8
|
verifyToken
|
|
9
9
|
} = require('../middleware/jwtToken');
|
|
10
|
+
const {
|
|
11
|
+
verifyTokenOrServiceKey
|
|
12
|
+
} = require('../middleware/serviceKey');
|
|
10
13
|
|
|
11
14
|
// Import all route modules
|
|
12
15
|
const commentsRoutes = require('./comments');
|
|
@@ -44,12 +47,12 @@ const createPowrRoutes = (options = {}) => {
|
|
|
44
47
|
router.use('/likes', verifyToken, likesRoutes);
|
|
45
48
|
router.use('/functions', verifyToken, functionsRoutes);
|
|
46
49
|
router.use('/ratings', verifyToken, ratingsRoutes);
|
|
47
|
-
router.use('/users',
|
|
50
|
+
router.use('/users', verifyTokenOrServiceKey, usersRoutes);
|
|
48
51
|
router.use('/waitlists', verifyToken, waitlistsRoutes);
|
|
49
52
|
router.use('/activities', verifyToken, activitiesRoutes);
|
|
50
53
|
router.use('/slides', verifyToken, slidesRoutes);
|
|
51
54
|
router.use('/notifications', verifyToken, notificationsRoutes);
|
|
52
|
-
router.use('/profiles',
|
|
55
|
+
router.use('/profiles', verifyTokenOrServiceKey, profilesRoutes);
|
|
53
56
|
router.use('/chat', verifyToken, chatRoutes);
|
|
54
57
|
router.use('/feeds', verifyToken, feedsRoutes);
|
|
55
58
|
router.use('/tools', verifyToken, toolsRoutes);
|
package/dist/routes/profiles.js
CHANGED
|
@@ -5,12 +5,15 @@ const router = express.Router();
|
|
|
5
5
|
const {
|
|
6
6
|
getDb
|
|
7
7
|
} = require("../services/mongo");
|
|
8
|
+
const {
|
|
9
|
+
parseObjectId
|
|
10
|
+
} = require("../utils/usersQuery");
|
|
11
|
+
const PROFILE_FIELDS = ["department", "notificationSettings", "isActive", "access"];
|
|
8
12
|
|
|
9
13
|
// Get all users for a project
|
|
10
14
|
router.get("/", async (req, res) => {
|
|
11
15
|
try {
|
|
12
|
-
const projectId = req.projectId;
|
|
13
|
-
|
|
16
|
+
const projectId = req.projectId;
|
|
14
17
|
const db = await getDb();
|
|
15
18
|
const profiles = await db.collection("profiles").find({
|
|
16
19
|
projectId: projectId
|
|
@@ -21,16 +24,12 @@ router.get("/", async (req, res) => {
|
|
|
21
24
|
users: []
|
|
22
25
|
});
|
|
23
26
|
}
|
|
24
|
-
|
|
25
|
-
// Get core user data for all profiles
|
|
26
27
|
const userIds = profiles.map(profile => profile.userId);
|
|
27
28
|
const users = await db.collection("users").find({
|
|
28
29
|
_id: {
|
|
29
30
|
$in: userIds
|
|
30
31
|
}
|
|
31
32
|
}).toArray();
|
|
32
|
-
|
|
33
|
-
// Create a map for quick lookup
|
|
34
33
|
const usersMap = users.reduce((acc, user) => {
|
|
35
34
|
const {
|
|
36
35
|
password,
|
|
@@ -39,8 +38,6 @@ router.get("/", async (req, res) => {
|
|
|
39
38
|
acc[user._id.toString()] = userWithoutPassword;
|
|
40
39
|
return acc;
|
|
41
40
|
}, {});
|
|
42
|
-
|
|
43
|
-
// Merge user and profile data
|
|
44
41
|
const usersWithProfiles = profiles.map(profile => ({
|
|
45
42
|
...usersMap[profile.userId.toString()],
|
|
46
43
|
...profile
|
|
@@ -57,4 +54,54 @@ router.get("/", async (req, res) => {
|
|
|
57
54
|
});
|
|
58
55
|
}
|
|
59
56
|
});
|
|
57
|
+
|
|
58
|
+
// Upsert extra profile fields for one user in this project (Office extras).
|
|
59
|
+
router.patch("/:userId", async (req, res) => {
|
|
60
|
+
try {
|
|
61
|
+
const projectId = req.projectId;
|
|
62
|
+
const userId = parseObjectId(req.params.userId);
|
|
63
|
+
if (!userId) {
|
|
64
|
+
return res.status(400).json({
|
|
65
|
+
success: false,
|
|
66
|
+
message: "Invalid userId"
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
const $set = {
|
|
70
|
+
updatedAt: new Date(),
|
|
71
|
+
lastActiveAt: new Date()
|
|
72
|
+
};
|
|
73
|
+
for (const key of PROFILE_FIELDS) {
|
|
74
|
+
var _req$body;
|
|
75
|
+
if (((_req$body = req.body) === null || _req$body === void 0 ? void 0 : _req$body[key]) !== undefined) $set[key] = req.body[key];
|
|
76
|
+
}
|
|
77
|
+
const db = await getDb();
|
|
78
|
+
await db.collection("profiles").updateOne({
|
|
79
|
+
userId,
|
|
80
|
+
projectId
|
|
81
|
+
}, {
|
|
82
|
+
$set,
|
|
83
|
+
$setOnInsert: {
|
|
84
|
+
userId,
|
|
85
|
+
projectId,
|
|
86
|
+
createdAt: new Date()
|
|
87
|
+
}
|
|
88
|
+
}, {
|
|
89
|
+
upsert: true
|
|
90
|
+
});
|
|
91
|
+
const profile = await db.collection("profiles").findOne({
|
|
92
|
+
userId,
|
|
93
|
+
projectId
|
|
94
|
+
});
|
|
95
|
+
return res.json({
|
|
96
|
+
success: true,
|
|
97
|
+
profile
|
|
98
|
+
});
|
|
99
|
+
} catch (error) {
|
|
100
|
+
console.error("Error updating profile:", error);
|
|
101
|
+
return res.status(500).json({
|
|
102
|
+
success: false,
|
|
103
|
+
message: "Failed to update profile"
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
});
|
|
60
107
|
module.exports = router;
|
package/dist/routes/users.js
CHANGED
|
@@ -8,27 +8,82 @@ const {
|
|
|
8
8
|
const {
|
|
9
9
|
ObjectId
|
|
10
10
|
} = require("mongodb");
|
|
11
|
-
const {
|
|
12
|
-
verifyToken
|
|
13
|
-
} = require("../middleware/jwtToken");
|
|
14
11
|
const {
|
|
15
12
|
getClientIp
|
|
16
13
|
} = require("../utils/getClientIp");
|
|
17
14
|
const {
|
|
18
15
|
coercePhoneForStorage
|
|
19
16
|
} = require("../utils/phone");
|
|
17
|
+
const {
|
|
18
|
+
buildUsersFilter,
|
|
19
|
+
phoneVariants
|
|
20
|
+
} = require("../utils/usersQuery");
|
|
21
|
+
function stripPassword(user) {
|
|
22
|
+
if (!user) return user;
|
|
23
|
+
const {
|
|
24
|
+
password,
|
|
25
|
+
...rest
|
|
26
|
+
} = user;
|
|
27
|
+
return rest;
|
|
28
|
+
}
|
|
29
|
+
function findUserQuery({
|
|
30
|
+
phoneNumber,
|
|
31
|
+
email
|
|
32
|
+
}) {
|
|
33
|
+
const or = [];
|
|
34
|
+
if (phoneNumber) {
|
|
35
|
+
const variants = phoneVariants(phoneNumber);
|
|
36
|
+
if (variants.length) or.push({
|
|
37
|
+
phoneNumber: {
|
|
38
|
+
$in: variants
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
if (email) {
|
|
43
|
+
const trimmed = String(email).trim();
|
|
44
|
+
if (trimmed) {
|
|
45
|
+
or.push({
|
|
46
|
+
email: trimmed
|
|
47
|
+
});
|
|
48
|
+
or.push({
|
|
49
|
+
email: trimmed.toLowerCase()
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return or.length ? {
|
|
54
|
+
$or: or
|
|
55
|
+
} : null;
|
|
56
|
+
}
|
|
57
|
+
async function mergeProfiles(db, users, projectId) {
|
|
58
|
+
const userIds = users.map(user => user._id);
|
|
59
|
+
const profiles = userIds.length ? await db.collection("profiles").find({
|
|
60
|
+
userId: {
|
|
61
|
+
$in: userIds
|
|
62
|
+
},
|
|
63
|
+
projectId
|
|
64
|
+
}).toArray() : [];
|
|
65
|
+
return users.map(user => {
|
|
66
|
+
const profile = profiles.find(p => p.userId.toString() === user._id.toString());
|
|
67
|
+
return {
|
|
68
|
+
...stripPassword(user),
|
|
69
|
+
access: profile ? profile.access : 1,
|
|
70
|
+
projectId,
|
|
71
|
+
department: profile === null || profile === void 0 ? void 0 : profile.department,
|
|
72
|
+
notificationSettings: profile === null || profile === void 0 ? void 0 : profile.notificationSettings,
|
|
73
|
+
isActive: profile === null || profile === void 0 ? void 0 : profile.isActive
|
|
74
|
+
};
|
|
75
|
+
});
|
|
76
|
+
}
|
|
20
77
|
|
|
21
78
|
// Create User
|
|
22
|
-
router.post("/",
|
|
79
|
+
router.post("/", async (req, res) => {
|
|
23
80
|
const {
|
|
24
81
|
phoneNumber,
|
|
25
82
|
email,
|
|
26
83
|
...userData
|
|
27
84
|
} = req.body;
|
|
28
|
-
const projectId = req.projectId;
|
|
29
|
-
|
|
85
|
+
const projectId = req.projectId;
|
|
30
86
|
try {
|
|
31
|
-
// Check if user already exists
|
|
32
87
|
const db = await getDb();
|
|
33
88
|
const storedPhone = phoneNumber && !String(phoneNumber).includes("@") ? coercePhoneForStorage(phoneNumber) : phoneNumber;
|
|
34
89
|
if (phoneNumber && !String(phoneNumber).includes("@") && !storedPhone) {
|
|
@@ -58,8 +113,6 @@ router.post("/", verifyToken, async (req, res) => {
|
|
|
58
113
|
updatedAt: new Date()
|
|
59
114
|
};
|
|
60
115
|
const result = await db.collection("users").insertOne(newUser);
|
|
61
|
-
|
|
62
|
-
// Create profile for this project
|
|
63
116
|
const newProfile = {
|
|
64
117
|
userId: result.insertedId,
|
|
65
118
|
projectId: projectId,
|
|
@@ -83,49 +136,133 @@ router.post("/", verifyToken, async (req, res) => {
|
|
|
83
136
|
}
|
|
84
137
|
});
|
|
85
138
|
|
|
86
|
-
// Get
|
|
87
|
-
router.
|
|
139
|
+
// Get-or-create user + profile upsert (identity resolution).
|
|
140
|
+
router.post("/ensure", async (req, res) => {
|
|
88
141
|
const {
|
|
89
|
-
_id,
|
|
90
142
|
phoneNumber,
|
|
91
|
-
email
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
143
|
+
email,
|
|
144
|
+
fullName,
|
|
145
|
+
access,
|
|
146
|
+
...userData
|
|
147
|
+
} = req.body || {};
|
|
148
|
+
const projectId = req.projectId;
|
|
95
149
|
try {
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
if (phoneNumber) {
|
|
103
|
-
query.phoneNumber = phoneNumber;
|
|
150
|
+
const storedPhone = phoneNumber && !String(phoneNumber).includes("@") ? coercePhoneForStorage(phoneNumber) : phoneNumber || null;
|
|
151
|
+
if (phoneNumber && !String(phoneNumber).includes("@") && !storedPhone) {
|
|
152
|
+
return res.status(400).json({
|
|
153
|
+
success: false,
|
|
154
|
+
message: "Invalid phone number"
|
|
155
|
+
});
|
|
104
156
|
}
|
|
105
|
-
if (email) {
|
|
106
|
-
|
|
157
|
+
if (!storedPhone && !email) {
|
|
158
|
+
return res.status(400).json({
|
|
159
|
+
success: false,
|
|
160
|
+
message: "phoneNumber or email is required"
|
|
161
|
+
});
|
|
107
162
|
}
|
|
108
163
|
const db = await getDb();
|
|
109
|
-
const
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
return {
|
|
124
|
-
...user,
|
|
125
|
-
access: profile ? profile.access : 1,
|
|
126
|
-
projectId: projectId
|
|
164
|
+
const lookup = findUserQuery({
|
|
165
|
+
phoneNumber: storedPhone,
|
|
166
|
+
email
|
|
167
|
+
});
|
|
168
|
+
let user = lookup ? await db.collection("users").findOne(lookup) : null;
|
|
169
|
+
let created = false;
|
|
170
|
+
if (!user) {
|
|
171
|
+
const insert = {
|
|
172
|
+
...userData,
|
|
173
|
+
phoneNumber: storedPhone,
|
|
174
|
+
email: email || null,
|
|
175
|
+
fullName: fullName || "",
|
|
176
|
+
createdAt: new Date(),
|
|
177
|
+
updatedAt: new Date()
|
|
127
178
|
};
|
|
179
|
+
delete insert.access;
|
|
180
|
+
const result = await db.collection("users").insertOne(insert);
|
|
181
|
+
user = {
|
|
182
|
+
...insert,
|
|
183
|
+
_id: result.insertedId
|
|
184
|
+
};
|
|
185
|
+
created = true;
|
|
186
|
+
} else if (fullName && !user.fullName) {
|
|
187
|
+
await db.collection("users").updateOne({
|
|
188
|
+
_id: user._id
|
|
189
|
+
}, {
|
|
190
|
+
$set: {
|
|
191
|
+
fullName,
|
|
192
|
+
updatedAt: new Date()
|
|
193
|
+
}
|
|
194
|
+
});
|
|
195
|
+
user.fullName = fullName;
|
|
196
|
+
}
|
|
197
|
+
const profileSet = {
|
|
198
|
+
updatedAt: new Date(),
|
|
199
|
+
lastActiveAt: new Date()
|
|
200
|
+
};
|
|
201
|
+
if (access !== undefined && access !== null && access !== "") {
|
|
202
|
+
const nextAccess = Number(access);
|
|
203
|
+
if (!Number.isFinite(nextAccess)) {
|
|
204
|
+
return res.status(400).json({
|
|
205
|
+
success: false,
|
|
206
|
+
message: "access must be a number"
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
profileSet.access = nextAccess;
|
|
210
|
+
}
|
|
211
|
+
const profile = await db.collection("profiles").findOne({
|
|
212
|
+
userId: user._id,
|
|
213
|
+
projectId
|
|
128
214
|
});
|
|
215
|
+
const setOnInsert = {
|
|
216
|
+
userId: user._id,
|
|
217
|
+
projectId,
|
|
218
|
+
createdAt: new Date()
|
|
219
|
+
};
|
|
220
|
+
if (profileSet.access === undefined) setOnInsert.access = 1;
|
|
221
|
+
await db.collection("profiles").updateOne({
|
|
222
|
+
userId: user._id,
|
|
223
|
+
projectId
|
|
224
|
+
}, {
|
|
225
|
+
$set: profileSet,
|
|
226
|
+
$setOnInsert: setOnInsert
|
|
227
|
+
}, {
|
|
228
|
+
upsert: true
|
|
229
|
+
});
|
|
230
|
+
const nextAccess = profileSet.access !== undefined ? profileSet.access : profile ? profile.access : 1;
|
|
231
|
+
return res.status(created ? 201 : 200).json({
|
|
232
|
+
success: true,
|
|
233
|
+
created,
|
|
234
|
+
userId: user._id,
|
|
235
|
+
user: {
|
|
236
|
+
...stripPassword(user),
|
|
237
|
+
access: nextAccess,
|
|
238
|
+
projectId
|
|
239
|
+
}
|
|
240
|
+
});
|
|
241
|
+
} catch (error) {
|
|
242
|
+
console.error("Error ensuring user:", error);
|
|
243
|
+
return res.status(500).json({
|
|
244
|
+
success: false,
|
|
245
|
+
message: "Failed to ensure user."
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
// Get Users (exact id / email, last-10 phone variants, batch ids or phones)
|
|
251
|
+
router.get("/", async (req, res) => {
|
|
252
|
+
const projectId = req.projectId;
|
|
253
|
+
try {
|
|
254
|
+
const built = buildUsersFilter(req.query, {
|
|
255
|
+
requireLookup: Boolean(req.serviceCall)
|
|
256
|
+
});
|
|
257
|
+
if (built.error) {
|
|
258
|
+
return res.status(400).json({
|
|
259
|
+
success: false,
|
|
260
|
+
message: built.error
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
const db = await getDb();
|
|
264
|
+
const users = await db.collection("users").find(built.filter).toArray();
|
|
265
|
+
const usersWithProfiles = await mergeProfiles(db, users, projectId);
|
|
129
266
|
return res.json({
|
|
130
267
|
success: true,
|
|
131
268
|
data: usersWithProfiles
|
|
@@ -140,7 +277,7 @@ router.get("/", verifyToken, async (req, res) => {
|
|
|
140
277
|
});
|
|
141
278
|
|
|
142
279
|
// Update User
|
|
143
|
-
router.put("/:id",
|
|
280
|
+
router.put("/:id", async (req, res) => {
|
|
144
281
|
const {
|
|
145
282
|
id
|
|
146
283
|
} = req.params;
|
|
@@ -149,10 +286,8 @@ router.put("/:id", verifyToken, async (req, res) => {
|
|
|
149
286
|
email,
|
|
150
287
|
...userData
|
|
151
288
|
} = req.body;
|
|
152
|
-
const projectId = req.projectId;
|
|
153
|
-
|
|
289
|
+
const projectId = req.projectId;
|
|
154
290
|
try {
|
|
155
|
-
// Check if user exists
|
|
156
291
|
const db = await getDb();
|
|
157
292
|
const existingUser = await db.collection("users").findOne({
|
|
158
293
|
_id: new ObjectId(id)
|
|
@@ -163,9 +298,6 @@ router.put("/:id", verifyToken, async (req, res) => {
|
|
|
163
298
|
message: "User not found"
|
|
164
299
|
});
|
|
165
300
|
}
|
|
166
|
-
|
|
167
|
-
// Only set contact fields when a real value is provided.
|
|
168
|
-
// Ignore undefined AND null so `{ access }` or `{ phoneNumber: null }` cannot wipe phone/email.
|
|
169
301
|
const updateData = {
|
|
170
302
|
updatedAt: new Date()
|
|
171
303
|
};
|
|
@@ -190,8 +322,6 @@ router.put("/:id", verifyToken, async (req, res) => {
|
|
|
190
322
|
}, {
|
|
191
323
|
$set: updateData
|
|
192
324
|
});
|
|
193
|
-
|
|
194
|
-
// Update profile if access level is provided
|
|
195
325
|
if (userData.access !== undefined) {
|
|
196
326
|
await db.collection("profiles").updateOne({
|
|
197
327
|
userId: new ObjectId(id),
|
|
@@ -218,15 +348,19 @@ router.put("/:id", verifyToken, async (req, res) => {
|
|
|
218
348
|
}
|
|
219
349
|
});
|
|
220
350
|
|
|
221
|
-
// Delete User
|
|
222
|
-
router.delete("/:id",
|
|
351
|
+
// Delete User — JWT only (service key cannot delete identity rows)
|
|
352
|
+
router.delete("/:id", async (req, res) => {
|
|
223
353
|
const {
|
|
224
354
|
id
|
|
225
355
|
} = req.params;
|
|
226
|
-
const projectId = req.projectId;
|
|
227
|
-
|
|
356
|
+
const projectId = req.projectId;
|
|
357
|
+
if (req.serviceCall) {
|
|
358
|
+
return res.status(403).json({
|
|
359
|
+
success: false,
|
|
360
|
+
message: "Service key cannot delete users."
|
|
361
|
+
});
|
|
362
|
+
}
|
|
228
363
|
try {
|
|
229
|
-
// Check if user exists
|
|
230
364
|
const db = await getDb();
|
|
231
365
|
const existingUser = await db.collection("users").findOne({
|
|
232
366
|
_id: new ObjectId(id)
|
|
@@ -237,13 +371,9 @@ router.delete("/:id", verifyToken, async (req, res) => {
|
|
|
237
371
|
message: "User not found"
|
|
238
372
|
});
|
|
239
373
|
}
|
|
240
|
-
|
|
241
|
-
// Delete user
|
|
242
374
|
await db.collection("users").deleteOne({
|
|
243
375
|
_id: new ObjectId(id)
|
|
244
376
|
});
|
|
245
|
-
|
|
246
|
-
// Delete profile for this project
|
|
247
377
|
await db.collection("profiles").deleteOne({
|
|
248
378
|
userId: new ObjectId(id),
|
|
249
379
|
projectId: projectId
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const {
|
|
4
|
+
ObjectId
|
|
5
|
+
} = require("mongodb");
|
|
6
|
+
const {
|
|
7
|
+
getPhoneLookupVariants
|
|
8
|
+
} = require("./phone");
|
|
9
|
+
function parseObjectId(value) {
|
|
10
|
+
const id = String(value || "").trim();
|
|
11
|
+
if (!id || !ObjectId.isValid(id) || id.length !== 24) return null;
|
|
12
|
+
return new ObjectId(id);
|
|
13
|
+
}
|
|
14
|
+
function parseIdList(raw) {
|
|
15
|
+
return String(raw || "").split(",").map(part => parseObjectId(part)).filter(Boolean);
|
|
16
|
+
}
|
|
17
|
+
function phoneVariants(raw) {
|
|
18
|
+
return getPhoneLookupVariants(String(raw || "").trim()).filter(Boolean);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Build a users collection filter from query params.
|
|
23
|
+
* Service calls must pass a lookup (no full-table scan).
|
|
24
|
+
*/
|
|
25
|
+
function buildUsersFilter(query = {}, {
|
|
26
|
+
requireLookup = false
|
|
27
|
+
} = {}) {
|
|
28
|
+
const clauses = [];
|
|
29
|
+
if (query._id) {
|
|
30
|
+
const id = parseObjectId(query._id);
|
|
31
|
+
if (id) clauses.push({
|
|
32
|
+
_id: id
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
if (query.ids) {
|
|
36
|
+
const ids = parseIdList(query.ids);
|
|
37
|
+
if (ids.length) clauses.push({
|
|
38
|
+
_id: {
|
|
39
|
+
$in: ids
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
if (query.phoneNumber) {
|
|
44
|
+
const variants = phoneVariants(query.phoneNumber);
|
|
45
|
+
if (variants.length) clauses.push({
|
|
46
|
+
phoneNumber: {
|
|
47
|
+
$in: variants
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
if (query.phones) {
|
|
52
|
+
const variants = [...new Set(String(query.phones).split(",").flatMap(part => phoneVariants(part)))];
|
|
53
|
+
if (variants.length) clauses.push({
|
|
54
|
+
phoneNumber: {
|
|
55
|
+
$in: variants
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
if (query.email) {
|
|
60
|
+
const email = String(query.email).trim();
|
|
61
|
+
if (email) {
|
|
62
|
+
const lower = email.toLowerCase();
|
|
63
|
+
clauses.push(lower === email ? {
|
|
64
|
+
email
|
|
65
|
+
} : {
|
|
66
|
+
$or: [{
|
|
67
|
+
email
|
|
68
|
+
}, {
|
|
69
|
+
email: lower
|
|
70
|
+
}]
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
if (requireLookup && !clauses.length) {
|
|
75
|
+
return {
|
|
76
|
+
error: "A lookup is required: _id, ids, phoneNumber, phones, or email."
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
if (!clauses.length) return {
|
|
80
|
+
filter: {}
|
|
81
|
+
};
|
|
82
|
+
if (clauses.length === 1) return {
|
|
83
|
+
filter: clauses[0]
|
|
84
|
+
};
|
|
85
|
+
return {
|
|
86
|
+
filter: {
|
|
87
|
+
$and: clauses
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
module.exports = {
|
|
92
|
+
parseObjectId,
|
|
93
|
+
parseIdList,
|
|
94
|
+
phoneVariants,
|
|
95
|
+
buildUsersFilter
|
|
96
|
+
};
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const {
|
|
4
|
+
ObjectId
|
|
5
|
+
} = require("mongodb");
|
|
6
|
+
const {
|
|
7
|
+
buildUsersFilter,
|
|
8
|
+
parseObjectId
|
|
9
|
+
} = require("./usersQuery");
|
|
10
|
+
describe("buildUsersFilter", () => {
|
|
11
|
+
it("expands phoneNumber to last-10 variants", () => {
|
|
12
|
+
const {
|
|
13
|
+
filter,
|
|
14
|
+
error
|
|
15
|
+
} = buildUsersFilter({
|
|
16
|
+
phoneNumber: "7903658469"
|
|
17
|
+
});
|
|
18
|
+
expect(error).toBeUndefined();
|
|
19
|
+
expect(filter.phoneNumber.$in).toEqual(expect.arrayContaining(["7903658469", "+917903658469", "917903658469"]));
|
|
20
|
+
});
|
|
21
|
+
it("accepts comma-separated ids", () => {
|
|
22
|
+
const a = "507f1f77bcf86cd799439011";
|
|
23
|
+
const b = "507f191e810c19729de860ea";
|
|
24
|
+
const {
|
|
25
|
+
filter
|
|
26
|
+
} = buildUsersFilter({
|
|
27
|
+
ids: `${a},${b}`
|
|
28
|
+
});
|
|
29
|
+
expect(filter._id.$in.map(String)).toEqual([a, b]);
|
|
30
|
+
});
|
|
31
|
+
it("rejects a service lookup with no keys", () => {
|
|
32
|
+
const {
|
|
33
|
+
error,
|
|
34
|
+
filter
|
|
35
|
+
} = buildUsersFilter({}, {
|
|
36
|
+
requireLookup: true
|
|
37
|
+
});
|
|
38
|
+
expect(filter).toBeUndefined();
|
|
39
|
+
expect(error).toMatch(/lookup is required/);
|
|
40
|
+
});
|
|
41
|
+
it("allows an empty filter for JWT list-all", () => {
|
|
42
|
+
const {
|
|
43
|
+
filter,
|
|
44
|
+
error
|
|
45
|
+
} = buildUsersFilter({});
|
|
46
|
+
expect(error).toBeUndefined();
|
|
47
|
+
expect(filter).toEqual({});
|
|
48
|
+
});
|
|
49
|
+
it("parses a 24-char ObjectId", () => {
|
|
50
|
+
const id = parseObjectId("507f1f77bcf86cd799439011");
|
|
51
|
+
expect(id).toBeInstanceOf(ObjectId);
|
|
52
|
+
});
|
|
53
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "powr-sdk-api",
|
|
3
|
-
"version": "4.10.
|
|
3
|
+
"version": "4.10.3",
|
|
4
4
|
"description": "Shared API core library for PowrStack projects. Zero dependencies - works with Express, Next.js API routes, and other frameworks. All features are optional and install only what you need.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|