-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathusers.service.js
More file actions
225 lines (205 loc) · 8.7 KB
/
users.service.js
File metadata and controls
225 lines (205 loc) · 8.7 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
/**
* Module dependencies
*/
import _ from 'lodash';
import config from '../../../config/index.js';
import AuthService from '../../auth/services/auth.service.js';
import UserRepository from '../repositories/users.repository.js';
import MembershipService from '../../organizations/services/organizations.membership.service.js';
import OrganizationsRepository from '../../organizations/repositories/organizations.repository.js';
import MembershipRepository from '../../organizations/repositories/organizations.membership.repository.js';
import { MEMBERSHIP_ROLES, MEMBERSHIP_STATUSES } from '../../organizations/lib/constants.js';
import { removeSensitive } from '../utils/sanitizeUser.js';
/**
* @desc Function to get all users in db
* @param {String} search
* @param {Int} page
* @param {Int} perPage
* @returns {Promise<Array>} users selected
*/
const list = async (search, page, perPage) => {
const result = await UserRepository.list(search, page || 0, perPage || 20);
return result.map((user) => removeSensitive(user));
};
/**
* @desc Function to ask repository to create a user (define provider, check & hashpassword, save)
* @param {Object} user
* @returns {Promise<Object>} created user (sanitized)
*/
const create = async (user) => {
// Set provider to local
if (!user.provider) user.provider = 'local';
// confirming to secure password policies
if (user.password) {
// Password-strength validation is enforced at the model layer via its schema refinement/helper.
// const validPassword = zxcvbn(user.password);
// if (!validPassword || !validPassword.score || validPassword.score < config.zxcvbn.minimumScore) {
// throw new AppError(`${validPassword.feedback.warning}. ${validPassword.feedback.suggestions.join('. ')}`);
// }
// When password is provided we need to make sure we are hashing it
user.password = await AuthService.hashPassword(user.password);
}
const result = await UserRepository.create(user);
// Remove sensitive data before return
return removeSensitive(result);
};
/**
* @desc Function to ask repository to search users by request
* @param {Object} input - mongoose query input
* @returns {Promise<Array>} matching users (sanitized)
*/
const search = async (input) => {
const result = await UserRepository.search(input);
return result.map((user) => removeSensitive(user));
};
/**
* @desc Function to ask repository to get a user by id or email
* @param {Object} user - object with id or email field
* @returns {Promise<Object|null>} sanitized user or null
*/
const get = async (user) => {
const result = await UserRepository.get(user);
return removeSensitive(result);
};
/**
* @desc Function to ask repository to get a user by id or email without filter data return (test & intern usage)
* @param {Object} user - object with id or email field
* @returns {Promise<Object|null>} full user document or null
*/
const getBrut = async (user) => {
const result = await UserRepository.get(user);
return result;
};
/**
* @desc Function to ask repository to update a user
* @param {Object} user - original user document
* @param {Object} body - fields to update
* @param {string} [option] - update mode: 'admin', 'recover', or undefined for user self-update
* @returns {Promise<Object>} updated user (sanitized)
*/
const update = async (user, body, option) => {
if (!option) user = _.assignIn(user, removeSensitive(body, config.whitelists.users.update));
else if (option === 'admin') user = _.assignIn(user, removeSensitive(body, config.whitelists.users.updateAdmin));
else if (option === 'recover') user = _.assignIn(user, removeSensitive(body, config.whitelists.users.recover));
const result = await UserRepository.update(user);
return removeSensitive(result);
};
/**
* @desc Function to ask repository to sign terms for current user
* @param {Object} user - original user document
* @returns {Promise<Object>} updated user (sanitized)
*/
const terms = async (user) => {
user = _.assignIn(user, { terms: new Date() });
const result = await UserRepository.update(user);
return removeSensitive(result);
};
/**
* @desc Function to remove a user from db and clean up associated memberships/orgs
* @param {Object} user - user document with _id or id field
* @returns {Promise<Object>} deletion result
*/
const remove = async (user) => {
const userId = user._id || user.id;
// Clean up memberships and handle orphaned orgs before deleting the user
const memberships = await MembershipService.listByUser(userId);
for (const membership of memberships) {
const orgId = membership.organizationId._id || membership.organizationId;
if (membership.role === MEMBERSHIP_ROLES.OWNER) {
// Check if this user is the only owner of the org
const ownerCount = await MembershipService.count({ organizationId: orgId, role: MEMBERSHIP_ROLES.OWNER, status: MEMBERSHIP_STATUSES.ACTIVE });
if (ownerCount <= 1) {
// Sole owner — delete org and cascade: repair co-member currentOrganization
// Step 1: Collect co-members whose currentOrganization points to this org
const affectedUsers = await UserRepository.findWithFilter({ currentOrganization: orgId }, '_id');
// Step 2: Delete all memberships for this org (including this user's and all co-members')
await MembershipService.deleteMany({ organizationId: orgId });
// Step 3: For each affected co-member, switch to their next available org or set null
await Promise.all(affectedUsers.map(async (u) => {
const remaining = await MembershipRepository.list({ userId: u._id, status: MEMBERSHIP_STATUSES.ACTIVE });
const nextOrg = remaining.length > 0 ? (remaining[0].organizationId._id || remaining[0].organizationId) : null;
await UserRepository.updateById(u._id, { currentOrganization: nextOrg });
}));
// Step 4: Delete the org (bare remove — org-scoped tasks are intentionally not deleted here)
await OrganizationsRepository.remove({ _id: orgId });
continue; // memberships for this org already cleaned up
}
}
// Delete this user's membership
await MembershipService.deleteMany({ _id: membership._id });
}
const result = await UserRepository.remove(user);
return result;
};
/**
* @desc Function to get all stats of db
* @returns {Promise<Object>} user statistics
*/
const stats = async () => {
const result = await UserRepository.stats();
return result;
};
/**
* @desc Function to update a user by ID with a partial update object
* @param {String} id - The user ID
* @param {Object} data - Fields to update
* @returns {Promise<Object>} update result
*/
const updateById = (id, data) => UserRepository.updateById(id, data);
/**
* @desc Function to find users matching a filter with optional field selection
* @param {Object} filter - Mongoose filter
* @param {String} [select] - Fields to select
* @returns {Promise<Array>} matching users
*/
const findWithFilter = (filter, select) => UserRepository.findWithFilter(filter, select);
/**
* @desc Function to find a user by ID, update, and return the populated document
* @param {String} id - The user ID
* @param {Object} data - Fields to update
* @param {String|Array|Object} populateFields - Fields to populate
* @returns {Promise<Object>} updated user
*/
const findByIdAndUpdatePopulated = (id, data, populateFields) => UserRepository.findByIdAndUpdatePopulated(id, data, populateFields);
/**
* @desc Function to search users by name or email
* @param {String} search - The search string
* @returns {Promise<Array>} matching user IDs
*/
const searchByNameOrEmail = (search) => UserRepository.searchByNameOrEmail(search);
/**
* @desc Function to find a user by email address
* @param {String} email - The email to search for
* @returns {Promise<Object|null>} The matching user or null
*/
const findByEmail = (email) => UserRepository.findByEmail(email);
/**
* @desc Atomically attach an OAuth provider to an existing user matched by email.
* Uses a single findOneAndUpdate to avoid TOCTOU races between concurrent OAuth callbacks.
* @param {string} email - The email to match
* @param {string} provider - The OAuth provider key (e.g. 'google', 'apple')
* @param {Object} providerData - The provider's identity data to store
* @returns {Promise<Object|null>} sanitized updated user or null if no match
*/
const linkProviderByEmail = async (email, provider, providerData) => {
const result = await UserRepository.linkProviderByEmail(email, provider, providerData);
return result ? removeSensitive(result) : null;
};
export default {
list,
create,
search,
get,
getBrut,
update,
terms,
remove,
stats,
updateById,
findWithFilter,
findByIdAndUpdatePopulated,
searchByNameOrEmail,
findByEmail,
linkProviderByEmail,
removeSensitive,
};