Skip to content

Commit d3712b9

Browse files
Merge pull request #10 from OneFineStarstuff/penify/auto_doc_b5926d5_e445a
[Penify]: Documentation for commit - b5926d5
2 parents 892249e + 77ea8a0 commit d3712b9

File tree

4 files changed

+255
-34
lines changed

4 files changed

+255
-34
lines changed

backend/config/database.js

Lines changed: 45 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,13 @@ pool.on('remove', (client) => {
5555
});
5656

5757
/**
58-
* Initialize database connection and create tables
58+
* Initialize database connection and create necessary tables.
59+
*
60+
* This function establishes a connection to the database using the provided configuration,
61+
* tests the connection by executing a simple query, and logs the connection details.
62+
* If the connection is successful, it proceeds to create the required tables by calling
63+
* the createTables function. In case of any errors during the process, it logs the error
64+
* and rethrows it for further handling.
5965
*/
6066
export async function initializeDatabase() {
6167
try {
@@ -84,7 +90,12 @@ export async function initializeDatabase() {
8490
}
8591

8692
/**
87-
* Create database tables
93+
* Create database tables and initialize the database schema.
94+
*
95+
* This function connects to the database, begins a transaction, and creates several tables including users, wheel_stages, user_progress, user_sessions, user_encrypted_data, analytics_events, and audit_logs. It also enables necessary extensions, creates indexes for performance, and sets up triggers for updating timestamps. Finally, it inserts default wheel stages if they do not already exist. If any error occurs, the transaction is rolled back.
96+
*
97+
* @returns {Promise<void>} A promise that resolves when the tables are created and initialized.
98+
* @throws {Error} If there is an error during the database operations.
8899
*/
89100
async function createTables() {
90101
const client = await pool.connect();
@@ -302,7 +313,12 @@ async function createTables() {
302313
}
303314

304315
/**
305-
* Insert default wheel stages
316+
* Insert default wheel stages into the database if none exist.
317+
*
318+
* This asynchronous function connects to the database and checks if any wheel stages are already present.
319+
* If no stages are found, it inserts a predefined set of default stages, each with attributes such as title,
320+
* symbol, essence, meaning, action, chant, and order_index. The function also logs the insertion process
321+
* and handles any potential errors during the database operations.
306322
*/
307323
async function insertDefaultWheelStages() {
308324
const defaultStages = [
@@ -425,7 +441,14 @@ async function insertDefaultWheelStages() {
425441
}
426442

427443
/**
428-
* Execute a database query with error handling and logging
444+
* Execute a database query with error handling and logging.
445+
*
446+
* This function connects to the database, executes the provided SQL query with optional parameters,
447+
* and logs the duration and result of the query. In case of an error, it logs the error message and
448+
* rethrows the error. The database client is released after the operation, ensuring proper resource management.
449+
*
450+
* @param {string} text - The SQL query to be executed.
451+
* @param {Array} [params=[]] - The parameters for the SQL query.
429452
*/
430453
export async function query(text, params = []) {
431454
const start = Date.now();
@@ -454,7 +477,15 @@ export async function query(text, params = []) {
454477
}
455478

456479
/**
457-
* Execute a transaction
480+
* Execute a transaction.
481+
*
482+
* This function establishes a connection to the database, begins a transaction,
483+
* and executes the provided callback function with the database client. If the
484+
* callback completes successfully, the transaction is committed; if an error
485+
* occurs, the transaction is rolled back. Finally, the database client is released.
486+
*
487+
* @param {Function} callback - A function that takes the database client as an argument
488+
* and performs operations within the transaction.
458489
*/
459490
export async function transaction(callback) {
460491
const client = await pool.connect();
@@ -473,7 +504,7 @@ export async function transaction(callback) {
473504
}
474505

475506
/**
476-
* Store encrypted data for a user
507+
* Store encrypted data for a user in the database.
477508
*/
478509
export async function storeEncryptedData(userId, dataType, data) {
479510
const encryptedData = encryptField(data);
@@ -487,7 +518,7 @@ export async function storeEncryptedData(userId, dataType, data) {
487518
}
488519

489520
/**
490-
* Retrieve encrypted data for a user
521+
* Retrieve and decrypt encrypted data for a user.
491522
*/
492523
export async function getEncryptedData(userId, dataType) {
493524
const result = await query(`
@@ -504,7 +535,7 @@ export async function getEncryptedData(userId, dataType) {
504535
}
505536

506537
/**
507-
* Close database connection
538+
* Closes the database connection.
508539
*/
509540
export async function closeDatabase() {
510541
try {
@@ -516,7 +547,12 @@ export async function closeDatabase() {
516547
}
517548

518549
/**
519-
* Health check
550+
* Performs a health check on the database.
551+
*
552+
* This function executes a simple query to verify the database's availability.
553+
* It checks if the result indicates a healthy state by comparing the returned value
554+
* to 1. In case of an error during the query execution, it logs the error and
555+
* returns false to indicate an unhealthy state.
520556
*/
521557
export async function healthCheck() {
522558
try {

backend/middleware/auth.js

Lines changed: 61 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ const JWT_EXPIRY = process.env.JWT_EXPIRY || '15m';
1616
const JWT_REFRESH_EXPIRY = process.env.JWT_REFRESH_EXPIRY || '7d';
1717

1818
/**
19-
* Generate JWT access token
19+
* Generates a JWT access token with the given payload.
2020
*/
2121
export function generateAccessToken(payload) {
2222
return jwt.sign(
@@ -37,7 +37,7 @@ export function generateAccessToken(payload) {
3737
}
3838

3939
/**
40-
* Generate JWT refresh token
40+
* Generates a JWT refresh token.
4141
*/
4242
export function generateRefreshToken(payload) {
4343
return jwt.sign(
@@ -58,7 +58,14 @@ export function generateRefreshToken(payload) {
5858
}
5959

6060
/**
61-
* Verify JWT token
61+
* Verify JWT token.
62+
*
63+
* This function checks the validity of a JWT token using a specified secret based on whether it is a refresh token or not.
64+
* It decodes the token and returns an object indicating its validity, the decoded payload, and whether it has expired.
65+
* If an error occurs during verification, it handles different error types to provide specific feedback on the token's status.
66+
*
67+
* @param {string} token - The JWT token to verify.
68+
* @param {boolean} [isRefresh=false] - Indicates if the token is a refresh token.
6269
*/
6370
export function verifyToken(token, isRefresh = false) {
6471
try {
@@ -103,7 +110,17 @@ export function verifyToken(token, isRefresh = false) {
103110
}
104111

105112
/**
106-
* Authentication middleware
113+
* Authentication middleware for validating user tokens.
114+
*
115+
* This middleware checks for a valid Bearer token in the authorization header, verifies its validity and type,
116+
* and retrieves user information. It handles various authentication errors, including blacklisted tokens,
117+
* expired tokens, and inactive accounts, responding with appropriate status codes and messages.
118+
* If successful, it attaches user and token information to the request object for further processing.
119+
*
120+
* @param req - The request object containing the HTTP request data.
121+
* @param res - The response object used to send HTTP responses.
122+
* @param next - The next middleware function in the stack.
123+
* @throws Error If an internal error occurs during authentication.
107124
*/
108125
export async function authMiddleware(req, res, next) {
109126
try {
@@ -212,7 +229,9 @@ export async function authMiddleware(req, res, next) {
212229
}
213230

214231
/**
215-
* Optional authentication middleware (doesn't fail if no token)
232+
* Optional authentication middleware that allows requests to proceed without a token.
233+
*
234+
* This middleware checks for the presence of an authorization header. If the header is missing or does not start with 'Bearer ', it sets req.user and req.token to null and calls next() to continue the request. If the header is present, it attempts to call the authMiddleware function. If authMiddleware throws an error, it catches the error, sets req.user and req.token to null, and continues the request.
216235
*/
217236
export async function optionalAuthMiddleware(req, res, next) {
218237
const authHeader = req.headers.authorization;
@@ -234,7 +253,14 @@ export async function optionalAuthMiddleware(req, res, next) {
234253
}
235254

236255
/**
237-
* Role-based authorization middleware
256+
* Role-based authorization middleware.
257+
*
258+
* This middleware checks if the user is authenticated and has one of the required roles.
259+
* If the user is not authenticated, a 401 status is returned with an appropriate message.
260+
* If the user's role is not included in the specified roles, a 403 status is returned,
261+
* indicating insufficient permissions. If both checks pass, the middleware calls the next function.
262+
*
263+
* @param {...string} roles - The roles that are required to access the resource.
238264
*/
239265
export function requireRole(...roles) {
240266
return (req, res, next) => {
@@ -259,7 +285,16 @@ export function requireRole(...roles) {
259285
}
260286

261287
/**
262-
* Refresh token middleware
288+
* Middleware to refresh the token for authenticated users.
289+
*
290+
* This function checks for the presence of a refresh token in the request body, verifies its validity, and ensures it is not blacklisted.
291+
* It also checks the token type and retrieves the associated user information, attaching it to the request object for further processing.
292+
* If any validation fails, appropriate error responses are sent back to the client.
293+
*
294+
* @param req - The request object containing the refresh token in the body.
295+
* @param res - The response object used to send responses back to the client.
296+
* @param next - The next middleware function in the stack.
297+
* @throws Error If an internal server error occurs during the token refresh process.
263298
*/
264299
export async function refreshTokenMiddleware(req, res, next) {
265300
try {
@@ -334,7 +369,16 @@ export async function refreshTokenMiddleware(req, res, next) {
334369
}
335370

336371
/**
337-
* Logout middleware - blacklist tokens
372+
* Logout middleware - blacklist tokens.
373+
*
374+
* This middleware handles the logout process by blacklisting the access token and, if provided, the refresh token.
375+
* It checks for the presence of the access token and blacklists it if available. If a refresh token is included in
376+
* the request body, it verifies the token and blacklists it if valid. The function logs the logout action and
377+
* proceeds to the next middleware, even if an error occurs during the blacklisting process.
378+
*
379+
* @param {Object} req - The request object containing user and token information.
380+
* @param {Object} res - The response object.
381+
* @param {Function} next - The next middleware function to call.
338382
*/
339383
export async function logoutMiddleware(req, res, next) {
340384
try {
@@ -367,7 +411,7 @@ export async function logoutMiddleware(req, res, next) {
367411
}
368412

369413
/**
370-
* Generate token pair (access + refresh)
414+
* Generates a token pair (access + refresh) from the given payload.
371415
*/
372416
export function generateTokenPair(payload) {
373417
const accessToken = generateAccessToken(payload);
@@ -383,7 +427,14 @@ export function generateTokenPair(payload) {
383427
}
384428

385429
/**
386-
* Extract token from request
430+
* Extract token from request.
431+
*
432+
* This function retrieves a token from the provided request object. It first checks the
433+
* authorization header for a Bearer token and returns it if present. If the header is
434+
* not available or does not contain a Bearer token, it falls back to checking the query
435+
* parameters for a token, specifically for WebSocket scenarios.
436+
*
437+
* @param {Object} req - The request object containing headers and query parameters.
387438
*/
388439
export function extractTokenFromRequest(req) {
389440
const authHeader = req.headers.authorization;

0 commit comments

Comments
 (0)