Skip to content

Commit d69b718

Browse files
[Penify]: Documentation for commit - b5926d5
1 parent 43256b8 commit d69b718

1 file changed

Lines changed: 126 additions & 15 deletions

File tree

backend/models/User.js

Lines changed: 126 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,22 @@ import logger from '../utils/logger.js';
99
import crypto from 'crypto';
1010

1111
/**
12-
* Create a new user
12+
* Create a new user.
13+
*
14+
* This function takes user data, including username, email, and password, and inserts a new user record into the database.
15+
* It handles default values for isActive, emailVerified, and role. After successfully creating the user, it logs the creation
16+
* event and returns the newly created user's information. In case of an error, it logs the error and rethrows it.
17+
*
18+
* @param {Object} userData - The data for the new user.
19+
* @param {string} userData.username - The username of the new user.
20+
* @param {string} userData.email - The email address of the new user.
21+
* @param {string} userData.password - The password for the new user.
22+
* @param {string} userData.firstName - The first name of the new user.
23+
* @param {string} userData.lastName - The last name of the new user.
24+
* @param {string} userData.encryptionSalt - The salt used for password encryption.
25+
* @param {boolean} [userData.isActive=true] - Indicates if the user is active.
26+
* @param {boolean} [userData.emailVerified=false] - Indicates if the user's email is verified.
27+
* @param {string} [userData.role='user'] - The role assigned to the new user.
1328
*/
1429
export async function createUser(userData) {
1530
try {
@@ -50,7 +65,17 @@ export async function createUser(userData) {
5065
}
5166

5267
/**
53-
* Get user by ID
68+
* Get user details by their ID.
69+
*
70+
* This function retrieves user information from the database based on the provided userId.
71+
* It allows for an optional inclusion of the user's password hash. The retrieved data is then
72+
* transformed from snake_case to camelCase for consistency in the API response. If no user is found,
73+
* it returns null. Any errors during the query process are logged and rethrown.
74+
*
75+
* @param userId - The ID of the user to retrieve.
76+
* @param includePassword - A boolean indicating whether to include the user's password hash in the response.
77+
* @returns An object containing user details in camelCase format, or null if no user is found.
78+
* @throws Error If there is an issue with the database query.
5479
*/
5580
export async function getUserById(userId, includePassword = false) {
5681
try {
@@ -94,7 +119,14 @@ export async function getUserById(userId, includePassword = false) {
94119
}
95120

96121
/**
97-
* Get user by email
122+
* Get user details by their email address.
123+
*
124+
* This function queries the database for a user with the specified email. It allows for the inclusion of the user's password hash based on the includePassword parameter. If no user is found, it returns null. The function also handles errors by logging them and rethrowing the error for further handling.
125+
*
126+
* @param email - The email address of the user to retrieve.
127+
* @param includePassword - A boolean indicating whether to include the user's password hash in the returned object.
128+
* @returns An object containing user details, or null if no user is found.
129+
* @throws Error If there is an issue querying the database.
98130
*/
99131
export async function getUserByEmail(email, includePassword = false) {
100132
try {
@@ -137,7 +169,11 @@ export async function getUserByEmail(email, includePassword = false) {
137169
}
138170

139171
/**
140-
* Get user by username
172+
* Get user by username.
173+
*
174+
* This function retrieves a user from the database based on the provided username. It executes a SQL query to fetch user details, including id, email, and role. If no user is found, it returns null. In case of an error during the query execution, it logs the error and rethrows it for further handling.
175+
*
176+
* @param {string} username - The username of the user to retrieve.
141177
*/
142178
export async function getUserByUsername(username) {
143179
try {
@@ -171,7 +207,7 @@ export async function getUserByUsername(username) {
171207
}
172208

173209
/**
174-
* Update user last login timestamp
210+
* Update the last login timestamp for a user.
175211
*/
176212
export async function updateUserLastLogin(userId) {
177213
try {
@@ -187,7 +223,7 @@ export async function updateUserLastLogin(userId) {
187223
}
188224

189225
/**
190-
* Update user last seen timestamp
226+
* Update user last seen timestamp in the database.
191227
*/
192228
export async function updateUserLastSeen(userId) {
193229
try {
@@ -201,7 +237,13 @@ export async function updateUserLastSeen(userId) {
201237
}
202238

203239
/**
204-
* Update user password and encryption salt
240+
* Update user password and encryption salt.
241+
*
242+
* This function updates the user's password hash and encryption salt in the database. It also clears all encrypted user data, as the previous data becomes unreadable with the new salt. Additionally, it invalidates all active user sessions to ensure security. The operation is performed within a transaction to maintain data integrity, and any errors during the process are logged for auditing purposes.
243+
*
244+
* @param {string} userId - The ID of the user whose password is being updated.
245+
* @param {string} newPasswordHash - The new password hash to be set for the user.
246+
* @param {string} newEncryptionSalt - The new encryption salt to be set for the user.
205247
*/
206248
export async function updateUserPassword(userId, newPasswordHash, newEncryptionSalt) {
207249
try {
@@ -232,7 +274,20 @@ export async function updateUserPassword(userId, newPasswordHash, newEncryptionS
232274
}
233275

234276
/**
235-
* Update user profile
277+
* Update user profile.
278+
*
279+
* This function updates the user's profile information in the database based on the provided userId and profileData.
280+
* It uses a SQL query to update fields such as first name, last name, bio, avatar URL, and preferences,
281+
* while ensuring that only non-null values are updated. If the user is not found, an error is thrown.
282+
* Additionally, it logs the update action and returns the updated user information.
283+
*
284+
* @param {string} userId - The ID of the user whose profile is to be updated.
285+
* @param {Object} profileData - The new profile data for the user.
286+
* @param {string} profileData.firstName - The user's first name.
287+
* @param {string} profileData.lastName - The user's last name.
288+
* @param {string} profileData.bio - The user's biography.
289+
* @param {string} profileData.avatarUrl - The URL of the user's avatar.
290+
* @param {Object} profileData.preferences - The user's preferences.
236291
*/
237292
export async function updateUserProfile(userId, profileData) {
238293
try {
@@ -291,7 +346,15 @@ export async function updateUserProfile(userId, profileData) {
291346
}
292347

293348
/**
294-
* Create password reset token
349+
* Create a password reset token for a user.
350+
*
351+
* This function updates the user's record in the database with a new password reset token and its expiration time.
352+
* It logs an audit message upon successful creation and handles any errors that occur during the database update,
353+
* logging the error details before rethrowing the error.
354+
*
355+
* @param {string} userId - The ID of the user for whom the password reset token is being created.
356+
* @param {string} token - The password reset token to be set for the user.
357+
* @param {Date} expiresAt - The expiration date and time for the password reset token.
295358
*/
296359
export async function createPasswordResetToken(userId, token, expiresAt) {
297360
try {
@@ -309,7 +372,14 @@ export async function createPasswordResetToken(userId, token, expiresAt) {
309372
}
310373

311374
/**
312-
* Validate password reset token and return user
375+
* Validate the password reset token and return user information.
376+
*
377+
* This function queries the database to check if the provided password reset token is valid
378+
* and has not expired. It retrieves the user's details if the token is valid and the user is active.
379+
* If the token is invalid or expired, it returns null. In case of an error during the query,
380+
* it logs the error and rethrows it.
381+
*
382+
* @param {string} token - The password reset token to validate.
313383
*/
314384
export async function validatePasswordResetToken(token) {
315385
try {
@@ -341,7 +411,23 @@ export async function validatePasswordResetToken(token) {
341411
}
342412

343413
/**
344-
* Get users with pagination
414+
* Get users with pagination and filtering options.
415+
*
416+
* This function retrieves a paginated list of users from the database based on the provided options.
417+
* It constructs a dynamic SQL query with filters for search, role, and active status, and returns
418+
* the user data along with pagination information such as total count, total pages, and current page.
419+
*
420+
* @param options - An object containing pagination and filtering options.
421+
* @param options.page - The page number to retrieve (default is 1).
422+
* @param options.limit - The number of users per page (default is 20).
423+
* @param options.sortBy - The field to sort by (default is 'created_at').
424+
* @param options.sortOrder - The order of sorting (default is 'desc').
425+
* @param options.search - A search term to filter users by username or email.
426+
* @param options.role - A specific role to filter users.
427+
* @param options.isActive - A boolean to filter users by active status.
428+
* @returns An object containing the list of users, total count, total pages, current page,
429+
* and flags indicating if there are next or previous pages.
430+
* @throws Error If the query fails to execute.
345431
*/
346432
export async function getUsers(options = {}) {
347433
try {
@@ -427,7 +513,13 @@ export async function getUsers(options = {}) {
427513
}
428514

429515
/**
430-
* Delete user (soft delete by deactivating)
516+
* Delete user (soft delete by deactivating).
517+
*
518+
* This function performs a soft delete of a user by deactivating their account and updating their email and username
519+
* to indicate deletion. It also invalidates all active sessions associated with the user. The function is wrapped in a
520+
* transaction to ensure atomicity. In case of an error, it logs the failure and rethrows the error for further handling.
521+
*
522+
* @param {string} userId - The ID of the user to be deleted.
431523
*/
432524
export async function deleteUser(userId) {
433525
try {
@@ -458,7 +550,15 @@ export async function deleteUser(userId) {
458550
}
459551

460552
/**
461-
* Store encrypted sensitive data for user
553+
* Store encrypted sensitive data for user.
554+
*
555+
* This function encrypts the provided data using the encryptField function and stores it in the user_encrypted_data table.
556+
* If a record for the userId and dataType already exists, it updates the encrypted_data and the updated_at timestamp.
557+
* The operation is wrapped in a try-catch block to handle any errors that may occur during the database operation.
558+
*
559+
* @param {string} userId - The unique identifier for the user.
560+
* @param {string} dataType - The type of data being stored.
561+
* @param {any} data - The sensitive data to be encrypted and stored.
462562
*/
463563
export async function storeUserEncryptedData(userId, dataType, data) {
464564
try {
@@ -482,7 +582,14 @@ export async function storeUserEncryptedData(userId, dataType, data) {
482582
}
483583

484584
/**
485-
* Retrieve encrypted sensitive data for user
585+
* Retrieve decrypted sensitive data for a user.
586+
*
587+
* This function queries the database for encrypted data associated with a specific userId and dataType.
588+
* If no data is found, it returns null. Otherwise, it decrypts the retrieved encrypted data using the
589+
* decryptField function and returns the decrypted result. Errors during the process are logged for debugging.
590+
*
591+
* @param {string} userId - The ID of the user whose data is being retrieved.
592+
* @param {string} dataType - The type of data to retrieve for the user.
486593
*/
487594
export async function getUserEncryptedData(userId, dataType) {
488595
try {
@@ -506,7 +613,11 @@ export async function getUserEncryptedData(userId, dataType) {
506613
}
507614

508615
/**
509-
* Get user statistics
616+
* Get user statistics for a specific user.
617+
*
618+
* This function retrieves various statistics related to a user's progress, including the number of stages completed, total time spent, total sessions, average rating, and the timestamp of the last session. It executes a SQL query to gather this data from the user_progress table, filtering by the provided userId. If an error occurs during the query execution, it logs the error and rethrows it.
619+
*
620+
* @param {number} userId - The ID of the user for whom to retrieve statistics.
510621
*/
511622
export async function getUserStats(userId) {
512623
try {

0 commit comments

Comments
 (0)