Created
July 4, 2024 14:25
-
-
Save montasim/9e7c9640c165fe923da49707deea69a6 to your computer and use it in GitHub Desktop.
This module defines middleware for authenticating users based on JSON Web Tokens (JWT). It checks for a valid token in the Authorization header, validates it, and retrieves the user details. If the token is valid and the user exists, it allows the request to proceed. If any validation fails, it returns an appropriate HTTP status code and error m…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import getAuthenticationToken from '../utilities/getAuthenticationToken.js'; | |
import httpStatus from '../constant/httpStatus.constants.js'; | |
import decodeAuthenticationToken | |
from '../utilities/decodeAuthenticationToken.js'; | |
import UsersModel from '../modules/api/users/users.model.js'; | |
const authenticateMiddleware = async (req, res, next) => { | |
const token = await getAuthenticationToken(req?.headers['authorization']); | |
if (!token) { | |
const forbiddenData = { | |
timeStamp: new Date(), | |
success: false, | |
data: {}, | |
message: 'Access forbidden. No token provided.', | |
status: httpStatus.FORBIDDEN, | |
route: req.originalUrl | |
}; | |
return res.status(forbiddenData.status).send(forbiddenData); | |
} | |
try { | |
const decodedData = await decodeAuthenticationToken(token); | |
const userDetails = await UsersModel.findById(decodedData.currentUser._id); | |
if (!userDetails) { | |
const unauthorizedData = { | |
timeStamp: new Date(), | |
success: false, | |
data: {}, | |
message: 'Unauthorized access.', | |
status: httpStatus.UNAUTHORIZED, | |
route: req.originalUrl | |
}; | |
return res.status(unauthorizedData.status).send(unauthorizedData); | |
} | |
req.sessionUser = decodedData; | |
next(); | |
} catch (error) { | |
const forbiddenData = { | |
timeStamp: new Date(), | |
success: false, | |
data: {}, | |
message: 'Access forbidden. Invalid token.', | |
status: httpStatus.FORBIDDEN, | |
route: req.originalUrl | |
}; | |
return res.status(forbiddenData.status).send(forbiddenData); | |
} | |
}; | |
export default authenticateMiddleware; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import jwt from 'jsonwebtoken'; | |
import configuration from '../configuration/configuration.js'; | |
const verifyAuthenticationToken = async (token) => { | |
return new Promise((resolve, reject) => { | |
jwt.verify(token, configuration.jwt.secret, (err, decodedToken) => { | |
if (err) { | |
reject(err); // Token verification failed (e.g., token is expired or invalid) | |
} else { | |
resolve(decodedToken); // Return the decoded token data | |
} | |
}); | |
}); | |
}; | |
// Example usage: | |
const decodeAuthenticationToken = async (token) => { | |
return await verifyAuthenticationToken(token); | |
}; | |
export default decodeAuthenticationToken; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const getAuthenticationToken = async (header) => { | |
const bearer = 'Bearer '; | |
return await header?.startsWith(bearer) ? header.slice(bearer.length) : null; | |
}; | |
export default getAuthenticationToken; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment