powr-sdk-api 4.9.6 → 4.10.1
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/middleware/resolvePowrUserFromToken.js +112 -0
- package/dist/routes/files.js +8 -3
- package/dist/routes/index.js +2 -0
- package/dist/routes/loginCode.js +140 -0
- package/dist/routes/users.js +6 -6
- package/dist/services/loginCodes.js +79 -0
- package/dist/services/uploadToGCS.js +12 -12
- package/package.json +1 -1
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const jwt = require("jsonwebtoken");
|
|
4
|
+
const {
|
|
5
|
+
ObjectId
|
|
6
|
+
} = require("mongodb");
|
|
7
|
+
const {
|
|
8
|
+
config
|
|
9
|
+
} = require("../config");
|
|
10
|
+
const {
|
|
11
|
+
getDb
|
|
12
|
+
} = require("../services/mongo");
|
|
13
|
+
const {
|
|
14
|
+
coercePhoneForStorage,
|
|
15
|
+
getPhoneLookupVariants
|
|
16
|
+
} = require("../utils/phone");
|
|
17
|
+
function readBearer(req) {
|
|
18
|
+
const authHeader = req.headers.authorization;
|
|
19
|
+
if (!authHeader) return null;
|
|
20
|
+
return authHeader.startsWith("Bearer ") ? authHeader.slice(7) : authHeader;
|
|
21
|
+
}
|
|
22
|
+
function decodeToken(token) {
|
|
23
|
+
try {
|
|
24
|
+
return jwt.verify(token, config.jwtToken);
|
|
25
|
+
} catch (error) {
|
|
26
|
+
if (error.name !== "TokenExpiredError") throw error;
|
|
27
|
+
const decoded = jwt.verify(token, config.jwtToken, {
|
|
28
|
+
ignoreExpiration: true
|
|
29
|
+
});
|
|
30
|
+
if (decoded.userId && !decoded.phone_number && !decoded.mobile) {
|
|
31
|
+
const expired = new Error("Token expired");
|
|
32
|
+
expired.status = 401;
|
|
33
|
+
throw expired;
|
|
34
|
+
}
|
|
35
|
+
return decoded;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
async function findOrCreateByPhone(db, decoded) {
|
|
39
|
+
const raw = decoded.phone_number || decoded.mobile || decoded.phoneNumber;
|
|
40
|
+
if (!raw) {
|
|
41
|
+
const err = new Error("Token has no phone number");
|
|
42
|
+
err.status = 400;
|
|
43
|
+
throw err;
|
|
44
|
+
}
|
|
45
|
+
const stored = coercePhoneForStorage(raw) || String(raw).trim();
|
|
46
|
+
const variants = getPhoneLookupVariants(raw);
|
|
47
|
+
const user = await db.collection("users").findOne({
|
|
48
|
+
phoneNumber: {
|
|
49
|
+
$in: variants.length ? variants : [stored]
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
if (user) return user;
|
|
53
|
+
const digits = String(stored).replace(/\D/g, "") || Date.now().toString();
|
|
54
|
+
const doc = {
|
|
55
|
+
fullName: decoded.fullName || "User",
|
|
56
|
+
email: "",
|
|
57
|
+
phoneNumber: stored,
|
|
58
|
+
username: `phone_${digits}`,
|
|
59
|
+
createdAt: new Date(),
|
|
60
|
+
createdFrom: "issue-login-code"
|
|
61
|
+
};
|
|
62
|
+
const inserted = await db.collection("users").insertOne(doc);
|
|
63
|
+
return {
|
|
64
|
+
_id: inserted.insertedId,
|
|
65
|
+
...doc
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
async function loadPowrUser(decoded) {
|
|
69
|
+
const db = await getDb();
|
|
70
|
+
if (decoded.userId) {
|
|
71
|
+
const user = await db.collection("users").findOne({
|
|
72
|
+
_id: new ObjectId(decoded.userId)
|
|
73
|
+
});
|
|
74
|
+
if (!user) {
|
|
75
|
+
const err = new Error("User not found");
|
|
76
|
+
err.status = 401;
|
|
77
|
+
throw err;
|
|
78
|
+
}
|
|
79
|
+
return user;
|
|
80
|
+
}
|
|
81
|
+
return findOrCreateByPhone(db, decoded);
|
|
82
|
+
}
|
|
83
|
+
async function resolvePowrUserFromToken(req, res, next) {
|
|
84
|
+
try {
|
|
85
|
+
const token = readBearer(req);
|
|
86
|
+
if (!token) {
|
|
87
|
+
return res.status(401).json({
|
|
88
|
+
success: false,
|
|
89
|
+
message: "No authorization token provided."
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
const decoded = decodeToken(token);
|
|
93
|
+
const user = await loadPowrUser(decoded);
|
|
94
|
+
req.user = {
|
|
95
|
+
powrId: user._id,
|
|
96
|
+
fullName: user.fullName,
|
|
97
|
+
access: decoded.access
|
|
98
|
+
};
|
|
99
|
+
req.powrUser = user;
|
|
100
|
+
return next();
|
|
101
|
+
} catch (error) {
|
|
102
|
+
return res.status(error.status || 401).json({
|
|
103
|
+
success: false,
|
|
104
|
+
message: error.message || "Invalid token"
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
module.exports = {
|
|
109
|
+
resolvePowrUserFromToken,
|
|
110
|
+
loadPowrUser,
|
|
111
|
+
decodeToken
|
|
112
|
+
};
|
package/dist/routes/files.js
CHANGED
|
@@ -12,7 +12,7 @@ const {
|
|
|
12
12
|
|
|
13
13
|
const router = express.Router();
|
|
14
14
|
const upload = multer();
|
|
15
|
-
|
|
15
|
+
async function handleUpload(req, res) {
|
|
16
16
|
try {
|
|
17
17
|
if (!req.file) {
|
|
18
18
|
return res.status(400).json({
|
|
@@ -24,7 +24,10 @@ router.post('/', upload.single('file'), async (req, res) => {
|
|
|
24
24
|
return res.status(200).json({
|
|
25
25
|
status: 'success',
|
|
26
26
|
message: 'File uploaded successfully',
|
|
27
|
-
url
|
|
27
|
+
url,
|
|
28
|
+
originalname: req.file.originalname,
|
|
29
|
+
mimetype: req.file.mimetype,
|
|
30
|
+
size: req.file.size
|
|
28
31
|
});
|
|
29
32
|
} catch (err) {
|
|
30
33
|
console.error('Error uploading file:', err);
|
|
@@ -34,7 +37,9 @@ router.post('/', upload.single('file'), async (req, res) => {
|
|
|
34
37
|
error: err.message || 'Unknown error occurred'
|
|
35
38
|
});
|
|
36
39
|
}
|
|
37
|
-
}
|
|
40
|
+
}
|
|
41
|
+
router.post('/', upload.single('file'), handleUpload);
|
|
42
|
+
router.post('/upload', upload.single('file'), handleUpload);
|
|
38
43
|
router.get('/', async (req, res) => {
|
|
39
44
|
try {
|
|
40
45
|
const [files] = await bucket.getFiles();
|
package/dist/routes/index.js
CHANGED
|
@@ -20,6 +20,7 @@ const usersRoutes = require('./users');
|
|
|
20
20
|
const waitlistsRoutes = require('./waitlists');
|
|
21
21
|
const activitiesRoutes = require('./activities');
|
|
22
22
|
const authRoutes = require('./auth');
|
|
23
|
+
const loginCodeRoutes = require('./loginCode');
|
|
23
24
|
const slidesRoutes = require('./slides');
|
|
24
25
|
const notificationsRoutes = require('./notifications');
|
|
25
26
|
const profilesRoutes = require('./profiles');
|
|
@@ -34,6 +35,7 @@ const createPowrRoutes = (options = {}) => {
|
|
|
34
35
|
|
|
35
36
|
// Use the dedicated projectId injection middleware
|
|
36
37
|
router.use(injectProjectId(options));
|
|
38
|
+
router.use('/auth', loginCodeRoutes);
|
|
37
39
|
router.use('/auth', authRoutes);
|
|
38
40
|
router.use('/comments', verifyToken, commentsRoutes);
|
|
39
41
|
router.use('/files', verifyToken, filesRoutes);
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const express = require("express");
|
|
4
|
+
const {
|
|
5
|
+
ObjectId
|
|
6
|
+
} = require("mongodb");
|
|
7
|
+
const {
|
|
8
|
+
getDb
|
|
9
|
+
} = require("../services/mongo");
|
|
10
|
+
const {
|
|
11
|
+
generateJWTToken,
|
|
12
|
+
generateRefreshToken
|
|
13
|
+
} = require("../middleware/jwtToken");
|
|
14
|
+
const {
|
|
15
|
+
resolvePowrUserFromToken
|
|
16
|
+
} = require("../middleware/resolvePowrUserFromToken");
|
|
17
|
+
const {
|
|
18
|
+
getClientIp
|
|
19
|
+
} = require("../utils/getClientIp");
|
|
20
|
+
const {
|
|
21
|
+
issueLoginCode,
|
|
22
|
+
consumeLoginCode
|
|
23
|
+
} = require("../services/loginCodes");
|
|
24
|
+
const router = express.Router();
|
|
25
|
+
async function sessionPayload(req, user, projectId) {
|
|
26
|
+
const db = await getDb();
|
|
27
|
+
let profile = await db.collection("profiles").findOne({
|
|
28
|
+
userId: user._id,
|
|
29
|
+
projectId
|
|
30
|
+
});
|
|
31
|
+
const now = new Date();
|
|
32
|
+
if (profile) {
|
|
33
|
+
await db.collection("profiles").updateOne({
|
|
34
|
+
_id: profile._id
|
|
35
|
+
}, {
|
|
36
|
+
$set: {
|
|
37
|
+
lastActiveAt: now,
|
|
38
|
+
lastActiveFrom: getClientIp(req)
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
} else if (projectId) {
|
|
42
|
+
const newProfile = {
|
|
43
|
+
userId: user._id,
|
|
44
|
+
projectId,
|
|
45
|
+
access: 1,
|
|
46
|
+
createdAt: now,
|
|
47
|
+
lastActiveAt: now,
|
|
48
|
+
lastActiveFrom: getClientIp(req)
|
|
49
|
+
};
|
|
50
|
+
const inserted = await db.collection("profiles").insertOne(newProfile);
|
|
51
|
+
profile = {
|
|
52
|
+
_id: inserted.insertedId,
|
|
53
|
+
...newProfile
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
const token = generateJWTToken(user, profile);
|
|
57
|
+
const refreshToken = generateRefreshToken(user);
|
|
58
|
+
await db.collection("users").updateOne({
|
|
59
|
+
_id: user._id
|
|
60
|
+
}, {
|
|
61
|
+
$set: {
|
|
62
|
+
refreshToken
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
const {
|
|
66
|
+
password,
|
|
67
|
+
refreshToken: _rt,
|
|
68
|
+
...safe
|
|
69
|
+
} = user;
|
|
70
|
+
let extra = {};
|
|
71
|
+
if (profile) {
|
|
72
|
+
const {
|
|
73
|
+
_id,
|
|
74
|
+
userId,
|
|
75
|
+
projectId: _p,
|
|
76
|
+
createdAt,
|
|
77
|
+
updatedAt,
|
|
78
|
+
lastActiveAt,
|
|
79
|
+
lastActiveFrom,
|
|
80
|
+
...profileData
|
|
81
|
+
} = profile;
|
|
82
|
+
extra = profileData;
|
|
83
|
+
}
|
|
84
|
+
return {
|
|
85
|
+
success: true,
|
|
86
|
+
message: "Login successful",
|
|
87
|
+
user: {
|
|
88
|
+
...safe,
|
|
89
|
+
...extra,
|
|
90
|
+
powrId: user._id
|
|
91
|
+
},
|
|
92
|
+
token,
|
|
93
|
+
refreshToken
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
router.post("/issue-login-code", resolvePowrUserFromToken, async (req, res) => {
|
|
97
|
+
try {
|
|
98
|
+
const issued = await issueLoginCode({
|
|
99
|
+
userId: req.user.powrId,
|
|
100
|
+
projectId: req.projectId
|
|
101
|
+
});
|
|
102
|
+
return res.json({
|
|
103
|
+
success: true,
|
|
104
|
+
loginId: issued.loginId,
|
|
105
|
+
expiresAt: issued.expiresAt
|
|
106
|
+
});
|
|
107
|
+
} catch (error) {
|
|
108
|
+
return res.status(error.status || 500).json({
|
|
109
|
+
success: false,
|
|
110
|
+
message: error.message || "Failed to issue login code"
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
router.post("/login-with-code", async (req, res) => {
|
|
115
|
+
try {
|
|
116
|
+
const {
|
|
117
|
+
loginId
|
|
118
|
+
} = req.body || {};
|
|
119
|
+
const projectId = req.projectId;
|
|
120
|
+
const row = await consumeLoginCode(loginId, projectId);
|
|
121
|
+
const db = await getDb();
|
|
122
|
+
const user = await db.collection("users").findOne({
|
|
123
|
+
_id: new ObjectId(row.userId)
|
|
124
|
+
});
|
|
125
|
+
if (!user) {
|
|
126
|
+
return res.status(400).json({
|
|
127
|
+
success: false,
|
|
128
|
+
message: "User not found"
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
const payload = await sessionPayload(req, user, projectId);
|
|
132
|
+
return res.json(payload);
|
|
133
|
+
} catch (error) {
|
|
134
|
+
return res.status(error.status || 500).json({
|
|
135
|
+
success: false,
|
|
136
|
+
message: error.message || "Failed to login with code"
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
module.exports = router;
|
package/dist/routes/users.js
CHANGED
|
@@ -164,17 +164,17 @@ router.put("/:id", verifyToken, async (req, res) => {
|
|
|
164
164
|
});
|
|
165
165
|
}
|
|
166
166
|
|
|
167
|
-
// Only set fields
|
|
168
|
-
//
|
|
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
169
|
const updateData = {
|
|
170
170
|
updatedAt: new Date()
|
|
171
171
|
};
|
|
172
172
|
for (const [key, value] of Object.entries(userData || {})) {
|
|
173
173
|
if (value !== undefined) updateData[key] = value;
|
|
174
174
|
}
|
|
175
|
-
if (phoneNumber
|
|
176
|
-
const normalizedPhone =
|
|
177
|
-
if (phoneNumber && !
|
|
175
|
+
if (typeof phoneNumber === "string") {
|
|
176
|
+
const normalizedPhone = !phoneNumber.includes("@") ? coercePhoneForStorage(phoneNumber) : phoneNumber;
|
|
177
|
+
if (phoneNumber && !phoneNumber.includes("@") && !normalizedPhone) {
|
|
178
178
|
return res.status(400).json({
|
|
179
179
|
success: false,
|
|
180
180
|
message: "Invalid phone number"
|
|
@@ -182,7 +182,7 @@ router.put("/:id", verifyToken, async (req, res) => {
|
|
|
182
182
|
}
|
|
183
183
|
updateData.phoneNumber = normalizedPhone;
|
|
184
184
|
}
|
|
185
|
-
if (email
|
|
185
|
+
if (typeof email === "string") {
|
|
186
186
|
updateData.email = email;
|
|
187
187
|
}
|
|
188
188
|
await db.collection("users").updateOne({
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const crypto = require("crypto");
|
|
4
|
+
const {
|
|
5
|
+
ObjectId
|
|
6
|
+
} = require("mongodb");
|
|
7
|
+
const {
|
|
8
|
+
getDb
|
|
9
|
+
} = require("./mongo");
|
|
10
|
+
const COLLECTION = "loginCodes";
|
|
11
|
+
const TTL_SECONDS = 120;
|
|
12
|
+
function hashLoginId(loginId) {
|
|
13
|
+
return crypto.createHash("sha256").update(String(loginId), "utf8").digest("hex");
|
|
14
|
+
}
|
|
15
|
+
async function codes() {
|
|
16
|
+
const db = await getDb();
|
|
17
|
+
return db.collection(COLLECTION);
|
|
18
|
+
}
|
|
19
|
+
async function issueLoginCode({
|
|
20
|
+
userId,
|
|
21
|
+
projectId
|
|
22
|
+
}) {
|
|
23
|
+
const loginId = crypto.randomBytes(32).toString("hex");
|
|
24
|
+
const now = new Date();
|
|
25
|
+
const expiresAt = new Date(now.getTime() + TTL_SECONDS * 1000);
|
|
26
|
+
await (await codes()).insertOne({
|
|
27
|
+
loginIdHash: hashLoginId(loginId),
|
|
28
|
+
userId: typeof userId === "string" ? new ObjectId(userId) : userId,
|
|
29
|
+
projectId: projectId || null,
|
|
30
|
+
createdAt: now,
|
|
31
|
+
expiresAt,
|
|
32
|
+
usedAt: null
|
|
33
|
+
});
|
|
34
|
+
return {
|
|
35
|
+
loginId,
|
|
36
|
+
expiresAt
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
async function consumeLoginCode(loginId, projectId) {
|
|
40
|
+
if (!loginId) {
|
|
41
|
+
const err = new Error("loginId is required");
|
|
42
|
+
err.status = 400;
|
|
43
|
+
throw err;
|
|
44
|
+
}
|
|
45
|
+
const col = await codes();
|
|
46
|
+
const doc = await col.findOne({
|
|
47
|
+
loginIdHash: hashLoginId(loginId),
|
|
48
|
+
usedAt: null
|
|
49
|
+
});
|
|
50
|
+
if (!doc || doc.expiresAt && doc.expiresAt < new Date()) {
|
|
51
|
+
const err = new Error("Invalid or expired loginId");
|
|
52
|
+
err.status = 400;
|
|
53
|
+
throw err;
|
|
54
|
+
}
|
|
55
|
+
if (projectId && doc.projectId && String(doc.projectId) !== String(projectId)) {
|
|
56
|
+
const err = new Error("loginId is for a different app");
|
|
57
|
+
err.status = 400;
|
|
58
|
+
throw err;
|
|
59
|
+
}
|
|
60
|
+
const used = await col.updateOne({
|
|
61
|
+
_id: doc._id,
|
|
62
|
+
usedAt: null
|
|
63
|
+
}, {
|
|
64
|
+
$set: {
|
|
65
|
+
usedAt: new Date()
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
if (used.modifiedCount !== 1) {
|
|
69
|
+
const err = new Error("loginId already used");
|
|
70
|
+
err.status = 400;
|
|
71
|
+
throw err;
|
|
72
|
+
}
|
|
73
|
+
return doc;
|
|
74
|
+
}
|
|
75
|
+
module.exports = {
|
|
76
|
+
issueLoginCode,
|
|
77
|
+
consumeLoginCode,
|
|
78
|
+
TTL_SECONDS
|
|
79
|
+
};
|
|
@@ -16,31 +16,31 @@ const storage = new Storage({
|
|
|
16
16
|
});
|
|
17
17
|
const bucketName = config.storageBucket;
|
|
18
18
|
const bucket = storage.bucket(bucketName);
|
|
19
|
-
console.log('Bucket:', bucketName);
|
|
20
|
-
console.log('Bucket:', bucket);
|
|
21
19
|
async function uploadToGCS(file) {
|
|
20
|
+
if (!bucketName) {
|
|
21
|
+
throw new Error('STORAGE_BUCKET is not set');
|
|
22
|
+
}
|
|
22
23
|
const timestamp = format(new Date(), 'yyyyMMdd-HHmmss');
|
|
23
24
|
const cleanFileName = file.originalname.replace(/[^a-zA-Z0-9.-]/g, '-');
|
|
24
25
|
const filename = `${timestamp}-${cleanFileName}`;
|
|
25
26
|
const blob = bucket.file(filename);
|
|
26
27
|
try {
|
|
27
|
-
console.log('Preparing to upload file:', {
|
|
28
|
-
name: file.originalname,
|
|
29
|
-
type: file.mimetype
|
|
30
|
-
});
|
|
31
28
|
const buffer = file.buffer;
|
|
32
|
-
console.log('Uploading file to GCS...');
|
|
33
29
|
await blob.save(buffer, {
|
|
34
30
|
contentType: file.mimetype,
|
|
35
31
|
metadata: {
|
|
36
32
|
contentType: file.mimetype
|
|
37
33
|
}
|
|
38
34
|
});
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
35
|
+
|
|
36
|
+
// Uniform bucket-level access rejects object ACLs. Public URL still works
|
|
37
|
+
// if the bucket (or object) is already publicly readable.
|
|
38
|
+
try {
|
|
39
|
+
await blob.makePublic();
|
|
40
|
+
} catch (aclError) {
|
|
41
|
+
console.warn('GCS makePublic skipped:', aclError.message);
|
|
42
|
+
}
|
|
43
|
+
return `https://storage.googleapis.com/${bucketName}/${filename}`;
|
|
44
44
|
} catch (error) {
|
|
45
45
|
console.error('Error uploading file to GCS:', error);
|
|
46
46
|
throw new Error(`Failed to upload file to GCS: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "powr-sdk-api",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.10.1",
|
|
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",
|