--- /dev/null
+/* Copyright (c) 2019 AT&T Intellectual Property. #\r
+# #\r
+# Licensed under the Apache License, Version 2.0 (the "License"); #\r
+# you may not use this file except in compliance with the License. #\r
+# You may obtain a copy of the License at #\r
+# #\r
+# http://www.apache.org/licenses/LICENSE-2.0 #\r
+# #\r
+# Unless required by applicable law or agreed to in writing, software #\r
+# distributed under the License is distributed on an "AS IS" BASIS, #\r
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #\r
+# See the License for the specific language governing permissions and #\r
+# limitations under the License. #\r
+##############################################################################*/\r
+\r
+\r
+module.exports = function(userObject, groups, defaultPermissions = []){\r
+ return getPermissions(userObject, groups, defaultPermissions);\r
+}\r
+\r
+function getPermissions(userObject, groups, defaultPermissions = []){\r
+ if(!groups || !groups.length){\r
+ return [];\r
+ }\r
+\r
+ let results = [];\r
+\r
+ for(let i = 0; i < groups.length; i++){\r
+\r
+ //Get user's roles in group\r
+ let userInfo = groups[i].members.find((e) => {\r
+ return e.userId.toString() == userObject._id.toString();\r
+ });\r
+\r
+ //grab permissions\r
+ //add default that was passed in\r
+ let perms = JSON.parse(JSON.stringify(defaultPermissions));\r
+\r
+ if(userInfo){\r
+ groups[i].roles.forEach((elem, val) => {\r
+ if(userInfo.roles.includes(elem.roleName)){\r
+ elem.permissions.forEach(elem => {\r
+ perms.push(elem);\r
+ })\r
+ }\r
+ });\r
+ }\r
+\r
+ addGroupPermissions(results, groups[i], perms);\r
+\r
+ //Run recusivley for parent and child groups\r
+ if(groups[i].parentGroups){\r
+ groups[i].parentGroups.forEach((e, v) => {\r
+ addGroupPermissions(results, e, ['read'])\r
+ });\r
+ }\r
+ if(groups[i].childGroups){\r
+ groups[i].childGroups.forEach((e,v) => {\r
+ addGroupPermissions(results, e, perms);\r
+ });\r
+ }\r
+\r
+ }\r
+\r
+ return results;\r
+}\r
+\r
+function addGroupPermissions(results, group, permissions){\r
+\r
+ // Look for group in result to make sure it doesnt alreay exist\r
+ let groupIndex = null;\r
+ results.forEach((elem, val) => {\r
+ if(elem._id.toString() == group._id.toString()){\r
+ groupIndex = val;\r
+ return;\r
+ }\r
+ })\r
+\r
+ //If group doesn't exist add it to the array.\r
+ if(groupIndex == null){\r
+ groupIndex = results.push(group) - 1;\r
+ }\r
+\r
+ //add permissions to group \r
+ if(results[groupIndex].permissions){\r
+ permissions = permissions.concat(results[groupIndex].permissions);\r
+ }\r
+\r
+ permissions = new Set(permissions);\r
+\r
+ //set permissions\r
+ results[groupIndex].permissions = Array.from(permissions);\r
+}
\ No newline at end of file