Skip to content

Commit

Permalink
added getUserV2 api method
Browse files Browse the repository at this point in the history
  • Loading branch information
anyoussefinia committed Dec 11, 2024
1 parent c4b9677 commit e0132f3
Show file tree
Hide file tree
Showing 5 changed files with 143 additions and 92 deletions.
2 changes: 1 addition & 1 deletion services/admin/serverless.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ plugins:
custom:
stage: ${opt:stage, 'dev'} # Ensure the 'stage' is being passed correctly
iamPermissionsBoundaryPolicy: ${ssm:/configuration/${self:custom.stage}/iam/permissionsBoundaryPolicy, ssm:/configuration/default/iam/permissionsBoundaryPolicy, ""}
oneMacTableName: onemac-${self:custom.stage}-one
oneMacTableName: onemac-develop-one

provider:
name: aws
Expand Down
89 changes: 2 additions & 87 deletions services/app-api/getUser.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import handler from "./libs/handler-lib";
import dynamoDb from "./libs/dynamodb-lib";
import jwt_decode from "jwt-decode";

import { getUserRoleObj, RESPONSE_CODE } from "cmscommonlib";
import { getUserRoleObj } from "cmscommonlib";

/**
* returns the User Table entry who's id is this email
Expand Down Expand Up @@ -67,94 +66,10 @@ export const getUser = async (userEmail) => {
return returnUser;
};

const allowedRoles = [
"cmsroleapprover",
"systemadmin",
"statesystemadmin",
"helpdesk",
"defaultcmsuser",
"cmsreviewer"
];

function checkMatchingRoles(arr1, arr2) {
// Iterate through each element in array1
for (let i = 0; i<arr1.length; i++) {
// Iterate through each element in array2
for (let j = 0; j<arr2.length; j++) {
// Check if both role and territory match
if (arr1[i].role === "active" && arr2[j].role === "active" && arr1[i].territory === arr2[j].territory) {
console.log("match found")
return true;
}
}
}
return false; // Return false if no match is found
}

function checkAdminUser(arr) {
for (let i = 0; i < arr.length; i++) {
if (allowedRoles.includes(arr[i])) {
console.log("not an admin user");
return true;
}
}
console.log("not an admin user");
return false;
}




// Gets owns user data from User DynamoDB table
export const main = handler(async (event) => {
console.log("get user invoked")
let body;
try {
body = JSON.parse(event.body);
} catch (e) {
console.error("Failed to parse body", e);
return RESPONSE_CODE.USER_SUBMISSION_FAILED;
}
console.log("body: ", body)
const idToken = body.idToken;
console.log("Received idToken:", idToken);
if (!idToken) {
console.log("idToken header is missing");
return {
statusCode: 400,
body: JSON.stringify({ error: "idToken header is missing" }),
};
}

const decodedIdToken = jwt_decode(idToken);
const idTokenEmail = decodedIdToken.email;
console.log("id token email: ", idTokenEmail);
console.log("event query email: ",event.queryStringParameters.email )
const userItem = (await getUser(event.queryStringParameters.email)) ?? {};

if(idTokenEmail !== event.queryStringParameters.email) {
let userRoles = decodedIdToken.user_roles;
try {
userRoles = JSON.parse(userRoles);
} catch (error) {
console.error('Error parsing user_roles:', error);
userRoles = [];
}
const loggedInUserItem = await getUser(idTokenEmail)
console.log("loggedInUserItem: ", loggedInUserItem)
const loggedInUserRoleList = JSON.parse(loggedInUserItem.roleList);
const queryUserRoleList = JSON.parse(userItem.roleList);
const hasMatchingRoles = checkMatchingRoles(loggedInUserRoleList, queryUserRoleList);
const isAdminUser = checkAdminUser(userRoles);
if(!hasMatchingRoles && !isAdminUser ) {
console.log("permission denied");
return {
statusCode: 400,
body: JSON.stringify({ error: "permission denied" }),
};
}
}
userItem.validRoutes = getUserRoleObj(userItem.roleList).getAccesses();

return userItem;
});
});
126 changes: 126 additions & 0 deletions services/app-api/getUserV2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import handler from "./libs/handler-lib";
import dynamoDb from "./libs/dynamodb-lib";

Check warning on line 2 in services/app-api/getUserV2.js

View workflow job for this annotation

GitHub Actions / Lint

'dynamoDb' is defined but never used
import jwt_decode from "jwt-decode";
import {getUser} from "./getUser";

import { getUserRoleObj, RESPONSE_CODE } from "cmscommonlib";

Check warning on line 6 in services/app-api/getUserV2.js

View workflow job for this annotation

GitHub Actions / Lint

'RESPONSE_CODE' is defined but never used

/**
* returns the User Table entry who's id is this email
* @param {String} userEmail User to return
* @returns {Object} the User json object
*/


const allowedRoles = [
"cmsroleapprover",
"systemadmin",
"statesystemadmin",
"helpdesk",
"defaultcmsuser",
"cmsreviewer"
];

function checkMatchingRoles(arr1, arr2) {
// Iterate through each element in array1
for (let i = 0; i<arr1.length; i++) {
// Iterate through each element in array2
for (let j = 0; j<arr2.length; j++) {
// Check if both role and territory match
if (arr1[i].role === "active" && arr2[j].role === "active" && arr1[i].territory === arr2[j].territory) {
console.log("match found")
return true;
}
}
}
return false; // Return false if no match is found
}

function checkAdminUser(arr) {
for (let i = 0; i < arr.length; i++) {
if (allowedRoles.includes(arr[i])) {
console.log("not an admin user");
return true;
}
}
console.log("not an admin user");
return false;
}

// Gets owns user data from User DynamoDB table
export const main = handler(async (event) => {
console.log("get user invoked")
let body = JSON.parse(event.body);

Check failure on line 53 in services/app-api/getUserV2.js

View workflow job for this annotation

GitHub Actions / Lint

'body' is never reassigned. Use 'const' instead
console.log("body: ", body)
const idToken = body.idToken;
console.log("Received idToken:", idToken);
if (!idToken) {
console.log("idToken header is missing");
return {
statusCode: 400,
body: JSON.stringify({ error: "idToken event body missing" }),
};
}
const decodedIdToken = jwt_decode(idToken);
console.log("decoded id token: ", decodedIdToken);
const idTokenEmail = decodedIdToken.email;
let userRoles = decodedIdToken.user_roles;
try {
userRoles = JSON.parse(userRoles);
} catch (error) {
console.error('Error parsing user_roles:', error);
return {
statusCode: 400,
body: JSON.stringify({ error: "no user roles for user: ", idTokenEmail}),
};
}
console.log("id token email: ", idTokenEmail);
console.log("event query email: ",event.queryStringParameters.email )
if(checkAdminUser(userRoles) || idTokenEmail === event.queryStringParameters.email) {
const userItem = (await getUser(event.queryStringParameters.email)) ?? {};
userItem.validRoutes = getUserRoleObj(userItem.roleList).getAccesses();
return userItem;
} else {
const userItem = (await getUser(event.queryStringParameters.email)) ?? {};
const loggedInUserItem = await getUser(idTokenEmail);
const queryUserRoleList = JSON.parse(userItem.roleList)
const loggedInUserRoleList = JSON.parse(loggedInUserItem.roleList);
const hasMatchingRoles = checkMatchingRoles(loggedInUserRoleList, queryUserRoleList);
if(!hasMatchingRoles) {
console.log("permission denied");
return {
statusCode: 400,
body: JSON.stringify({ error: "permission denied" }),
}
} else {
userItem.validRoutes = getUserRoleObj(userItem.roleList).getAccesses();
return userItem;
}
}
// const userItem = (await getUser(event.queryStringParameters.email)) ?? {};
// if(idTokenEmail !== event.queryStringParameters.email) {
// let userRoles = decodedIdToken.user_roles;
// try {
// userRoles = JSON.parse(userRoles);
// } catch (error) {
// console.error('Error parsing user_roles:', error);
// userRoles = [];
// }
// const loggedInUserItem = await getUser(idTokenEmail)
// console.log("loggedInUserItem: ", loggedInUserItem)
// const loggedInUserRoleList = JSON.parse(loggedInUserItem.roleList);
// const queryUserRoleList = JSON.parse(userItem.roleList);
// const hasMatchingRoles = checkMatchingRoles(loggedInUserRoleList, queryUserRoleList);
// // const isAdminUser = checkAdminUser(userRoles);
// if(!hasMatchingRoles && !isAdminUser ) {
// console.log("permission denied");
// return {
// statusCode: 400,
// body: JSON.stringify({ error: "permission denied" }),
// };
// }
// }
// // userItem.validRoutes = getUserRoleObj(userItem.roleList).getAccesses();

// return userItem;
});
16 changes: 13 additions & 3 deletions services/app-api/serverless.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ plugins:
- serverless-dynamodb-local
- serverless-associate-waf
- serverless-offline
- serverless-iam-helper
- serverless-s3-bucket-helper
# - serverless-iam-helper
# - serverless-s3-bucket-helper
custom:
stage: ${opt:stage, self:provider.stage}
oneMacTableName: onemac-${self:custom.stage}-one
oneMacTableName: onemac-develop-one
iamPath: ${ssm:/configuration/${self:custom.stage}/iam/path, ssm:/configuration/default/iam/path, "/"}
iamPermissionsBoundaryPolicy: ${ssm:/configuration/${self:custom.stage}/iam/permissionsBoundaryPolicy, ssm:/configuration/default/iam/permissionsBoundaryPolicy, ""}
emailSource: ${ssm:/configuration/${self:custom.stage}/email/cms_spa_form_from_email, ssm:/configuration/default/email/cms_spa_form_from_email, file(resources/ssm-params.yml):Resources.CmsSpaFormFromEmail.Properties.Value}
Expand Down Expand Up @@ -567,6 +567,16 @@ functions:
events:
- http:
path: getUser
method: get
cors: true
authorizer: aws_iam

getUserV2:
handler: getUserV2.main
role: LambdaApiRole
events:
- http:
path: getUserV2
method: post
cors: true
authorizer: aws_iam
Expand Down
2 changes: 1 addition & 1 deletion services/ui-src/src/utils/UserDataApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ class UserDataApi {

try {
const idToken = await this.getIdToken();
return await API.post("oneMacAPI", `/getUser`, {
return await API.post("oneMacAPI", `/getUserV2`, {
queryStringParameters: { email: userEmail },
body: {idToken: idToken}
});
Expand Down

0 comments on commit e0132f3

Please sign in to comment.