Skip to content

Commit 43256b8

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

1 file changed

Lines changed: 61 additions & 10 deletions

File tree

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)