-
Notifications
You must be signed in to change notification settings - Fork 8
middle-ware-added #175
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
middle-ware-added #175
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
61f08bb
middle-ware-added
MallanagoudaB 1ca287f
fix-for-middleware
MallanagoudaB e69ebf2
added-check
MallanagoudaB 214615b
added-function-sign
MallanagoudaB 29d49de
auth-fix
MallanagoudaB a86e0ff
auth-file-change
MallanagoudaB 2e00a40
handled-file-check
MallanagoudaB File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,181 @@ | ||
| /** | ||
| * name : checkAdminRole.js | ||
| * author : Mallanagouda R Biradar | ||
| * Date : 7-Aug-2025 | ||
| * Description : checkAdminRole middleware. | ||
| */ | ||
|
|
||
| const jwt = require('jsonwebtoken') | ||
| const path = require('path') | ||
| const fs = require('fs') | ||
| const _ = require('lodash') | ||
| var respUtil = function (resp) { | ||
| return { | ||
| status: resp.errCode, | ||
| message: resp.errMsg, | ||
| currentDate: new Date().toISOString(), | ||
| } | ||
| } | ||
|
|
||
| module.exports = async function (req, res, next) { | ||
| // Define paths that require admin role validation | ||
| let adminPath = ['admin/deleteEntity'] | ||
| // Initialize response object for error formatting | ||
| let rspObj = {} | ||
| // Flag to check if the current request path needs admin validation | ||
| let requiresAdminValidation = false | ||
| // Check if the incoming request path matches any admin paths | ||
| await Promise.all( | ||
| adminPath.map(async function (path) { | ||
| if (req.path.includes(path)) { | ||
| requiresAdminValidation = true | ||
| } | ||
| }) | ||
| ) | ||
|
|
||
| // If path needs admin check, validate the user's role using JWT token | ||
| if (requiresAdminValidation) { | ||
| // Get token from request headers | ||
| const token = req.headers['x-auth-token'] | ||
|
|
||
| // If no token found, return unauthorized error | ||
| if (!token) { | ||
| rspObj.errCode = CONSTANTS.apiResponses.TOKEN_MISSING_CODE | ||
| rspObj.errMsg = CONSTANTS.apiResponses.TOKEN_MISSING_MESSAGE | ||
| rspObj.responseCode = HTTP_STATUS_CODE['unauthorized'].status | ||
| return res.status(HTTP_STATUS_CODE['unauthorized'].status).send(respUtil(rspObj)) | ||
| } | ||
|
|
||
| let decodedToken | ||
| try { | ||
| // Decode and verify JWT token using secret key | ||
| if (process.env.AUTH_METHOD === CONSTANTS.common.AUTH_METHOD.NATIVE) { | ||
| try { | ||
| // If using native authentication, verify the JWT using the secret key | ||
| decodedToken = jwt.verify(token, process.env.ACCESS_TOKEN_SECRET) | ||
| } catch (err) { | ||
| // If verification fails, send an unauthorized response | ||
| rspObj.errCode = CONSTANTS.apiResponses.TOKEN_MISSING_CODE | ||
| rspObj.errMsg = CONSTANTS.apiResponses.TOKEN_MISSING_MESSAGE | ||
| rspObj.responseCode = HTTP_STATUS_CODE['unauthorized'].status | ||
| return res.status(HTTP_STATUS_CODE['unauthorized'].status).send(respUtil(rspObj)) | ||
| } | ||
| } else if (process.env.AUTH_METHOD === CONSTANTS.common.AUTH_METHOD.KEYCLOAK_PUBLIC_KEY) { | ||
| // If using Keycloak with a public key for authentication | ||
| const keycloakPublicKeyPath = `${process.env.KEYCLOAK_PUBLIC_KEY_PATH}/` | ||
| const PEM_FILE_BEGIN_STRING = '-----BEGIN PUBLIC KEY-----' | ||
| const PEM_FILE_END_STRING = '-----END PUBLIC KEY-----' | ||
|
|
||
| // Decode the JWT to extract its claims without verifying | ||
| const tokenClaims = jwt.decode(token, { complete: true }) | ||
|
|
||
| if (!tokenClaims || !tokenClaims.header) { | ||
| // If the token does not contain valid claims or header, send an unauthorized response | ||
| rspObj.errCode = CONSTANTS.apiResponses.TOKEN_MISSING_CODE | ||
| rspObj.errMsg = CONSTANTS.apiResponses.TOKEN_MISSING_MESSAGE | ||
| rspObj.responseCode = HTTP_STATUS_CODE['unauthorized'].status | ||
| return res.status(HTTP_STATUS_CODE['unauthorized'].status).send(respUtil(rspObj)) | ||
| } | ||
|
|
||
| // Extract the key ID (kid) from the token header | ||
| const kid = tokenClaims.header.kid | ||
|
|
||
| // Construct the path to the public key file using the key ID | ||
| let filePath = path.resolve(__dirname, keycloakPublicKeyPath, kid.replace(/\.\.\//g, '')) | ||
|
|
||
| // Read the public key file from the resolved file path | ||
| const accessKeyFile = await fs.promises.readFile(filePath, 'utf8') | ||
|
|
||
| // Ensure the public key is properly formatted with BEGIN and END markers | ||
| const cert = accessKeyFile.includes(PEM_FILE_BEGIN_STRING) | ||
| ? accessKeyFile | ||
| : `${PEM_FILE_BEGIN_STRING}\n${accessKeyFile}\n${PEM_FILE_END_STRING}` | ||
| let verifiedClaims | ||
| try { | ||
| // Verify the JWT using the public key and specified algorithms | ||
| verifiedClaims = jwt.verify(token, cert, { algorithms: ['sha1', 'RS256', 'HS256'] }) | ||
| } catch (err) { | ||
| // If the token is expired or any other error occurs during verification | ||
| if (err.name === 'TokenExpiredError') { | ||
| rspObj.errCode = CONSTANTS.apiResponses.TOKEN_INVALID_CODE | ||
| rspObj.errMsg = CONSTANTS.apiResponses.TOKEN_INVALID_MESSAGE | ||
| rspObj.responseCode = HTTP_STATUS_CODE['unauthorized'].status | ||
| return res.status(HTTP_STATUS_CODE['unauthorized'].status).send(respUtil(rspObj)) | ||
| } | ||
| } | ||
|
|
||
| // Extract the external user ID from the verified claims | ||
| const externalUserId = verifiedClaims.sub.split(':').pop() | ||
|
|
||
| const data = { | ||
| id: externalUserId, | ||
| roles: [], // this is temporariy set to an empty array, it will be corrected soon... | ||
| name: verifiedClaims.name, | ||
| organization_id: verifiedClaims.org || null, | ||
| } | ||
|
|
||
| // Ensure decodedToken is initialized as an object | ||
| decodedToken = decodedToken || {} | ||
| decodedToken['data'] = data | ||
| } | ||
| } catch (error) { | ||
| return res.status(HTTP_STATUS_CODE.unauthorized.status).send( | ||
| respUtil({ | ||
| errCode: CONSTANTS.apiResponses.TOKEN_MISSING_CODE, | ||
| errMsg: CONSTANTS.apiResponses.TOKEN_MISSING_MESSAGE, | ||
| responseCode: HTTP_STATUS_CODE['unauthorized'].status, | ||
| }) | ||
| ) | ||
| } | ||
MallanagoudaB marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| // Path to config.json | ||
| const configFilePath = path.resolve(__dirname, '../../config.json') | ||
| // Initialize variables | ||
| let configData = {} | ||
| let defaultRoleExtraction | ||
| // Check if config.json exists | ||
| if (fs.existsSync(configFilePath)) { | ||
| // Read and parse the config.json file | ||
| const rawData = fs.readFileSync(configFilePath) | ||
| try { | ||
| configData = JSON.parse(rawData) | ||
| if (!configData.userRolesInformationKey) { | ||
| defaultRoleExtraction = decodedToken.data.organizations[0].roles | ||
MallanagoudaB marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } else { | ||
| defaultRoleExtraction = _.get({ decodedToken }, configData.userRolesInformationKey) | ||
| } | ||
| } catch (error) { | ||
| console.error('Error parsing config.json:', error) | ||
| } | ||
| } else { | ||
| defaultRoleExtraction = decodedToken.data.organizations[0].roles | ||
| } | ||
|
|
||
| if (!defaultRoleExtraction) { | ||
| rspObj.errCode = CONSTANTS.apiResponses.TENANTID_AND_ORGID_REQUIRED_IN_TOKEN_CODE | ||
| rspObj.errMsg = CONSTANTS.apiResponses.TENANTID_AND_ORGID_REQUIRED_IN_TOKEN_MESSAGE | ||
| rspObj.responseCode = HTTP_STATUS_CODE['unauthorized'].status | ||
| return res.status(HTTP_STATUS_CODE['unauthorized'].status).send(respUtil(rspObj)) | ||
| } | ||
|
|
||
| // Convert roles array to list of role titles | ||
| let roles = defaultRoleExtraction.map((roles) => { | ||
| return roles.title | ||
| }) | ||
|
|
||
| // Check if user has the admin role | ||
| if (roles.includes(CONSTANTS.common.ADMIN_ROLE)) { | ||
| // If admin, allow the request to continue | ||
| return next() | ||
| } else { | ||
| // If not admin, throw forbidden error | ||
| return next({ | ||
| status: responseCode.forbidden.status, | ||
| message: reqMsg.ADMIN_ROLE_REQUIRED, | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| next() | ||
| return | ||
| } | ||
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
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@MallanagoudaB we should also take the scenario of keycloak usage as well