aloux-iam 0.0.141 → 0.0.143
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/lib/controllers/log.js +85 -141
- package/lib/controllers/user.js +16 -17
- package/lib/middleware.js +24 -9
- package/lib/models/Log.js +1 -0
- package/lib/models/User.js +3 -1
- package/lib/services/user.js +128 -68
- package/package.json +1 -1
package/lib/controllers/log.js
CHANGED
|
@@ -9,9 +9,11 @@ self.create = async (req, res) => {
|
|
|
9
9
|
req.header("Company") !== "undefined" ? req.header("Company") : null;
|
|
10
10
|
|
|
11
11
|
const log = new Log(req.body);
|
|
12
|
+
const businessId = req.header("business") !== "undefined" ? req.header("business") : null;
|
|
12
13
|
log.createdAt = new Date().getTime();
|
|
13
14
|
log._user = req.user._id;
|
|
14
15
|
log._company = companyId;
|
|
16
|
+
log._business = businessId;
|
|
15
17
|
|
|
16
18
|
log.label = req.body.label;
|
|
17
19
|
await log.save();
|
|
@@ -54,110 +56,36 @@ self.retrieve = async (req, res) => {
|
|
|
54
56
|
const companyId =
|
|
55
57
|
req.header("Company") !== "undefined" ? req.header("Company") : null;
|
|
56
58
|
|
|
57
|
-
const
|
|
59
|
+
const query = { _company: companyId };
|
|
58
60
|
|
|
59
61
|
if (req.body.users?.length) {
|
|
60
|
-
|
|
62
|
+
query._user = {
|
|
61
63
|
$in: req.body.users.map((id) => new mongoose.Types.ObjectId(id)),
|
|
62
64
|
};
|
|
63
65
|
}
|
|
64
66
|
|
|
65
67
|
if (req.body.dateStart || req.body.dateEnd) {
|
|
66
|
-
|
|
67
|
-
if (req.body.dateStart)
|
|
68
|
-
|
|
69
|
-
if (req.body.dateEnd)
|
|
70
|
-
matchStage.createdAt.$lte = Number(req.body.dateEnd);
|
|
68
|
+
query.createdAt = {};
|
|
69
|
+
if (req.body.dateStart) query.createdAt.$gte = Number(req.body.dateStart);
|
|
70
|
+
if (req.body.dateEnd) query.createdAt.$lte = Number(req.body.dateEnd);
|
|
71
71
|
}
|
|
72
72
|
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
{ $group: { _id: "$label", count: { $sum: 1 } } },
|
|
79
|
-
{ $sort: { count: -1 } },
|
|
80
|
-
]),
|
|
81
|
-
|
|
82
|
-
Log.aggregate([
|
|
83
|
-
{ $match: matchStage },
|
|
84
|
-
{
|
|
85
|
-
$group: {
|
|
86
|
-
_id: {
|
|
87
|
-
$dateToString: {
|
|
88
|
-
format: "%Y-%m-%d",
|
|
89
|
-
date: { $toDate: "$createdAt" },
|
|
90
|
-
},
|
|
91
|
-
},
|
|
92
|
-
count: { $sum: 1 },
|
|
93
|
-
},
|
|
94
|
-
},
|
|
95
|
-
{ $sort: { _id: 1 } },
|
|
96
|
-
]),
|
|
97
|
-
|
|
98
|
-
Log.aggregate([
|
|
99
|
-
{ $match: matchStage },
|
|
100
|
-
{ $group: { _id: "$_user", count: { $sum: 1 } } },
|
|
101
|
-
{
|
|
102
|
-
$lookup: {
|
|
103
|
-
from: "users",
|
|
104
|
-
localField: "_id",
|
|
105
|
-
foreignField: "_id",
|
|
106
|
-
as: "user",
|
|
107
|
-
},
|
|
108
|
-
},
|
|
109
|
-
{ $unwind: "$user" },
|
|
110
|
-
{
|
|
111
|
-
$project: {
|
|
112
|
-
name: { $concat: ["$user.name", " ", "$user.lastName"] },
|
|
113
|
-
count: 1,
|
|
114
|
-
},
|
|
115
|
-
},
|
|
116
|
-
{ $sort: { count: -1 } },
|
|
117
|
-
]),
|
|
118
|
-
]);
|
|
119
|
-
|
|
120
|
-
const topUsers = byUser.slice(0, 10);
|
|
121
|
-
const leastUsers = [...byUser]
|
|
122
|
-
.sort((a, b) => a.count - b.count)
|
|
123
|
-
.slice(0, 10);
|
|
124
|
-
|
|
125
|
-
// for (let i in consulta) {
|
|
126
|
-
// consulta[i].label = consulta[i]._label.label;
|
|
127
|
-
// await consulta[i].save();
|
|
128
|
-
// }
|
|
73
|
+
if (req.body.business?.length) {
|
|
74
|
+
query._business = { $in: req.body.business };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const consulta = await Log.find(query).populate("_user", "name lastName email");
|
|
129
78
|
|
|
130
79
|
const response = {
|
|
131
|
-
dataset0: { field: "Visualizaciones totales", count:
|
|
132
|
-
dataset1:
|
|
133
|
-
dataset2:
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
items: byLabel.map((i) => ({
|
|
141
|
-
addGroup: i._id,
|
|
142
|
-
totalResponse: i.count,
|
|
143
|
-
})),
|
|
144
|
-
},
|
|
145
|
-
dataset4: {
|
|
146
|
-
field: "Actividad en la plataforma",
|
|
147
|
-
counts: byDate.map((i) => i.count),
|
|
148
|
-
actionsName: byDate.map((i) => formatDate(i._id)),
|
|
149
|
-
},
|
|
150
|
-
dataset5: [],
|
|
151
|
-
dataset6: {
|
|
152
|
-
field: "Usuarios con mas actividad en la plataforma",
|
|
153
|
-
counts: topUsers.map((i) => i.count),
|
|
154
|
-
actionsName: topUsers.map((i) => i.name.split(" ")),
|
|
155
|
-
},
|
|
156
|
-
dataset7: {
|
|
157
|
-
field: "Usuarios con menos actividad en la plataforma",
|
|
158
|
-
counts: leastUsers.map((i) => i.count),
|
|
159
|
-
actionsName: leastUsers.map((i) => i.name.split(" ")),
|
|
160
|
-
},
|
|
80
|
+
dataset0: { field: "Visualizaciones totales", count: consulta.length },
|
|
81
|
+
dataset1: processDataset1(consulta),
|
|
82
|
+
dataset2: processDataset2(consulta),
|
|
83
|
+
dataset3: processDataset3(consulta),
|
|
84
|
+
dataset4: processDataset4(consulta),
|
|
85
|
+
dataset5: processDataset5(consulta),
|
|
86
|
+
dataset6: processDataset6(consulta),
|
|
87
|
+
dataset7: processDataset7(consulta),
|
|
88
|
+
dataset8: processDataset8(consulta, req.body.search, req.body.page, req.body.limit),
|
|
161
89
|
};
|
|
162
90
|
|
|
163
91
|
res.status(200).send(response);
|
|
@@ -170,31 +98,20 @@ self.retrieve = async (req, res) => {
|
|
|
170
98
|
function formatDate(isoDate) {
|
|
171
99
|
const [year, month, day] = isoDate.split("-");
|
|
172
100
|
const monthNames = [
|
|
173
|
-
"Ene",
|
|
174
|
-
"
|
|
175
|
-
"Mar",
|
|
176
|
-
"Abr",
|
|
177
|
-
"May",
|
|
178
|
-
"Jun",
|
|
179
|
-
"Jul",
|
|
180
|
-
"Ago",
|
|
181
|
-
"Sep",
|
|
182
|
-
"Oct",
|
|
183
|
-
"Nov",
|
|
184
|
-
"Dic",
|
|
101
|
+
"Ene", "Feb", "Mar", "Abr", "May", "Jun",
|
|
102
|
+
"Jul", "Ago", "Sep", "Oct", "Nov", "Dic",
|
|
185
103
|
];
|
|
186
104
|
return `${day} ${monthNames[parseInt(month) - 1]} ${year}`;
|
|
187
105
|
}
|
|
188
106
|
|
|
189
107
|
function processDataset1(consulta) {
|
|
190
|
-
return consulta.map((item) => {
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
});
|
|
108
|
+
return consulta.map((item) => ({
|
|
109
|
+
_id: item._id,
|
|
110
|
+
labelDescription: item.label,
|
|
111
|
+
userName: item._user.name + " " + item._user.lastName,
|
|
112
|
+
userEmail: item._user.email,
|
|
113
|
+
createdAt: item.createdAt,
|
|
114
|
+
}));
|
|
198
115
|
}
|
|
199
116
|
|
|
200
117
|
function processDataset2(consulta) {
|
|
@@ -229,7 +146,8 @@ function processDataset3(consulta) {
|
|
|
229
146
|
|
|
230
147
|
function processDataset4(consulta) {
|
|
231
148
|
const dateCounts = consulta.reduce((acc, item) => {
|
|
232
|
-
const
|
|
149
|
+
const isoDate = new Date(item.createdAt).toISOString().split("T")[0];
|
|
150
|
+
const date = formatDate(isoDate);
|
|
233
151
|
acc[date] = (acc[date] || 0) + 1;
|
|
234
152
|
return acc;
|
|
235
153
|
}, {});
|
|
@@ -246,7 +164,8 @@ function processDataset5(consulta) {
|
|
|
246
164
|
const categories = new Set();
|
|
247
165
|
|
|
248
166
|
consulta.forEach((item) => {
|
|
249
|
-
const
|
|
167
|
+
const isoDate = new Date(item.createdAt).toISOString().split("T")[0];
|
|
168
|
+
const date = formatDate(isoDate);
|
|
250
169
|
const label = item.label;
|
|
251
170
|
categories.add(date);
|
|
252
171
|
|
|
@@ -276,55 +195,80 @@ function processDataset5(consulta) {
|
|
|
276
195
|
function processDataset6(data) {
|
|
277
196
|
const userActivity = {};
|
|
278
197
|
|
|
279
|
-
// Count activity per user. Assuming data contains _user with name and lastName
|
|
280
198
|
data.forEach((item) => {
|
|
281
199
|
const fullName = `${item._user.name} ${item._user.lastName}`;
|
|
282
200
|
userActivity[fullName] = (userActivity[fullName] || 0) + 1;
|
|
283
201
|
});
|
|
284
202
|
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
(
|
|
288
|
-
);
|
|
289
|
-
|
|
290
|
-
// Extract top 10 users
|
|
291
|
-
const topUsers = sortedUsers.slice(0, 10);
|
|
203
|
+
const topUsers = Object.entries(userActivity)
|
|
204
|
+
.sort(([, a], [, b]) => b - a)
|
|
205
|
+
.slice(0, 10);
|
|
292
206
|
|
|
293
|
-
|
|
294
|
-
|
|
207
|
+
return {
|
|
208
|
+
field: "Usuarios con mas actividad en la plataforma",
|
|
295
209
|
counts: topUsers.map(([, count]) => count),
|
|
296
210
|
actionsName: topUsers.map(([fullName]) => fullName.split(" ")),
|
|
297
|
-
field: "Usuarios con mas actividad en la plataforma",
|
|
298
211
|
};
|
|
299
|
-
|
|
300
|
-
return result;
|
|
301
212
|
}
|
|
302
213
|
|
|
303
214
|
function processDataset7(data) {
|
|
304
215
|
const userActivity = {};
|
|
305
216
|
|
|
306
|
-
// Count activity per user. Assuming data contains _user with name and lastName
|
|
307
217
|
data.forEach((item) => {
|
|
308
218
|
const fullName = `${item._user.name} ${item._user.lastName}`;
|
|
309
219
|
userActivity[fullName] = (userActivity[fullName] || 0) + 1;
|
|
310
220
|
});
|
|
311
221
|
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
(
|
|
315
|
-
);
|
|
222
|
+
const leastUsers = Object.entries(userActivity)
|
|
223
|
+
.sort(([, a], [, b]) => a - b)
|
|
224
|
+
.slice(0, 10);
|
|
316
225
|
|
|
317
|
-
|
|
318
|
-
const leastActiveUsers = sortedUsers.slice(0, 10);
|
|
319
|
-
|
|
320
|
-
// Build the result object
|
|
321
|
-
const result = {
|
|
322
|
-
counts: leastActiveUsers.map(([, count]) => count),
|
|
323
|
-
actionsName: leastActiveUsers.map(([fullName]) => fullName.split(" ")),
|
|
226
|
+
return {
|
|
324
227
|
field: "Usuarios con menos actividad en la plataforma",
|
|
228
|
+
counts: leastUsers.map(([, count]) => count),
|
|
229
|
+
actionsName: leastUsers.map(([fullName]) => fullName.split(" ")),
|
|
325
230
|
};
|
|
231
|
+
}
|
|
326
232
|
|
|
327
|
-
|
|
233
|
+
function processDataset8(data, search = "", page = 1, limit = 10) {
|
|
234
|
+
const userActivity = {};
|
|
235
|
+
|
|
236
|
+
data.forEach((item) => {
|
|
237
|
+
const fullName = `${item._user.name} ${item._user.lastName}`;
|
|
238
|
+
if (!userActivity[fullName]) {
|
|
239
|
+
userActivity[fullName] = {
|
|
240
|
+
name: item._user.name,
|
|
241
|
+
lastName: item._user.lastName,
|
|
242
|
+
email: item._user.email,
|
|
243
|
+
count: 0,
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
userActivity[fullName].count++;
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
let users = Object.values(userActivity).sort((a, b) => b.count - a.count);
|
|
250
|
+
|
|
251
|
+
if (search) {
|
|
252
|
+
const s = search.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
|
|
253
|
+
users = users.filter((u) => {
|
|
254
|
+
const full = `${u.name} ${u.lastName} ${u.email}`.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
|
|
255
|
+
return full.includes(s);
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
const total = users.length;
|
|
260
|
+
const totalPages = Math.ceil(total / limit);
|
|
261
|
+
const start = (page - 1) * limit;
|
|
262
|
+
const items = users.slice(start, start + limit);
|
|
263
|
+
|
|
264
|
+
return {
|
|
265
|
+
field: "Actividad de usuarios",
|
|
266
|
+
total,
|
|
267
|
+
page,
|
|
268
|
+
limit,
|
|
269
|
+
totalPages,
|
|
270
|
+
items,
|
|
271
|
+
};
|
|
328
272
|
}
|
|
329
273
|
|
|
330
274
|
self.get = async (req, res) => {
|
package/lib/controllers/user.js
CHANGED
|
@@ -14,29 +14,29 @@ const self = module.exports;
|
|
|
14
14
|
|
|
15
15
|
self.create = async (req, res) => {
|
|
16
16
|
try {
|
|
17
|
-
let user = await serviceUser.create(req.body)
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
file =
|
|
21
|
-
file = file.replace("{{
|
|
22
|
-
file = file.replace("{{
|
|
23
|
-
|
|
24
|
-
const
|
|
25
|
-
|
|
26
|
-
if (urlEmail) {
|
|
27
|
-
|
|
28
|
-
}
|
|
17
|
+
let user = await serviceUser.create(req.body)
|
|
18
|
+
|
|
19
|
+
if (process.env.SEND_EMAIL_USER === "true" && user.email) {
|
|
20
|
+
let file = _brand.template("TEMPLATE_ACCOUNT")
|
|
21
|
+
file = file.replace("{{user}}", user.name)
|
|
22
|
+
file = file.replace("{{email}}", req.body.email)
|
|
23
|
+
file = file.replace("{{password}}", req.body.pwd)
|
|
24
|
+
const app = process.env.APP
|
|
25
|
+
const urlEmail = process.env[`URL_EMAIL_${app}`]
|
|
26
|
+
if (urlEmail) file = file.replaceAll("{{urlToken}}", urlEmail)
|
|
27
|
+
|
|
29
28
|
await AWS_SES.sendCustom(
|
|
30
29
|
user.email,
|
|
31
30
|
file,
|
|
32
31
|
process.env.SUBJECT_EMAIL || "bienvenido"
|
|
33
|
-
)
|
|
32
|
+
)
|
|
34
33
|
}
|
|
35
|
-
|
|
34
|
+
|
|
35
|
+
res.status(201).send(user)
|
|
36
36
|
} catch (error) {
|
|
37
|
-
utils.responseError(res, error, 400, "Error al crear usuario", "Revisa el detalle del error")
|
|
37
|
+
utils.responseError(res, error, 400, "Error al crear usuario", "Revisa el detalle del error")
|
|
38
38
|
}
|
|
39
|
-
}
|
|
39
|
+
}
|
|
40
40
|
|
|
41
41
|
self.update = async (req, resp) => {
|
|
42
42
|
try {
|
|
@@ -936,7 +936,6 @@ self.addTimeToken = async (req, res) => {
|
|
|
936
936
|
|
|
937
937
|
if (tokenObject) {
|
|
938
938
|
tokenObject.dateEnd = Date.now() + process.env.SESSION_TIME * 60 * 1000;
|
|
939
|
-
// Guarda los cambios en la base de datos
|
|
940
939
|
await User.updateOne(
|
|
941
940
|
{ _id: userTokens._id, "tokens.token": req.params.TOKEN },
|
|
942
941
|
{ $set: { "tokens.$.dateEnd": tokenObject.dateEnd } }
|
package/lib/middleware.js
CHANGED
|
@@ -4,6 +4,15 @@ const Permission = require("./models/Permission");
|
|
|
4
4
|
const historyController = require("./controllers/history");
|
|
5
5
|
|
|
6
6
|
const getAccess = (user, resource) => {
|
|
7
|
+
// Cuenta de servicio
|
|
8
|
+
const userApis = user?.data?.apis || [];
|
|
9
|
+
if (userApis.length > 0) {
|
|
10
|
+
return userApis.some(
|
|
11
|
+
(apiId) => apiId.toString() === resource._id.toString(),
|
|
12
|
+
);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// Flujo normal
|
|
7
16
|
for (let i in user._functions) {
|
|
8
17
|
for (let j in user._functions[i]._permissions) {
|
|
9
18
|
if (user._functions[i]._permissions[j].status === "Activo") {
|
|
@@ -50,7 +59,7 @@ const auth = async (req, res, next) => {
|
|
|
50
59
|
const data = jwt.verify(token, process.env.AUTH_SECRET);
|
|
51
60
|
const user = await User.findOne(
|
|
52
61
|
{ _id: data._id, "tokens.token": token, status: "Activo" },
|
|
53
|
-
{ tokens: 0, pwd: 0 }
|
|
62
|
+
{ tokens: 0, pwd: 0 },
|
|
54
63
|
)
|
|
55
64
|
.populate({ path: "_functions", populate: [{ path: "_permissions" }] })
|
|
56
65
|
.lean();
|
|
@@ -69,7 +78,7 @@ const auth = async (req, res, next) => {
|
|
|
69
78
|
if (process.env.SESSION_INTERRUPTOR === "true") {
|
|
70
79
|
const userTokens = await User.findOne(
|
|
71
80
|
{ _id: user._id, status: "Activo" },
|
|
72
|
-
{ tokens: 1 }
|
|
81
|
+
{ tokens: 1 },
|
|
73
82
|
).lean();
|
|
74
83
|
const tokenObject = userTokens.tokens.find((t) => t.token === token);
|
|
75
84
|
if (tokenObject.dateEnd <= Date.now()) {
|
|
@@ -79,7 +88,7 @@ const auth = async (req, res, next) => {
|
|
|
79
88
|
$pull: {
|
|
80
89
|
tokens: { token: tokenObject.token }, // Condición para eliminar el token específico
|
|
81
90
|
},
|
|
82
|
-
}
|
|
91
|
+
},
|
|
83
92
|
);
|
|
84
93
|
throw {
|
|
85
94
|
code: 401,
|
|
@@ -113,15 +122,21 @@ const auth = async (req, res, next) => {
|
|
|
113
122
|
if (resource.auth && !resource.default) {
|
|
114
123
|
const access = getAccess(user, resource);
|
|
115
124
|
if (!access) {
|
|
125
|
+
const userApis = user?.data?.apis || [];
|
|
116
126
|
throw {
|
|
117
127
|
code: 403,
|
|
118
|
-
title: "
|
|
128
|
+
title: "Acceso denegado",
|
|
119
129
|
detail:
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
130
|
+
userApis.length > 0
|
|
131
|
+
? "No cuentas con acceso a esta API"
|
|
132
|
+
: "No cuentas con permisos para el recurso [" +
|
|
133
|
+
resource.api +
|
|
134
|
+
"] que: " +
|
|
135
|
+
(resource ? resource.description : "Recurso indefinido"),
|
|
136
|
+
suggestion:
|
|
137
|
+
userApis.length > 0
|
|
138
|
+
? "Contacta con el administrador para asignar acceso a esta API"
|
|
139
|
+
: "Contacta con el administrador",
|
|
125
140
|
error: new Error(),
|
|
126
141
|
};
|
|
127
142
|
}
|
package/lib/models/Log.js
CHANGED
|
@@ -5,6 +5,7 @@ const menuSchema = mongoose.Schema({
|
|
|
5
5
|
label: { type: String, required: true },
|
|
6
6
|
_user: { type: ObjectId, required: true, ref: "User" },
|
|
7
7
|
_company: { type: ObjectId, required: false, ref: "Company" },
|
|
8
|
+
_business: { type: ObjectId, required: false, ref: "Business" },
|
|
8
9
|
createdAt: { type: Number },
|
|
9
10
|
});
|
|
10
11
|
|
package/lib/models/User.js
CHANGED
|
@@ -8,9 +8,10 @@ const adminSchema = mongoose.Schema({
|
|
|
8
8
|
lastName: { type: String, required: false, trim: true },
|
|
9
9
|
email: {
|
|
10
10
|
type: String,
|
|
11
|
-
required:
|
|
11
|
+
required: false,
|
|
12
12
|
trim: true,
|
|
13
13
|
unique: true,
|
|
14
|
+
sparse: true,
|
|
14
15
|
lowercase: true,
|
|
15
16
|
},
|
|
16
17
|
pwd: { type: String, trim: true, minLength: 8 },
|
|
@@ -78,6 +79,7 @@ const adminSchema = mongoose.Schema({
|
|
|
78
79
|
token: { type: String, required: true },
|
|
79
80
|
date: { type: Number },
|
|
80
81
|
dateEnd: { type: Number },
|
|
82
|
+
type: { type: String, enum: ["session", "api"], default: "session" },
|
|
81
83
|
},
|
|
82
84
|
],
|
|
83
85
|
|
package/lib/services/user.js
CHANGED
|
@@ -1,99 +1,159 @@
|
|
|
1
|
+
const jwt = require("jsonwebtoken")
|
|
1
2
|
const User = require('../models/User')
|
|
2
3
|
const self = module.exports
|
|
3
4
|
|
|
4
5
|
self.create = async (body) => {
|
|
5
|
-
|
|
6
|
-
|
|
6
|
+
let user
|
|
7
|
+
const isServiceAccount = !body.email && !body.pwd
|
|
7
8
|
|
|
8
|
-
|
|
9
|
+
const nullableUnique = ['username', 'phone', 'email']
|
|
10
|
+
nullableUnique.forEach(field => {
|
|
11
|
+
if (!body[field]) delete body[field]
|
|
12
|
+
})
|
|
13
|
+
|
|
14
|
+
if (isServiceAccount) {
|
|
15
|
+
user = new User(body)
|
|
16
|
+
user.createdAt = new Date().getTime()
|
|
17
|
+
user.status = body?.status ?? 'Activo'
|
|
18
|
+
user.data = { changePwd: false }
|
|
19
|
+
|
|
20
|
+
const token = jwt.sign({ _id: user._id }, process.env.AUTH_SECRET)
|
|
21
|
+
user.tokens = [{
|
|
22
|
+
token,
|
|
23
|
+
date: new Date().getTime(),
|
|
24
|
+
dateEnd: Number.MAX_SAFE_INTEGER,
|
|
25
|
+
type: 'api'
|
|
26
|
+
}]
|
|
27
|
+
|
|
28
|
+
try {
|
|
29
|
+
await user.save()
|
|
30
|
+
} catch (error) {
|
|
31
|
+
if (error.code === 11000) {
|
|
9
32
|
throw {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
33
|
+
code: 409,
|
|
34
|
+
title: 'Upss!',
|
|
35
|
+
detail: 'Clave duplicada',
|
|
36
|
+
suggestion: 'El username ya se encuentra registrado',
|
|
37
|
+
error
|
|
15
38
|
}
|
|
39
|
+
}
|
|
40
|
+
throw error
|
|
16
41
|
}
|
|
17
|
-
|
|
18
|
-
user = new User(body)
|
|
19
|
-
user.createdAt = (new Date()).getTime()
|
|
20
|
-
user.status = body?.status ? body?.status : 'Activo'
|
|
21
|
-
|
|
22
|
-
delete user.pwd
|
|
23
|
-
user.data.changePwd = false
|
|
24
|
-
await user.save()
|
|
25
42
|
|
|
26
43
|
return user
|
|
27
|
-
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Flujo normal
|
|
47
|
+
if (body.email) {
|
|
48
|
+
const exists = await User.findOne({ email: body.email }).lean()
|
|
49
|
+
if (exists) {
|
|
50
|
+
throw {
|
|
51
|
+
code: 409,
|
|
52
|
+
title: 'Upss!',
|
|
53
|
+
detail: '',
|
|
54
|
+
suggestion: 'El correo ya se encuentra registrado',
|
|
55
|
+
error: new Error()
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
28
59
|
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
60
|
+
user = new User(body)
|
|
61
|
+
user.createdAt = new Date().getTime()
|
|
62
|
+
user.status = body?.status ?? 'Activo'
|
|
63
|
+
user.data = { changePwd: false }
|
|
32
64
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
65
|
+
try {
|
|
66
|
+
await user.save()
|
|
67
|
+
} catch (error) {
|
|
68
|
+
if (error.code === 11000) {
|
|
69
|
+
throw {
|
|
70
|
+
code: 409,
|
|
71
|
+
title: 'Upss!',
|
|
72
|
+
detail: 'Clave duplicada',
|
|
73
|
+
suggestion: 'El correo o username ya se encuentra registrado',
|
|
74
|
+
error
|
|
75
|
+
}
|
|
41
76
|
}
|
|
77
|
+
throw error
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
return user
|
|
81
|
+
}
|
|
42
82
|
|
|
43
|
-
|
|
44
|
-
|
|
83
|
+
self.update = async (USER_ID, body) => {
|
|
84
|
+
const _id = USER_ID
|
|
85
|
+
const user = await User.findOne({ _id }).countDocuments().lean()
|
|
86
|
+
|
|
87
|
+
if (!user) {
|
|
88
|
+
throw {
|
|
89
|
+
code: 404,
|
|
90
|
+
title: 'Upss!',
|
|
91
|
+
detail: 'No se encontró el elemento',
|
|
92
|
+
suggestion: 'Verifica que el usuario aun este activo en la plataforma',
|
|
93
|
+
error: new Error()
|
|
45
94
|
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
if (body.phone) {
|
|
98
|
+
await User.updateOne({ _id }, { 'validateKey.validatePhone.validCodePhone': false })
|
|
99
|
+
}
|
|
46
100
|
|
|
47
|
-
|
|
48
|
-
|
|
101
|
+
body.lastUpdate = new Date().getTime()
|
|
102
|
+
const result = await User.updateOne({ _id }, { $set: body })
|
|
49
103
|
|
|
50
|
-
|
|
104
|
+
return result
|
|
51
105
|
}
|
|
52
106
|
|
|
53
107
|
self.status = async (USER_ID, body) => {
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
}
|
|
108
|
+
const _id = USER_ID
|
|
109
|
+
const user = await User.findOne({ _id })
|
|
110
|
+
|
|
111
|
+
if (!user) {
|
|
112
|
+
throw {
|
|
113
|
+
code: 404,
|
|
114
|
+
title: 'Upss!',
|
|
115
|
+
detail: 'No se encontró el elemento',
|
|
116
|
+
suggestion: 'Verifica que el usuario aun este activo en la plataforma',
|
|
117
|
+
error: new Error()
|
|
65
118
|
}
|
|
119
|
+
}
|
|
66
120
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
const result = await user.save()
|
|
121
|
+
user.status = body.status
|
|
122
|
+
user.lastUpdate = new Date().getTime()
|
|
71
123
|
|
|
72
|
-
|
|
124
|
+
return await user.save()
|
|
73
125
|
}
|
|
74
126
|
|
|
75
127
|
self.updatepassword = async (body, USER_ID) => {
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
detail: 'No se encontró el elemento',
|
|
87
|
-
suggestion: 'Verifica que el usuario aun este activo en la plataforma',
|
|
88
|
-
error: new Error()
|
|
89
|
-
}
|
|
128
|
+
const _id = USER_ID
|
|
129
|
+
const user = await User.findOne({ _id })
|
|
130
|
+
|
|
131
|
+
if (!user) {
|
|
132
|
+
throw {
|
|
133
|
+
code: 404,
|
|
134
|
+
title: 'Upss!',
|
|
135
|
+
detail: 'No se encontró el elemento',
|
|
136
|
+
suggestion: 'Verifica que el usuario aun este activo en la plataforma',
|
|
137
|
+
error: new Error()
|
|
90
138
|
}
|
|
139
|
+
}
|
|
91
140
|
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
const result = await user.save()
|
|
141
|
+
user.pwd = body.pwd
|
|
142
|
+
user.lastUpdate = new Date().getTime()
|
|
96
143
|
|
|
97
|
-
|
|
144
|
+
return await user.save()
|
|
98
145
|
}
|
|
99
146
|
|
|
147
|
+
self.checkUsername = async (name) => {
|
|
148
|
+
if (!name) {
|
|
149
|
+
throw {
|
|
150
|
+
code: 400,
|
|
151
|
+
title: 'El nombre es requerido',
|
|
152
|
+
detail: '',
|
|
153
|
+
suggestion: 'Envía un nombre para generar el username',
|
|
154
|
+
error: new Error()
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
const username = await generateUniqueUsername(name)
|
|
158
|
+
return { username }
|
|
159
|
+
}
|