summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.gitignore7
-rw-r--r--deliveries/.env36
-rw-r--r--deliveries/Apps_Users_OnBoarding_Script.sql11
-rwxr-xr-xdeliveries/build_portalapps_dockers.sh179
-rw-r--r--deliveries/keystoreONAP.keystorebin0 -> 2228 bytes
-rw-r--r--deliveries/server.xml1
-rw-r--r--deliveries/start-apache-tomcat.sh8
-rw-r--r--deliveries/truststoreONAPall.jksbin0 -> 117990 bytes
-rw-r--r--ecomp-portal-BE-common/pom.xml2
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/conf/MusicSessionRepositoryHandler.java4
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsController.java112
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RoleManageController.java225
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/SchedulerController.java226
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/UserRolesController.java16
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPUser.java10
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/interceptor/PortalResourceInterceptor.java46
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/HealthMonitor.java2
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/UserSessionListener.java3
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/AdminRolesService.java5
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/AdminRolesServiceImpl.java77
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPAppCommonServiceImpl.java215
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPAppService.java6
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesService.java7
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImpl.java7418
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java137
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/AppWithRolesForUser.java16
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EcompPortalUtils.java222
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/util/EPUserUtils.java38
-rw-r--r--ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml29
-rw-r--r--ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppsControllerTest.java103
-rw-r--r--ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/SchedulerControllerTest.java145
-rw-r--r--ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPAppCommonServiceImplTest.java52
-rw-r--r--ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImplTest.java24
-rw-r--r--ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImplTest.java8
-rw-r--r--ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/transport/AppWithRolesForUserTest.java5
-rw-r--r--ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/utils/EcompPortalUtilsTest.java19
-rw-r--r--ecomp-portal-BE-os/cadi.properties52
-rw-r--r--ecomp-portal-BE-os/pom.xml2
-rw-r--r--ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/sql.properties13
-rw-r--r--ecomp-portal-BE-os/src/main/webapp/WEB-INF/web.xml54
-rw-r--r--ecomp-portal-FE-common/client/app/services/applications/applications.service.js26
-rw-r--r--ecomp-portal-FE-common/client/app/services/users/users.service.js4
-rw-r--r--ecomp-portal-FE-common/client/app/views/role/role-controller.js2
-rw-r--r--ecomp-portal-FE-common/client/app/views/role/role-list-controller.js7
-rw-r--r--ecomp-portal-FE-common/client/app/views/role/rolefunctionpopupController.js4
-rw-r--r--ecomp-portal-FE-common/client/app/views/users/new-user-dialogs/bulk-user.controller.js2
-rw-r--r--ecomp-portal-FE-common/client/app/views/users/new-user-dialogs/new-user.controller.js29
-rw-r--r--ecomp-portal-FE-common/client/app/views/users/new-user-dialogs/new-user.modal.html36
-rw-r--r--ecomp-portal-FE-common/client/bower_components_external/utils/purify.js1131
-rw-r--r--ecomp-portal-FE-os/client/configurations/dev.json6
-rw-r--r--ecomp-portal-FE-os/client/configurations/integ.json1
-rw-r--r--ecomp-portal-FE-os/client/index.html1
-rw-r--r--ecomp-portal-FE-os/client/src/views/applications/application-details-dialog/application-details.controller.js50
-rw-r--r--ecomp-portal-FE-os/client/src/views/applications/application-details-dialog/application-details.modal.html124
-rw-r--r--ecomp-portal-FE-os/client/src/views/applications/applications.controller.js22
-rw-r--r--ecomp-portal-FE-os/pom.xml2
-rw-r--r--ecomp-portal-widget-ms/common-widgets/pom.xml2
-rw-r--r--ecomp-portal-widget-ms/pom.xml2
-rw-r--r--ecomp-portal-widget-ms/widget-ms/pom.xml2
-rw-r--r--pom.xml4
60 files changed, 6550 insertions, 4442 deletions
diff --git a/.gitignore b/.gitignore
index a237ad37..5c18f3b0 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,9 +2,16 @@
*.iml
*/*.iml
/.project
+**/.project
+**/requirements.lock
/.settings
/dmaapbc
/sdk
/target/*/*.*
/target/*
/ecomp-portal-BE-common/jacoco.exec
+kubernetes/.classpath
+kubernetes/.settings
+kubernetes/.classpath/*
+kubernetes/.settings/*
+ecomp-portal-FE-att/client/bower* \ No newline at end of file
diff --git a/deliveries/.env b/deliveries/.env
index 898e9a40..babd90e8 100644
--- a/deliveries/.env
+++ b/deliveries/.env
@@ -2,13 +2,37 @@
# used by docker-compose AND by other shell scripts
# The name ".env" is required by docker-compose
+# Dockerfile names. To skip building one or more docker images,
+# change dockerfile name to "skip"
+PORTAL_DOCKERFILE=Dockerfile.portal
+SDK_DOCKERFILE=Dockerfile.sdk
+DB_DOCKERFILE=Dockerfile.mariadb
+WMS_DOCKERFILE=Dockerfile.wms
+# These are FE only and BE only docker images. Change to Dockerfile.fe and Dockerfile.be to enable.
+FE_DOCKERFILE=skip
+BE_DOCKERFILE=skip
+
+# Relative directories and filenames for builds
+SDK_APP_DIR=sdk/ecomp-sdk/epsdk-app-os
+SDK_WAR_DIR=sdk/ecomp-sdk/epsdk-app-os/target
+SDK_WAR_FILE=epsdk-app-os.war
+BE_WAR_DIR=ecomp-portal-BE-os/target
+BE_WAR_FILE=portal-be-os.war
+FE_DIR=ecomp-portal-FE-os/dist/public
+WIDGET_MS_JAR_DIR=ecomp-portal-widget-ms/widget-ms/target
+WIDGET_MS_JAR_FILE=widget-ms.jar
+
# Following are ALSO used in demo/boot/portal_vm_init.sh
EP_IMG_NAME=onap/portal-app
SDK_IMG_NAME=onap/portal-sdk
+FE_IMG_NAME=onap/portal-fe
+BE_IMG_NAME=onap/portal-be
DB_IMG_NAME=onap/portal-db
+WMS_IMG_NAME=onap/portal-wms
+
CDR_IMG_NAME=onap/music/cassandra_music
ZK_IMG_NAME=zookeeper
-WMS_IMG_NAME=onap/portal-wms
+
# Deployed with portal; built elsewhere
CLI_IMG_NAME=onap/cli
@@ -29,9 +53,9 @@ TOMCAT_KEY=keystoreONAP.keystore
TOMCAT_TRUST=truststoreONAPall.jks
CERT_PWD=changeit
-
# Required settings with default values.
# Export shell environment variables on ALL hosts.
+SERVER_XML_DIR=.
LOGS_DIR=./logs
PROPS_DIR=./properties_simpledemo
@@ -43,3 +67,11 @@ EXTRA_HOST_NAME=""
# For example:
#EXTRA_HOST_IP="-i 10.11.12.13"
#EXTRA_HOST_NAME="-n portal.api.simpledemo.onap.org"
+
+#Portal Context
+PORTALCONTEXT=ONAPPORTAL
+FECONTEXT=ONAPPORTAL
+SDKCONTEXT=ONAPPORTALSDK
+
+#Nexus repository for os_docker_base/push/release scripts
+NEXUS_REPO=nexus3.onap.org:10003
diff --git a/deliveries/Apps_Users_OnBoarding_Script.sql b/deliveries/Apps_Users_OnBoarding_Script.sql
index a7b084e1..8cb05624 100644
--- a/deliveries/Apps_Users_OnBoarding_Script.sql
+++ b/deliveries/Apps_Users_OnBoarding_Script.sql
@@ -8,10 +8,10 @@ SET FOREIGN_KEY_CHECKS=1;
INSERT INTO `fn_app` (`app_id`, `app_name`, `app_image_url`, `app_description`, `app_notes`, `app_url`, `app_alternate_url`, `app_rest_endpoint`, `ml_app_name`, `ml_app_admin_id`, `mots_id`, `app_password`, `open`, `enabled`, `thumbnail`, `app_username`, `ueb_key`, `ueb_secret`, `ueb_topic_name`, `app_type`,`auth_central`,`auth_namespace`) VALUES
(2, 'xDemo App', 'images/cache/portal-222865671_37476.png', NULL, NULL, 'http://portal.api.simpledemo.onap.org:8990/ONAPPORTALSDK/welcome.htm', NULL, 'http://portal.api.simpledemo.onap.org:8990/ONAPPORTALSDK/api/v2', '', '', NULL, '2VxipM8Z3SETg32m3Gp0FvKS6zZ2uCbCw46WDyK6T5E=', 'N', 'Y', NULL, 'Default', 'ueb_key', 'ueb_secret', 'ECOMP-PORTAL-OUTBOX', 1,'N',NULL),
(3, 'DMaaP Bus Ctrl', 'images/cache/portal944583064_80711.png', NULL, NULL, 'http://portal.api.simpledemo.onap.org:8989/ECOMPDBCAPP/dbc#/dmaap', NULL, 'http://portal.api.simpledemo.onap.org:8989/ECOMPDBCAPP/api/v2', '', '', NULL, 'okYTaDrhzibcbGVq5mjkVQ==', 'N', 'N', NULL, 'Default', 'ueb_key', 'ueb_secret', 'ECOMP-PORTAL-OUTBOX', 1,'N',NULL),
-(4, 'SDC', 'images/cache/portal956868231_53879.png', NULL, NULL, 'http://sdc.api.simpledemo.onap.org:8181/sdc1/portal', NULL, 'http://sdc.api.simpledemo.onap.org:8080/api/v3', '', '', NULL, 'j85yNhyIs7zKYbR1VlwEfNhS6b7Om4l0Gx5O8931sCI=', 'N', 'Y', NULL, 'sdc', 'ueb_key', 'ueb_secret', 'ECOMP-PORTAL-OUTBOX', 1,'N',NULL),
-(5, 'Policy', 'images/cache/portal1470452815_67021.png', NULL, NULL, 'http://policy.api.simpledemo.onap.org:8443/onap/policy', NULL, 'http://policy.api.simpledemo.onap.org:8443/onap/api/v2', '', '', NULL, '2VxipM8Z3SETg32m3Gp0FvKS6zZ2uCbCw46WDyK6T5E', 'N', 'Y', NULL, 'Default', 'ueb_key_5', 'ueb_secret', 'ECOMP-PORTAL-OUTBOX', 1,'N',NULL),
-(6, 'Virtual Infrastructure Deployment', 'images/cache/portal-345993588_92550.png', NULL, NULL, 'https://vid.api.simpledemo.onap.org:8443/vid/welcome.htm', NULL, 'http://vid.api.simpledemo.onap.org:8080/vid/api/v2', '', '', NULL, '2VxipM8Z3SETg32m3Gp0FvKS6zZ2uCbCw46WDyK6T5E', 'N', 'Y', NULL, 'Default', '2Re7Pvdkgw5aeAUD', 'S31PrbOzGgL4hg4owgtx47Da', 'ECOMP-PORTAL-OUTBOX-90', 1,'N',NULL),
-(7, 'A&AI UI', 'images/cache/portal-345993588_92550.png', NULL, NULL, 'http://aai.api.simpledemo.onap.org:9517/services/aai/webapp/index.html#/viewInspect', NULL, 'http://aai.api.simpledemo.onap.org:9517/api/v2', '', '', NULL, '4LK69amiIFtuzcl6Gsv97Tt7MLhzo03aoOx7dTvdjKQ=', 'N', 'Y', NULL, 'aaiui', 'ueb_key', 'ueb_secret', 'ECOMP-PORTAL-OUTBOX', 1,'N',NULL),
+(4, 'SDC', 'images/cache/portal956868231_53879.png', NULL, NULL, 'http://sdc.api.simpledemo.onap.org:8181/sdc1/portal', NULL, 'http://sdc.api.simpledemo.onap.org:8080/api/v2', '', '', NULL, 'j85yNhyIs7zKYbR1VlwEfNhS6b7Om4l0Gx5O8931sCI=', 'N', 'Y', NULL, 'Default', 'ueb_key', 'ueb_secret', 'ECOMP-PORTAL-OUTBOX', 1,'N',NULL),
+(5, 'Policy', 'images/cache/portal1470452815_67021.png', NULL, NULL, 'http://policy.api.simpledemo.onap.org:8443/onap/policy', NULL, 'http://policy.api.simpledemo.onap.org:8443/onap/api/v2', '', '', NULL, 'okYTaDrhzibcbGVq5mjkVQ==', 'N', 'Y', NULL, 'Default', 'ueb_key', 'ueb_secret', 'ECOMP-PORTAL-OUTBOX', 1,'N',NULL),
+(6, 'Virtual Infrastructure Deployment', 'images/cache/portal-345993588_92550.png', NULL, NULL, 'https://vid.api.simpledemo.onap.org:8443/vid/welcome.htm', NULL, 'https://vid.api.simpledemo.onap.org:8443/vid/api/v2', '', '', NULL, 'okYTaDrhzibcbGVq5mjkVQ==', 'N', 'Y', NULL, 'Default', '2Re7Pvdkgw5aeAUD', 'S31PrbOzGgL4hg4owgtx47Da', 'ECOMP-PORTAL-OUTBOX-90', 1,'N',NULL),
+(7, 'A&AI UI', 'images/cache/portal-345993588_92550.png', NULL, NULL, 'http://aai.api.simpledemo.onap.org:9517/services/aai/webapp/index.html#/viewInspect', NULL, 'http://aai.api.simpledemo.onap.org:9517/api/v2', '', '', NULL, 't1oqm6wCXrGUXUSL8mS7pQ==', 'N', 'Y', NULL, 'aaiui', 'ueb_key', 'ueb_secret', 'ECOMP-PORTAL-OUTBOX', 1,'N',NULL),
(8, 'CLI', 'images/cache/portal-345993588_92550.png', NULL, NULL, 'http://portal.api.simpledemo.onap.org:8080/', NULL, NULL, '', '', NULL, '', 'Y', 'Y', NULL, '', '', '', '', 1,'N',NULL),
(9, 'MSB', 'images/cache/portal-345993588_92550.png', NULL, NULL, 'http://msb.api.simpledemo.onap.org:80/iui/microservices/default.html', NULL, NULL, '', '', NULL, '', 'Y', 'Y', NULL, '', '', '', '', 2,'N',NULL),
(11, 'LF Acumos Marketplace', 'images/cache/portal_907838932_26954.png', NULL, NULL, 'https://marketplace.acumos.org/#/home', NULL, NULL, '', '', NULL, '', 'Y', 'Y', NULL, '', '', '', '', 2,'N',NULL);
@@ -21,11 +21,14 @@ INSERT INTO `fn_app` (`app_id`, `app_name`, `app_image_url`, `app_description`,
-- add Acumos thumbnail
UPDATE`fn_app`SET`thumbnail`=0x89504E470D0A1A0A0000000D494844520000010D0000004408060000009B326018000000017352474200AECE1CE90000000467414D410000B18F0BFC6105000000097048597300000EC400000EC401952B0E1B000051D749444154785EED7D07605555D6F54AEFBDF742120221F41E7A930E0A2A36D451B18E7DFC6C63EF3ACE388EBD6043054511A448EFBD844012D27BEFBD27FF5EFBBD28202558E67766B2E0E625EFB673CB5E67ED7DF639C7A443803F289A9BDB50515E8F152BE2B07A6D124C4C4DE0E06085871F9A0467672B242695A0ADDD048BBF3884E69676B8B8D962D8207F0C1FE887A8084F24A69600268087AB9D2CB63031913FBAD18D6EFC2AFC7F278DC2FC2AC41F2F4479692D2CADCD919F5B0D5F7F27F48EF6C5FAB509D8B93B0BA56575B077B4468B10C3002185E8DEDE58BE2A1E0E7696080E71C5965DE9B07790F56D406D630B5AE592AEBA241A3985B5D8B43713013E8E1814ED8388101739A329C2839CD13FD2D350806E74A31B1784FF6FA471707726962CDE8F92E21A2585BBFE321EC34787E2F18757A3674F2F9C482E415646194C2DCC6061618EC6D636F8783BE1A69B87E3B3250771F0483EEEBF672C3E5A72081DA6663033073ACC4CE507D0C2A5AD1D174F8BC489CC0A1C8C2B8095ADA5F085095ADADB10E2EB84293121F074B3C194E1C1C61275A31BDDE80AFEADA4D12A522023A504AFBFB811B107F2E02C465B5BDB8C19F3FBE1BE4726EB36CDB2CDE5733ED46D69E8266626686BEB40B390C05F1F9D821DBB32F0FDDA440C1D120467576BECDA93250AC502EDE27A989ACBB67239266666FA49A2B9624E1F1C4E2844625AB91CCF02AD72ACB0205704F9D8E3D3D589880872C193B78E44DF080F3D7F37BAD18D7343AAE6DF1759A92538B8331DFF7A76039EB9F73B3C74F357488E2F4280B8080162BC93A6F746700F77E3D6404E6639AAAB1B6069694E6140E180CAAA465CBB70308A44956CDB960A7B714B7CBCEC91935D095321156E632A3FDB4918F20779D054AECC4294C7722198FE3D3D1112E084E6A656D9B203365666B2AD097C3DEC515AD18067DFDF8BC389C5D87630475C20F171BAD18D6E9C15664F088CBFFF66686D6EC3C615C7F1CE4B9B4425B4E3BD57B6E2C89E0CE48991F78CF6C6806181E83F34182EEE7628CCADC4FEDD194200E5B016C5B0757332FAF4F545427C21CCC5E8EBEA5B3054B69F32B5279E7AEA079889AB626F6F891E611E481443178610C63085528709DD13611A3287280F33F9BEADBD0369D9559838320825E50DA8AC6D52F78401D29CC26A580939719BB6D60EFCE3B343D8775C084D088984D28D6E74E3E7F85D94464D5503CA4BAA111EE585CDDFC5C3D1C91A73AE1E827B9F9A0EDF405714E455E3DB2507B0EEDB38A48B12A14BB272D951EC1215B172591CEA6B9A71DB9DA34519B4C04388E5A2A99178F491756AE02489800017716B1A505BD748DB97A55D7F76B4B70B6F1874877E25DB9A8B5C696C6EC5EAADE9983C32183616E2CAC8AACADA46833221C7D0B591ED6C6DCC91955F855B9EDA886D877265AB6E74A31BA7E3778D6964A79562C95BBBE0EBE78CF8B83C242714C1CCDC1466A220CCADCDD121864AA36D1745D0DED20107676BF419E087E5CB6231624C18EEB8670C7C7D9CF0FE7B7BF1CD3747E1EC6A8792D25ADC7DCF587CF6C5117525CCCDCD657F03515068B4CBF13AC465818919AF4E8F4D57A54A148BAD9D05AE9E1D8DE89EEE2815D5F1F83BBB61696E8656F15AE64EEC818D7BB3515A590F37671B0CE8E981876E18063B1B0BC3C574A31BDD50FCA64AA3AEA6D1F89B01813DDC917EA2108BFFB90D19C9C5B013B7C2D6C61216E286988A410B65A82230E96817B7C314B9D915080C71839D9D158E1ECA868DAD052CACCC30615218EAEB5A9095550E7F21A0CCCC72545634A83A686B6B13C26947B3587E93B8450DCDED528E6654563608C1D4A1A0A81AC5A58D701542F2F3B4C7F4B1A1880EF7C0787179E68C0FD37D064779E2C68BFBE09EAB07E0A2114118D4CB03E5D54D4817D7A91BDDE8C6A9F8554AA3BDAD1DA50535D8BF351947F765236A4000D62F3F8A1B1F9D2CC6EF8A7D5B528420CC912A0AE3D8A11C5494D5A343C8C2C2C2523EDBD101337527DACD4415886BD1D8D486E8817EDAA272FC7821264C8D40AFDEBED8B02E11B32FE98BB008778486BAE39147D6E0E0915CB8B8DA6A1CC4D28A8B1C43140609C743C8C1DBD3019E1E767075B245634B2BF28A6B909255851BE747CB3A43BCE2D977F748194CB070566F04FA38EA77052535C8C8AB4589B85835428225423E61FECE18290AC84DDCAC6E74E37F1DBF9834F2324A11BB3303C7850C18836453C7F6EFE331686C0F210A4B34D43521490C7FD2DC3E6896DA9F6E4987FC4B4F2A467A6AA9A80E2B3172C377A6421A8C2FB4B677C02FD0052E1EF6D8B92D0DD3E74623E158018E1D2FC082AB07E3EE7BC7EAB95B455D3CF6F8063838580A5998CB37A259E4FC248DBAFA6694890A2912822A1157A356DC121373463D4C34DFE396AB07C2C949CE2D0AE799F7F68942E9C0B0BEDE78EECE51F866630A36EDCF4190B783B6CA3434B6C2CFCB1EF72F1CACE7ED4637BAF10B5B4FF2C43D483A9287A37BB3509A5F8D82AC0AA4C717C1D1CD0EA3A6F4C2F6B509E839C01F1525B5C84B2F478F282FA42516A140DC8F7E4383316058104E08193436B4AA719A98507188D10B5A5BDBE01BE08ADCCC32F41F1C80C2C26A3489F13258397D666FDD265548870961B1B105881342C9C8AC405A7A2952A55C39B955281375C0E42E4BB6B4385AC1C6CA12E6421C57CE89C2CE43F958B53515FE5E0EC82DAA858D28A176718F2AC5A5F97455BC0665738A6A905520D75552872BA74522C4CF49CF7B5814934F77AB4A37FEC771C1A4919F5186D59F1DC4CAC507909F5E863A632B04839AA3A7F5C291BD99A8AD6A847FB02B6A6B9A502D069C23063D767A14F2B24BB16753AAB8297598B770089CDCAC5155DE246E40931CD9A038D844EBE5EB888A8A460487B9232DA5144D0D2D98785124BEFD260E8D8D2D78E7ED3DEABE4C9A180E5F712B68E8241636B1527958989B69BC8344441DD5D8D48A9821816810923A9258289E503B22A47CCDADEDC828A8C2A59323B0799F2826E12D531353398E09A2C40D9A363A04EF7E7D0CF58D4DC82DAE45627A051EFEE72E38DA5B2032C4CD7043FECD484F4F47515109CA2BCA51525A8ABABA7A383B1B48AD1BDD381D35627F6952515695D6A1BCA0064599557016F5CCC688AE808E48E29E6C146654222FA904D6F69617E69E241ECEC1130B3F1735D00E7B91F8CC99606442BC0538B9DAA0F7D020ECDD9484E6A6360C1917266AA11C456294B4DC167103E6888B117F24178971F9AA307A0D0C44786F4F0D5A1E3D948B8AF23A315C33F41DE48FCAAA06F48EF6C1DAD509983AB30FF2F32AB17D7B3A1A8520DE7C6B3EEEB9F73B58D95868BE464888AB2809536489CA484A2B81B98519CC2CCDE59CEDA86F6E4564B827860DF4C7D2D5F13057774688A4A51DF75E3F148FBDB113B72D18802FD69D1032E980BBB30D068B32AAAD6FC57E51316CAE8D94E3975736C2CED60243FAF860E59654FCF5E6E188E9EFA7C7FA77A1AABA1AB7DF719794A54AAED70C2D52B6007F3FBCFBF6BF8C5B74A31BA762C9939BF1F1131BE1225E80982A8ACA2BB1F8E87D081197BC2B6066F69F7ABC8AAAE27A5434D5E2910F1674BDF5A4A2B806FFBCFF3B357647210833062F850C5833D78981470F0B46767231DA9A8546C4F8E84EB0C6679E9585F61F31C3FA15C7101EE58D9E7D7D5401A4C4E763CDD77128CAADC678511293448D58DB98225D8E13262A836C16DDD7175555F538723817F6F656183E2C5093BF7AF7F28295A5190A0A2AB1735726E2C4DD610BC96C513BE13DDC515FD3027F512C7D7A0A610CF0C39ACD295A16930EBA432668686A41AAB84B93C4553A72A244FE6EC55021A9182197A32965D829E446E5C126597B21272F775BA464552253C86BEAA810DCF7CA367CBE26D17073FE4D484FCF40756DAD90A2B9DE7F0B21C6CAEA2AE4648B4AEA4637CE80836B93606B632DCA9BFDB3E49D811992F6753D07898A9DEADD5AD4B5B5ECCD0AB9CBA4B14C6AE48AA23A58DB592963197E98A059DC054F7F6771356C912A866B2E86CC55861805C39C063010DA2A35E3C6157188EAEF8F3031FA56A9ED2D8484524F1461D5D223C813A39C3AA72FAEB969246EBD672C6EBC7524C27B7A61DBA614588B8190A7AEB86AB09245CCA8505538E6723318AFA8AA6EC4814379DA2BD65A2EF2963F0DC67BAFCEC11BCFCF10C337415E41B5121E6326CCEFA04B532F6ECF8BF78DC590686F5C3A25920D381AEF2816F7C9C64A6E2F133CE41A790D24391B6B33511F4568927D678DED81E73ED8872FD69CD0EBFB7720AFA040DD370B7323695858A05648242D33D3B84537BA712AF2922A602D0A99F6672A2E899D8D0DF67C7B21EFAC89DA0DED598EA079555D228DF48442EC58190F4B1BB28C9108E4477B7B1B3AE40833AF1A88AFDED90D3B472B35311EB8435E6EF57CD4E2E4D4F2BB419D9862F597471035C01F3DA37C34186A618C43241ECFC3CA2F631112E6AAB5285B3B7CFD1C515FDB2C46DE8AFEB24F546F2F9E1DE3C6F5808BB315DAC405A172A08B66656586868666ACDB90AC01CE4E8C1911848B64FB61E24E0CECE38D3E111E1810E98587160DD7F5D7CEEA8D84F412EC1275C1E0A9A5B02955462778CD3C07FFD94859576E4D839790E4D491C178FE83FD2828A9356EF9FB8171A3B4D474BDA72C0BC1CF367906054226DDE8C6E9488BCD47637DB3D8DD4F66CEE127B2C49E7F0DBA441A6B3E3E8086DA4635640365C84B2BFF5B5B3A10D9CF1FC70FE648ED4F16922FD53581760E63A733F15594343AC42DE0BE06C633C1C695C7111CEE8E883EBE68A8695426B31515D3D6DA8A7D3B33F4BC3C46B528883113C25059D1881917472361733ABE7C6E2B02029C1112EA8626512F3421AA045E0CF7099675B572B30A8A6BD1246EC8079FC7E2D0D13CA46694A1B8B4566E648B2A0DF639518821E617D769CCC2688FA7C2F825B7A65C73B4B5C4C7AB12B4235C94B851EF7F7B4CD7FF9E686C6840764E8E14C55066067309733373A4A6A58B826267BC5F86D2B2721C8F4F405CDC71A4A4A619BF3D376A6AEB909B9B2F845588A2A2626D81EA0A2A2A2A919F5F8002594A4B4B8DDF1A617C1C67425171313233B3905F58A0EE6F5751585884CCAC6C3DE7AF459DA8BAE494541C8D3BA69F3535BFAEB2A895FD4F2425EBBD4FCFC8D0BCA7DF12E9B185686E6E517BEB7C5F482035E50D28C9ADD2BF7F09BA14089DEEFD28BC825C55DEB00F28E3027CC2ACFD46CDE885C3DB33505FDF045331AE0E133331E416F4ECE7AB599EF187F345013065DCF0A2B38584BBD34D6017F68BE6F5D5CE6C69C92586B13398013AAD0F32334A515C5CA3B189B03E5E181113825917F7C513B33E959B51808F33EE475C6201EEB97B259C5D6DF5980CC07AFB3A62D28470AC589D48FEC29851C158B12E093636426062F0ADCC3597B25709A98C1E1288BBAE1BA22FE15FFEBE0D85A5F5E2FF9D9A36CE817FFAF52439B5235148874A8460F9A9662E9D128135DB33B1E485E9FAFDEF85FCC2423CF0E0C342A2B55A067D09E47EF3A5F0F1F6C2DF5F7E11F60E17D61CBC69F3567CBBE23B949697CBF3AB5715C3B47C6727470C1F3E14575F7105ECECEC8C5B9F8AE5DFACC0DBEF7F0027074778C9F99F7FFA49383A3A18D79E1D7FFBFB6BD8BE63973C810EF4EAD51B2F3EFBA4710DB0E09AEBE4FEDBA0AAAA0A77DE7E0B468F1A854F967C8E6DDB7748F91A9418593E2B2B4B840405E3F65B6F86A7E7CF8734A8936B79F783C5883B7A4C5CD07AC37EF2AED9D8DA62C4D0A1B8FCF2F9728D5D6F714A494DC5871F7E82ACDC6C51B28D72CF9BA542B494725821223C0CB7DF7233BCBCBA3EA8D3B1F8447CF8F147282E2CD6B2F259D2D5B4B1B6469F3E5172BC9BE020F7F5D7E2ADBB5663CD5BFBE1E06A2395B229DAE59DA50D971556E3E9D50B31647A4FE39667477B5B076E897A0DD5ECEC595287073E9D7F6EA5D12086F5C683AB60EF6CA3014FC801CC483152DBD5D736A1F7E0409497D6A1A2A446D7EB2A13210659DF202E859DAD35CF4A7A817C6DD88635921C877EB954F5F8F6A3FD881A148879D70CC6F5778CC6B44BFA234708E3C4B17CD456376B3F921D9B92111AE18E385119C7B6666A6C65F9ABBBD02FDA0F11F27D436D0B5AEA5BD1A7B73762860663F98A63A8AD6B4249592DECACE56188E2618F59AA040B59AC84CCE86A4489D2197BF5122CF93E01D7CE8ED2DEAD4CE8D20B3905244983DAE8045B2FAAEB5AB0646D12E64D0A47A5361BFF7E28CC93DAB9A0486B0A7B0707C4C4C4FC68E4256565C8931AB8ABC8CECDC51D77DD8FBF3CF81032B2B2D0D8D8A8C7B1104320A83C967CB10CD366CEC5DE7DFBF4BBD3D1D6D62A06D480C6A646DDBFD3653A1F9A5B9AE51E1BF669967D4F46BEB859C5A228D84AF4C3C64D983BEF727CF0E1C7A248CA757B1A575353132A2BABB067FF7E4C9F7B095E7BFD0D253C82EB972DFF0613264FC3AA55DFCB7594EAF6BA9F187A9990E3E7CB9661C6EC8BF1DDCAD57AFFCE052A89E75F7A190BAFBF09878FC66AF336AFD35A8C9B9FBCFE3DFBF663EEA597E39DF73F947B72EE6115CA45653DFEE4B3B8F6FA3F21E944326AEAEAF438DA7F4ACA585D5383F51B3763F28C3958FAF572E35EBF0C3C5EC2CE6CD8DA5BA2BAAC01F31F18A53DB9F96ED3ED4FDCFDCB83E767250DD6BE2FDFFE35B689013AB8D8A9AA2028723AE4E4D622D1C3A27D70786BAA30B8A53E00C37BC3D609533437081B4B4DCCDD648D128D6E4349201BF2A218CD6564F6E0F6345C77C718CC5D301033E645235E5C89BABA66D4892196145523BABF1FA2A27CF1BDB02607E4616067C757F168916D66CC8C4265553D2688E17A78D861D5DA04348BE133586A21ECCA1A8DA9EB94CFDA7222A4C1E65F17276B0D74BA3AD9606F5C81E68AF41577C35D58992ECF8FC4219FBC2EC3B59D0AC63758CE6FB6A42221B5144542A0BF1732A59663262CEF2163436347C7E82789902F7757E5774949291EFEEB13E2D2A4A0478F1EF2C25AA8D151FE17899AA9A8A8D04BF7F4F080938B339E7AF605AC5DFB8361E79340C94BD7882F3C09B9ABE0B6BA8F2CA7E70A58496DCB1A9C2A80AE9289AC670DCE6746A2A91405C2C06F9BBC3BF6A280820202F0FDDA75F8EB134FE9FEFF7AE36DBCFFFE62F8F9F9C2D5D555BFA3A1733FD6E87C193DDCDDE12ECBEB6FBD850F167FACDB9C0D4F3EFBBCAA315F5F1FD8DBDB0B41CAFB5852823CA36BC5BF1D85C0BDBDBCF09518F94B7FFB8771CF9F83E57FE6F917B06BCF6EBDEF241E920CCB5626A4CF67C867EB2AF7DCC7CB1B1F8852FAE8E34F8D7B5F38CAF36B64A916F56E8EA6D666F41E1988B0413E1AE360AA42AA7800BF14674DEE7A6CC12738BE37138ECEB654F5F222D1E06485B046A348E27173FB885B928646A9E5D90C43FFA3C354B7926DE4B593173A24D203A9C70B35B6C17C0E53715D94DDE580A6F2A9BD5CE54F4BB988590B06E879EDEDAD11D4C31DC347F5C0D09860F4EAE38BEB6F1B898AAC2ABC7AC7D770F370D2F3652617C23BD415D32FEF2F72DD547CC20AEC3B98A301513359CF7270F42E929BB5FC5D5ED5242445E33741ADB852F32E8AC4BA9DE92AD7AA453579BAD9A1ACAA01BD42DD902B6E115B584C29E984A4BC3D6C95344BCAEB7FF6A233685A2EFB6517D6A0A2BA51D3CE1DD8C2F41BE3BD0F3E16D96EE84047497CF5950BB062E52A91CAAD526337C1C5D909C3447A9F0F575F7B83D468D56A04AC29298BC78C1E2D527F11E6CE9E8D5E3D7B222B3B5B6B452B3160BA905BB76F47FF7E7DD5383A91909888FD070EC34A5E7E1AF094C993D46D381F76EFD9A33106C2C3C35DF7EB045D114AFECEDA97464E92701302183A7408264F1C0FFFA000A914C4784BCB94F429E9A950D6AD5F8FB8E3C7F5BA181C6E1077C64B5C9751A34662C2D831F0F1F4929ABD560D94C4642DE7D9272AC1598C3452AEF974BC4A376AD72EB9AFCEF22EB4A84B327CC810DC74D30D5878CD9518346080BA3D1999D9FA4ED8885B159F9080D696560C1CD0DF78949FF0F853CFE2C8915838CBF1E8BEB7C812E8EF8FF9975C82C99326C0C7C70BE5E5157ADFA90458C69DBB760B89B8213232C27894AEE3C09A64ECFE3651EE9189DC232B2C78740C9A4419EFFB3E09B68E56EA098CB9AC0F6CD89DE31C904780EFDFDC87A686568D05C65CD2FBCC4A63E5077B706C4F269CC490280CC8017439A8325A9ADBE017ECA646999F5AA63108AD8D4D459AB5B33A66CD2E062B37CFD2D2C2A8500CF91C1DF2309581A4A6903DE49FB8398DCDB0B631C7210EC493558E171F5E8D6D1B92B07CC9413CF9C04A1CDE9F096F4F47ACF8FB6E5881B2507615B8B838E0D34737CB31A05DEF776C4F959ACA4C5F24BD5259CC854CB2B32B85D9DD34206A2A17C3264B27B9515413F57213581C5B7161761CCA41CF6057EC3E928FE9A3427558C056B600C975B3A4C6D39E11DCFF84943D59CE157BA2CCF8ED6F8BD8B8A35A3B35CB0B1C121CA4DF458485C97535C2567CF5838762F5BB73E1F32FBE446945191CC4B0688CBD7AF5C45BFF7A0D0FDC77B71A419FA8DE98356B063E7AFF5D5C77F55572EC668D05D0C0FEFEFABF37818CB5708B18EAEC9933F0F187EFE1A1BFDC87CB2F9D8F3B6FB9056FFFEB9F78F2AF8FC8B336536366DC8535353F196B6240F1E6458BB058AEE39E3BFF8CCB64BFBBEFFE3316BFF70E16CA7551E5B2F2721445B3F893CF548D9C8CC38763B165C74E5511748B78DCA79F7C0C4F3CF608468F1C81F0D0508C17227AF2B147657958899704C2ED7FD8B0116969E9C62319B07BEF3EECD8B1038E8E8E5A5E1AF1C30FDE8FB7DFF827165C360F53A74CC6AD52DE8F3E7817375EBF50EF3B89D343D4DE3FFEF5CBEE7B6A6C3E5A44713339CB23C409F62EB6088CF65295C177B9AEBC1129877E99DAF8196964261661E5FB7BE12CB52B0FAE8BFC508540F690DFC3C52D39BE3F1B162C00BF5362309000C17DF467A7C1A9111BBEE3EFBC2134C60631DAB09E5E183ABA075E796C2D567C7608DB37266947B7F0080F5C76CD50F1170DAC3DED96A1B2B761842DC2D2DA0C1585B558FBEE014D275F70C540D48BABC0726A49F8299BB68A9131C78365D77F42062E4EB6A8956D35182BFC45366EA86F456E41B52671ED921B3E634CA8BA68243D5E3F8F792E38D858E2B0DCBBDDE25A192FF637035D8616216183F2694770908134FAF58BD60021C939F53CAD1ED5D5D5D82852DB450C852F2E7B1A3FFDC4E3521B9F3980B7E0F24B317BC674A9F92AB416E5F11910FC77A15E8C75EA9429B8E3B65BF4BA4FC730511E7F11B2A30A2009D070F91E9697970B09DE8B8B67CF306E792AAEBAE2725CB56081920CF761D075CBB6EDC6B506ACDFB4194D727E3E75BA7F2C0349F54C60396EF8D3427DB7E82E928C491227E34371833A039B54770FFDDF5F306AE448FDFB74CC9F7709AEBEEA0A7D5EBC6E12E3CA95DF1BD7761D25A2CCD95193EEBC5F989BAA73EF1017B87839C87B2DA421AA9895FE2FC1CF9EC6966F8EA2B2B816E63434351543FC81710AB624048A31338DBC30B35C5B4714F45BC44E9434E4C119BE6BD702F36FD11946E313C333AE673F10BF00174D375FF7F551B4092BDAD859C0D6CE5A7BC86E589388267123464F88C0076FED127FCC1753FE3408B5150DBA3FCF66EF6C8DE57FDB857629CF94291122A17D3536A18511B074626BAA2AACD9314DCAC37F9C07A5B8ACE1470223B998C90D8E4D2A45FF087764E456A348D6C70CF4937D0DC1ADCECB3A1B781C2A8E8DFBB2B16C7D8AF1DBDF06FB0F1E9617DC102C6300B957642FFD3EB26784948BD7C001884C909A7E76E2484E4ED5788685100C9B3D6FBDF90695F6E7C22D37DF68787EB2588A81B1D5E3DF01D6DA2E4E8E5824AEC0B9307CD8505C24C4525D5D23F700A815831C346800468B4B722E5C76E9251ADBE0794888DB4E228D969666ECD9BB57BF671075A8B82431230CF93C67C3B42917A17764A46E4F1C893DAACF8AA8A8AC404E7E9E1CCF5ACB396EDC580C1057EF5CB85208DBD3C35355A5B5EC177BEC9851B1770D65F9D5C84928D1CA84EF65483F43CAB8930801375F074365292E555EF26F401AC53995D8BD3A01760E56CA467C59D4E4E95AC817EDE287450D0F46DCAE74B918CA1C59ABEE0037960388FCEFBCB48E16832B63705FD8A2C24D643B395693280CBF00678C98148E355F1E5212222B32BB9379086672A1ACE5A7CCEA836C21A74FDED98D155FC7E2EA47C7C3C9D356FD4682637514A557206177365C84087A84BAA15F5F1F7978CCDD907F72523605B734B7C3D5C95A1E244B67026747A9618469D9BB5624882CE2CA48F92AAA1B50585287617D3DB1F560166CAD2C101DE681EA9A6634C98D56123C07D8FFC55AAE978AE3B704E3077413784F2CAD2DD5FF2502038244C2BA6A6D6B67678B6DDBCF6ED46C31696D6F55A5E2E4ECA43182AE60CCA81891EF75EA021D3B9E60FCF6F705DD8551725EBEF4E743CC88611A07E1B36D1675306FEE6CE39A7363FEFCB9DA4A43E24C3C9164FC562A98C616E4E6E4684C81EFFFC8E1C38C6BCE8DBE7DFB295170BFC2C242D4D51B82E2F1F189F23E1B62798C7D4C1A3F5EBF3F1FA65E344594739D3E77E69A5455767D402806414BB2AB74747E33331304F531BC2F768ED608161785E66A25B6937A300F7555A7B6607505A79046E2A16CD456366820B1D33C9406C48829FDFB8F0D436E7209AAA5B6A7B8A0612AC882FC9555B63C3CB23E13A7DAA586B79207CF422A64A7C6BA4678FA3961A4B8141BBE3D267FB3ED9DC3FD71F42ED9460ED1D0206E4BA427060E0BC28A2F63E5C19A61C907FBE01AEC8411737AA159540A37ACAF6AC2A069E1881CE10F6F0F7B79099A7464AF1E216E22C1DB34D8CA547533291753CB99A52AF7105E6EF6C6B472C335D018D98E6D29E5D87D341F23FBFA098199E2EB8DC9880872C64DF3FB625A4C885E42A9DC9FCA9A46540AE9742E0C80F2B35C1E4095289DEADA66DDF6B7006B85DCDC3C7D199BA416EC21FE742748141E6E547E2D2AB5D3334EF5A54F4683B1F5802D0FCE22959953D315D8D9DBA3B2AA5ADDA092B262E3B7BF2F5AE47AFC7C7C8C7F9D1B0E0EF64268361A0321B1D9D9762D57C5D7DB5B2B1FD6C4AD6DAD3FAA847A1A3B5F0C45071C1CBB962FC15C1955D282063916DD498284AB55AFDC7B4B2B4B25ECAE80DB65E7E46AAB566E5EBEC656BA8A8C6345FADEF09C76A2C67D420D2D490CFA07F47297EFDBD55D29CCA84055E9A9F19CAEE014D2387120076D2DA22CA486A6FD134A00626C6CC2ECD93F0087B7A569932779829B74928AFE4572503211C2905A9929DE6C52D56C41594D77C3D5C31113664561FD37C7502B8646C6E30BCC6DD984C7E1726A2A1BB170D1485494D661FBA6243839D92991FC202ECBC2C727C88368D45A9F893637BD320DFB572763EDBBFB70D32DC3F1AD10D184096172BA0E1D538342889DD148029CBA31C0D711F945D55A460E2DCA1B687CD61ADBE0A03D8744294C1D1D8A8AAA0684FA3962402F4FCC1A1B8AC76E1E81CBA7F4C49FE646E3964BFBE3D605FD71BB2C775C3E00B75D219FF2FB7D0B0763D2B04075E57E0B544A0D939797A7A4C09A67D8905307040A09095183A1FF5B595125EE598D71CD69A00AD440B53C1F7DEAC68B3E0F2E131FFBEF2FBF80179E7B1AF7DF738FF1DBDF0F343C4A71ED72D005E8BB6ABC14EE4BF2EF0AD8818BEF00F7E1313A732CA8167E245429C78F15E379C0B3D21E0883ED18FEB21322D3E3C8319988D7D0D0B566F9A183066AC21E03B0F7DF7B175C5C9C8D6BCE8F9443B91AFBA38DDA89C20E8AFA296EE51DEAA2F796EF404B633B724E9418D7741DA7DCE18C8442F179E526C9C90C2F9618BFBC68EC68367EDE006CFEFAB0484133BDA97A33C528F9A9FE96BC94FCCAB4DD38C0AFB0378D941314313FA2A9A1195E3ECE9830A70F562E39887AA9ADA942E404421386F8079B4E1BEADA30626C0F0C15A37DFD858D1ADF3097F7C7CAD214CB3EDE0F73776B4CBB7E08F28A4B31E78E91F00A71C66B37ADC0A78F6D85B3BD15AEBD76089E7F710B6EBF6504EC6C2CF502B3322BE1EFEF84DADA464C1EDD039B77640A9919A2C86C5161F9DAE5A5E1C3B61355B3FB709E267A3197C3C5591EBA11EEAED6281195B5431ECA27E2C6BDF6E921FC4B94D0BBDFC4E1BDAFE2F0CED771787F791C5EFA683F46DFB014B9856731E00B405A7ABA1099210988FD6F4EF7D7478E1CAEE3A3B28992E9DC59523B9D11BC58230CAF73D7C0969A91E2D30F1D3CE8BCBEF8FF179C7631AC2CBA02D6C23F816F89F1067512C685A2B3963D0D43878B1BA8F6C23398E09D7717D3AA0C2BCF011F1F6FCC9C310D93274C5017D1DADAC6B8E6FC48DE97AFEA9D15B157D0A9CAA6FFC41EB07660ACC3545CB166C46D3CBB3A3D1B4E218D9A8A7AED1B42A864978BA50FECEEE388C6FA46D494378A9F644898D25B4072E00DE08DD687209FFC2F44D32E4CD72612894A8299A5B6F6D61833B31776AC494093B83A1C8D9C7E0B9B67D97B8E8F9B29E6249149337BA3A2BC16FB76A58B3CB4963398889C3247B1B814EBBF4BC0C26726C0C5CA5EB3DC7EF8E020EA2AC43510F5B0E38B384C9FDD0B9EEE36F8528C79EA9408D8D858A0B4B4162E0EC2B801CE48CF2A975A9BE794F24A99D98AC3739BC9C568DC465D1513EC8DCDC7A8FE7E282EAFC396FDD9D8139B87A7DEDEAB4DC4D1E1EE9837310C574FEF8D20512E0DE2073343D456AE89FD57DC8468189C5DB7FBD7F73E4DCFCC56A5C71AD0CFD7578E7F6A5A3765B185B156A6FB525C7AE13547377E3F589A5B62A8A843B642D9DBDB69B0FAF1279E4195B87CBF07182FCC4B2D85A58DB9DA59FF2961C6350670D6421B3B4B7D9F989290117FE1F1B71F49E318FB7F70701C3118150DF283E4502F7E7ACF8101C817FF877E9A2637899D71ADEE2E864716FD31206A0447CBAA979ABD4E5C0D5B29E4DCEB0663EDD2232893DA9783F7980AB1F03CCA32240F35D876788B22183BB5173EFCC70E752998F04D22A1BAB1950B7EFBD5ED70F575C23F0FDD0A3731D88F1FD9A8AD288E2EB678EF8175F076B3C784F111484E29C521510C93C7856917782670B9CA368C653053B4336783B114CDD9901BDCC84C5271919CED2DE1EFE380C76F1B816F37A6E858A22BB7A7A14CAEE5586A197E103258B72B03C9B9E5983F290C8F2E1A0E2F371B1D098C933BD12D627F1B8ED3F16B9199912EB7A75D9B49434282B46FC6C9707674D20C48CA6B76F6CB48EBEE26FF47C3BD77DEAEA3ABD58A7BC96CD783878F60D16D7760F3D66DC62D7E3B146555C87B5AAD71C9BAB6460C9BF9F3C4B5DE314168A869520249FB0599A14A1A1C1323764B0AE6DC3412EE62904DA20C18372053B9FB39C1C5D316F1FB45D25B5BA87A205DD0255135220BA55EBB100AFD282693B00DD83FC405F3E478D73F380193E6F5C35AA9F91B6A9A6121F29F2D2406CA919F240C2106D6FD9C64E9D607262235B110077667E81406EA73CA5A06312D2C99CCD3847FBDBA4DFC342FBC7AFD724346AAA5B996ADAAB4012BFEB60B77DF351A33847838C87071492DA6882AE817ED8D0517472345589803F070D8401DB9DCCD4E7BAA4E1BDF03B3274660EA9810CC1A178E948C723C2BCAA257A8AB8E48EEED6AAF2D23D65206A6423736B7214988F4F9F70FE05D714BA68E0CC575B3A330634C0FF879D8C9353139ECDC7D11CE07F695C8C894FB6E69A81998CCD5D93FA413EE1E1CA13D5454468B3E07E652B0A9AE1B7F1C383939E31FAFBC02773737CDBF60C09681D7871E7D1CB7FDF96E6CDBB14353D27F0B6CFF2A1EB626563ACBA1B7872B3C835C8C6B7EC2F8ABFBA1BAA9415B368BCA2A50947D6153752869EC5A158F0DAA02AAD137A607265F31087D4784E0CFAFCCC5D34BAFC5C7CF6D109FCA122DA21E480C6D523B33D049D7857641DF89C1155B276BB8793B20A8A71716DE3701BD06FA638818A0871051694115CCA590745D0C1E5E2759C83F2111CAF946510403460663A39487C4C5E09E12926CC920255B66786E9F00839F66EF62A8753BFD53DE845DDF26A043882BBCA79BEC63AA599DE3C78661DAE49E18C39EB25323316E6408A68CEB81417DBC1115E1A199A4F12925D8272EC88A0DC958FCCD511D7478EBC11C8C18E0077B212492048FC773D17DE1EF9CF1CD5B08A249CAF4CED7B1F876530AF28A6A30B09717668E09C56C39C7D603BFBC6310D38AF30B0AF53E30101A1814605C732AD8078339272497DCDC5C7476E0EAC61F0741F2EC9E79F2714446466A65400406F823332B0B2FBCF8373CFED433DA09EFD722767D0A6C1CACD44DE931E0CC2D503DFAF9E8085E740C6C618D436B928D6BBA06531AFE916DA93A18F0814D4958FEC6766C5F1187BFBC7D29864B6DEDE6ED88EB1E9A8251337B63D2E5FD31FD9AC1987DE308CCBB3D0657DC331E57DD370E57DF3B1E178B441F3F371AFD4785C027D8552CD9780601ED9DC4221667F446D86221EA41B7216130FFC00C834787A24654CA66210D8EDD41462365304F84CA8663657096B57997F65797E28697A68A41B175C770322B31EE9423F9D8B5E204E6CCED8394B412AC597B420C4EB95131697C1876EFCBC61E21841DFBB2B079473A62138A5020245121F780238939DA5BA9A2609EC6BA1D9998333E140919A5F017426C6939E9C204BC060B7353383958A34E48EF6872093E5D2DC425DFD7335FBFE997AB8DA2E222D4371A92D94808BE3EBEFAFBE90813A541523113D78A636ED49E9616DD8D3F06820203F0F2F3CFE09A2BAF906754ABFD4CA83A98C075FC783C9E78F2193CF4C863F2DC7FB95B5B985E29B6648E5679EF7A0CF8A9AFD0C9B077B5416098A776ECB411577CEFAA9FF254BA025376712F2F96DA5164F54221873B5EB9180327448832F829505353598F0431B24352936E5A1E8B95EFEFC1672F6FC63B7FFD1E6F3FB2066F3DFA3D168B1AF9F2F5ED58FDD1416C5F790C6F3EB606B13BD3B1EA9383CA1F0347F740A3B827DAB4C51A5B3844DD0E59C7C2F71D168CC131A178FDC91FB4C544C7E0602C83D4411746544643631BFEFC9771422C0DB8FDFA2FD061698A2B1E9B809A52C3602854004C8679FFFEB5B0B630C7FD778FC30DD70FC3B7DFC5232BBB02B97955F87C692C6EB87A304244B63166C24E6DA41473EDB569D0403C17E3289C802921AD0C6EAEB64A003D7C1DB5A5E24C20A9B1BF8A839D05AE9D19A54DC45BF7E768B098B3D177AAA10BC1A1234785C4D853B8035EEE1E67CD5D0809098615631DBC4FB26D6CEC61E39A6EFCD1C044B43F5DB7102BBF5A863933A76B9C83791DAC141C1C1CE499C7E28AABAFC5D7DF7E6BDCA3EB483A90AB7147BE031636E6E815136C5CF373840AA1508D305C50927981EE495D7513FC42DC44DA5B60F3D24358F2D206EC5C791C2F2D5AAA999F6545D5F8FCD5ADA82AAB456579BD32189B73EC1DADE1222A84B9EC74495CDC1DE0EC6E0B7B7151189D8D1A1288951FEDC7472F6D4296487F374F7B8C12D78064A18381C8C9D54151FB6CC7F4F9FD34B6B26D5D229C5D6CB58F080D98A0BDB536B76B7F940917F5C292C5FB112B3768B3A888E9370D82AB9FA3BA4E848DA395104411F6AF4A44CC9860EC946BF8E18713D8BD374B5B4E366F4FC357E27E70D4F1A913C230415C155F2F3BED7BD2748A2A10BA1235C4806E49590382FD9C747473954AA741B311C5250A0B70C68C3161A811D2B3B1B1E421B06A5B1A0E8992F97194B00BC0891349DA94DA2244E5EEE90157D79FFBA704BF0FF0F3D52659F6F2DCBE73AF714D37FEA8B0B5B7C39D77DC867FBCF222A64C9CA041F9BADA3A1DC888CB3BEF7D88F73E586CDCBA6BC8385A8016A9586963D6527985449F7DC4F188C1FEE0F0066C8D600C3233AEEB43009A16A4976205E711D99381FADA16F1D54596DB5AA238BF123F2C398C6FDEDC8509F3FAE928E3E652B36B2F52A9D1D5748C06CF58039B2E69DCFC9B391001611EC816A9CE74F3CA925A241DCD07C79E9872991C4B24BEE6BF930C5ADAE1EC668721A274BE786B37EC8470D80CABAC42188D8DA9E131E37BE8EF5F7E7C4088C5068BDFDE0D07773B4CB8B29F0E61C6425125B8393AE3B3C736C3D9DE1AC1E22A31C18C6AA1A8B01691E11E62D4CD58BF350D1BB7A6A2A2A20183FBF9E1C605FDD4FD282EA9D332F1CEB37C74AD9233CB94102A850C1CE56118D2D10DA0A1322374CAF0204C1C1E28F7A70385A50D3ADEE8D1A462047A39A24E941453E32F046C2D292D2B53D260AB88CF394686622DC5E658068959932526FE7B4749EFC62F07BBE5DF7BD79FF1F4937F4540803F8AC535A1EBCEE106BE5CF6B528E365C62DCF8FA28C4AD99759C4EDDAC7C4DEEDECB91D3D870B6998339E086DA02848AF30AE393F4CD9D468C3E1C96D3962B1D81D9BFCE540AC299D4439FC20EEC584CB07E877ED5299B79BB2B615A391B39930218A2422166E224C492A61EE7EAF210128C828456D65A3924CA618CF00914ABBD726E2D8DE6C5C7CE3102513C628CA8BAB71FF0BB3502424B5ED87C41FBBEE1A5A650C6569935ADCDDDD1E975E33043B36A760E2E4484C9DD95B9487A7D4C6459871CB5078048A1210E324380072F689526CF9E408EEBB6F9C1CC29038969C528C90401725167BB95E2A8BA30985F86A550296AF49C298C101B87FD17084FA3B69AC84528F6549CAAC90BF4D10E0E928FB59A94B43E2600CC3C1D61A2FDC3D0AE181AE3896528A2FD625238E5339C87AE66E84C8B102BDEDD575BA10A4A6A7A3B4A44449835DA5274E9E685C73660CECD74F5B6BF8C23112CFDE9EDDF8CF41BFE868BCFBD6BF70E7ED37EBF3A68BE1E4E488D7DF780B79F9EC397D6ED063483B92AFF6D82236D86F620FED437636F845B88B7DDBFF58D1A7C7757DE43753361FAA0F6F30553A0CCA09CCA560B771CE7770684312A245C63333D4A49D244183E6468CC08A93A1BBCABE721CFAF011D17E38B63F5B0393661626282BA84695D4E8034787E284D4C0DBBE4BC084397DE1E5EB8C88BE7E88ECE78B4DDFC5EBCC6B8651A0581E39243FE43CEC421F332E14B93995080876C34D778FC6D5370CC3ED42081C04C725D809E3456D340A01B25C6C6DE0540AABDF3B085771A3E6CC8E467E7E2D32B32A101AE26A28BB94952D3296B29D9D101573393E581A8BAF57272042B699383C5849C4C3C55AC8A34DF335C60FF597ED9AB58F4B656D232EBB28024FDF3142DC8F627C2E84C8D6160645D9A396E5E6F1796CED9A7F81E0C8E324015E8B95B5158EC6C6E29B15DFE1ABE5CB65F9E6A7E5EBE558F9FDF7481192E1B817DC9E2FC1B1F87F4FE7B26EFCB6983F6F9E0E88545D53AB158093A323967DF58D71EDD951535E8FC2CC4A7539F8EEB3C3DA9A77F6E3DB5777FD6C59F18F5DD8F6459C0805434F769A5BE6B1628D2D7605A694EE6CC6645E01FF913668549A192AFF5970BA199E81CEFA1D5B334C384AB06CA3C627309A3838E3975F30272A6A5077A1B3431893BBB67D770C03C6F68083938D065E37AF8843589437FEFCF4547DC9BFFBE4006CAD2DF5B86421CDCC947F3CBA9DB8043BB7A4E1A15B97E1D13BBFC1BD8B96E1BE9B97E1DE5B64B9F56B2CFBEC10AE7C688C468D7F6C491125C131128F6E4AC14D8B862127AF123672FCA3C70A10DDDB5BBBBCB3FC1A8A95FF9672B399365E55DB84EFB7A462F7E15C1416D761D4403FDC7EE5202109A6B39BE1D93B47A177A80B5EBD7F9CB82C4EF8DBC787B0666786AE77B4B352A2E03D6339388A57567E159284AC2E14F1274E68649D65A454FDECF3A5F8F0A34FF0F1A79FCBB2E4A7E5B3CFF1EEFB8BB166ED3A1DA487E7668A704ECED99B7A0DF7B56BE0F81094CC1C8794A35E75827EF34FE8FAF10C3D8BFFC030BED3178E9FEEC12F3D4227664C9B8A9E11E1A238E49D13A599939BA7CFE15C28CDAD464D5983D4E326B0167B8BDD9C8EC5FFB71E4B9EDAF2B3E5B327B6E08BA7B7EA40C10C3990688A33CBD54BE80A4CFB8882182FEE0787FFD2F13B694672E3A812B42399D47625F2E2536A734224E10CD9C4D8642ABFAB3010A3E7AD62EFD369570FD6002883A1541DDC486B4BA971F74B6D3D6C4298BEB4D515F5483E96877031E0379F5A8FFABA4698B269942FBD1C8BC76F2741C93FC6591A1B9BD022EE446B738B2A1E76086BD79EACED58F9751C6A65DBB9778D447589B12545F6E7B066FFBC7535AC85EC82839CB5DFCC8103391832C01FEDA21E38D298216E21D7A9D740F210E5214CCD818953B2CA7532A42FD724E05F0F4D4044B00BA2C33DB0F8E969784FCEF9D06BBB74B268E67970391924A5882017A4E5566A30F54271F8D0E11FC7BBD0B89180B930675B884E12E7D81709423AECFDFA230C8F563FB4AF5017F1F77FBE81F1932FC28CD997E0C65B6F377E2BC791676AA8643ACBD7B56372F01B92DAAF35ACDF0B1C6782D765FCEBA4DFCF0DDE03DE0B425EA71FC151DBA3070DC5C0A131183966220A8BBA1670E4A8E91CB087A4C18E881C55FD5C483B9CA7E3E0680F7516597EB0572B33B8CFB4A87D69A7B60E4D6FC84FAD40614AD75C5A534EA9D8536A53CE92C64E657A93E4803459551642240C0C166494212CDA57FB91E8CD64A1C4C6F57D919BC40998A3470623E14096DE3C164A098672C558B0A29C72588A02E0A44AECBA3E536A709E6FD7BA24383A1A460AE3B979D19DF79D464DF2E09804ACC5C98A3AC51C2F5C162A25E698ACFDEE38163C3C46FBA8D09D20AC44A1E4A596E1E0EA645C76697FA9B90DA33B151454C1DBC7116D1D0CC692FC486C72CD525E9687F79C44C5291939C749B9B8565FAEFD6956AAACBC2A1C4F2B83A7AB8DBA477AADA7A15594928F9B1D0A4AEBE1E57EE66900CE869CBC3C343637C9359A89E1B78203F0B05584CAC3D6EE0C8B7CCFF51CA087DB731C8ABCBC7C1DF4A5133A7E279FAB2C8CD2333FA72B607ABF7F4000BCBD3C11141068FC167075711165D962385E5D9D066EBB8292B252AD80FEA8B0B3B5F98904E5B1F25E7505159595FADE12EC02CF1EDB849B9B1B02FDFC34B9CBCBDB531B00BA829A9A6A2566123C9FA799E9B95DDC13FB7235B99121022EECDD7AB6854998EC326FEB64C81CA51D5557D6212FFDB47968CE02531BF1F9930FE5E222510864A956AD15A50611A3616D4EB140D97F58247BDFD1A172435928F9928662346E1A1E47F10A087347F2913C0D721AEF1FDF3A250F1EA7A1AE1935158D70F77680A7AF232E12435EFAF61EA989D9E1CB50FBE8D080DC4DFE19F238A42C727C133929D790C4F82DB7D36EEDB295958D39562C3B8A7629C3FCFB63502F464E704B5B7B2B2C7D7EBBFC06EDE9CA099D2BAB9B0C83F2880B61A89D0DE7309CCB703D1A9F91752437C635DC9D6DB1F5500E12D2CBB0725B1AAE9ADE4B5D1236959D0E9EAB455E0E1F4F079455D623A6DF9993B2CE866371C775AC07AA3C1AE5FDF7DE83575E7C0E2F3DFF0C5E7AEE0C8B7CFFEACB2FE0964537FDE80B9F3E423913C3CC85184944CC484C4AE95A16E0AE3D7BB5BF0BC7D3080BFB692C8FE0C040796686347F9E335194CDF9C0E9127440602A23C363FEC3C1C2C20A9E9E46E3960779E4E851E39A73233E21514D82DDDF3DDCDD748E152258C8822A966A9BC316242777EDBEEF3F74489526DF2F573717D8D99FBBE239B42E453B85D6D73463C49C9E7879C78D787ADDC2332ECF70F9E15A3CB7E13AB8F9396843839585250EAFEBDA708E1AD31832B9273E7F79132EBD638CD6B0CDF5AD70F5B64779A1B01D6B76B9199C6D7DFBB7719830BF9F14CC3031924E0B205293FD51DCBD9D34A6515956A76A8037DCC0D7F276F0006280249F435B5310DADB1757DC3E4AB7FDE1AB233ACC5F3BEFB8323C771283E501480CF2A9E792DF4822BACE786E1D514CD650113088FAE9E27DB8445C144F7145D83243D83A5822F9601E762D3D8E5973FBA81B51284AC3CBD35E4981C76302998EF921903368994972754DCD70177299240AAAB4BC16474F94E0AB0DC9F8E0DBE33AD6C68D17B3AB78C78F430276822D2775A2DA4843574EEB85C1515D9BA1BB13CCEA646DC7C5D1C911D17DFAC0C7DB1B01FEFE675D38D667AFC8087848CD462264EDCF7E2B9D888C0C878BA883565122EC3CF5F2DFFE6E5C73762CF972A98E5942894C793C6ECC58E31AC0D3CB4B0726E67C2224EF4F3EFB5CC7DB3C17962FFF56D50F0DE88F0A2AB211C386E9FD638C68CBB66D421C71C6B567C6E123B13878E8883677F399F5EDD3D730AF8F20383858542087D86B5512F8F093CFF4FB7361EBB6EDC8C9310CBCD4228A93CDB20C729F0B59E5C53A921DFB8BF51D1FAA9D39D94272B6C537CC4D47F38F1CEEAF95B99DA88E1DCBE28D473B37F4E9C5CCEE83E1D322717C6F16864CE9A9BD533DFC9CB52F8A8EAA25352F3B6BA51E2BD06EF29438ECD36130E676D9BE19BD0607203BA9C4207B69D86230AA066886ACB5655B1A24E550716E39C6CF89C6AA4F0FEAC44794AB6C62E5365AC3CB86DC9FBF185E2F2A1EFE4697C8401C9AF7A0E7D1CDE026AEC277CBE26029AA20E6E2DEDAFCCA6311ECCCB6EADDFDF076B1434C4C30F272AB35B8AA2D353C8CA194FCC5B08FFCA72209957B103328003FECC84474B82736EFCD86AB8395CE4EBF715F0E9232CB7199DC2F3B5B73ED1E4FF0A5610AFAD5337A6340A40716CE8ED2EFBB8A26794972F3F38CAE491B0244DA1A5A94CE0F66147A7B7B8942E460BB1D48CFCC32AEA13BE18A0913C669976C1A0695C3934F3F7B4A70B313725BB16ACD1A2CFB6A39DCDD5C512B12BD57644FF489328C4D4AB09BF784F163B4C2E0580F59D93978F99557751CD2D34137E69F6FBEA5031B53FEFFD13169FC58706A0682D7F7AF37DE4262D29953AD3945E3ABAFBDAEC4C967EF24CF60A2DC979371D51597EA044F2495E2A2623CF5CCF3670D6C1E3A74186FBCF39EDE5F1E8FCF72F6AC99C6B567C6A1F529B083B855627BECDF151875E6F4F133217C903F9A1B9B6126EF6C517DD73243F56D64C0E4FAC7A78B4F648EF0817E08EDE32335B4853695AA918A66679E013B9115E757232852E41B7D211AB9487C4E6F10DAC70B2744BE33804AA353A3979F6A8CD4FC84F049B3B822A3C5A0483A3BD7246AEE3B41C3D7FD68C4F283718AD2C21A21AE2A9415F1B31A25F2C9EF4AE5B3443F6BF5772EE525F528CAAFC23B6FEEC482BF8ED3B66A553902BA4BC9FBF270684D126EBB7524B2732B35DF42E76311E3523747889165E6B93938F1005107FD7B7963F9FA2444043AA3A8B45ED58521B80B384AB90F1C2FC49E6385B8E2A2489D74A95ECE49CE614D7AF3BCBEF076BFB069120906BDF272F3953438C176787898F62BE90A6CC42003FCFDF4771DA13C2DED94CE6BD72DBC5A0CDC4A0983C3E9D3F5B8FFA147F0F5B72B703C3E5E0D63EFFE0378FCA9A7F0C69BEFE8C3A06A69696952D7E774CC9E3153550E87C82361ED97DAF69E071EC4A79F7FAE83F3EE93637DB362251E78F8117CBB6215382CDF1F59657482031B0DECDF4FE3191C60989D0639C114A73B88157785F795E9DE1F7CF4311E7BF269255E2A810A515A13268CD75EC72763EEEC590811C541F562B8EF7BF0E0238F61FD864DEA4272F024BA776FBFF73E9E78F6397068463E738EC171F97C4E2179EE2107F7AF4A82BDB85574339C3DEC11D4BBEB534486F6F796774D14BBBCB876B042E2DEF377B0FC31BAC2D60E670F3B1CDF9D89DB5E9C85C29C4A94FE7D3B9C7D1CC0742B1AA08D9D15920E6461D0A4089C607F0A21010ED9B7F0FF26E1CBBF6F3510006B7F1ABE18A1928DC18AF41C4CD5EED9DF1F638434BE7E772F8AC54D7072B553A3A5356A70553E2BCBEA3145DC20E66F68CC408EA5E6AF0C64000FCB2011D54E87B8C83C678B7824765206067AC65CDE073BBE4A80935C135D2C96FFAB9777E3852DD763EEDC286CD8948298618158B5EE84A6BE931B9BDBDAB483D99431A1DA0D7FE58624396E07FACB43D8B23F476A7C294A1B0D89E733D1795FD3B22B7440E22BA6F7C2AA2DA93A695249533D9E7E771F5EB96FAC3C90930ADD05B069939319A9DF2FF017A5D155D0B50C0D09C6D6ED3BF4A54B4FCB503F9A815282B4F8CA0BCFE3C147FFAA64C2F12FCB4ACBF0DEFB1FEAF36259194761F77BC31C22ADA8961AF1BA85D760C8A0817A8C93C111B6FFF6D2F39877D9023508D68E35D5D558F2F952AD25F97C34A02C04E6E6EAA25DF6CDF89D5C1B9FD71F1574B9FFFAC843B8EA9AEB9408D8E4CD7773E9B2AFF0E5D265EAAE711C535E1B49850BA7B21C36648890EBCF4750E7F11E79E87E3CF0D05F75A63706ADE982BEFCEA6B4AA40C74733065B531516D266295548423860DC5CD37FDC97894B32337A9545C130B6DB0F00CB1D5F86257D163901FAC39F1BA54FED61652117E9F845EC3CFDC9BBA13A71CFD4F8F4F4573430B5EFFCB4A78FA3A63E845BDE013E40A8EE8C52EF17CA94A447D70EED4E09E5EDA8E1C18E6AE69E295A575F2B21903A07293A828749C42F993B33355091188A7838B6FE4E8CE2658FAC64E4D19570B145E2068884C170FEAE18E9BEE1B8F11E3C231606810068E08C26059060DE7673006CA2753CA675ED2176326C93603033072540F8C1DD703FDFAF9A9AB70FB5B73B4F5847116C256DC8A235B5370786D326EBE79848E72CE4994B4CBBD180C035896F2325C3CAD9794B705AB44F2F1A58F08729732B523471416F98B1DE9D83242854270C0E2CAAA267CFC5D3CC60D0D44BF084F6DBD49CFA9405ED1858FCE94949CA44A802F2967E3EA9CE3A4AB080A0C82995C07F7E7485E1C9CF664F4E9D31BAFFFE35584F508155553A1D7C8DACFD1D15E89C2C9C949FD71CE2BCA87F7D003F76BAFCCB381FD24967EFE29060E1820954283BE139DC7E1EC641CF897E0E0C4ECC2EFE9E1AE711212C8E92D092C73E7A227EF0AE4F1F1BD3979E90A0CDB1A9A1ECF94ADCB9C9CCF3EF950E31B3A676D63A31A3B1515631D8E0E8E62F076DAE18CD73C67F64CEDC17A36848785E395979E5352E7B8AF8493B383D894A912B5AD9D0D1CE4BE3536362801733472CE4B73BE314F8B332B509455295E82A9A64D746552E793C1F003E743610308BB7F7465CCD09F4DCB386862381C9C6DF08F3BBF86BDB32D82C5151934210279A925282FAE5557860F2A6C801FE2F76469A6684176B9CE2A4D52A1BB4217A2471F6FF41B1D8AFD9B9231784218068D0B130272C1BC453158F6F62E1CDB9BA9FDFE69B0ACE6492F7C88ECE13AF38A81E83B2C08775CF2117E5811872DDF27602397EF8ECB673C36AC3A8ECD3F9C407A4A99B82CB53828C77AEDF94D58BFE604D6CAFA43077230636EB4DED0E403F986D4747939A84AD20E17E0F2FB462129B51469E9A5F2825B2135BD0C2EE25E5C3CB3378E9D28466C62B1BC14E27F0A11DE75C3507CB93A0135F52DB85AD65F33BBB7908B09F61D37B44C903BF89ED637B6E28410D188BEDEE2AAD8E9C03DECE41626AECD8560DD0F1B919C9CA24AC1D9C901D75C75E505497A1AC096AD3BB409942ACD4B8C748048ED934163E6140116E616C8CDCB4392B825242AB68270F46B1B2B6B796927E1969B6ED0C980CE07D6B49CFC2730D05F95526A4AAA48EE2254881F5F2D06E2EDEDA3D348DEBAE8464D3ACBCACE52A3F4F5F5C6A489138C4701FEF1FA9BE2F636699F9B98E1237406F5F38123757FFEE5328DA5D0B59B3C792202859CCE07B66230598E6AAA54D4D69FAE5DA83187934125312A66A4AABD4271218E27C4A3DA38323B9545AD10EB6859BF48D4C0FC8BE71AF73A3BD84C1D337284E6D1C4279CD0B14FD8558144C1C1798AA51C51BD7A61D10D7FC282CBE7FF184C3D17328F1763C34747947C2A6A6B70E3F353E1117061EF5C567C1112F7E4AA1B4F5BE488FFD6C6B001F9FBF469194D84D5CF48E9B1DBD2F0F7BB966BFF11F6629D76ED10ED0D7760638ACE123FE1D2FED8B3F604068D0FC3AEB589689603D2FE59F871F3A371D363D35057D3888DCB8E222DBE0015A5F578E0F58BB5167FE8AA4F74EA0253710118EE603095E383729E14B61DBFB5F2267CF9F61E2C7D6F9761A01D3930678FD7CA87AA5DC8852D142DB2C8AF888CF2C5485119BB7666205B082025A5046F2CBE12FE2EB67868CA6234D5B66A6A2D512DE57870C9A570EAE781D7FFB90BFF77FF387CF5ED71F8FAD863F5C65454D43408C958EAA85FE346896F6AD681551BD3A4E6B4C6BA0F2F37C478044FBCB90719F99CEF94B107B906294B93288C1AD96FECA00084073AC1CED60A13879EFF053E19372CBA0545620094F7C3870FC5630F3D685CD375DC7EE73D2A7FD93B3632A227FEF1B7178D6BCE8C86FA46A4A4A7A901F9FAF8C0DB537C62C365FE22B0E6A4EA68E96885A39D83925EA702E8541252BF6B4571322132E8C7BFB9DEE0C29CBF10DC873912DC962D602ECE2E6A94E7836116F932254E96F7E4796ACF06AA8DDCFC7C550A6CAD62D099FBFF52F058B1B171AA5438E136E780E5B4141782556FECC5470F6F04C7E26516F6E2CCFBE0EED7B569173A11B72D1D778D7B073E5E2E6A6B8F7D770522871B72729896704BD46B2A0A9841FAC0A7F34F754F4E46FFB13DF0F69EBBB1E899E9DA99EDBD27D662DB37C7102E0A234A5440A330CF9839D1422AF57072B5C1D46B8660D153D3F0ECD26B953008469EE3F766A9B1370A8130857C87D4DA745538A319BF37280C060B20C4528B990B06A97FC5161AAA1AB22D0740E55817ECD7C10995D89AC098839DF87136E2129D905AFF9DD7B68BEF698911A26EA832D67E2F4410E18E81E2BE90213BC1710656BF770091216EF8DBCBD31112EC8207EE198D5DFBB2919EC597C84C034A541A21FE8E58BF3503D1911E1831D00FA5E2A6119C28DADCC204413E8EF0F37480AF879D2C0E08F37746FF9E9EC82BAE4190AF1396AE4D425965D7679267F43B39254D836A7C910644471BD75C18428383757F4EE0CC0C440654CF051B5B6BF4955A9DC13F2671FD1AC22068F0F6E296B8383AFFCCF855F19144847C4F5750868184E4F9CA33EF0A6110DC8706C719D3BC3C3CBB441804EF8DAF2820EED715C220E89670C0A3C103076A00F8D71006E1EFEB8B99D3A762DEC5737494F90B250C2223AE5087C264BF91F021BEDA747AA17074B38713BB2C48E5D7D2D4725E17E59CBA973D5D99F4F5D4B2EBF1D28A1B31EBC661FAA07B0F0DC645570DC2FCDB6370F1AD3178EEABEB71ED4313B50B7D70AF9F1E80A38B9DF84966F861E9617171C2A550EDD8FC350796F9A9E661B32C0BC1D803DD8839A268BEFE600F7233C475B0B712792BFE3D7D8076D624861A9D39186CC9A9AD6D1235D3A4DFB393D8813D9938202495256EC7A25B47E9F1E7FFDF281D4A908C4930269172300F8736A4C0CEE6A71B3C636A4FCC99162935A3A5D4D0ED080970D159E22F9F1585406F27A46654E0FE97B6E0B3550978EBCB58AC1676DE7E384F3BA9ED389287DD4773B12B2E1FFB8F152036A90471C9A5F2029B8ADBD2B50C4022252D55DC0AC358911C6BB577EFDEFAFB85222666B8DC9B7A35BEA2C2229414772DD3AF1BFF59A8AF6E425E5299E645913442FB79E37CB3C09F092E5E7608EAE5A1EF1C6D2B33FEDC93629D93343AE1EC6E873E234230FBA691B8ED85999875C3308408397034E390DE3EB0170571368C9D172D4AC416972C1A81551F1F405672B148294B250B064059E3B4494DC85C8F85F71A92872A8A6A1110EA2A6ECA0D98BB70B02A0506CD982549C5C13960FB0E0EC00431F28BE6F4C1745966CDED8B05B2ED1C21AE71137B225B4887F00B77C7E8CB7A8B7433D4F89C82817D58963D6798BFB3BAB6116BD625E1D57FEE444E5E35268FEFA1C1D01993C2E0266A67BD90C3CE83D9AA2EB265FDD6FDD93A0607550E7BB072FE562E36425A9CA18D04E6CF56A89452F878DAC2435CA4AE62CBB6ADDAA24137C1D3D3FD825A4E4EC6B061C3447E372AC153B227249E3F5BB31BFF7928C9AD448E9006BB68507987F6BFB0CCE34EB0853128DA5BFB74B11B46C69142B1B9B3770BE81269FC1A440D0EC45D2FCFD63E221F3EB74147F832382572724E712656C65EB67E212E9879C560BCFDEC7A24C6E662F69583E1244AE5BABBC6E2D29B8663F61503B140486BFAFCFE8888F2D666BCA2FC6A51156548901A7EFB96547CF3E511BCFFE60E7C2A4AE5D9277EC0F2A547B41975C123E361290A824C4AD0F5D9BF2B055922ED92D2CA5052560B1B295F5656053E5A7204ABD69F406D5D0BD66E4943430365BE19D88A65239F1C48884153114BAA9C7E822172CF5884AFA73D0AC4D5AAAC6ED6D695AE62F79E7D7A5F2AABAA743E13ED2FF20B400DC77E22F4BD793C1EB71BFF7D284CAB40B6284956AA8CED0544BA19D75C3882A23C34219236727C5B262A0A8CC96752B973C8090ED5590F4E37D9F6F3D693DF1A4C180B0CF7C0AAC5FB10BB3313B6F686082DC9828954FCC75EA093850CFA8F0846FCFE1CF885BA232CCA47833BE525B5F8E2AD5DD8BF231DC70E6423510822536AF182BC4A9496D4E9D48DB5E2A270B83F364F31026C6B6FA9C65227EE4B4E76A52A92C2D47224EDCF85B5A8232D57BB39D28F16E0DA07C7A1548EC1418539DD818383B5BA27CC300D0A70425246A5AA9B0E792A2C76A3105C9F080FA4E6541A5C7FFAE77A44DEDF0E6D8E1D35C05FE74519D1D71723BBC8FE6D6DAD484E4D838F97B712C6C8E1C3D1BB57A471ED85A34194065B0342434234159D6DFEDDF8EF425662319A4A9B7552E7F0813E187559F42F724F08CEED5A5DDA28C4E3AE794E232FE90D07171B55AAD90986A131BCBC5D307466CFB3B79EFC96600EC7D3377C89A2DC0A5508AA6F8430A83728E739C8CE927DF760DBEA04BCF9F85A38893B34EB1A511AE2D65455D463D907FBB4B9D4D482E6C95610A9E1A5AA67C169E034544B210BED15C86F59E38B298F9ED0035B36A6E0ED8FAE40656A251E9EF6B1F67F610B0F150107567D76ED4258063961F386147CF1F55138898A68956344F5F602F3483834E0816385B0B7B7469B1CB55DC863E2C820EC3C92A70462222E49A75C63E7B6405F7B784AB9B71DCAC3E72F4C47B04FD726FCE56360993A633DA707092F143C5EE7A3E527038CDDF8EFC28F3D95B5F2950F63CBDE2F058F6750CBF2BEC87BDD093D0FDF4B798FD838F1EBDECC2E62C3B223C8482CD20B6312155501A3B42DCDED282FAAC1C5370CD3C140367E15ABBE59CCE49E58BFFC285EBC6F05F66E4EC5A8493DC5CFE70D22D1C885D1A0C41E1807F1F275C4CC79FDF5780C9872E6341A092F8C199BCC5578E78DDDE8393200E31744A34AD409E516C7FE681417E4A3BF6E42A89F13A2FA78C2C3C3FEC7D1C639F6C6A61D19888AF094DADF5EDBD3CDE4A88C379495D523C0DB41632C1A9B11F0A3555899FD55E2D3CA71FDECA82E1306C18745C32659FC5AC22078BCCE637513C67F27D480B90859FC5AC220782C1EE764C2203ACFC14FFD5B7FFE8EA8A96CC09EB509DA2C6BEB680D3B59989D692B6E000730F60974C1823B4661EBCAE3B0B435C7DC1B86EBD080A585B5F0F67541765A29EC1DADE0EA61A7FE166F0D0DB4AABC1E4E2EB678F0B999B86AD17078783A68162A099142C44248884DB7BC4066BBB1DFC8C5F7C6207CB02F027A792030CA1311F23BB35D930FE461C4902084063133AECD7002F9EF2EF26CC50F27306A70A02A9D36F9C76629E663B0795789DEB0A91295159B6B65F71E4242375CFCCB9A4BBBD18D3F3A7E77F784929B4921741FD4BA3A21C6CD7C0B0ECBC7AEB90B635E5337E5E9C557E2E8DE4C6C59755C13B8B80BE310532F1D80CFDFDA21BF5B81B3BF47447BE3FE6767C237C030ACFFD60D27F0FCC3E2DAE808CCA67076B3D51696B5ABE2316E5284C6396EBF734CA785EB3E945D9462ECF64F6CDF9581C79ED90807676B0C88F6436A56B9E6668C1E1E846A295BACA8252689798BF288E8E18EF5BB3285F82C741EDB7A59EFED618BD9637BE09249E1BF685CD06E74E33F01BF7B20943299C119B69E309ED0B950E6337FE3C4913C6C13C33EBA3B13B73C3E056F3FB55E8D7AFCAC28241CCE57E5C04E710D421481E19EA8AE6EC00DF78EC3ED8F4CD164B14E048B11B3D973F7D634915880978F231C9DAC909F5785BEFDFCF0DD8A63484F2FC3F163F9D8BD371B3BC4E05DDD6DB176433212840CBE5F93A0EE0C07182E29AD87AFAF834E1ACDF94C720B6B103324007945B53A7646496523268F0CC6A1F822ED6CC48C42073B2BDC77ED604C1F15AA64D88D6EFCB7E277278DB38135B6A3932DAA2B840C22DC5122C6DD50D7826431EAC2EC0A9D2680533CC6EEC9D06DD971EEF2452330EB8A811830FCCC3347F51672A03F76787F964EB844C5502C6E4E5884078EC515A020B74A08A204A9C9C538129BAF81CED8238699F2BF5F73029C152D44CE939E5E0E5F219DDAFA66B0031D83ADB50DAD1831D81FC7924A8448DA1133D01F87138AC0FE369CCB756A4C302E9D72619D85BAD18DFF44FC5B5A4FBA024E0F59905589F88359A8969A9CB3D68F9C14090F76CDB7B280A30BBB10772DA0979D518655DFC4A9CAA0C2E1644699A2323A5B6E74DC53B96C27671B8C1063DF2BCA63842887152BE371E55503F0E55771888EF64171591D0AC5B5E25CB0354228532786EBDF7B8FE663DCC8203470DE9494523409A9DCB37030E6895BD28D6EFCB7E30F431ABF0798F895975B89679F58077B7191D84D8AF1070D6C88BAE04CF0D3A6478AEA2880BBB82A2666667070B0425E418DBA50B50DCDC82FAED5EEC36DE22771E0A0CBE74663A5B834754D2DB8E692BE78E38B23B011B7E6A367A722F0025A4BBAD18DFF54FC573BDF41A16EDA52C33142080EA843BED01616015B44E2138A316448000E1ECE852B9359841882039D35B5DD446E0F9B54C9AB1C5E902D27FB8FE422667080E668B03F0B6769EB27EE55376174E37F05FFF511BBFE03FCD1B3B70FAAAA0C23940B0B0871086BC887B9A50952928AB5F9D4CFD719078438CCCCCDD0BB1747A366A28B6104746D02975F2C2C4C90262E948D85B99084233272AA7454F3FBAF3BFF9813DDE8C67F0BFE27C2FCCFFE6D16BC4509D45437EB781E1C48954DC166F28FB922DFAD3A8EB9B3A390935581FCC22A9DCB64D8C0001D7884DD63D4ADE9304C914802D9B8271DE3449D5454D5E38DC726C3CFFBC2C62FE84637FE93F15F1DD338194585D5D8BB2B13E9E9A548882FD2690C6AEB5B60EF60ADAEC6C409E1422C0E183A2C10FEBE4E282CAEC57D0FAF41AD900CBBECB3058789951DF283718E6103FDF1C89F4769E7B46E74E37F09FF33A4D1095E6E4D75132ACAEB70F46801F6EFCF425A6639FCFC9DF1E273D3D53D216A6A9B448124205BC885638032C9ABACAA11CD6D1D183AC00F57CF8B4678B0AB6EDB8D6EFCEF00F87F9ED91B4B4AFAE0D90000000049454E44AE426082 WHERE`app_id`='11';
+
-- aaf centralize
update fn_app set auth_central = 'Y' , auth_namespace = 'org.onap.portal' where app_id = 1;
+update fn_app set auth_central = 'Y' , auth_namespace = 'org.onap.sdc' where app_id = 4;
update fn_app set auth_central = 'Y' , auth_namespace = 'org.onap.policy' where app_id = 5;
update fn_app set auth_central = 'Y' , auth_namespace = 'org.onap.vid' where app_id = 6;
+update fn_app set auth_central = 'Y' , auth_namespace = 'org.onap.aai' where app_id = 7;
-- insert SDC users user id2-8
diff --git a/deliveries/build_portalapps_dockers.sh b/deliveries/build_portalapps_dockers.sh
index 5092b407..2a09997c 100755
--- a/deliveries/build_portalapps_dockers.sh
+++ b/deliveries/build_portalapps_dockers.sh
@@ -10,13 +10,22 @@ set -e -x
# This reuses the docker-compose environment file
echo "Set image tag name variables"
source $(dirname $0)/.env
+if [ $1 ]; then
+ echo "Sourcing extra parameters from $1"
+ source $(dirname $0)/$1
+else
+ echo "Using only base parameters from .env"
+fi
# Check for Jenkins build number
if [ -n "$BUILD_NUMBER" ]; then
- echo "Using Jenkins build number $BUILD_NUMBER"
+ export PORTAL_TAG=$BUILD_NUMBER
+ echo "Using Jenkins build number $BUILD_NUMBER; Docker Tag $PORTAL_TAG"
else
# This indicates a non-Jenkins build
export BUILD_NUMBER="999"
+ echo "Using Default build number $BUILD_NUMBER; Docker Tag $PORTAL_TAG"
+
fi
# Must work when called by ONAP Jenkins AND local builds.
@@ -30,12 +39,10 @@ else
fi
# This expects to start in the deliveries folder; make sure
-PORTAL_DOCKERFILE=Dockerfile.portal
-if [ ! -f $PORTAL_DOCKERFILE ] ; then
+if [ "$PORTAL_DOCKERFILE" != "skip"] && [ ! -f $PORTAL_DOCKERFILE ] ; then
echo "Failed to find file ${PORTAL_DOCKERFILE}; must start in deliveries folder; exiting"
exit 1
fi
-SDK_DOCKERFILE=Dockerfile.sdk
# Store directory names as variables
# This is the deliveries area.
@@ -65,26 +72,36 @@ else
echo "Build jar and war files"
cd $BASEDIR
- ${MVN} clean install
+ ${MVN} ${MVN_EXTRA_PORTAL} clean install
- echo "Build Portal-SDK app"
- cd $BASEDIR/sdk/ecomp-sdk/epsdk-app-os
- ${MVN} clean package
+ if [ "$SDK_DOCKERFILE" != "skip" ] && [ "SDK_APP_DIR" != "skip" ]; then
+ echo "Build Portal-SDK app"
+ cd $BASEDIR/$SDK_APP_DIR
+ ${MVN} ${MVN_EXTRA_SDK} clean package
+ fi
echo "Java build complete."
fi
-echo "Copy Portal app BE"
-cp $BASEDIR/ecomp-portal-BE-os/target/portal-be-os.war $BUILD_ABS
+if [ "$BE_DOCKERFILE" != "skip" ] || [ "PORTAL_DOCKERFILE" != "skip" ]; then
+ echo "Copy Portal app BE"
+ cp $BASEDIR/$BE_WAR_DIR/$BE_WAR_FILE $BUILD_ABS
+fi
-echo "Copy Portal app FE"
-cp -r $BASEDIR/ecomp-portal-FE-os/dist/public $BUILD_ABS
+if [ "$FE_DOCKERFILE" != "skip" ] || [ "PORTAL_DOCKERFILE" != "skip" ]; then
+ echo "Copy Portal app FE"
+ cp -r $BASEDIR/$FE_DIR $BUILD_ABS
+fi
-echo "Copy Portal widget-ms"
-cp $BASEDIR/ecomp-portal-widget-ms/widget-ms/target/widget-ms.jar $BUILD_ABS
+if [ "$WMS_DOCKERFILE" != "skip" ]; then
+ echo "Copy Portal widget-ms"
+ cp $BASEDIR/$WIDGET_MS_JAR_DIR/$WIDGET_MS_JAR_FILE $BUILD_ABS
+fi
-echo "Copy Portal-SDK app build results"
-cp $BASEDIR/sdk/ecomp-sdk/epsdk-app-os/target/epsdk-app-os.war $BUILD_ABS
+if [ "$SDK_DOCKERFILE" != "skip" ] && [ "SDK_APP_DIR" != "skip" ]; then
+ echo "Copy Portal-SDK app build results"
+ cp $BASEDIR/$SDK_WAR_DIR/$SDK_WAR_FILE $BUILD_ABS
+fi
# Build Docker images
@@ -99,59 +116,107 @@ fi
# must work in delivery directory
cd $DELIVDIR
+if [ "$DB_DOCKERFILE" = "skip" ]; then
+ echo "SKIPPING DB DOCKER BUILD!"
+else
# Copy DDL/DML to required directories
# RELATIVE PATHS to local directories with database scripts
# bcos Docker looks within this build area only
-DB_SCRIPT_DIR=$BUILD_REL/db-scripts
-mkdir -p ${DELIVDIR}/${DB_SCRIPT_DIR}
+ DB_SCRIPT_DIR=$BUILD_REL/db-scripts
+ mkdir -p ${DELIVDIR}/${DB_SCRIPT_DIR}
# Portal
-cp $BASEDIR/ecomp-portal-DB-common/*.sql ${DB_SCRIPT_DIR}
-cp $BASEDIR/ecomp-portal-DB-os/*.sql ${DB_SCRIPT_DIR}
+ cp $BASEDIR/ecomp-portal-DB-common/*.sql ${DB_SCRIPT_DIR}
+ cp $BASEDIR/ecomp-portal-DB-os/*.sql ${DB_SCRIPT_DIR}
# SDK app
-cp $BASEDIR/sdk/ecomp-sdk/epsdk-app-common/db-scripts/*.sql ${DB_SCRIPT_DIR}
-cp $BASEDIR/sdk/ecomp-sdk/epsdk-app-os/db-scripts/*.sql ${DB_SCRIPT_DIR}
-
-echo "Build mariadb docker image"
-DB_DOCKER_CMD="
- docker build -t ${DB_IMG_NAME}:${PORTAL_TAG} ${PROXY_ARGS}
- --build-arg DB_SCRIPT_DIR=${DB_SCRIPT_DIR}
- -f Dockerfile.mariadb .
-"
-$DB_DOCKER_CMD
+ cp $BASEDIR/sdk/ecomp-sdk/epsdk-app-common/db-scripts/*.sql ${DB_SCRIPT_DIR}
+ cp $BASEDIR/sdk/ecomp-sdk/epsdk-app-os/db-scripts/*.sql ${DB_SCRIPT_DIR}
+
+ echo "Build mariadb docker image"
+ DB_DOCKER_CMD="
+ docker build -t ${DB_IMG_NAME}:${PORTAL_TAG} ${PROXY_ARGS}
+ --build-arg DB_SCRIPT_DIR=${DB_SCRIPT_DIR}
+ -f $DB_DOCKERFILE .
+ "
+ $DB_DOCKER_CMD
+fi
# Copy cassandra scripts to required directories
# Portal
-cp $BASEDIR/ecomp-portal-DB-common/*.cql ${DELIVDIR}
+#cp $BASEDIR/ecomp-portal-DB-common/*.cql ${DELIVDIR}
# SDK app
-cp $BASEDIR/sdk/ecomp-sdk/epsdk-app-common/db-scripts/*.cql ${DELIVDIR}
+#cp $BASEDIR/sdk/ecomp-sdk/epsdk-app-common/db-scripts/*.cql ${DELIVDIR}
# Build Docker Images
-echo "Build portal docker image"
-PORTAL_DOCKER_CMD="
- docker build -t ${EP_IMG_NAME}:${PORTAL_TAG} ${PROXY_ARGS}
- --build-arg FE_DIR=$BUILD_REL/public
- --build-arg PORTAL_WAR=$BUILD_REL/portal-be-os.war
- --build-arg SERVERXML=${DELIVDIR}/server.xml
- -f $PORTAL_DOCKERFILE .
-"
-$PORTAL_DOCKER_CMD
-
-echo "Build sdk demo app docker image"
-SDK_DOCKER_CMD="
- docker build -t ${SDK_IMG_NAME}:${PORTAL_TAG} ${PROXY_ARGS}
- --build-arg SDK_WAR=$BUILD_REL/epsdk-app-os.war
- -f $SDK_DOCKERFILE .
-"
-$SDK_DOCKER_CMD
-
-echo "Build widget-ms docker image"
-WMS_DOCKER_CMD="
- docker build -t ${WMS_IMG_NAME}:${PORTAL_TAG} ${PROXY_ARGS}
- --build-arg WMS_JAR=$BUILD_REL/widget-ms.jar
- -f Dockerfile.widgetms .
-"
-$WMS_DOCKER_CMD
+#Combined FE/BE image
+if [ "$PORTAL_DOCKERFILE" = "skip" ]; then
+ echo "SKIPPING PORTAL DOCKER IMAGE BUILD!"
+else
+ echo "Build portal docker image"
+ PORTAL_DOCKER_CMD="
+ docker build -t ${EP_IMG_NAME}:${PORTAL_TAG} ${PROXY_ARGS}
+ --build-arg FE_DIR=$BUILD_REL/public
+ --build-arg PORTAL_WAR=$BUILD_REL/$BE_WAR_FILE
+ --build-arg SERVERXML=${SERVER_XML_DIR}/server.xml
+ --build-arg PORTALCONTEXT=$PORTALCONTEXT
+ -f $PORTAL_DOCKERFILE .
+ "
+ $PORTAL_DOCKER_CMD
+fi
+
+if [ "$SDK_DOCKERFILE" = "skip" ]; then
+ echo "SKIPPING SDK DOCKER IMAGE BUILD!"
+else
+ echo "Build sdk demo app docker image"
+ SDK_DOCKER_CMD="
+ docker build -t ${SDK_IMG_NAME}:${PORTAL_TAG} ${PROXY_ARGS}
+ --build-arg SDK_WAR=$BUILD_REL/$SDK_WAR_FILE
+ --build-arg SDKCONTEXT=$SDKCONTEXT
+ -f $SDK_DOCKERFILE .
+ "
+ $SDK_DOCKER_CMD
+fi
+
+if [ "$BE_DOCKERFILE" = "skip" ]; then
+ echo "SKIPPING BE DOCKER IMAGE BUILD!"
+else
+ echo "Build portal be image"
+ BE_DOCKER_CMD="
+ docker build -t ${BE_IMG_NAME}:${PORTAL_TAG} ${PROXY_ARGS}
+ --build-arg PORTAL_WAR=$BUILD_REL/$BE_WAR_FILE
+ --build-arg SERVERXML=${SERVER_XML_DIR}/server.xml
+ --build-arg PORTALCONTEXT=$PORTALCONTEXT
+ --build-arg BE_BASE_IMAGE=$BE_BASE_IMAGE
+ -f $BE_DOCKERFILE .
+ "
+ $BE_DOCKER_CMD
+fi
+
+if [ "$FE_DOCKERFILE" = "skip" ]; then
+ echo "SKIPPING FE DOCKER IMAGE BUILD!"
+else
+ echo "Build portal fe image"
+ FE_DOCKER_CMD="
+ docker build -t ${FE_IMG_NAME}:${PORTAL_TAG} ${PROXY_ARGS}
+ --build-arg FE_DIR=$BUILD_REL/public
+ --build-arg FECONTEXT=$FECONTEXT
+ --build-arg FE_BASE_IMAGE=$FE_BASE_IMAGE
+ -f $FE_DOCKERFILE .
+ "
+ $FE_DOCKER_CMD
+fi
+
+if [ "$WMS_DOCKERFILE" = "skip" ]; then
+ echo "SKIPPING WIDGET-MS DOCKER IMAGE BUILD!"
+else
+ echo "Build widget-ms docker image"
+ WMS_DOCKER_CMD="
+ docker build -t ${WMS_IMG_NAME}:${PORTAL_TAG} ${PROXY_ARGS}
+ --build-arg WMS_JAR=$BUILD_REL/$WIDGET_MS_JAR_FILE
+ -f Dockerfile.widgetms .
+ "
+ $WMS_DOCKER_CMD
+fi
# For ease of debugging, leave the build dir
# echo "Cleaning up"
diff --git a/deliveries/keystoreONAP.keystore b/deliveries/keystoreONAP.keystore
new file mode 100644
index 00000000..ff0f0d76
--- /dev/null
+++ b/deliveries/keystoreONAP.keystore
Binary files differ
diff --git a/deliveries/server.xml b/deliveries/server.xml
index e23771cc..cf202a91 100644
--- a/deliveries/server.xml
+++ b/deliveries/server.xml
@@ -14,6 +14,7 @@
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+
Modifications to this file for use in ONAP are also subject to the Apache-2.0 license.
-->
<!-- Note: A "Server" is not itself a "Container", so you may not
diff --git a/deliveries/start-apache-tomcat.sh b/deliveries/start-apache-tomcat.sh
index 522eaf2a..98dde8b9 100644
--- a/deliveries/start-apache-tomcat.sh
+++ b/deliveries/start-apache-tomcat.sh
@@ -5,6 +5,7 @@
hostip=""
hostname=""
+BASE=/opt/apache-tomcat-8.0.37
while [ $# -gt 0 ]; do
key="$1"
case $key in
@@ -20,6 +21,12 @@ while [ $# -gt 0 ]; do
shift # past argument
shift # past value
;;
+ -b|--base)
+ BASE="$2"
+ echo "$0: option -b value is $BASE"
+ shift # past argument
+ shift # past value
+ ;;
*)
echo "$0: ignoring argument $key"
shift
@@ -43,7 +50,6 @@ else
fi
fi
-BASE=/opt/apache-tomcat-8.0.37
if [ ! -d $BASE ] ; then
echo "$0: $BASE not found or not a directory"
exit 1
diff --git a/deliveries/truststoreONAPall.jks b/deliveries/truststoreONAPall.jks
new file mode 100644
index 00000000..ff844b10
--- /dev/null
+++ b/deliveries/truststoreONAPall.jks
Binary files differ
diff --git a/ecomp-portal-BE-common/pom.xml b/ecomp-portal-BE-common/pom.xml
index aca5e2af..61f166db 100644
--- a/ecomp-portal-BE-common/pom.xml
+++ b/ecomp-portal-BE-common/pom.xml
@@ -5,7 +5,7 @@
<parent>
<groupId>org.onap.portal</groupId>
<artifactId>onap-portal-parent</artifactId>
- <version>2.5.0</version>
+ <version>2.6.0-SNAPSHOT</version>
</parent>
<artifactId>portal-be-common</artifactId>
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/conf/MusicSessionRepositoryHandler.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/conf/MusicSessionRepositoryHandler.java
index cd911b80..7b42d52d 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/conf/MusicSessionRepositoryHandler.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/conf/MusicSessionRepositoryHandler.java
@@ -80,9 +80,7 @@ public class MusicSessionRepositoryHandler {
MusicService.removeSession(id);
} catch (MusicLockingException e) {
logger.error(EELFLoggerDelegate.errorLogger, "removeSession locking failed with id " + id, e);
- } catch (MusicServiceException e) {
- logger.error(EELFLoggerDelegate.errorLogger, "removeSession failed with id " + id, e);
- }
+ }
}
}
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsController.java
index 789a4097..4b401e22 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsController.java
@@ -42,10 +42,18 @@ package org.onap.portalapp.portal.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
+import java.util.Map;
import java.util.Set;
+import java.util.stream.Stream;
+
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+
+import org.json.JSONArray;
+import org.json.JSONObject;
import org.onap.portalapp.controller.EPRestrictedBaseController;
import org.onap.portalapp.portal.domain.AdminUserApplications;
import org.onap.portalapp.portal.domain.AppIdAndNameTransportModel;
@@ -54,10 +62,13 @@ import org.onap.portalapp.portal.domain.EPApp;
import org.onap.portalapp.portal.domain.EPUser;
import org.onap.portalapp.portal.domain.EcompApp;
import org.onap.portalapp.portal.domain.UserRoles;
+import org.onap.portalapp.portal.exceptions.InvalidApplicationException;
import org.onap.portalapp.portal.logging.aop.EPAuditLog;
+import org.onap.portalapp.portal.logging.logic.EPLogUtil;
import org.onap.portalapp.portal.service.AdminRolesService;
import org.onap.portalapp.portal.service.EPAppService;
import org.onap.portalapp.portal.service.EPLeftMenuService;
+import org.onap.portalapp.portal.service.ExternalAccessRolesService;
import org.onap.portalapp.portal.transport.EPAppsManualPreference;
import org.onap.portalapp.portal.transport.EPAppsSortPreference;
import org.onap.portalapp.portal.transport.EPDeleteAppsManualSortPref;
@@ -65,6 +76,7 @@ import org.onap.portalapp.portal.transport.EPWidgetsSortPreference;
import org.onap.portalapp.portal.transport.FieldsValidator;
import org.onap.portalapp.portal.transport.LocalRole;
import org.onap.portalapp.portal.transport.OnboardingApp;
+import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
import org.onap.portalapp.portal.utils.EcompPortalUtils;
import org.onap.portalapp.portal.utils.PortalConstants;
import org.onap.portalapp.util.EPUserUtils;
@@ -75,12 +87,18 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.client.HttpClientErrorException;
+import org.springframework.web.client.HttpStatusCodeException;
+import org.springframework.web.client.RestTemplate;
@RestController
@EnableAspectJAutoProxy
@@ -96,6 +114,10 @@ public class AppsController extends EPRestrictedBaseController {
@Autowired
private EPLeftMenuService leftMenuService;
+
+ @Autowired
+ private ExternalAccessRolesService externalAccessRolesService;
+ RestTemplate template = new RestTemplate();
/**
* RESTful service method to fetch all Applications available to current
@@ -470,7 +492,7 @@ public class AppsController extends EPRestrictedBaseController {
if (!adminRolesService.isSuperAdmin(user)) {
EcompPortalUtils.setBadPermissions(user, response, "getApps");
} else {
- apps = appService.getAllApps(false);
+ apps = appService.getAllApplications(false);
EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/availableApps", "GET result =", apps);
}
} catch (Exception e) {
@@ -663,10 +685,18 @@ public class AppsController extends EPRestrictedBaseController {
EPUser user = EPUserUtils.getUserSession(request);
List<OnboardingApp> onboardingApps = null;
try {
- if (!adminRolesService.isSuperAdmin(user)) {
+ if (!adminRolesService.isSuperAdmin(user) && !adminRolesService.isAccountAdmin(user)) {
EcompPortalUtils.setBadPermissions(user, response, "getOnboardingApps");
} else {
+
+ if(adminRolesService.isSuperAdmin(user)){
onboardingApps = appService.getOnboardingApps();
+ }
+ else if(adminRolesService.isAccountAdmin(user))
+ {
+ //get all his admin apps
+ onboardingApps = appService.getAdminAppsOfUser(user);
+ }
EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/onboardingApps", "GET result =",
"onboardingApps of size " + onboardingApps.size());
}
@@ -686,19 +716,39 @@ public class AppsController extends EPRestrictedBaseController {
* @param modifiedOnboardingApp
* app to update
* @return FieldsValidator
+ * @throws Exception
*/
@RequestMapping(value = { "/portalApi/onboardingApps" }, method = RequestMethod.PUT, produces = "application/json")
public FieldsValidator putOnboardingApp(HttpServletRequest request,
- @RequestBody OnboardingApp modifiedOnboardingApp, HttpServletResponse response) {
+ @RequestBody OnboardingApp modifiedOnboardingApp, HttpServletResponse response) throws Exception {
FieldsValidator fieldsValidator = null;
EPUser user = null;
EPApp oldEPApp = null;
+ oldEPApp = appService.getApp(modifiedOnboardingApp.id);
+ ResponseEntity<String> res = null;
+
try {
user = EPUserUtils.getUserSession(request);
- if (!adminRolesService.isSuperAdmin(user)) {
+ if (!adminRolesService.isSuperAdmin(user) && !adminRolesService.isAccountAdminOfAnyActiveorInactiveApplication(user, oldEPApp) ) {
EcompPortalUtils.setBadPermissions(user, response, "putOnboardingApp");
} else {
- oldEPApp = appService.getApp(modifiedOnboardingApp.id);
+ if((oldEPApp.getCentralAuth() && modifiedOnboardingApp.isCentralAuth && !oldEPApp.getNameSpace().equalsIgnoreCase(modifiedOnboardingApp.nameSpace) && modifiedOnboardingApp.nameSpace!= null ) || (!oldEPApp.getCentralAuth() && modifiedOnboardingApp.isCentralAuth && modifiedOnboardingApp.nameSpace!= null))
+ {
+ try {
+ res = appService.checkIfNameSpaceIsValid(modifiedOnboardingApp.nameSpace);
+ } catch (HttpClientErrorException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e);
+ EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+ if (e.getStatusCode() == HttpStatus.NOT_FOUND || e.getStatusCode() == HttpStatus.FORBIDDEN) {
+ fieldsValidator = setResponse(e.getStatusCode(),fieldsValidator,response);
+ throw new InvalidApplicationException("Invalid NameSpace");
+ }else{
+ fieldsValidator = setResponse(e.getStatusCode(),fieldsValidator,response);
+ throw e;
+ }
+ }
+
+ }
modifiedOnboardingApp.normalize();
fieldsValidator = appService.modifyOnboardingApp(modifiedOnboardingApp, user);
response.setStatus(fieldsValidator.httpStatusCode.intValue());
@@ -722,6 +772,8 @@ public class AppsController extends EPRestrictedBaseController {
return fieldsValidator;
}
+
+
/**
*
* @param request
@@ -742,17 +794,58 @@ public class AppsController extends EPRestrictedBaseController {
EcompPortalUtils.setBadPermissions(user, response, "postOnboardingApps");
} else {
newOnboardingApp.normalize();
+ ResponseEntity<String> res = null;
+ try {
+ if( !(newOnboardingApp.nameSpace == null) && !newOnboardingApp.nameSpace.isEmpty())
+ res = appService.checkIfNameSpaceIsValid(newOnboardingApp.nameSpace);
+ } catch (HttpClientErrorException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e);
+ EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+ if (e.getStatusCode() == HttpStatus.NOT_FOUND || e.getStatusCode() == HttpStatus.FORBIDDEN) {
+ fieldsValidator = setResponse(e.getStatusCode(),fieldsValidator,response);
+ throw new InvalidApplicationException("Invalid NameSpace");
+ }else{
+ fieldsValidator = setResponse(e.getStatusCode(),fieldsValidator,response);
+ throw e;
+ }
+ }
fieldsValidator = appService.addOnboardingApp(newOnboardingApp, user);
response.setStatus(fieldsValidator.httpStatusCode.intValue());
}
+ if(response.getStatus()==200) {
+ try {
+ String newvaluesAsJson = new ObjectMapper().writeValueAsString(newOnboardingApp);
+ logger.info(EELFLoggerDelegate.auditLogger, "/portalApi/onboardingApps, loginId="+user.getLoginId()+", values ="+newvaluesAsJson);
+ } catch (JsonProcessingException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "postOnboardingApps failed", e);
+ }
+ }
} catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "postOnboardingApp failed", e);
+ logger.error(EELFLoggerDelegate.errorLogger, "postOnboardingApp failed", e);
}
EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/onboardingApps", "POST result =",
response.getStatus());
return fieldsValidator;
}
+
+ private FieldsValidator setResponse(HttpStatus statusCode,FieldsValidator fieldsValidator,HttpServletResponse response)
+ {
+ fieldsValidator = new FieldsValidator();
+ if (statusCode == HttpStatus.NOT_FOUND || statusCode == HttpStatus.FORBIDDEN) {
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
+ logger.error(EELFLoggerDelegate.errorLogger, "setResponse failed"+ "invalid namespace");
+ }else if (statusCode == HttpStatus.UNAUTHORIZED) {
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_UNAUTHORIZED);
+ logger.error(EELFLoggerDelegate.errorLogger, "setResponse failed"+ "unauthorized");
+ } else{
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
+ logger.error(EELFLoggerDelegate.errorLogger, "setResponse failed ",statusCode);
+
+ }
+ response.setStatus(fieldsValidator.httpStatusCode.intValue());
+ return fieldsValidator;
+ }
/**
* REST endpoint to process a request to delete an on-boarded application.
@@ -778,11 +871,15 @@ public class AppsController extends EPRestrictedBaseController {
fieldsValidator = appService.deleteOnboardingApp(user, appId);
response.setStatus(fieldsValidator.httpStatusCode.intValue());
}
+ if (response.getStatus() == 200) {
+ logger.info(EELFLoggerDelegate.auditLogger,
+ "/portalApi/onboardingApps/" + appId + "deleted by user " + user.getLoginId());
+ }
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "deleteOnboardingApp failed", e);
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
-
+
EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/onboardingApps" + appId, "DELETE result =",
response.getStatus());
return fieldsValidator;
@@ -823,5 +920,6 @@ public class AppsController extends EPRestrictedBaseController {
header.setContentLength(app.getThumbnail().length);
return new HttpEntity<byte[]>(app.getThumbnail(), header);
}
+
}
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RoleManageController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RoleManageController.java
index 3fda5392..b50d1cf4 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RoleManageController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RoleManageController.java
@@ -130,37 +130,36 @@ public class RoleManageController extends EPRestrictedBaseController {
@Autowired
private RoleListController roleListController;
-
+
@Autowired
private EPAppService appService;
@Autowired
private AuditService auditService;
-
+
@Autowired
private ExternalAccessRolesService externalAccessRolesService;
-
-
+
@Autowired
private AdminRolesService adminRolesService;
/**
* Calls an SDK-Core library method that gets the available roles and writes
- * them to the request object. Portal specifies a Hibernate mappings from
- * the Role class to the fn_role_v view, which ensures that only Portal
- * (app_id is null) roles are fetched.
+ * them to the request object. Portal specifies a Hibernate mappings from the
+ * Role class to the fn_role_v view, which ensures that only Portal (app_id is
+ * null) roles are fetched.
*
- * Any method declared void (no return value) or returning null causes the
- * audit log aspect method to declare failure. TODO: should return a JSON
- * string.
+ * Any method declared void (no return value) or returning null causes the audit
+ * log aspect method to declare failure. TODO: should return a JSON string.
*
* @param request
* @param response
- * @throws Exception
+ * @throws Exception
*/
-
+
@RequestMapping(value = { "/portalApi/get_roles/{appId}" }, method = RequestMethod.GET)
- public void getRoles(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId) throws Exception {
+ public void getRoles(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId)
+ throws Exception {
try {
EPUser user = EPUserUtils.getUserSession(request);
EPApp requestedApp = appService.getApp(appId);
@@ -186,12 +185,10 @@ public class RoleManageController extends EPRestrictedBaseController {
logger.error(EELFLoggerDelegate.errorLogger, "getRoles failed", e);
}
}
-
-
@RequestMapping(value = { "/portalApi/role_list/toggleRole/{appId}/{roleId}" }, method = RequestMethod.POST)
- public Map<String, Object> toggleRole(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId,
- @PathVariable("roleId") Long roleId) throws Exception {
+ public Map<String, Object> toggleRole(HttpServletRequest request, HttpServletResponse response,
+ @PathVariable("appId") Long appId, @PathVariable("roleId") Long roleId) throws Exception {
EPApp requestedApp = null;
String restcallStatus = null;
HashMap<String, Object> responseMap = new HashMap<>();
@@ -232,10 +229,10 @@ public class RoleManageController extends EPRestrictedBaseController {
}
return responseMap;
}
-
+
@RequestMapping(value = { "/portalApi/role_list/removeRole/{appId}/{roleId}" }, method = RequestMethod.POST)
- public Map<String, Object> removeRole(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId,
- @PathVariable("roleId") Long roleId) throws Exception {
+ public Map<String, Object> removeRole(HttpServletRequest request, HttpServletResponse response,
+ @PathVariable("appId") Long appId, @PathVariable("roleId") Long roleId) throws Exception {
EPUser user = EPUserUtils.getUserSession(request);
EPApp requestedApp = null;
@@ -298,7 +295,7 @@ public class RoleManageController extends EPRestrictedBaseController {
}
return responseMap;
}
-
+
@RequestMapping(value = { "/portalApi/role/saveRole/{appId}" }, method = RequestMethod.POST)
public Map<String, Object> saveRole(HttpServletRequest request, HttpServletResponse response,
@PathVariable("appId") Long appId) throws Exception {
@@ -353,9 +350,13 @@ public class RoleManageController extends EPRestrictedBaseController {
throw new InvalidRoleException("Invalid role function type:" + roleFunction.getType()
+ " and action: " + roleFunction.getAction() + " found while saving!");
}
- roleFunction.setCode(externalAccessRolesService.encodeFunctionCode(roleFunction.getCode()));
- roleFunction.setCode(roleFunction.getType() + PIPE + roleFunction.getCode() + PIPE
- + roleFunction.getAction());
+ if (EcompPortalUtils.checkFunctionCodeHasEncodePattern(roleFunction.getCode()))
+ roleFunction.setCode(roleFunction.getType() + PIPE
+ + EcompPortalUtils.encodeFunctionCode(roleFunction.getCode()) + PIPE
+ + roleFunction.getAction());
+ else
+ roleFunction.setCode(roleFunction.getType() + PIPE + roleFunction.getCode() + PIPE
+ + roleFunction.getAction());
domainRole.addRoleFunction((CentralV2RoleFunction) roleFunction);
}
} else {
@@ -444,29 +445,29 @@ public class RoleManageController extends EPRestrictedBaseController {
@PathVariable("roleId") Long roleId) throws Exception {
try {
EPUser user = EPUserUtils.getUserSession(request);
- ObjectMapper mapper = new ObjectMapper();
- EPApp requestedApp = appService.getApp(appId);
- if (isAuthorizedUser(user, requestedApp)) {
- fieldsValidation(requestedApp);
- if (requestedApp.getCentralAuth()) {
- CentralV2Role answer = externalAccessRolesService.getRoleInfo(roleId, requestedApp.getUebKey());
- logger.info(EELFLoggerDelegate.applicationLogger, "role_id" + roleId);
- Map<String, Object> model = new HashMap<>();
- model.put("availableRoleFunctions", mapper.writeValueAsString(
- externalAccessRolesService.getRoleFuncList(requestedApp.getUebKey())));
- model.put("availableRoles",
- mapper.writeValueAsString(getAvailableChildRoles(requestedApp.getUebKey(), roleId)));
- model.put("role", mapper.writeValueAsString(answer));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
- } else
- throw new NonCentralizedAppException(requestedApp.getName());
- } else {
- logger.info(EELFLoggerDelegate.auditLogger,
- "RoleManageController.getRoleFunctionList, Unauthorized user");
- SendErrorForUnauthorizedUser(response, user);
- }
+ ObjectMapper mapper = new ObjectMapper();
+ EPApp requestedApp = appService.getApp(appId);
+ if (isAuthorizedUser(user, requestedApp)) {
+ fieldsValidation(requestedApp);
+ if (requestedApp.getCentralAuth()) {
+ CentralV2Role answer = externalAccessRolesService.getRoleInfo(roleId, requestedApp.getUebKey());
+ logger.info(EELFLoggerDelegate.applicationLogger, "role_id" + roleId);
+ Map<String, Object> model = new HashMap<>();
+ model.put("availableRoleFunctions", mapper
+ .writeValueAsString(externalAccessRolesService.getRoleFuncList(requestedApp.getUebKey())));
+ model.put("availableRoles",
+ mapper.writeValueAsString(getAvailableChildRoles(requestedApp.getUebKey(), roleId)));
+ model.put("role", mapper.writeValueAsString(answer));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ } else
+ throw new NonCentralizedAppException(requestedApp.getName());
+ } else {
+ logger.info(EELFLoggerDelegate.auditLogger,
+ "RoleManageController.getRoleFunctionList, Unauthorized user");
+ SendErrorForUnauthorizedUser(response, user);
+ }
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "getRole failed", e);
throw e;
@@ -478,26 +479,26 @@ public class RoleManageController extends EPRestrictedBaseController {
@PathVariable("appId") Long appId) throws Exception {
try {
EPUser user = EPUserUtils.getUserSession(request);
- EPApp requestedApp = appService.getApp(appId);
- if (isAuthorizedUser(user, requestedApp)) {
- fieldsValidation(requestedApp);
- if (requestedApp.getCentralAuth()) {
- List<CentralV2RoleFunction> answer = null;
- Map<String, Object> model = new HashMap<>();
- ObjectMapper mapper = new ObjectMapper();
- answer = externalAccessRolesService.getRoleFuncList(requestedApp.getUebKey());
- model.put("availableRoleFunctions", answer);
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
- } else
- throw new NonCentralizedAppException(requestedApp.getName());
- } else {
- logger.info(EELFLoggerDelegate.auditLogger,
- "RoleManageController.getRoleFunctionList, Unauthorized user");
- EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
- response.getWriter().write("Unauthorized User");
- }
+ EPApp requestedApp = appService.getApp(appId);
+ if (isAuthorizedUser(user, requestedApp)) {
+ fieldsValidation(requestedApp);
+ if (requestedApp.getCentralAuth()) {
+ List<CentralV2RoleFunction> answer = null;
+ Map<String, Object> model = new HashMap<>();
+ ObjectMapper mapper = new ObjectMapper();
+ answer = externalAccessRolesService.getRoleFuncList(requestedApp.getUebKey());
+ model.put("availableRoleFunctions", answer);
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ } else
+ throw new NonCentralizedAppException(requestedApp.getName());
+ } else {
+ logger.info(EELFLoggerDelegate.auditLogger,
+ "RoleManageController.getRoleFunctionList, Unauthorized user");
+ EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
+ response.getWriter().write("Unauthorized User");
+ }
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunctionList failed", e);
throw e;
@@ -523,13 +524,14 @@ public class RoleManageController extends EPRestrictedBaseController {
if (isAuthorizedUser(user, requestedApp)) {
fieldsValidation(requestedApp);
if (requestedApp.getCentralAuth()) {
- String code = roleFunc.getType()+PIPE+roleFunc.getCode()+PIPE+roleFunc.getAction();
+ String code = roleFunc.getType() + PIPE + roleFunc.getCode() + PIPE + roleFunc.getAction();
CentralV2RoleFunction domainRoleFunction = externalAccessRolesService.getRoleFunction(code,
requestedApp.getUebKey());
- if(domainRoleFunction != null && (domainRoleFunction.getType() == null || domainRoleFunction.getAction() == null)) {
+ if (domainRoleFunction != null
+ && (domainRoleFunction.getType() == null || domainRoleFunction.getAction() == null)) {
addIfTypeActionDoesNotExits(domainRoleFunction);
}
- boolean isSave = true;
+ boolean isSave = true;
if (domainRoleFunction != null && domainRoleFunction.getCode().equals(roleFunc.getCode())
&& domainRoleFunction.getType().equals(roleFunc.getType())
&& domainRoleFunction.getAction().equals(roleFunc.getAction())) {
@@ -545,16 +547,14 @@ public class RoleManageController extends EPRestrictedBaseController {
if (saveOrUpdateResponse) {
EPUser requestedUser = externalAccessRolesService.getUser(user.getOrgUserId()).get(0);
EPApp app = externalAccessRolesService.getApp(requestedApp.getUebKey()).get(0);
- String activityCode = (isSave)
- ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_FUNCTION
+ String activityCode = (isSave) ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_FUNCTION
: EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_FUNCTION;
logExterlaAuthRoleFunctionActivity(code, requestedUser, app, activityCode);
}
} else
throw new NonCentralizedAppException(requestedApp.getName() + " is not Centralized Application");
} else {
- logger.info(EELFLoggerDelegate.auditLogger,
- "RoleManageController.saveRoleFunction, Unauthorized user");
+ logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.saveRoleFunction, Unauthorized user");
EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
}
@@ -564,35 +564,29 @@ public class RoleManageController extends EPRestrictedBaseController {
}
return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Saved Successfully!", "Success");
}
-
+
private void logExterlaAuthRoleFunctionActivity(String code, EPUser requestedUser, EPApp app, String activityCode) {
- logger.info(EELFLoggerDelegate.applicationLogger,
- "saveRoleFunction: succeeded for app {}, function {}", app.getId(), code);
+ logger.info(EELFLoggerDelegate.applicationLogger, "saveRoleFunction: succeeded for app {}, function {}",
+ app.getId(), code);
AuditLog auditLog = getAuditInfo(requestedUser, activityCode);
- auditLog.setComments(EcompPortalUtils.truncateString("saveRoleFunction role for app:"
- + app.getId() + " and function:'" + code + "'",
+ auditLog.setComments(EcompPortalUtils.truncateString(
+ "saveRoleFunction role for app:" + app.getId() + " and function:'" + code + "'",
PortalConstants.AUDIT_LOG_COMMENT_SIZE));
auditService.logActivity(auditLog, null);
- MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
- EPEELFLoggerAdvice.getCurrentDateTimeUTC());
- MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
- EPEELFLoggerAdvice.getCurrentDateTimeUTC());
- EcompPortalUtils.calculateDateTimeDifferenceForLog(
- MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
+ MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+ MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+ EcompPortalUtils.calculateDateTimeDifferenceForLog(MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
logger.info(EELFLoggerDelegate.auditLogger,
EPLogUtil.formatAuditLogMessage("RoleManageController.saveRoleFunction", activityCode,
- String.valueOf(requestedUser.getId()), requestedUser.getOrgUserId(),
- code));
+ String.valueOf(requestedUser.getId()), requestedUser.getOrgUserId(), code));
MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
MDC.remove(SystemProperties.MDC_TIMER);
}
-
-
private void addIfTypeActionDoesNotExits(CentralV2RoleFunction domainRoleFunction) {
- if(domainRoleFunction.getCode().contains(PIPE)) {
+ if (domainRoleFunction.getCode().contains(PIPE)) {
String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(domainRoleFunction.getCode());
String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(domainRoleFunction.getCode());
String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(domainRoleFunction.getCode());
@@ -697,19 +691,19 @@ public class RoleManageController extends EPRestrictedBaseController {
return null;
}
}
-
EPUser user = EPUserUtils.getUserSession(request);
List<CentralizedApp> applicationsList = null;
- if (adminRolesService.isAccountAdmin(user) || adminRolesService.isSuperAdmin(user) || adminRolesService.isRoleAdmin(user)) {
- applicationsList = externalAccessRolesService.getCentralizedAppsOfUser(userId);
- } else {
- logger.info(EELFLoggerDelegate.auditLogger,
- "RoleManageController.getCentralizedAppRoles, Unauthorized user");
- EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
- }
+ if (adminRolesService.isAccountAdmin(user) || adminRolesService.isSuperAdmin(user)
+ || adminRolesService.isRoleAdmin(user)) {
+ applicationsList = externalAccessRolesService.getCentralizedAppsOfUser(userId);
+ } else {
+ logger.info(EELFLoggerDelegate.auditLogger,
+ "RoleManageController.getCentralizedAppRoles, Unauthorized user");
+ EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
+ }
return applicationsList;
}
-
+
public RoleListController getRoleListController() {
return roleListController;
}
@@ -726,7 +720,6 @@ public class RoleManageController extends EPRestrictedBaseController {
this.roleController = roleController;
}
-
@RequestMapping(value = { "/portalApi/syncRoles" }, method = RequestMethod.POST, produces = "application/json")
public PortalRestResponse<String> syncRoles(HttpServletRequest request, HttpServletResponse response,
@RequestBody Long appId) {
@@ -748,7 +741,7 @@ public class RoleManageController extends EPRestrictedBaseController {
}
return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Sync roles completed successfully!", "Success");
}
-
+
@RequestMapping(value = { "/portalApi/syncFunctions" }, method = RequestMethod.POST, produces = "application/json")
public PortalRestResponse<String> syncFunctions(HttpServletRequest request, HttpServletResponse response,
@RequestBody Long appId) {
@@ -798,30 +791,30 @@ public class RoleManageController extends EPRestrictedBaseController {
}
return allParentRoles;
}
-
- public AuditLog getAuditInfo(EPUser user, String activityCode)
- {
+
+ public AuditLog getAuditInfo(EPUser user, String activityCode) {
AuditLog auditLog = new AuditLog();
auditLog.setUserId(user.getId());
auditLog.setActivityCode(activityCode);
auditLog.setAffectedRecordId(user.getOrgUserId());
-
+
return auditLog;
}
-
- private void fieldsValidation(EPApp app) throws Exception{
+
+ private void fieldsValidation(EPApp app) throws Exception {
app.getUebKey();
List<EPApp> appInfo = externalAccessRolesService.getApp(app.getUebKey());
- if(appInfo.isEmpty()){
+ if (appInfo.isEmpty()) {
throw new InvalidApplicationException("Invalid credentials");
}
- if(!appInfo.isEmpty() && EcompPortalUtils.checkIfRemoteCentralAccessAllowed() && appInfo.get(0).getCentralAuth()){
+ if (!appInfo.isEmpty() && EcompPortalUtils.checkIfRemoteCentralAccessAllowed()
+ && appInfo.get(0).getCentralAuth()) {
ResponseEntity<String> response = externalAccessRolesService.getNameSpaceIfExists(appInfo.get(0));
if (response.getStatusCode().value() == HttpServletResponse.SC_NOT_FOUND)
throw new InvalidApplicationException("Invalid NameSpace");
}
}
-
+
private boolean isAuthorizedUser(EPUser user, EPApp requestedApp) {
if (user != null && (adminRolesService.isAccountAdminOfApplication(user, requestedApp)
|| (adminRolesService.isSuperAdmin(user) && requestedApp.getId() == PortalConstants.PORTAL_APP_ID)))
@@ -833,8 +826,9 @@ public class RoleManageController extends EPRestrictedBaseController {
EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
response.getWriter().write("Unauthorized User");
}
-
- @RequestMapping(value = { "/portalApi/uploadRoleFunction/{appId}" }, method = RequestMethod.POST, produces = "application/json")
+
+ @RequestMapping(value = {
+ "/portalApi/uploadRoleFunction/{appId}" }, method = RequestMethod.POST, produces = "application/json")
public PortalRestResponse<String> bulkUploadRoleFunc(HttpServletRequest request, HttpServletResponse response,
@RequestBody UploadRoleFunctionExtSystem data, @PathVariable("appId") Long appId) {
EPUser user = EPUserUtils.getUserSession(request);
@@ -843,9 +837,10 @@ public class RoleManageController extends EPRestrictedBaseController {
if (isAuthorizedUser(user, app)) {
fieldsValidation(app);
externalAccessRolesService.bulkUploadRoleFunc(data, app);
- String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_ROLE_AND_FUNCTION;
- String code = data.getName()+","+data.getType()+ PIPE + data.getInstance() + PIPE + data.getAction();
- logExterlaAuthRoleFunctionActivity(code , user, app, activityCode);
+ String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_ROLE_AND_FUNCTION;
+ String code = data.getName() + "," + data.getType() + PIPE + data.getInstance() + PIPE
+ + data.getAction();
+ logExterlaAuthRoleFunctionActivity(code, user, app, activityCode);
} else {
logger.info(EELFLoggerDelegate.auditLogger,
"RoleManageController.syncRoles, Unauthorized user:{}", user != null ? user.getOrgUserId() : "");
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/SchedulerController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/SchedulerController.java
index 0be83c97..af34176c 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/SchedulerController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/SchedulerController.java
@@ -41,7 +41,9 @@ import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
@@ -49,8 +51,10 @@ import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONObject;
import org.onap.portalapp.controller.EPRestrictedBaseController;
+import org.onap.portalapp.portal.domain.EPUser;
import org.onap.portalapp.portal.ecomp.model.PortalRestResponse;
import org.onap.portalapp.portal.ecomp.model.PortalRestStatusEnum;
+import org.onap.portalapp.portal.exceptions.RoleFunctionException;
import org.onap.portalapp.portal.logging.aop.EPAuditLog;
import org.onap.portalapp.portal.logging.logic.EPLogUtil;
import org.onap.portalapp.portal.scheduler.SchedulerProperties;
@@ -62,8 +66,11 @@ import org.onap.portalapp.portal.scheduler.restobjects.PostSubmitVnfChangeRestOb
import org.onap.portalapp.portal.scheduler.wrapper.GetTimeSlotsWrapper;
import org.onap.portalapp.portal.scheduler.wrapper.PostCreateNewVnfWrapper;
import org.onap.portalapp.portal.scheduler.wrapper.PostSubmitVnfChangeTimeSlotsWrapper;
+import org.onap.portalapp.portal.service.AdminRolesService;
import org.onap.portalapp.portal.utils.PortalConstants;
+import org.onap.portalapp.util.EPUserUtils;
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.service.DataAccessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@@ -84,6 +91,9 @@ public class SchedulerController extends EPRestrictedBaseController {
@Autowired
private SchedulerRestInterface schedulerRestController;
+
+ @Autowired
+ private AdminRolesService adminRolesService;
private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerController.class);
@@ -93,33 +103,36 @@ public class SchedulerController extends EPRestrictedBaseController {
@RequestMapping(value = "/get_time_slots/{scheduler_request}", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<String> getTimeSlots(HttpServletRequest request,
@PathVariable("scheduler_request") String scheduler_request) throws Exception {
- try {
-
- Date startingTime = new Date();
- String startTimeRequest = requestDateFormat.format(startingTime);
- logger.debug(EELFLoggerDelegate.debugLogger, "Controller Scheduler GET Timeslots for startTimeRequest: ",
- startTimeRequest);
- logger.debug(EELFLoggerDelegate.debugLogger, "Original Request = {} ", scheduler_request);
-
- String path = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_GET_TIME_SLOTS)
- + scheduler_request;
-
- GetTimeSlotsWrapper schedulerResWrapper = getTimeSlots(scheduler_request, path, scheduler_request);
-
- Date endTime = new Date();
- String endTimeRequest = requestDateFormat.format(endTime);
- logger.debug(EELFLoggerDelegate.debugLogger, "Controller Scheduler - GET for EndTimeRequest = {}",
- endTimeRequest);
- return (new ResponseEntity<String>(schedulerResWrapper.getResponse(),
- HttpStatus.valueOf(schedulerResWrapper.getStatus())));
- } catch (Exception e) {
- GetTimeSlotsWrapper schedulerResWrapper=new GetTimeSlotsWrapper();
- schedulerResWrapper.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
- schedulerResWrapper.setEntity(e.getMessage());
- logger.error(EELFLoggerDelegate.errorLogger, "Exception with getTimeslots", e);
- return (new ResponseEntity<String>(schedulerResWrapper.getResponse(), HttpStatus.INTERNAL_SERVER_ERROR));
+ if (checkIfUserISValidToMakeSchedule(request)) {
+ try {
+ Date startingTime = new Date();
+ String startTimeRequest = requestDateFormat.format(startingTime);
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "Controller Scheduler GET Timeslots for startTimeRequest: ", startTimeRequest);
+ logger.debug(EELFLoggerDelegate.debugLogger, "Original Request = {} ", scheduler_request);
+
+ String path = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_GET_TIME_SLOTS)
+ + scheduler_request;
+
+ GetTimeSlotsWrapper schedulerResWrapper = getTimeSlots(scheduler_request, path, scheduler_request);
+
+ Date endTime = new Date();
+ String endTimeRequest = requestDateFormat.format(endTime);
+ logger.debug(EELFLoggerDelegate.debugLogger, "Controller Scheduler - GET for EndTimeRequest = {}",
+ endTimeRequest);
+ return (new ResponseEntity<String>(schedulerResWrapper.getResponse(),
+ HttpStatus.valueOf(schedulerResWrapper.getStatus())));
+ } catch (Exception e) {
+ GetTimeSlotsWrapper schedulerResWrapper = new GetTimeSlotsWrapper();
+ schedulerResWrapper.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
+ schedulerResWrapper.setEntity(e.getMessage());
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception with getTimeslots", e);
+ return (new ResponseEntity<String>(schedulerResWrapper.getResponse(),
+ HttpStatus.INTERNAL_SERVER_ERROR));
+ }
+ }else{
+ return (new ResponseEntity<String>("User is unauthorized to make this call", HttpStatus.UNAUTHORIZED));
}
-
}
protected GetTimeSlotsWrapper getTimeSlots(String request, String path, String uuid) throws Exception {
@@ -157,41 +170,45 @@ public class SchedulerController extends EPRestrictedBaseController {
@RequestMapping(value = "/post_create_new_vnf_change", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<String> postCreateNewVNFChange(HttpServletRequest request,
@RequestBody JSONObject scheduler_request) throws Exception {
- try {
- Date startingTime = new Date();
- String startTimeRequest = requestDateFormat.format(startingTime);
+ if (checkIfUserISValidToMakeSchedule(request)) {
+ try {
+ Date startingTime = new Date();
+ String startTimeRequest = requestDateFormat.format(startingTime);
- logger.debug(EELFLoggerDelegate.debugLogger, "Controller Scheduler POST : post_create_new_vnf_change",
- startTimeRequest);
+ logger.debug(EELFLoggerDelegate.debugLogger, "Controller Scheduler POST : post_create_new_vnf_change",
+ startTimeRequest);
- // Generating uuid
- String uuid = UUID.randomUUID().toString();
+ // Generating uuid
+ String uuid = UUID.randomUUID().toString();
- scheduler_request.put("scheduleId", uuid);
- logger.debug(EELFLoggerDelegate.debugLogger, "UUID = {} ", uuid);
+ scheduler_request.put("scheduleId", uuid);
+ logger.debug(EELFLoggerDelegate.debugLogger, "UUID = {} ", uuid);
- // adding uuid to the request payload
- scheduler_request.put("scheduleId", uuid);
- logger.debug(EELFLoggerDelegate.debugLogger, "Original Request = {}", scheduler_request.toString());
+ // adding uuid to the request payload
+ scheduler_request.put("scheduleId", uuid);
+ logger.debug(EELFLoggerDelegate.debugLogger, "Original Request = {}", scheduler_request.toString());
- String path = SchedulerProperties
- .getProperty(SchedulerProperties.SCHEDULER_CREATE_NEW_VNF_CHANGE_INSTANCE_VAL) + uuid;
+ String path = SchedulerProperties
+ .getProperty(SchedulerProperties.SCHEDULER_CREATE_NEW_VNF_CHANGE_INSTANCE_VAL) + uuid;
- PostCreateNewVnfWrapper responseWrapper = postSchedulingRequest(scheduler_request, path, uuid);
+ PostCreateNewVnfWrapper responseWrapper = postSchedulingRequest(scheduler_request, path, uuid);
- Date endTime = new Date();
- String endTimeRequest = requestDateFormat.format(endTime);
- logger.debug(EELFLoggerDelegate.debugLogger, "Controller Scheduler - POST= {}", endTimeRequest);
+ Date endTime = new Date();
+ String endTimeRequest = requestDateFormat.format(endTime);
+ logger.debug(EELFLoggerDelegate.debugLogger, "Controller Scheduler - POST= {}", endTimeRequest);
- return new ResponseEntity<String>(responseWrapper.getResponse(),
- HttpStatus.valueOf(responseWrapper.getStatus()));
- } catch (Exception e) {
- PostCreateNewVnfWrapper responseWrapper=new PostCreateNewVnfWrapper();
- responseWrapper.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
- responseWrapper.setEntity(e.getMessage());
- logger.error(EELFLoggerDelegate.errorLogger, "Exception with postCreateNewVNFChange ", e);
- return (new ResponseEntity<String>(responseWrapper.getResponse(), HttpStatus.INTERNAL_SERVER_ERROR));
+ return new ResponseEntity<String>(responseWrapper.getResponse(),
+ HttpStatus.valueOf(responseWrapper.getStatus()));
+ } catch (Exception e) {
+ PostCreateNewVnfWrapper responseWrapper = new PostCreateNewVnfWrapper();
+ responseWrapper.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
+ responseWrapper.setEntity(e.getMessage());
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception with postCreateNewVNFChange ", e);
+ return (new ResponseEntity<String>(responseWrapper.getResponse(), HttpStatus.INTERNAL_SERVER_ERROR));
+ }
+ }else{
+ return (new ResponseEntity<String>("User is unauthorized to make this call",HttpStatus.UNAUTHORIZED));
}
}
@@ -233,6 +250,7 @@ public class SchedulerController extends EPRestrictedBaseController {
@RequestMapping(value = "/submit_vnf_change_timeslots", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<String> postSubmitVnfChangeTimeslots(HttpServletRequest request,
@RequestBody JSONObject scheduler_request) throws Exception {
+ if (checkIfUserISValidToMakeSchedule(request)) {
try {
Date startingTime = new Date();
String startTimeRequest = requestDateFormat.format(startingTime);
@@ -259,13 +277,16 @@ public class SchedulerController extends EPRestrictedBaseController {
endTimeRequest);
return (new ResponseEntity<String>(responseWrapper.getResponse(),HttpStatus.valueOf(responseWrapper.getStatus())));
- } catch (Exception e) {
- PostSubmitVnfChangeTimeSlotsWrapper responseWrapper=new PostSubmitVnfChangeTimeSlotsWrapper();
- responseWrapper.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
- responseWrapper.setEntity(e.getMessage());
- logger.error(EELFLoggerDelegate.errorLogger, "Exception with Post submit Vnf change Timeslots", e);
- return (new ResponseEntity<String>(responseWrapper.getResponse(), HttpStatus.INTERNAL_SERVER_ERROR));
+ } catch (Exception e) {
+ PostSubmitVnfChangeTimeSlotsWrapper responseWrapper = new PostSubmitVnfChangeTimeSlotsWrapper();
+ responseWrapper.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
+ responseWrapper.setEntity(e.getMessage());
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception with Post submit Vnf change Timeslots", e);
+ return (new ResponseEntity<String>(responseWrapper.getResponse(), HttpStatus.INTERNAL_SERVER_ERROR));
+ }
+ }else{
+ return (new ResponseEntity<String>("User is unauthorized to make this call",HttpStatus.UNAUTHORIZED));
}
}
@@ -310,43 +331,74 @@ public class SchedulerController extends EPRestrictedBaseController {
* Get Scheduler UI constant values from properties file
*
* @return Rest response wrapped around a String; e.g., "success" or "ERROR"
+ * @throws Exception
*/
@RequestMapping(value = "/get_scheduler_constant", method = RequestMethod.GET, produces = "application/json")
public PortalRestResponse<Map<String, String>> getSchedulerConstant(HttpServletRequest request,
- HttpServletResponse response) {
+ HttpServletResponse response) throws Exception {
logger.debug(EELFLoggerDelegate.debugLogger, "get scheduler constant");
PortalRestResponse<Map<String, String>> portalRestResponse = null;
- String errorMsg = " is not defined in property file. Please check the property file and make sure all the schedule constant values are defined";
- HashMap<String, String> constantMap = new HashMap<>();
- constantMap.put(SchedulerProperties.SCHEDULER_DOMAIN_NAME, "domainName");
- constantMap.put(SchedulerProperties.SCHEDULER_SCHEDULE_NAME, "scheduleName");
- constantMap.put(SchedulerProperties.SCHEDULER_WORKFLOW_NAME, "workflowName");
- constantMap.put(SchedulerProperties.SCHEDULER_CALLBACK_URL, "callbackUrl");
- constantMap.put(SchedulerProperties.SCHEDULER_APPROVAL_TYPE, "approvalType");
- constantMap.put(SchedulerProperties.SCHEDULER_APPROVAL_SUBMIT_STATUS, "approvalSubmitStatus");
- constantMap.put(SchedulerProperties.SCHEDULER_APPROVAL_REJECT_STATUS, "approvalRejectStatus");
- constantMap.put(SchedulerProperties.SCHEDULER_POLICY_NAME, "policyName");
- constantMap.put(SchedulerProperties.SCHEDULER_INTERVAL_GET_TIMESLOT_RATE, "intervalRate");
- constantMap.put(SchedulerProperties.SCHEDULER_GROUP_ID, "groupId");
- try {
- Map<String, String> map = new HashMap<>();
- for (Map.Entry<String, String> entry : constantMap.entrySet()) {
- if (SchedulerProperties.containsProperty(entry.getKey()))
- map.put(entry.getValue(), SchedulerProperties.getProperty(entry.getKey()));
- else
- throw new Exception(entry.getKey() + errorMsg);
+
+ if (checkIfUserISValidToMakeSchedule(request)) {
+ String errorMsg = " is not defined in property file. Please check the property file and make sure all the schedule constant values are defined";
+ HashMap<String, String> constantMap = new HashMap<>();
+ constantMap.put(SchedulerProperties.SCHEDULER_DOMAIN_NAME, "domainName");
+ constantMap.put(SchedulerProperties.SCHEDULER_SCHEDULE_NAME, "scheduleName");
+ constantMap.put(SchedulerProperties.SCHEDULER_WORKFLOW_NAME, "workflowName");
+ constantMap.put(SchedulerProperties.SCHEDULER_CALLBACK_URL, "callbackUrl");
+ constantMap.put(SchedulerProperties.SCHEDULER_APPROVAL_TYPE, "approvalType");
+ constantMap.put(SchedulerProperties.SCHEDULER_APPROVAL_SUBMIT_STATUS, "approvalSubmitStatus");
+ constantMap.put(SchedulerProperties.SCHEDULER_APPROVAL_REJECT_STATUS, "approvalRejectStatus");
+ constantMap.put(SchedulerProperties.SCHEDULER_POLICY_NAME, "policyName");
+ constantMap.put(SchedulerProperties.SCHEDULER_INTERVAL_GET_TIMESLOT_RATE, "intervalRate");
+ constantMap.put(SchedulerProperties.SCHEDULER_GROUP_ID, "groupId");
+ try {
+ Map<String, String> map = new HashMap<>();
+ for (Map.Entry<String, String> entry : constantMap.entrySet()) {
+ if (SchedulerProperties.containsProperty(entry.getKey()))
+ map.put(entry.getValue(), SchedulerProperties.getProperty(entry.getKey()));
+ else
+ throw new Exception(entry.getKey() + errorMsg);
+ }
+ logger.debug(EELFLoggerDelegate.debugLogger, " portalRestResponse - getSchedulerConstant= {}", map);
+ portalRestResponse = new PortalRestResponse<Map<String, String>>(PortalRestStatusEnum.OK, "success",
+ map);
+
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getSchedulerConstant failed", e);
+ portalRestResponse = new PortalRestResponse<Map<String, String>>(PortalRestStatusEnum.ERROR,
+ e.getMessage(), null);
}
- logger.debug(EELFLoggerDelegate.debugLogger, " portalRestResponse - getSchedulerConstant= {}",
- map);
- portalRestResponse = new PortalRestResponse<Map<String, String>>(PortalRestStatusEnum.OK, "success", map);
-
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getSchedulerConstant failed", e);
- portalRestResponse = new PortalRestResponse<Map<String, String>>(PortalRestStatusEnum.ERROR, e.getMessage(),
- null);
+
}
- return portalRestResponse;
+ else{
+ logger.error(EELFLoggerDelegate.errorLogger, "getSchedulerConstant failed: User unauthorized to make this call");
+ portalRestResponse = new PortalRestResponse<Map<String, String>>(PortalRestStatusEnum.ERROR, "failed : Unauthorized", null);
+ }
+ return portalRestResponse;
}
+ private String getPath(HttpServletRequest request)
+ {
+ String requestURI = request.getRequestURI();
+ String portalApiPath = "";
+ if (requestURI != null) {
+ String[] uriArray = requestURI.split("/portalApi/");
+ if (uriArray.length > 1) {
+ portalApiPath = uriArray[1];
+ }
+ }
+ return portalApiPath;
+ }
+
+ private boolean checkIfUserISValidToMakeSchedule(HttpServletRequest request) throws Exception
+ {
+ EPUser user = EPUserUtils.getUserSession(request);
+ String portalApiPath = getPath(request);
+ Set<String> functionCodeList = adminRolesService.getAllAppsFunctionsOfUser(user.getId().toString());
+ boolean isValidUser = EPUserUtils.matchRoleFunctions(portalApiPath, functionCodeList);
+// boolean isValidUser = functionCodeList.stream().anyMatch(x -> functionCodeList.contains(portalApiPath));
+ return isValidUser;
+ }
}
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/UserRolesController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/UserRolesController.java
index 72ae07da..97888e56 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/UserRolesController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/UserRolesController.java
@@ -285,7 +285,7 @@ public class UserRolesController extends EPRestrictedBaseController {
@RequestMapping(value = { "/portalApi/userAppRoles" }, method = {
RequestMethod.GET }, produces = "application/json")
public List<RoleInAppForUser> getAppRolesForUser(HttpServletRequest request, @RequestParam("user") String orgUserId,
- @RequestParam("app") Long appid, @RequestParam("externalRequest") Boolean extRequestValue,
+ @RequestParam("app") Long appid, @RequestParam("externalRequest") Boolean extRequestValue,@RequestParam("isSystemUser") Boolean isSystemUser,
HttpServletResponse response) {
EPUser user = EPUserUtils.getUserSession(request);
List<RoleInAppForUser> result = null;
@@ -295,7 +295,7 @@ public class UserRolesController extends EPRestrictedBaseController {
EcompPortalUtils.setBadPermissions(user, response, "getAppRolesForUser");
feErrorString = EcompPortalUtils.getFEErrorString(true, response.getStatus());
} else {
- if (EcompPortalUtils.legitimateUserId(orgUserId)) {
+ if ((!isSystemUser && EcompPortalUtils.legitimateUserId(orgUserId)) || isSystemUser) {
result = userRolesService.getAppRolesForUser(appid, orgUserId, extRequestValue, user);
logger.debug(EELFLoggerDelegate.debugLogger, "getAppRolesForUser: result {}, appId {}", result , appid);
int responseCode = EcompPortalUtils.getExternalAppResponseCode();
@@ -561,4 +561,16 @@ public class UserRolesController extends EPRestrictedBaseController {
return result;
}
+ @RequestMapping(value = { "/portalApi/checkIfUserIsSuperAdmin" }, method = RequestMethod.GET, produces = "application/json")
+ public boolean checkIfUserIsSuperAdmin(HttpServletRequest request,
+ HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ boolean isSuperAdmin = false;
+ try {
+ isSuperAdmin = adminRolesService.isSuperAdmin(user) ;
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "checkIfUserIsSuperAdmin failed: " + e.getMessage());
+ }
+ return isSuperAdmin;
+ }
}
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPUser.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPUser.java
index dff5601b..a3c9c481 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPUser.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPUser.java
@@ -135,9 +135,11 @@ public class EPUser extends User {
private boolean online;
@SafeHtml
private String chatId;
+ private boolean systemUser;
private Integer languageId;
private static final long serialVersionUID = 1L;
+
private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPUser.class);
private static final String ECOMP_PORTAL_NAME = "ECOMP";
private boolean isGuest = false;
@@ -691,6 +693,14 @@ public class EPUser extends User {
public void setGuest(boolean isGuest) {
this.isGuest = isGuest;
}
+
+ public boolean isSystemUser() {
+ return systemUser;
+ }
+
+ public void setSystemUser(boolean systemUser) {
+ this.systemUser = systemUser;
+ }
@Override
public String toString() {
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/interceptor/PortalResourceInterceptor.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/interceptor/PortalResourceInterceptor.java
index b1439060..146050a4 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/interceptor/PortalResourceInterceptor.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/interceptor/PortalResourceInterceptor.java
@@ -154,8 +154,8 @@ public class PortalResourceInterceptor extends ResourceInterceptor {
SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
//RoleAdmin check is being added because the role belongs to partner application
//inorder to access portal api's, bypassing this with isRoleAdmin Check
- if ((matchRoleFunctions(portalApiPath, allRoleFunctions)
- && !matchRoleFunctions(portalApiPath, roleFunctions)) && !adminRolesService.isRoleAdmin(user)) {
+ if ((EPUserUtils.matchRoleFunctions(portalApiPath, allRoleFunctions)
+ && !EPUserUtils.matchRoleFunctions(portalApiPath, roleFunctions)) && !adminRolesService.isRoleAdmin(user)) {
logger.error(EELFLoggerDelegate.errorLogger,
"preHandle: User {} not authorized for path {} ", user.getOrgUserId(),
portalApiPath);
@@ -296,9 +296,13 @@ public class PortalResourceInterceptor extends ResourceInterceptor {
}catch(ClassCastException e){
logger.debug(EELFLoggerDelegate.debugLogger, "Entering in the classcastexception block if the UN is not the mechid : {}");
-
+ String secretKey = null;
// Unauthorized access due to missing HTTP Authorization request header
if (authHeader == null) {
+ if (remoteWebServiceCallService.verifyRESTCredential(secretKey, request.getHeader(EPCommonSystemProperties.UEB_KEY),
+ request.getHeader("username"), request.getHeader("password"))) {
+ return true;
+ }
final String msg = "no authorization found";
logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
@@ -396,42 +400,6 @@ public class PortalResourceInterceptor extends ResourceInterceptor {
return result;
}
- private Boolean matchRoleFunctions(String portalApiPath, Set<? extends String> roleFunctions) {
- String[] path = portalApiPath.split("/");
- List<String> roleFunList = new ArrayList<>();
- if (path.length > 1) {
- roleFunList = roleFunctions.stream().filter(item -> item.startsWith(path[0])).collect(Collectors.toList());
- if (roleFunList.size() >= 1) {
- for (String roleFunction : roleFunList) {
- String[] roleFunctionArray = roleFunction.split("/");
- boolean b = true;
- if (roleFunctionArray.length == path.length) {
- for (int i = 0; i < roleFunctionArray.length; i++) {
- if (b) {
- if (!roleFunctionArray[i].equals("*")) {
- Pattern p = Pattern.compile(Pattern.quote(path[i]), Pattern.CASE_INSENSITIVE);
- Matcher m = p.matcher(roleFunctionArray[i]);
- b = m.matches();
-
- }
- }
- }
- if (b)
- return b;
- }
- }
- }
- } else {
- for (String roleFunction : roleFunctions) {
- if (portalApiPath.matches(roleFunction))
- return true;
- }
- }
- return false;
- }
-
-
-
protected void handleSessionUpdates(HttpServletRequest request) {
PortalTimeoutHandler.handleSessionUpdatesNative(request, null, null, null, null, manageService);
}
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/HealthMonitor.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/HealthMonitor.java
index 891da3b7..45b5323c 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/HealthMonitor.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/HealthMonitor.java
@@ -333,7 +333,7 @@ public class HealthMonitor {
zkNodeStatistics.indexOf("Node"));
logger.info(EELFLoggerDelegate.applicationLogger,
"Getting Status for zookeeper :" + zookeeperNodes[i].trim() + ":------:" + state);
- if (state.contains("leader"))
+ if (state.contains("leader") || state.contains("follower"))
return true;
}
} catch (Exception e) {
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/UserSessionListener.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/UserSessionListener.java
index aa97d0b3..7dbcc025 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/UserSessionListener.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/UserSessionListener.java
@@ -109,7 +109,8 @@ public class UserSessionListener implements HttpSessionListener {
// Clean the shared context each time a session is destroyed.
// TODO: move the threshold to configuration file.
- getSharedContextService().expireSharedContexts(60 * 60 * 8);
+ //June2019:Commented as sharedContext is no more needed.
+// getSharedContextService().expireSharedContexts(60 * 60 * 8);
}
logger.info(EELFLoggerDelegate.debugLogger, "Session Destroyed : " + session.getId());
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/AdminRolesService.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/AdminRolesService.java
index a9d55fc8..3c228dff 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/AdminRolesService.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/AdminRolesService.java
@@ -38,10 +38,12 @@
package org.onap.portalapp.portal.service;
import java.util.List;
+import java.util.Set;
import org.onap.portalapp.portal.domain.EPApp;
import org.onap.portalapp.portal.domain.EPRole;
import org.onap.portalapp.portal.domain.EPUser;
+import org.onap.portalapp.portal.exceptions.RoleFunctionException;
import org.onap.portalapp.portal.transport.AppsListWithAdminRole;
public interface AdminRolesService {
@@ -78,4 +80,7 @@ public interface AdminRolesService {
List<EPRole> getRolesByApp(EPUser user, Long appId);
public boolean isAccountAdminOfApplication(EPUser user, EPApp app);
+ public Set<String> getAllAppsFunctionsOfUser(String OrgUserId)throws RoleFunctionException;
+
+ boolean isAccountAdminOfAnyActiveorInactiveApplication(EPUser user, EPApp app);
}
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/AdminRolesServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/AdminRolesServiceImpl.java
index 7099eda5..18aac6f4 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/AdminRolesServiceImpl.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/AdminRolesServiceImpl.java
@@ -65,6 +65,7 @@ import org.onap.portalapp.portal.domain.EPUser;
import org.onap.portalapp.portal.domain.EPUserApp;
import org.onap.portalapp.portal.domain.UserIdRoleId;
import org.onap.portalapp.portal.domain.UserRole;
+import org.onap.portalapp.portal.exceptions.RoleFunctionException;
import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
import org.onap.portalapp.portal.logging.logic.EPLogUtil;
@@ -77,6 +78,7 @@ import org.onap.portalapp.portal.utils.EcompPortalUtils;
import org.onap.portalapp.portal.utils.PortalConstants;
import org.onap.portalapp.util.EPUserUtils;
import org.onap.portalsdk.core.domain.RoleFunction;
+import org.onap.portalsdk.core.domain.User;
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
import org.onap.portalsdk.core.restful.domain.EcompRole;
import org.onap.portalsdk.core.service.DataAccessService;
@@ -168,8 +170,10 @@ public class AdminRolesServiceImpl implements AdminRolesService {
appsListWithAdminRole.orgUserId = orgUserId;
List<EPApp> appsList = null;
try {
- appsList = dataAccessService.getList(EPApp.class,
- " where ( enabled = 'Y' or id = " + ECOMP_APP_ID + ")", null, null);
+// appsList = dataAccessService.getList(EPApp.class,
+// null, null, null);
+
+ appsList = dataAccessService.getList(EPApp.class, null);
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "getAppsWithAdminRoleStateForUser 2 failed", e);
EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
@@ -202,9 +206,9 @@ public class AdminRolesServiceImpl implements AdminRolesService {
List<EPApp> apps = appsService.getAppsFullList();
HashMap<Long, EPApp> enabledApps = new HashMap<Long, EPApp>();
for (EPApp app : apps) {
- if (app.getEnabled().booleanValue() || app.getId() == ECOMP_APP_ID) {
+// if (app.getEnabled().booleanValue() || app.getId() == ECOMP_APP_ID) {
enabledApps.put(app.getId(), app);
- }
+// }
}
List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin = new ArrayList<AppNameIdIsAdmin>();
for (AppNameIdIsAdmin adminRole : newAppsListWithAdminRoles.appsRoles) {
@@ -499,18 +503,13 @@ public class AdminRolesServiceImpl implements AdminRolesService {
String type = externalAccessRolesService.getFunctionCodeType(roleFunction);
getRoleFuncListOfPortalSet1.add(type);
}
+
+ boolean checkIfFunctionsExits = getRoleFuncListOfPortalSet1.stream()
+ .anyMatch(roleFunction -> roleFunction.equalsIgnoreCase("Approver"));
+ logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has approver rolefunction" , checkIfFunctionsExits);
- for (String rolefunc : getRoleFuncListOfPortalSet1) {
- logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has approver rolefunction" , rolefunc);
- if (rolefunc.equalsIgnoreCase(TYPE_APPROVER)) {
- logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has approver rolefunction" , rolefunc);
- return true;
- }else{
- return false;
-
- }
- }
-
+ return checkIfFunctionsExits;
+
} catch (Exception e) {
EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isRoleAdmin operation",
@@ -578,4 +577,52 @@ public class AdminRolesServiceImpl implements AdminRolesService {
return isApplicationAccountAdmin;
}
+
+ @Override
+ public Set<String> getAllAppsFunctionsOfUser(String OrgUserId) throws RoleFunctionException {
+ final Map<String, String> params = new HashMap<>();
+ params.put("userId", OrgUserId);
+ List getRoleFuncListOfPortal = dataAccessService.executeNamedQuery("getAllAppsFunctionsOfUser", params, null);
+ Set<String> getRoleFuncListOfPortalSet = new HashSet<>(getRoleFuncListOfPortal);
+ Set<String> roleFunSet = new HashSet<>();
+ roleFunSet = getRoleFuncListOfPortalSet.stream().filter(x -> x.contains("|")).collect(Collectors.toSet());
+ if (roleFunSet.size() > 0)
+ for (String roleFunction : roleFunSet) {
+ String roleFun = EcompPortalUtils.getFunctionCode(roleFunction);
+ getRoleFuncListOfPortalSet.remove(roleFunction);
+ getRoleFuncListOfPortalSet.add(roleFun);
+ }
+
+ Set<String> finalRoleFunctionSet = new HashSet<>();
+ for (String roleFn : getRoleFuncListOfPortalSet) {
+ finalRoleFunctionSet.add(EPUserUtils.decodeFunctionCode(roleFn));
+ }
+
+// List<String> functionsOfUser = new ArrayList<>(getRoleFuncListOfPortal);
+ return finalRoleFunctionSet;
+ }
+
+
+ @Override
+ public boolean isAccountAdminOfAnyActiveorInactiveApplication(EPUser user, EPApp app) {
+ Boolean isApplicationAccountAdmin=false;
+ try {
+ final Map<String, Long> userParams = new HashMap<>();
+ userParams.put("userId", user.getId());
+ logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for user {}", user.getId());
+ List<Integer> userAdminApps = new ArrayList<>();
+ userAdminApps =dataAccessService.executeNamedQuery("getAllAdminAppsofTheUser", userParams, null);
+ if(userAdminApps.size()>=1){
+ isApplicationAccountAdmin=userAdminApps.contains((int) (long) app.getId());
+ logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for user is true{} ,appId {}", user.getId(),app.getId());
+ }
+ } catch (Exception e) {
+ EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "Exception occurred while executing isAccountAdminOfApplication operation", e);
+ }
+ logger.debug(EELFLoggerDelegate.debugLogger, "In AdminRolesServiceImpl() - isAccountAdminOfApplication = {} and userId ={} ", isApplicationAccountAdmin, user.getOrgUserId());
+ return isApplicationAccountAdmin;
+
+ }
}
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPAppCommonServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPAppCommonServiceImpl.java
index bbb83827..c3cc2864 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPAppCommonServiceImpl.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPAppCommonServiceImpl.java
@@ -50,6 +50,7 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
+import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
@@ -60,6 +61,8 @@ import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
+import org.json.JSONArray;
+import org.json.JSONObject;
import org.onap.portalapp.portal.domain.AdminUserApp;
import org.onap.portalapp.portal.domain.AdminUserApplications;
import org.onap.portalapp.portal.domain.AppIdAndNameTransportModel;
@@ -96,6 +99,13 @@ import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
import org.onap.portalsdk.core.service.DataAccessService;
import org.onap.portalsdk.core.util.SystemProperties;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.client.HttpClientErrorException;
+import org.springframework.web.client.RestTemplate;
import com.att.nsa.apiClient.http.HttpException;
import com.att.nsa.cambria.client.CambriaClient.CambriaApiException;
@@ -110,7 +120,9 @@ public class EPAppCommonServiceImpl implements EPAppService {
protected String ACCOUNT_ADMIN_ROLE_ID = "999";
protected String RESTRICTED_APP_ROLE_ID = "900";
- private static final String urlField = "url";
+ //private static final String urlField = "url";
+ private static final String nameSpaceField = "url";
+
private static final String nameField = "name";
private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPAppCommonServiceImpl.class);
@@ -121,6 +133,8 @@ public class EPAppCommonServiceImpl implements EPAppService {
protected SessionFactory sessionFactory;
@Autowired
private DataAccessService dataAccessService;
+
+ RestTemplate template = new RestTemplate();
@PostConstruct
private void init() {
@@ -129,6 +143,65 @@ public class EPAppCommonServiceImpl implements EPAppService {
ECOMP_APP_ID = SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID);
RESTRICTED_APP_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.RESTRICTED_APP_ROLE_ID);
}
+
+ public Boolean onboardingAppFieldsValidation(OnboardingApp onboardingApp) {
+ //FieldsValidator fieldsValidator = new FieldsValidator();
+
+ if ((!onboardingApp.restrictedApp) &&( onboardingApp.name == null || onboardingApp.name.length() == 0 || onboardingApp.restrictedApp == null
+ || onboardingApp.url == null || onboardingApp.url.length() == 0 || onboardingApp.restUrl == null || onboardingApp.restUrl.length() == 0
+ || onboardingApp.username == null || onboardingApp.username.length() == 0
+ || onboardingApp.isOpen == null
+ || (onboardingApp.id != null && onboardingApp.id.equals(ECOMP_APP_ID)))
+ // For a normal app (appType == PortalConstants.PortalAppId),
+ // these fields must be filled
+ // in.
+ // For a restricted app (appType==2), they will be empty.
+ || ((onboardingApp.restrictedApp) && (onboardingApp.name == null || onboardingApp.name.length() == 0
+ || onboardingApp.url == null || onboardingApp.url.length() == 0 || onboardingApp.isOpen == null))) {
+ return false;
+ }
+ return true;
+
+ }
+
+ private Boolean onboardingInactiveAppFieldsForValidation(OnboardingApp onboardingApp) {
+ if (onboardingApp.name == null || onboardingApp.name.length() == 0
+ || onboardingApp.isOpen == null) {
+ return false;
+ }
+ return true;
+ }
+
+ protected FieldsValidator onboardingAppFieldsChecker(OnboardingApp onboardingApp) {
+ FieldsValidator fieldsValidator = new FieldsValidator();
+ if (onboardingApp.isCentralAuth) {
+ if (!onboardingApp.isEnabled) {
+ if (!onboardingInactiveAppFieldsForValidation(onboardingApp)) {
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
+ }
+ } else if (onboardingApp.isEnabled) {
+ if (onboardingAppFieldsValidation(onboardingApp) == false || onboardingApp.nameSpace == null
+ || onboardingApp.nameSpace.length() == 0) {
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
+ }
+ }
+ } else {
+ if (!onboardingApp.isEnabled) {
+ if (!onboardingInactiveAppFieldsForValidation(onboardingApp)) {
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
+ }
+ } else if (onboardingApp.isEnabled) {
+ if(onboardingApp.restrictedApp && onboardingAppFieldsValidation(onboardingApp) == false){
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
+ }
+ else if (!onboardingApp.restrictedApp && (onboardingAppFieldsValidation(onboardingApp) == false || onboardingApp.appPassword == null
+ || onboardingApp.appPassword.length() == 0)) {
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
+ }
+ }
+ }
+ return fieldsValidator;
+ }
@Override
public List<EPApp> getUserAsAdminApps(EPUser user) {
@@ -406,6 +479,23 @@ public class EPAppCommonServiceImpl implements EPAppService {
return appsModified;
}
+
+ @Override
+ public List<AppsResponse> getAllApplications(Boolean all) {
+ // If all is true, return both active and inactive apps. Otherwise, just
+ // active apps.
+ @SuppressWarnings("unchecked")
+ // Sort the list by application name so the drop-down looks pretty.
+ List<EPApp> apps = all
+ ? (List<EPApp>) dataAccessService.getList(EPApp.class, " where id != " + ECOMP_APP_ID, "name", null)
+ :dataAccessService.getList(EPApp.class, null);
+
+ List<AppsResponse> appsModified = new ArrayList<AppsResponse>();
+ for (EPApp app : apps) {
+ appsModified.add(new AppsResponse(app.getId(), app.getName(), app.isRestrictedApp(), app.getEnabled()));
+ }
+ return appsModified;
+ }
@Override
public UserRoles getUserProfile(String loginId) {
final Map<String, String> params = new HashMap<>();
@@ -488,7 +578,7 @@ public class EPAppCommonServiceImpl implements EPAppService {
return query.toString();
}
- protected FieldsValidator onboardingAppFieldsChecker(OnboardingApp onboardingApp) {
+ /*protected FieldsValidator onboardingAppFieldsChecker(OnboardingApp onboardingApp) {
FieldsValidator fieldsValidator = new FieldsValidator();
if(onboardingApp.isCentralAuth){
if (onboardingApp.name == null || onboardingApp.name.length() == 0 || onboardingApp.url == null
@@ -526,7 +616,7 @@ public class EPAppCommonServiceImpl implements EPAppService {
}
return fieldsValidator;
- }
+ }*/
@Override
public List<EPApp> getUserApps(EPUser user) {
@@ -739,6 +829,27 @@ public class EPAppCommonServiceImpl implements EPAppService {
}
return onboardingAppsList;
}
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<OnboardingApp> getAdminAppsOfUser(EPUser user) {
+
+ List<OnboardingApp> onboardingAppsList = new ArrayList<OnboardingApp>();
+ List<Integer> userAdminApps = new ArrayList<>();
+ final Map<String, Long> userParams = new HashMap<>();
+ userParams.put("userId", user.getId());
+ userAdminApps = dataAccessService.executeNamedQuery("getAllAdminAppsofTheUser", userParams, null);
+
+// userAdminApps.removeIf(x -> x == Integer.valueOf(ECOMP_APP_ID));
+
+ logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for userAdminApps() - for user {}, found userAdminAppsSize {}", user.getOrgUserId(), userAdminApps.size());
+ onboardingAppsList = getOnboardingApps();
+
+ final List<Integer> userAdminApps1 = userAdminApps;
+ List<OnboardingApp> userApplicationAdmins = onboardingAppsList.stream().filter(x -> userAdminApps1.contains((int) (long)x.id)).collect(Collectors.toList());
+
+ return userApplicationAdmins;
+ }
@Override
public List<OnboardingApp> getEnabledNonOpenOnboardingApps() {
@@ -757,25 +868,33 @@ public class EPAppCommonServiceImpl implements EPAppService {
@SuppressWarnings("unchecked")
private void validateOnboardingApp(OnboardingApp onboardingApp, FieldsValidator fieldsValidator) {
- boolean duplicatedUrl = false;
+ boolean duplicatedNameSpace = false;
boolean duplicatedName = false;
List<EPApp> apps;
if (onboardingApp.id == null) {
List<Criterion> restrictionsList = new ArrayList<Criterion>();
- Criterion urlCrit =Restrictions.eq("url", onboardingApp.url);
- Criterion nameCrit = Restrictions.eq("name",onboardingApp.name);
- Criterion orCrit = Restrictions.or(urlCrit, nameCrit);
-
+ Criterion nameCrit = Restrictions.eq("name",onboardingApp.name);
+ Criterion nameSpaceCrit = null;
+ Criterion orCrit = null;
+ if (onboardingApp.isCentralAuth) {
+ nameSpaceCrit = Restrictions.eq("nameSpace", onboardingApp.nameSpace);
+ orCrit = Restrictions.or(nameCrit, nameSpaceCrit);
+ } else
+ orCrit = Restrictions.or(nameCrit);
restrictionsList.add(orCrit);
apps = (List<EPApp>) dataAccessService.getList(EPApp.class, null, restrictionsList, null);
-
-
} else {
List<Criterion> restrictionsList = new ArrayList<Criterion>();
Criterion idCrit =Restrictions.eq("id", onboardingApp.id);
- Criterion urlCrit =Restrictions.eq("url", onboardingApp.url);
- Criterion nameCrit = Restrictions.eq("name",onboardingApp.name);
- Criterion orCrit = Restrictions.or(idCrit, urlCrit, nameCrit);
+ Criterion nameCrit = Restrictions.eq("name",onboardingApp.name);
+ Criterion nameSpaceCrit = null;
+ Criterion orCrit= null;
+ if (onboardingApp.isCentralAuth) {
+ nameSpaceCrit = Restrictions.eq("nameSpace",onboardingApp.nameSpace);
+ orCrit = Restrictions.or(idCrit, nameSpaceCrit, nameCrit);
+ }
+ else
+ orCrit = Restrictions.or(idCrit, nameCrit);
restrictionsList.add(orCrit);
apps = (List<EPApp>) dataAccessService.getList(EPApp.class, null, restrictionsList, null);
@@ -785,22 +904,23 @@ public class EPAppCommonServiceImpl implements EPAppService {
if (onboardingApp.id != null && onboardingApp.id.equals(app.getId())) {
continue;
}
- if (!duplicatedUrl && app.getUrl().equalsIgnoreCase(onboardingApp.url)) {
- duplicatedUrl = true;
+ if (!duplicatedName && app.getName().equalsIgnoreCase(onboardingApp.name)) {
+ duplicatedName = true;
if (duplicatedName) {
break;
}
}
- if (!duplicatedName && app.getName().equalsIgnoreCase(onboardingApp.name)) {
- duplicatedName = true;
- if (duplicatedUrl) {
+ if (!duplicatedNameSpace && app.getNameSpace().equalsIgnoreCase(onboardingApp.nameSpace)) {
+ duplicatedNameSpace = true;
+ if (duplicatedNameSpace) {
break;
}
}
+
}
- if (duplicatedUrl || duplicatedName) {
- if (duplicatedUrl) {
- fieldsValidator.addProblematicFieldName(urlField);
+ if (duplicatedNameSpace || duplicatedName) {
+ if (duplicatedNameSpace) {
+ fieldsValidator.addProblematicFieldName(nameSpaceField);
}
if (duplicatedName) {
fieldsValidator.addProblematicFieldName(nameField);
@@ -1801,4 +1921,57 @@ public class EPAppCommonServiceImpl implements EPAppService {
return userAndRoles;
}
+
+ @SuppressWarnings("unused")
+ @Override
+ public ResponseEntity<String> checkIfNameSpaceIsValid(String namespace) throws Exception {
+ HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+ HttpEntity<String> entity = new HttpEntity<>(headers);
+ logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Connecting to External Auth system for : "+namespace);
+ ResponseEntity<String> response = null;
+ try {
+ response = template
+ .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
+ + "nss/" + namespace, HttpMethod.GET, entity, String.class);
+ logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists for"+ namespace ,
+ response.getStatusCode().value());
+ if (response.getStatusCode().value() == 200) {
+ String res = response.getBody();
+ JSONObject jsonObj = new JSONObject(res);
+ JSONArray namespaceArray = jsonObj.getJSONArray("ns");
+ if(!namespaceArray.getJSONObject(0).has("admin")){
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "No admins are available for requested namespace:" + namespace);
+ throw new HttpClientErrorException(HttpStatus.UNAUTHORIZED,
+ "Portal Mechid is not an admin of" + namespace);
+ }
+
+ JSONArray namespaceAdminArray = namespaceArray.getJSONObject(0).getJSONArray("admin");
+ ArrayList<String> list = new ArrayList<String>();
+ if (namespaceAdminArray != null) {
+ int len = namespaceAdminArray.length();
+ for (int i = 0; i < len; i++) {
+ list.add(namespaceAdminArray.get(i).toString());
+ }
+ }
+ logger.debug(EELFLoggerDelegate.debugLogger, "List of Admins of requested namespace" + list);
+ final String userName = SystemProperties
+ .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME);
+ boolean idExists = list.stream().anyMatch(t -> userName.equals(t));
+ if (false) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "Portal mechid is not admin of requested namespace:" + namespace);
+ throw new HttpClientErrorException(HttpStatus.UNAUTHORIZED,
+ "Portal Mechid is not an admin of" + namespace);
+ }
+ }
+
+ } catch (HttpClientErrorException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e);
+ EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+ throw e;
+ }
+ return response;
+
+ }
}
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPAppService.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPAppService.java
index b314adec..6838ae4a 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPAppService.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPAppService.java
@@ -54,6 +54,7 @@ import org.onap.portalapp.portal.transport.EPWidgetsSortPreference;
import org.onap.portalapp.portal.transport.FieldsValidator;
import org.onap.portalapp.portal.transport.LocalRole;
import org.onap.portalapp.portal.transport.OnboardingApp;
+import org.springframework.http.ResponseEntity;
public interface EPAppService {
@@ -244,5 +245,10 @@ public interface EPAppService {
UserRoles getUserProfileForRolesLeftMenu(String loginId);
UserRoles getUserProfileNormalizedForRolesLeftMenu(EPUser user);
+ public List<OnboardingApp> getAdminAppsOfUser(EPUser user);
+
+ public ResponseEntity<String> checkIfNameSpaceIsValid(String namespace) throws Exception ;
+
+ List<AppsResponse> getAllApplications(Boolean all);
}
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesService.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesService.java
index ee960c40..d064545d 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesService.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesService.java
@@ -416,13 +416,6 @@ public interface ExternalAccessRolesService {
public JSONArray getAppRolesJSONFromExtAuthSystem(EPApp app) throws Exception;
/**
- * It encodes the function code based on Hex encoding
- * @param funCode
- *
- */
- public String encodeFunctionCode(String funCode);
-
- /**
*
* It returns list of ExternalRoleDetails which is converted from JSON array of roles
*
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImpl.java
index 7bb9995b..786ad429 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImpl.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImpl.java
@@ -47,11 +47,9 @@ import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
-import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.codec.DecoderException;
-import org.apache.commons.codec.binary.Hex;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
@@ -113,3742 +111,3682 @@ import com.fasterxml.jackson.databind.type.TypeFactory;
@EPMetricsLog
@EPAuditLog
public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesService {
- private static final String APP_ROLE_NAME_PARAM = "appRoleName";
- private static final String GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM = "getRoletoUpdateInExternalAuthSystem";
- private static final String GET_PORTAL_APP_ROLES_QUERY = "getPortalAppRoles";
- private static final String GET_ROLE_FUNCTION_QUERY = "getRoleFunction";
- private static final String FUNCTION_CODE_PARAMS = "functionCode";
- private static final String AND_FUNCTION_CD_EQUALS = " and function_cd = '";
- private static final String OWNER = ".owner";
- private static final String ADMIN = ".admin";
- private static final String ACCOUNT_ADMINISTRATOR = ".Account_Administrator";
- private static final String FUNCTION_PIPE = "|";
- private static final String EXTERNAL_AUTH_PERMS = "perms";
- private static final String EXTERNAL_AUTH_ROLE_DESCRIPTION = "description";
- private static final String IS_EMPTY_JSON_STRING = "{}";
- private static final String CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE = "Connecting to External Auth system";
- private static final String APP_ID = "appId";
- private static final String ROLE_NAME = "name";
- private static final String APP_ID_EQUALS = " app_id = ";
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesServiceImpl.class);
- @Autowired
- private DataAccessService dataAccessService;
- @Autowired
- private EPAppService epAppService;
- @Autowired
- private SessionFactory sessionFactory;
- @Autowired
- EPRoleService ePRoleService;
- RestTemplate template = new RestTemplate();
- // These decode values are based on HexDecoder
- static final String decodeValueOfForwardSlash = "2f";
- static final String decodeValueOfHiphen = "2d";
- static final String decodeValueOfStar = "2a";
-
- @SuppressWarnings("unchecked")
- @Override
- public List<EPRole> getAppRoles(Long appId) throws Exception {
- List<EPRole> applicationRoles = null;
- final Map<String, Long> appParams = new HashMap<>();
- try {
- if (appId == 1) {
- applicationRoles = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
- } else {
- appParams.put("appId", appId);
- applicationRoles = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getAppRoles: failed", e);
- throw e;
- }
- return applicationRoles;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public List<EPApp> getApp(String uebkey) throws Exception {
- List<EPApp> app = null;
- try {
- final Map<String, String> appUebkeyParams = new HashMap<>();
- appUebkeyParams.put("appKey", uebkey);
- app = dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null);
- if (!app.isEmpty() && !app.get(0).getEnabled()
- && !app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
- throw new InactiveApplicationException("Application:" + app.get(0).getName() + " is Unavailable");
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getApp: failed", e);
- throw e;
- }
- return app;
- }
-
- /**
- * It returns single application role from external auth system
- *
- * @param addRole
- * @param app
- * @return JSON string which contains application role details
- * @throws Exception
- */
- private String getSingleAppRole(String addRole, EPApp app) throws Exception {
- HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
- HttpEntity<String> entity = new HttpEntity<>(headers);
- ResponseEntity<String> response = null;
- logger.debug(EELFLoggerDelegate.debugLogger, "getSingleAppRole: Connecting to External Auth system");
- response = template.exchange(
- SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
- + app.getNameSpace() + "." + addRole
- .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
- HttpMethod.GET, entity, String.class);
- logger.debug(EELFLoggerDelegate.debugLogger,
- "getSingleAppRole: Finished GET app role from External Auth system and status code: {} ",
- response.getStatusCode().value());
- return response.getBody();
- }
-
- @Override
- public boolean addRole(Role addRole, String uebkey) throws Exception {
- boolean response = false;
- ResponseEntity<String> addResponse = null;
- HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
- EPApp app = getApp(uebkey).get(0);
- String newRole = updateExistingRoleInExternalSystem(addRole, app);
- HttpEntity<String> entity = new HttpEntity<>(newRole, headers);
- logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Connecting to External Auth system");
- addResponse = template.exchange(
- SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
- HttpMethod.POST, entity, String.class);
- if (addResponse.getStatusCode().value() == 201) {
- response = true;
- logger.debug(EELFLoggerDelegate.debugLogger,
- "addRole: Finished adding role in the External Auth system and response code: {} ",
- addResponse.getStatusCode().value());
- }
- if (addResponse.getStatusCode().value() == 406) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "addRole: Failed to add in the External Auth system due to {} and status code: {}",
- addResponse.getBody(), addResponse.getStatusCode().value());
- }
- return response;
- }
-
- /**
- *
- * It deletes record in external auth system
- *
- * @param delRole
- * @return JSON String which has status code and response body
- * @throws Exception
- */
- private ResponseEntity<String> deleteRoleInExternalSystem(String delRole) throws Exception {
- ResponseEntity<String> delResponse = null;
- HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
- HttpEntity<String> entity = new HttpEntity<>(delRole, headers);
- logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: {} for DELETE: {}",
- CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, delRole);
- delResponse = template.exchange(
- SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role?force=true",
- HttpMethod.DELETE, entity, String.class);
- logger.debug(EELFLoggerDelegate.debugLogger,
- "deleteRoleInExternalSystem: Finished DELETE operation in the External Auth system {} and status code: {} ",
- delRole, delResponse.getStatusCode().value());
- return delResponse;
- }
-
- /**
- * It updates role in external auth system
- *
- * @param updateExtRole
- * @param app
- * @return true if success else false
- * @throws Exception If updateRoleInExternalSystem fails we catch it in logger for detail message
- */
- private boolean updateRoleInExternalSystem(Role updateExtRole, EPApp app, boolean isGlobalRole) throws Exception {
- boolean response = false;
- ObjectMapper mapper = new ObjectMapper();
- ResponseEntity<String> deleteResponse = null;
- List<EPRole> epRoleList = null;
- if (app.getId().equals(PortalConstants.PORTAL_APP_ID)
- || (isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
- epRoleList = getPortalAppRoleInfo(updateExtRole.getId());
- } else {
- epRoleList = getPartnerAppRoleInfo(updateExtRole.getId(), app);
- }
- // Assigning functions to global role
- if ((isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
- List<RoleFunction> globalRoleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole);
- EPApp portalAppInfo = epAppService.getApp(PortalConstants.PORTAL_APP_ID);
- addFunctionsTOGlobalRole(epRoleList, updateExtRole, globalRoleFunctionListNew, mapper, app, portalAppInfo);
- response = true;
- } else {
- String appRole = getSingleAppRole(epRoleList.get(0).getName(), app);
- List<RoleFunction> roleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole);
- if (!appRole.equals(IS_EMPTY_JSON_STRING)) {
- JSONObject jsonObj = new JSONObject(appRole);
- JSONArray extRole = jsonObj.getJSONArray("role");
- if (!extRole.getJSONObject(0).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
- String roleName = extRole.getJSONObject(0).getString(ROLE_NAME);
- Map<String, String> delRoleKeyMapper = new HashMap<>();
- delRoleKeyMapper.put(ROLE_NAME, roleName);
- String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
- deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
- if (deleteResponse.getStatusCode().value() != 200) {
- throw new ExternalAuthSystemException(deleteResponse.getBody());
- }
- addRole(updateExtRole, app.getUebKey());
- } else {
- String desc = extRole.getJSONObject(0).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
- String name = extRole.getJSONObject(0).getString(ROLE_NAME);
- List<ExternalAccessPerms> list = new ArrayList<>();
- if (extRole.getJSONObject(0).has(EXTERNAL_AUTH_PERMS)) {
- JSONArray perms = extRole.getJSONObject(0).getJSONArray(EXTERNAL_AUTH_PERMS);
- list = mapper.readValue(perms.toString(), TypeFactory.defaultInstance()
- .constructCollectionType(List.class, ExternalAccessPerms.class));
- }
- // If role name or role functions are updated then delete
- // record in External System and add new record to avoid
- // conflicts
- boolean isRoleNameChanged = false;
- if (!desc.equals(updateExtRole.getName())) {
- isRoleNameChanged = true;
- deleteRoleInExtSystem(mapper, name);
- addRole(updateExtRole, app.getUebKey());
- // add partner functions to the global role in External
- // Auth System
- if (!list.isEmpty() && isGlobalRole) {
- addPartnerHasRoleFunctionsToGlobalRole(list, mapper, app, updateExtRole);
- }
- list.removeIf(
- perm -> EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace()));
- // if role name is changes please ignore the previous
- // functions in External Auth
- // and update with user requested functions
- addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name, list);
- }
- // Delete role in External System if role is inactive
- if (!updateExtRole.getActive()) {
- deleteRoleInExtSystem(mapper, name);
- }
- if (!isRoleNameChanged) {
- response =
- addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name, list);
- }
- }
- } else {
- // It seems like role exists in local DB but not in External
- // Access system
- if (updateExtRole.getActive()) {
- addRole(updateExtRole, app.getUebKey());
- ExternalAccessRolePerms extAddRolePerms = null;
- ExternalAccessPerms extAddPerms = null;
- List<RoleFunction> roleFunctionListAdd = convertSetToListOfRoleFunctions(updateExtRole);
- HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
- for (RoleFunction roleFunc : roleFunctionListAdd) {
- extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + roleFunc.getType(),
- roleFunc.getCode(), roleFunc.getAction());
- extAddRolePerms =
- new ExternalAccessRolePerms(extAddPerms,
- app.getNameSpace() + "." + updateExtRole.getName().replaceAll(
- EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
- "_"));
- response = addRoleFuncExtSysRestAPI(mapper, extAddRolePerms, headers);
- }
- }
- }
- }
- return response;
- }
-
- private void deleteRoleInExtSystem(ObjectMapper mapper, String name)
- throws JsonProcessingException, Exception, ExternalAuthSystemException {
- ResponseEntity<String> deleteResponse;
- Map<String, String> delRoleKeyMapper = new HashMap<>();
- delRoleKeyMapper.put(ROLE_NAME, name);
- String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
- deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
- if (deleteResponse.getStatusCode().value() != 200) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "updateRoleInExternalSystem: Failed to delete role in external system due to {} ",
- deleteResponse.getBody());
- throw new ExternalAuthSystemException(deleteResponse.getBody());
- }
- }
-
- private boolean addRemoveFunctionsToRole(Role updateExtRole, EPApp app, ObjectMapper mapper,
- List<RoleFunction> roleFunctionListNew, String name, List<ExternalAccessPerms> list) throws Exception {
- boolean response;
- Map<String, RoleFunction> updateRoleFunc = new HashMap<>();
- for (RoleFunction addPerm : roleFunctionListNew) {
- updateRoleFunc.put(addPerm.getCode(), addPerm);
- }
- final Map<String, ExternalAccessPerms> extRolePermMap = new HashMap<>();
- final Map<String, ExternalAccessPerms> extRolePermMapPipes = new HashMap<>();
- list.removeIf(perm -> !EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace()));
- // Update permissions in the ExternalAccess System
- HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
- if (!list.isEmpty()) {
- for (ExternalAccessPerms perm : list) {
- RoleFunction roleFunc = updateRoleFunc.get(perm.getType().substring(app.getNameSpace().length() + 1)
- + FUNCTION_PIPE + perm.getInstance() + FUNCTION_PIPE + perm.getAction());
- if (roleFunc == null) {
- RoleFunction roleFuncPipeFilter = updateRoleFunc.get(perm.getInstance());
- if (roleFuncPipeFilter == null)
- removePermForRole(perm, mapper, name, headers);
- }
- extRolePermMap.put(perm.getInstance(), perm);
- extRolePermMapPipes.put(perm.getType().substring(app.getNameSpace().length() + 1) + FUNCTION_PIPE
- + perm.getInstance() + FUNCTION_PIPE + perm.getAction(), perm);
- }
- }
- response = true;
- if (!roleFunctionListNew.isEmpty()) {
- for (RoleFunction roleFunc : roleFunctionListNew) {
- if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
- ExternalAccessPerms perm = extRolePermMapPipes.get(roleFunc.getCode());
- if (perm == null) {
- response =
- addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers, roleFunc);
- }
- } else {
- if (!extRolePermMap.containsKey(EcompPortalUtils.getFunctionCode(roleFunc.getCode()))) {
- response =
- addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers, roleFunc);
- }
- }
- }
- }
- return response;
- }
-
- /*
- * Adds function to the role in the external auth system while editing a role or updating new
- * functions to a role
- *
- */
- private boolean addFunctionsToRoleInExternalAuthSystem(Role updateExtRole, EPApp app, ObjectMapper mapper,
- HttpHeaders headers, RoleFunction roleFunc) throws JsonProcessingException {
- boolean response;
- ExternalAccessRolePerms extRolePerms;
- ExternalAccessPerms extPerms;
- String code = "";
- String type = "";
- String action = "";
- if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
- code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
- type = EcompPortalUtils.getFunctionType(roleFunc.getCode());
- action = getFunctionCodeAction(roleFunc.getCode());
- } else {
- code = roleFunc.getCode();
- type = roleFunc.getCode().contains("menu") ? "menu" : "url";
- action = "*";
- }
- extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, code, action);
- extRolePerms = new ExternalAccessRolePerms(extPerms, app.getNameSpace() + "." + updateExtRole.getName()
- .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
- String updateRolePerms = mapper.writeValueAsString(extRolePerms);
- HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
- logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: {} for POST: {}",
- CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
- ResponseEntity<String> addResponse = template.exchange(
- SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
- HttpMethod.POST, entity, String.class);
- if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 409) {
- response = false;
- logger.debug(EELFLoggerDelegate.debugLogger,
- "updateRoleInExternalSystem: Connected to External Auth system but something went wrong! due to {} and statuscode: {}",
- addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
- } else {
- response = true;
- logger.debug(EELFLoggerDelegate.debugLogger,
- "updateRoleInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ",
- updateRolePerms, addResponse.getStatusCode().value());
- }
- return response;
- }
-
- private void addPartnerHasRoleFunctionsToGlobalRole(List<ExternalAccessPerms> permslist, ObjectMapper mapper,
- EPApp app, Role updateExtRole) throws Exception {
- for (ExternalAccessPerms perm : permslist) {
- if (!EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace())) {
- ExternalAccessRolePerms extAddGlobalRolePerms = null;
- ExternalAccessPerms extAddPerms = null;
- extAddPerms = new ExternalAccessPerms(perm.getType(), perm.getInstance(), perm.getAction());
- extAddGlobalRolePerms = new ExternalAccessRolePerms(extAddPerms,
- app.getNameSpace() + "." + updateExtRole.getName().replaceAll(
- EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
- String addPerms = mapper.writeValueAsString(extAddGlobalRolePerms);
- HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
- HttpEntity<String> entity = new HttpEntity<>(addPerms, headers);
- logger.debug(EELFLoggerDelegate.debugLogger, "addPartnerHasRoleFunctionsToGlobalRole: {} ",
- CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
- try {
- ResponseEntity<String> addResponse = template
- .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
- + "role/perm", HttpMethod.POST, entity, String.class);
- if (addResponse.getStatusCode().value() != 201) {
- logger.debug(EELFLoggerDelegate.debugLogger,
- "addPartnerHasRoleFunctionsToGlobalRole: While adding permission to the role in External Auth system something went wrong! due to {} and statuscode: {}",
- addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
- } else {
- logger.debug(EELFLoggerDelegate.debugLogger,
- "addPartnerHasRoleFunctionsToGlobalRole: Finished adding permissions to roles in External Auth system and status code: {} ",
- addResponse.getStatusCode().value());
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "addPartnerHasRoleFunctionsToGlobalRole: Failed for POST request: {} due to ", addPerms, e);
- }
- }
- }
- }
-
- @SuppressWarnings("unchecked")
- private void addFunctionsTOGlobalRole(List<EPRole> epRoleList, Role updateExtRole,
- List<RoleFunction> roleFunctionListNew, ObjectMapper mapper, EPApp app, EPApp portalAppInfo)
- throws Exception {
- try {
- logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addFunctionsTOGlobalRole");
- // GET Permissions from External Auth System
- JSONArray extPerms = getExtAuthPermissions(app);
- List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);
- final Map<String, ExternalAccessPermsDetail> existingPermsWithRoles = new HashMap<>();
- final Map<String, ExternalAccessPermsDetail> existingPermsWithRolesWithPipes = new HashMap<>();
- final Map<String, RoleFunction> userRquestedFunctionsMap = new HashMap<>();
- final Map<String, RoleFunction> userRquestedFunctionsMapPipesFilter = new HashMap<>();
- for (ExternalAccessPermsDetail permDetail : permsDetailList) {
- existingPermsWithRoles.put(EcompPortalUtils.getFunctionCode(permDetail.getInstance()), permDetail);
- existingPermsWithRolesWithPipes.put(permDetail.getInstance(), permDetail);
- }
- // Add If function does not exists for role in External Auth System
- for (RoleFunction roleFunc : roleFunctionListNew) {
- String roleFuncCode = "";
- ExternalAccessPermsDetail permsDetail;
- if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
- roleFuncCode = roleFunc.getCode();
- permsDetail = existingPermsWithRolesWithPipes.get(roleFunc.getCode());
- } else {
- roleFuncCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
- permsDetail = existingPermsWithRoles.get(roleFuncCode);
- }
- if (null == permsDetail.getRoles()
- || !permsDetail.getRoles()
- .contains(portalAppInfo.getNameSpace() + FUNCTION_PIPE
- + epRoleList.get(0).getName().replaceAll(
- EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
- "_"))) {
- addRoleFunctionsToGlobalRoleInExternalSystem(roleFunc, updateExtRole, mapper, app, portalAppInfo);
- }
- userRquestedFunctionsMap.put(roleFuncCode, roleFunc);
- userRquestedFunctionsMapPipesFilter.put(EcompPortalUtils.getFunctionCode(roleFuncCode), roleFunc);
- }
- // Delete functions if exists in External Auth System but not in
- // incoming
- // request
- final Map<String, Long> epAppRoleFuncParams = new HashMap<>();
- epAppRoleFuncParams.put("requestedAppId", app.getId());
- epAppRoleFuncParams.put("roleId", updateExtRole.getId());
- List<GlobalRoleWithApplicationRoleFunction> globalRoleFunctionList =
- dataAccessService.executeNamedQuery("getGlobalRoleForRequestedApp", epAppRoleFuncParams, null);
- for (GlobalRoleWithApplicationRoleFunction globalRoleFunc : globalRoleFunctionList) {
- String globalRoleFuncWithoutPipes = "";
- RoleFunction roleFunc = null;
- if (globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
- globalRoleFuncWithoutPipes = globalRoleFunc.getFunctionCd();
- roleFunc = userRquestedFunctionsMap.get(globalRoleFuncWithoutPipes);
- } else {
- globalRoleFuncWithoutPipes = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd());
- roleFunc = userRquestedFunctionsMapPipesFilter.get(globalRoleFuncWithoutPipes);
- }
- if (roleFunc == null) {
- ExternalAccessPermsDetail permDetailFromMap = globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)
- ? existingPermsWithRolesWithPipes.get(globalRoleFuncWithoutPipes)
- : existingPermsWithRoles.get(globalRoleFuncWithoutPipes);
- ExternalAccessPerms perm = new ExternalAccessPerms(permDetailFromMap.getType(),
- EcompPortalUtils.getFunctionCode(permDetailFromMap.getInstance()),
- permDetailFromMap.getAction());
- String roleName = portalAppInfo.getNameSpace() + "." + globalRoleFunc.getRoleName()
- .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_");
- HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
- removePermForRole(perm, mapper, roleName, headers);
- }
- }
- logger.debug(EELFLoggerDelegate.debugLogger, "Finished addFunctionsTOGlobalRole");
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "addFunctionsTOGlobalRole: Failed", e);
- throw e;
- }
- }
-
- private void addRoleFunctionsToGlobalRoleInExternalSystem(RoleFunction addFunction, Role globalRole,
- ObjectMapper mapper, EPApp app, EPApp portalAppInfo) throws Exception {
- try {
- logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addRoleFunctionsToGlobalRoleInExternalSystem");
- ExternalAccessRolePerms extAddRolePerms = null;
- ExternalAccessPerms extAddPerms = null;
- HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
- String code = "";
- String type = "";
- String action = "";
- if (addFunction.getCode().contains(FUNCTION_PIPE)) {
- code = EcompPortalUtils.getFunctionCode(addFunction.getCode());
- type = getFunctionCodeType(addFunction.getCode());
- action = getFunctionCodeAction(addFunction.getCode());
- } else {
- code = addFunction.getCode();
- type = addFunction.getCode().contains("menu") ? "menu" : "url";
- action = "*";
- }
- extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, code, action);
- extAddRolePerms = new ExternalAccessRolePerms(extAddPerms, portalAppInfo.getNameSpace() + "." + globalRole
- .getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
- String updateRolePerms = mapper.writeValueAsString(extAddRolePerms);
- HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
- logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} ",
- CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
- ResponseEntity<String> addResponse = template.exchange(
- SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
- HttpMethod.POST, entity, String.class);
- if (addResponse.getStatusCode().value() != 201) {
- logger.debug(EELFLoggerDelegate.debugLogger,
- "addRoleFunctionsInExternalSystem: While adding permission to the role in External Auth system something went wrong! due to {} and statuscode: {}",
- addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
- } else {
- logger.debug(EELFLoggerDelegate.debugLogger,
- "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system and status code: {} ",
- addResponse.getStatusCode().value());
- }
- logger.debug(EELFLoggerDelegate.debugLogger, "Finished addRoleFunctionsToGlobalRoleInExternalSystem");
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionsToGlobalRoleInExternalSystem: Failed", e);
- throw e;
- }
- }
-
- private boolean addRoleFuncExtSysRestAPI(ObjectMapper addPermsMapper, ExternalAccessRolePerms extAddRolePerms,
- HttpHeaders headers) throws JsonProcessingException {
- boolean response;
- String updateRolePerms = addPermsMapper.writeValueAsString(extAddRolePerms);
- HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
- logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} for POST: {} ",
- CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
- ResponseEntity<String> addResponse = template.exchange(
- SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
- HttpMethod.POST, entity, String.class);
- if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 409) {
- response = false;
- logger.debug(EELFLoggerDelegate.debugLogger,
- "addRoleFunctionsInExternalSystem: While adding permission to the role in External Auth system something went wrong! due to {} and statuscode: {}",
- addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
- } else {
- response = true;
- logger.debug(EELFLoggerDelegate.debugLogger,
- "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ",
- updateRolePerms, addResponse.getStatusCode().value());
- }
- return response;
- }
-
- /**
- *
- * It converts list of functions in updateExtRole parameter to the RoleFunction object
- *
- * @param updateExtRole
- * @return list of functions
- */
- @SuppressWarnings("unchecked")
- private List<RoleFunction> convertSetToListOfRoleFunctions(Role updateExtRole) {
- Set<RoleFunction> roleFunctionSetList = updateExtRole.getRoleFunctions();
- List<RoleFunction> roleFunctionList = new ArrayList<>();
- ObjectMapper roleFuncMapper = new ObjectMapper();
- Iterator<RoleFunction> itetaror = roleFunctionSetList.iterator();
- while (itetaror.hasNext()) {
- Object nextValue = itetaror.next();
- RoleFunction roleFunction = roleFuncMapper.convertValue(nextValue, RoleFunction.class);
- roleFunctionList.add(roleFunction);
- }
- return roleFunctionList.stream().distinct().collect(Collectors.toList());
- }
-
- /**
- * It delete permissions/functions in the external auth system
- *
- * @param perm
- * @param permMapper
- * @param name
- * @param headers
- * @throws JsonProcessingException
- * @throws Exception
- */
- private void removePermForRole(ExternalAccessPerms perm, ObjectMapper permMapper, String name, HttpHeaders headers)
- throws ExternalAuthSystemException, JsonProcessingException {
- ExternalAccessRolePerms extAccessRolePerms = new ExternalAccessRolePerms(perm, name);
- String permDetails = permMapper.writeValueAsString(extAccessRolePerms);
- try {
- HttpEntity<String> deleteEntity = new HttpEntity<>(permDetails, headers);
- logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: {} for DELETE: {} ",
- CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, permDetails);
- ResponseEntity<String> deletePermResponse =
- template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
- + "role/" + name + "/perm", HttpMethod.DELETE, deleteEntity, String.class);
- if (deletePermResponse.getStatusCode().value() != 200) {
- throw new ExternalAuthSystemException(deletePermResponse.getBody());
- }
- logger.debug(EELFLoggerDelegate.debugLogger,
- "removePermForRole: Finished deleting permission to role in External Auth system: {} and status code: {}",
- permDetails, deletePermResponse.getStatusCode().value());
- } catch (Exception e) {
- if (e.getMessage().contains("404")) {
- logger.error(EELFLoggerDelegate.errorLogger, "Failed to add role for DELETE request: {} due to {}",
- permDetails, e.getMessage());
- } else {
- throw e;
- }
- }
- }
-
- /**
- * It will create new role in the External Auth System
- *
- * @param newRole
- * @param app
- * @return true if successfully added in the system else false
- * @throws Exception If fails to add role in the system
- */
- private void addNewRoleInExternalSystem(List<EPRole> newRole, EPApp app)
- throws Exception, HttpClientErrorException {
- try {
- HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
- ObjectMapper mapper = new ObjectMapper();
- String addNewRole = "";
- ExternalAccessRole extRole = new ExternalAccessRole();
- extRole.setName(app.getNameSpace() + "." + newRole.get(0).getName()
- .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
- extRole.setDescription(String.valueOf(newRole.get(0).getName()));
- addNewRole = mapper.writeValueAsString(extRole);
- HttpEntity<String> postEntity = new HttpEntity<>(addNewRole, headers);
- logger.debug(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: {} for POST: {} ",
- CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addNewRole);
- ResponseEntity<String> addNewRoleInExternalSystem = template.exchange(
- SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
- HttpMethod.POST, postEntity, String.class);
- if (addNewRoleInExternalSystem.getStatusCode().value() == 201) {
- logger.debug(EELFLoggerDelegate.debugLogger,
- "addNewRoleInExternalSystem: Finished adding into External Auth system for POST: {} and status code: {}",
- addNewRole, addNewRoleInExternalSystem.getStatusCode().value());
- }
- } catch (HttpClientErrorException ht) {
- dataAccessService.deleteDomainObjects(EPRole.class, " role_id = " + newRole.get(0).getId(), null);
- logger.error(EELFLoggerDelegate.debugLogger,
- "addNewRoleInExternalSystem: Failed to add in External Auth system and status code: {}", ht);
- throw new HttpClientErrorException(ht.getStatusCode());
- }
- }
-
- /**
- *
- * It updates existing role in the External Auth System
- *
- * @param addRole It Contains role information
- * @param app
- * @return string which is formatted to match with the external auth system
- * @throws JsonProcessingException
- */
- private String updateExistingRoleInExternalSystem(Role addRole, EPApp app) throws JsonProcessingException {
- ObjectMapper mapper = new ObjectMapper();
- String addNewRole = "";
- ExternalAccessRole extRole = new ExternalAccessRole();
- extRole.setName(app.getNameSpace() + "." + addRole.getName()
- .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
- extRole.setDescription(String.valueOf(addRole.getName()));
- addNewRole = mapper.writeValueAsString(extRole);
- return addNewRole;
- }
-
- /**
- * It create a role in the external auth system and then in our local
- *
- * @param addRoleInDB
- * @param app
- * @return true else false
- * @throws Exception
- */
- @SuppressWarnings("unchecked")
- @Transactional(rollbackFor = Exception.class)
- public boolean addRoleInEcompDB(Role addRoleInDB, EPApp app) throws Exception {
- boolean result = false;
- EPRole epRole = null;
- Set<RoleFunction> roleFunctionList = addRoleInDB.getRoleFunctions();
- List<RoleFunction> roleFunctionListNew = new ArrayList<>();
- ObjectMapper mapper = new ObjectMapper();
- Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
- while (itetaror.hasNext()) {
- Object nextValue = itetaror.next();
- RoleFunction roleFunction = mapper.convertValue(nextValue, RoleFunction.class);
- roleFunctionListNew.add(roleFunction);
- }
- List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct().collect(Collectors.toList());
- try {
- if (addRoleInDB.getId() == null) { // check if it is new role
- if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
- checkIfRoleExitsInExternalSystem(addRoleInDB, app);
- }
- EPRole epRoleNew = new EPRole();
- epRoleNew.setActive(addRoleInDB.getActive());
- epRoleNew.setName(addRoleInDB.getName());
- epRoleNew.setPriority(addRoleInDB.getPriority());
- if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
- epRoleNew.setAppId(null);
- } else {
- epRoleNew.setAppId(app.getId());
- }
- dataAccessService.saveDomainObject(epRoleNew, null);
- List<EPRole> getRoleCreated = null;
- final Map<String, String> epAppRoleParams = new HashMap<>();
- final Map<String, String> epAppPortalRoleParams = new HashMap<>();
- if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
- epAppRoleParams.put("appId", String.valueOf(app.getId()));
- epAppRoleParams.put(APP_ROLE_NAME_PARAM, addRoleInDB.getName());
- List<EPRole> roleCreated = dataAccessService
- .executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, epAppRoleParams, null);
- EPRole epUpdateRole = roleCreated.get(0);
- epUpdateRole.setAppRoleId(epUpdateRole.getId());
- dataAccessService.saveDomainObject(epUpdateRole, null);
- getRoleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
- epAppRoleParams, null);
- } else {
- epAppPortalRoleParams.put(APP_ROLE_NAME_PARAM, addRoleInDB.getName());
- getRoleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY,
- epAppPortalRoleParams, null);
- }
- // Add role in External Auth system
- if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
- addNewRoleInExternalSystem(getRoleCreated, app);
- }
- result = true;
- } else { // if role already exists then update it
- EPRole globalRole = null;
- List<EPRole> applicationRoles;
- List<EPRole> globalRoleList = getGlobalRolesOfPortal();
- boolean isGlobalRole = false;
- if (!globalRoleList.isEmpty()) {
- EPRole role = globalRoleList.stream().filter(x -> addRoleInDB.getId().equals(x.getId())).findAny()
- .orElse(null);
- if (role != null) {
- globalRole = role;
- isGlobalRole = true;
- }
- }
- if (app.getId().equals(PortalConstants.PORTAL_APP_ID)
- || (globalRole != null && app.getId() != globalRole.getAppId())) {
- applicationRoles = getPortalAppRoleInfo(addRoleInDB.getId());
- } else {
- applicationRoles = getPartnerAppRoleInfo(addRoleInDB.getId(), app);
- }
- if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
- updateRoleInExternalSystem(addRoleInDB, app, isGlobalRole);
- // Add all user to the re-named role in external auth system
- if (!applicationRoles.isEmpty()
- && !addRoleInDB.getName().equals(applicationRoles.get(0).getName())) {
- bulkUploadUsersSingleRole(app.getUebKey(), applicationRoles.get(0).getId(),
- addRoleInDB.getName());
- }
- }
- deleteRoleFunction(app, applicationRoles);
- if (!applicationRoles.isEmpty()) {
- epRole = applicationRoles.get(0);
- epRole.setName(addRoleInDB.getName());
- epRole.setPriority(addRoleInDB.getPriority());
- epRole.setActive(addRoleInDB.getActive());
- if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
- epRole.setAppId(null);
- epRole.setAppRoleId(null);
- } else if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)
- && applicationRoles.get(0).getAppRoleId() == null) {
- epRole.setAppRoleId(epRole.getId());
- }
- dataAccessService.saveDomainObject(epRole, null);
- }
- Long roleAppId = null;
- if (globalRole != null && !app.getId().equals(globalRole.getAppId()))
- roleAppId = PortalConstants.PORTAL_APP_ID;
- saveRoleFunction(listWithoutDuplicates, app, applicationRoles, roleAppId);
- result = true;
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "addRoleInEcompDB is failed", e);
- throw e;
- }
- return result;
- }
-
- /**
- *
- * It validates whether role exists in external auth system
- *
- * @param checkRole
- * @param app
- * @throws Exception If role exits
- */
- private void checkIfRoleExitsInExternalSystem(Role checkRole, EPApp app) throws Exception {
- getNameSpaceIfExists(app);
- HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
- String roleName = app.getNameSpace() + "." + checkRole.getName()
- .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_");
- HttpEntity<String> checkRoleEntity = new HttpEntity<>(headers);
- logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRoleExitsInExternalSystem: {} ",
- CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
- ResponseEntity<String> checkRoleInExternalSystem =
- template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
- + "roles/" + roleName, HttpMethod.GET, checkRoleEntity, String.class);
- if (!checkRoleInExternalSystem.getBody().equals(IS_EMPTY_JSON_STRING)) {
- logger.debug(
- "checkIfRoleExitsInExternalSystem: Role already exists in external system {} and status code: {} ",
- checkRoleInExternalSystem.getBody(), checkRoleInExternalSystem.getStatusCode().value());
- throw new ExternalAuthSystemException(" Role already exists in external system");
- }
- }
-
- /**
- * It saves list of functions to the role in portal
- *
- * @param roleFunctionListNew
- * @param app
- * @param applicationRoles
- * @throws Exception
- */
- @SuppressWarnings("unchecked")
- private void saveRoleFunction(List<RoleFunction> roleFunctionListNew, EPApp app, List<EPRole> applicationRoles,
- Long roleAppId) throws Exception {
- final Map<String, String> getAppFunctionParams = new HashMap<>();
- for (RoleFunction roleFunc : roleFunctionListNew) {
- String code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
- EPAppRoleFunction appRoleFunc = new EPAppRoleFunction();
- appRoleFunc.setAppId(app.getId());
- appRoleFunc.setRoleId(applicationRoles.get(0).getId());
- appRoleFunc.setRoleAppId(String.valueOf(roleAppId));
- getAppFunctionParams.put("appId", String.valueOf(app.getId()));
- getAppFunctionParams.put(FUNCTION_CODE_PARAMS, roleFunc.getCode());
- // query to check if function code has pipes
- List<CentralV2RoleFunction> roleFunction =
- dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null);
- if (roleFunction.isEmpty()) {
- getAppFunctionParams.put(FUNCTION_CODE_PARAMS, code);
- roleFunction = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null);
- }
- if (roleFunction.size() > 1) {
- CentralV2RoleFunction getExactFunctionCode = appFunctionListFilter(code, roleFunction);
- appRoleFunc.setCode(getExactFunctionCode.getCode());
- } else {
- appRoleFunc.setCode(roleFunction.get(0).getCode());
- }
- dataAccessService.saveDomainObject(appRoleFunc, null);
- }
- }
-
- /**
- *
- * It filters the app functions which starts with similar name in the result set
- *
- * @param roleFunc
- * @param roleFunction
- * @return CentralRoleFunction
- */
- private CentralV2RoleFunction appFunctionListFilter(String roleFuncCode, List<CentralV2RoleFunction> roleFunction) {
- final Map<String, CentralV2RoleFunction> appFunctionsFilter = new HashMap<>();
- final Map<String, CentralV2RoleFunction> appFunctionsFilterPipes = new HashMap<>();
- CentralV2RoleFunction getExactFunctionCode = null;
- for (CentralV2RoleFunction cenRoleFunction : roleFunction) {
- appFunctionsFilter.put(cenRoleFunction.getCode(), cenRoleFunction);
- appFunctionsFilterPipes.put(EcompPortalUtils.getFunctionCode(cenRoleFunction.getCode()), cenRoleFunction);
- }
- getExactFunctionCode = appFunctionsFilter.get(roleFuncCode);
- if (getExactFunctionCode == null) {
- getExactFunctionCode = appFunctionsFilterPipes.get(roleFuncCode);
- }
- return getExactFunctionCode;
- }
-
- /**
- * It deletes all EPAppRoleFunction records in the portal
- *
- * @param app
- * @param role
- */
- @SuppressWarnings("unchecked")
- private void deleteRoleFunction(EPApp app, List<EPRole> role) {
- final Map<String, Long> appRoleFuncsParams = new HashMap<>();
- appRoleFuncsParams.put("appId", app.getId());
- appRoleFuncsParams.put("roleId", role.get(0).getId());
- List<EPAppRoleFunction> appRoleFunctionList =
- dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null);
- if (!appRoleFunctionList.isEmpty()) {
- for (EPAppRoleFunction approleFunction : appRoleFunctionList) {
- dataAccessService.deleteDomainObject(approleFunction, null);
- }
- }
- }
-
- @Override
- @SuppressWarnings("unchecked")
- public List<EPUser> getUser(String loginId) throws InvalidUserException {
- final Map<String, String> userParams = new HashMap<>();
- userParams.put("org_user_id", loginId);
- List<EPUser> userList = dataAccessService.executeNamedQuery("getEPUserByOrgUserId", userParams, null);
- if (userList.isEmpty()) {
- throw new InvalidUserException("User not found");
- }
- return userList;
- }
-
- @Override
- public String getV2UserWithRoles(String loginId, String uebkey) throws Exception {
- final Map<String, String> params = new HashMap<>();
- List<EPUser> userList = null;
- CentralV2User cenV2User = null;
- String result = null;
- try {
- params.put("orgUserIdValue", loginId);
- List<EPApp> appList = getApp(uebkey);
- if (!appList.isEmpty()) {
- userList = getUser(loginId);
- if (!userList.isEmpty()) {
- ObjectMapper mapper = new ObjectMapper();
- cenV2User = getV2UserAppRoles(loginId, uebkey);
- result = mapper.writeValueAsString(cenV2User);
- } else if (userList.isEmpty()) {
- throw new InvalidUserException("User not found");
- }
- } else {
- throw new InactiveApplicationException("Application not found");
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getUser: failed", e);
- throw e;
- }
- return result;
- }
-
- @Override
- public List<CentralV2Role> getRolesForApp(String uebkey) throws Exception {
- logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Entering into getRolesForApp");
- List<CentralV2Role> roleList = new ArrayList<>();
- final Map<String, Long> params = new HashMap<>();
- try {
- List<EPApp> app = getApp(uebkey);
- List<EPRole> appRolesList = getAppRoles(app.get(0).getId());
- roleList = createCentralRoleObject(app, appRolesList, roleList, params);
- if (app.get(0).getId() != PortalConstants.PORTAL_APP_ID) {
- List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
- List<EPRole> globalRolesList = getGlobalRolesOfPortal();
- List<CentralV2Role> portalsGlobalRolesFinlaList = new ArrayList<>();
- if (!globalRolesList.isEmpty()) {
- for (EPRole eprole : globalRolesList) {
- CentralV2Role cenRole = convertRoleToCentralV2Role(eprole);
- portalsGlobalRolesFinlaList.add(cenRole);
- }
- roleList.addAll(globalRoleList);
- for (CentralV2Role role : portalsGlobalRolesFinlaList) {
- CentralV2Role result =
- roleList.stream().filter(x -> role.getId().equals(x.getId())).findAny().orElse(null);
- if (result == null)
- roleList.add(role);
- }
- } else {
- for (EPRole role : globalRolesList) {
- CentralV2Role cenRole = convertRoleToCentralV2Role(role);
- roleList.add(cenRole);
- }
- }
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getRolesForApp: Failed!", e);
- throw e;
- }
- logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Finished!");
- return roleList.stream().distinct().collect(Collectors.toList());
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public List<CentralV2RoleFunction> getRoleFuncList(String uebkey) throws Exception {
- EPApp app = getApp(uebkey).get(0);
- List<CentralV2RoleFunction> finalRoleList = new ArrayList<>();
- final Map<String, Long> params = new HashMap<>();
- params.put(APP_ID, app.getId());
- List<CentralV2RoleFunction> getRoleFuncList =
- dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null);
- for (CentralV2RoleFunction roleFuncItem : getRoleFuncList) {
- String code = EcompPortalUtils.getFunctionCode(roleFuncItem.getCode());
- String type = "";
- if (roleFuncItem.getCode().contains("|"))
- type = EcompPortalUtils.getFunctionType(roleFuncItem.getCode());
- else
- type = getFunctionCodeType(roleFuncItem.getCode());
- String action = getFunctionCodeAction(roleFuncItem.getCode());
- roleFuncItem.setCode(EPUserUtils.decodeFunctionCode(code));
- roleFuncItem.setType(type);
- roleFuncItem.setAction(action);
- finalRoleList.add(roleFuncItem);
- }
- return finalRoleList;
- }
-
- @Override
- public String getFunctionCodeAction(String roleFuncItem) {
- return (!roleFuncItem.contains(FUNCTION_PIPE)) ? "*" : EcompPortalUtils.getFunctionAction(roleFuncItem);
- }
-
- @Override
- public String getFunctionCodeType(String roleFuncItem) {
- String type = null;
- if ((roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))
- || (!roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))) {
- type = "menu";
- } else if (checkIfCodeHasNoPipesAndHasTypeUrl(roleFuncItem) || checkIfCodeHasPipesAndHasTypeUrl(roleFuncItem)
- || checkIfCodeHasNoPipesAndHasNoTypeUrl(roleFuncItem)) {
- type = "url";
- } else if (roleFuncItem.contains(FUNCTION_PIPE)
- && (!roleFuncItem.contains("menu") || roleFuncItem.contains("url"))) {
- type = EcompPortalUtils.getFunctionType(roleFuncItem);
- }
- return type;
- }
-
- /**
- *
- * It check whether function code has no pipes and no url string in it
- *
- * @param roleFuncItem
- * @return true or false
- */
- private boolean checkIfCodeHasNoPipesAndHasNoTypeUrl(String roleFuncItem) {
- return !roleFuncItem.contains(FUNCTION_PIPE) && !roleFuncItem.contains("url");
- }
-
- /**
- *
- * It check whether function code has pipes and url string in it
- *
- * @param roleFuncItem
- * @return true or false
- */
- private boolean checkIfCodeHasPipesAndHasTypeUrl(String roleFuncItem) {
- return roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
- }
-
- /**
- *
- * It check whether function code has no pipes and has url string in it
- *
- * @param roleFuncItem
- * @return true or false
- */
- private boolean checkIfCodeHasNoPipesAndHasTypeUrl(String roleFuncItem) {
- return !roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
- }
-
- /**
- * It returns user detail information which is deep copy of EPUser.class object
- *
- * @param userInfo
- * @param userAppSet
- * @param app
- * @return
- * @throws Exception
- */
- @SuppressWarnings("unchecked")
- private CentralV2User createEPUser(EPUser userInfo, Set<EPUserApp> userAppSet, EPApp app) throws Exception {
- final Map<String, Long> params = new HashMap<>();
- CentralV2User userAppList = new CentralV2User();
- CentralV2User user1 = null;
- final Map<String, Long> params1 = new HashMap<>();
- List<EPRole> globalRoleList = new ArrayList<>();
- try {
- if (app.getId() != PortalConstants.PORTAL_APP_ID) {
- params1.put("userId", userInfo.getId());
- params1.put("appId", app.getId());
- globalRoleList = dataAccessService.executeNamedQuery("userAppGlobalRoles", params1, null);
- }
- userAppList.setUserApps(new TreeSet<CentralV2UserApp>());
- for (EPUserApp userApp : userAppSet) {
- if (userApp.getRole().getActive()) {
- EPApp epApp = userApp.getApp();
- String globalRole = userApp.getRole().getName().toLowerCase();
- if (((epApp.getId().equals(app.getId()))
- && (!userApp.getRole().getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)))
- || ((epApp.getId().equals(PortalConstants.PORTAL_APP_ID))
- && (globalRole.toLowerCase().startsWith("global_")))) {
- CentralV2UserApp cua = new CentralV2UserApp();
- cua.setUserId(null);
- CentralApp cenApp = new CentralApp(1L, epApp.getCreated(), epApp.getModified(),
- epApp.getCreatedId(), epApp.getModifiedId(), epApp.getRowNum(), epApp.getName(),
- epApp.getImageUrl(), epApp.getDescription(), epApp.getNotes(), epApp.getUrl(),
- epApp.getAlternateUrl(), epApp.getAppRestEndpoint(), epApp.getMlAppName(),
- epApp.getMlAppAdminId(), String.valueOf(epApp.getMotsId()), epApp.getAppPassword(),
- String.valueOf(epApp.getOpen()), String.valueOf(epApp.getEnabled()),
- epApp.getThumbnail(), epApp.getUsername(), epApp.getUebKey(), epApp.getUebSecret(),
- epApp.getUebTopicName());
- cenApp.setAppPassword(EPCommonSystemProperties.APP_DISPLAY_PASSWORD);
- cua.setApp(cenApp);
- Long appId = null;
- if (globalRole.toLowerCase().startsWith("global_")
- && epApp.getId().equals(PortalConstants.PORTAL_APP_ID)
- && !epApp.getId().equals(app.getId())) {
- appId = app.getId();
- EPRole result = null;
- if (globalRoleList.size() > 0)
- result = globalRoleList.stream()
- .filter(x -> userApp.getRole().getId().equals(x.getId())).findAny()
- .orElse(null);
- if (result == null)
- continue;
- } else {
- appId = userApp.getApp().getId();
- }
- params.put("roleId", userApp.getRole().getId());
- params.put(APP_ID, appId);
- List<CentralV2RoleFunction> appRoleFunctionList =
- dataAccessService.executeNamedQuery("getAppRoleFunctionList", params, null);
- SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>();
- for (CentralV2RoleFunction roleFunc : appRoleFunctionList) {
- String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
- String type = getFunctionCodeType(roleFunc.getCode());
- String action = getFunctionCodeAction(roleFunc.getCode());
- CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(roleFunc.getId(),
- functionCode, roleFunc.getName(), null, type, action, null);
- roleFunctionSet.add(cenRoleFunc);
- }
- Long userRoleId = null;
- if (globalRole.toLowerCase().startsWith("global_")
- || epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) {
- userRoleId = userApp.getRole().getId();
- } else {
- userRoleId = userApp.getRole().getAppRoleId();
- }
- CentralV2Role cenRole = new CentralV2Role(userRoleId, userApp.getRole().getCreated(),
- userApp.getRole().getModified(), userApp.getRole().getCreatedId(),
- userApp.getRole().getModifiedId(), userApp.getRole().getRowNum(),
- userApp.getRole().getName(), userApp.getRole().getActive(),
- userApp.getRole().getPriority(), roleFunctionSet, null, null);
- cua.setRole(cenRole);
- userAppList.getUserApps().add(cua);
- }
- }
- }
- user1 = new CentralV2User(null, userInfo.getCreated(), userInfo.getModified(), userInfo.getCreatedId(),
- userInfo.getModifiedId(), userInfo.getRowNum(), userInfo.getOrgId(), userInfo.getManagerId(),
- userInfo.getFirstName(), userInfo.getMiddleInitial(), userInfo.getLastName(), userInfo.getPhone(),
- userInfo.getFax(), userInfo.getCellular(), userInfo.getEmail(), userInfo.getAddressId(),
- userInfo.getAlertMethodCd(), userInfo.getHrid(), userInfo.getOrgUserId(), userInfo.getOrgCode(),
- userInfo.getAddress1(), userInfo.getAddress2(), userInfo.getCity(), userInfo.getState(),
- userInfo.getZipCode(), userInfo.getCountry(), userInfo.getOrgManagerUserId(),
- userInfo.getLocationClli(), userInfo.getBusinessCountryCode(), userInfo.getBusinessCountryName(),
- userInfo.getBusinessUnit(), userInfo.getBusinessUnitName(), userInfo.getDepartment(),
- userInfo.getDepartmentName(), userInfo.getCompanyCode(), userInfo.getCompany(),
- userInfo.getZipCodeSuffix(), userInfo.getJobTitle(), userInfo.getCommandChain(),
- userInfo.getSiloStatus(), userInfo.getCostCenter(), userInfo.getFinancialLocCode(),
- userInfo.getLoginId(), userInfo.getLoginPwd(), userInfo.getLastLoginDate(), userInfo.getActive(),
- userInfo.getInternal(), userInfo.getSelectedProfileId(), userInfo.getTimeZoneId(),
- userInfo.isOnline(), userInfo.getChatId(), userAppList.getUserApps(), null);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "createEPUser: createEPUser failed", e);
- throw e;
- }
- return user1;
- }
-
- @Override
- public CentralV2Role getRoleInfo(Long roleId, String uebkey) throws Exception {
- final Map<String, Long> params = new HashMap<>();
- List<CentralV2Role> roleList = new ArrayList<>();
- CentralV2Role cenRole = new CentralV2Role();
- List<EPRole> roleInfo = null;
- List<EPApp> app = null;
- try {
- app = getApp(uebkey);
- if (app.isEmpty()) {
- throw new InactiveApplicationException("Application not found");
- }
- if (app.get(0).getId() != PortalConstants.PORTAL_APP_ID) {
- List<EPRole> globalRoleList = new ArrayList<>();
- globalRoleList = getGlobalRolesOfPortal();
- if (globalRoleList.size() > 0) {
- EPRole result =
- globalRoleList.stream().filter(x -> roleId.equals(x.getId())).findAny().orElse(null);
- if (result != null)
- return getGlobalRoleForRequestedApp(app.get(0).getId(), roleId);
- }
- }
- if (app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
- roleInfo = getPortalAppRoleInfo(roleId);
- } else {
- roleInfo = getPartnerAppRoleInfo(roleId, app.get(0));
- }
- roleList = createCentralRoleObject(app, roleInfo, roleList, params);
- if (roleList.isEmpty()) {
- return cenRole;
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo: failed", e);
- throw e;
- }
- return roleList.get(0);
- }
-
- @SuppressWarnings("unchecked")
- private List<EPRole> getPartnerAppRoleInfo(Long roleId, EPApp app) {
- List<EPRole> roleInfo;
- final Map<String, Long> getPartnerAppRoleParams = new HashMap<>();
- getPartnerAppRoleParams.put("appRoleId", roleId);
- getPartnerAppRoleParams.put("appId", app.getId());
- roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams, null);
- if (roleInfo.isEmpty()) {
- getPartnerAppRoleParams.put("appRoleId", roleId);
- roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleById", getPartnerAppRoleParams, null);
- }
- return roleInfo;
- }
-
- @SuppressWarnings("unchecked")
- private List<EPRole> getPortalAppRoleInfo(Long roleId) {
- List<EPRole> roleInfo;
- final Map<String, Long> getPortalAppRoleParams = new HashMap<>();
- getPortalAppRoleParams.put("roleId", roleId);
- roleInfo = dataAccessService.executeNamedQuery("getPortalAppRoleByRoleId", getPortalAppRoleParams, null);
- return roleInfo;
- }
-
- /**
- *
- * It returns list of app roles along with role functions and which went through deep copy
- *
- * @param app
- * @param roleInfo
- * @param roleList
- * @param params
- * @return
- * @throws DecoderException
- */
- @SuppressWarnings("unchecked")
- @Override
- public List<CentralV2Role> createCentralRoleObject(List<EPApp> app, List<EPRole> roleInfo,
- List<CentralV2Role> roleList, Map<String, Long> params) throws RoleFunctionException {
- for (EPRole role : roleInfo) {
- params.put("roleId", role.getId());
- params.put(APP_ID, app.get(0).getId());
- List<CentralV2RoleFunction> cenRoleFuncList =
- dataAccessService.executeNamedQuery("getAppRoleFunctionList", params, null);
- SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>();
- for (CentralV2RoleFunction roleFunc : cenRoleFuncList) {
- String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
- functionCode = EPUserUtils.decodeFunctionCode(functionCode);
- String type = getFunctionCodeType(roleFunc.getCode());
- String action = getFunctionCodeAction(roleFunc.getCode());
- CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(role.getId(), functionCode,
- roleFunc.getName(), null, type, action, null);
- roleFunctionSet.add(cenRoleFunc);
- }
- SortedSet<CentralV2Role> childRoles = new TreeSet<>();
- SortedSet<CentralV2Role> parentRoles = new TreeSet<>();
- CentralV2Role cenRole = null;
- if (role.getAppRoleId() == null) {
- cenRole = new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
- role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
- roleFunctionSet, childRoles, parentRoles);
- } else {
- cenRole = new CentralV2Role(role.getAppRoleId(), role.getCreated(), role.getModified(),
- role.getCreatedId(), role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(),
- role.getPriority(), roleFunctionSet, childRoles, parentRoles);
- }
- roleList.add(cenRole);
- }
- return roleList;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public CentralV2RoleFunction getRoleFunction(String functionCode, String uebkey) throws Exception {
- String code = EcompPortalUtils.getFunctionCode(functionCode);
- String encodedCode = encodeFunctionCode(code);
- CentralV2RoleFunction roleFunc = null;
- EPApp app = getApp(uebkey).get(0);
- List<CentralV2RoleFunction> getRoleFuncList = null;
- final Map<String, String> params = new HashMap<>();
- try {
- params.put(FUNCTION_CODE_PARAMS, functionCode);
- params.put(APP_ID, String.valueOf(app.getId()));
- getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
- if (getRoleFuncList.isEmpty()) {
- params.put(FUNCTION_CODE_PARAMS, encodedCode);
- getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
- if (getRoleFuncList.isEmpty()) {
- return roleFunc;
- }
- }
- if (getRoleFuncList.size() > 1) {
- CentralV2RoleFunction cenV2RoleFunction = appFunctionListFilter(encodedCode, getRoleFuncList);
- if (cenV2RoleFunction == null)
- return roleFunc;
- roleFunc = checkIfPipesExitsInFunctionCode(cenV2RoleFunction);
- } else {
- // Check even if single record have pipes
- if (!getRoleFuncList.isEmpty() && getRoleFuncList.get(0).getCode().contains(FUNCTION_PIPE)) {
- roleFunc = checkIfPipesExitsInFunctionCode(getRoleFuncList.get(0));
- } else {
- roleFunc = getRoleFuncList.get(0);
- }
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction: failed", e);
- throw e;
- }
- return roleFunc;
- }
-
- private CentralV2RoleFunction checkIfPipesExitsInFunctionCode(CentralV2RoleFunction getRoleFuncList) {
- CentralV2RoleFunction roleFunc;
- String functionCodeFormat = getRoleFuncList.getCode();
- if (functionCodeFormat.contains(FUNCTION_PIPE)) {
- String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(functionCodeFormat);
- String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(functionCodeFormat);
- String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(functionCodeFormat);
- roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), newfunctionCodeFormat,
- getRoleFuncList.getName(), getRoleFuncList.getAppId(), newfunctionTypeFormat,
- newfunctionActionFormat, getRoleFuncList.getEditUrl());
- } else {
- roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), functionCodeFormat, getRoleFuncList.getName(),
- getRoleFuncList.getAppId(), getRoleFuncList.getEditUrl());
- }
- return roleFunc;
- }
-
- @Override
- public boolean saveCentralRoleFunction(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
- throws Exception {
- boolean saveOrUpdateFunction = false;
- try {
- domainCentralRoleFunction.setCode(encodeFunctionCode(domainCentralRoleFunction.getCode()));
- final Map<String, String> functionParams = new HashMap<>();
- functionParams.put("appId", String.valueOf(app.getId()));
- if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
- addRoleFunctionInExternalSystem(domainCentralRoleFunction, app);
- }
- if (domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null) {
- domainCentralRoleFunction.setCode(domainCentralRoleFunction.getType() + FUNCTION_PIPE
- + domainCentralRoleFunction.getCode() + FUNCTION_PIPE + domainCentralRoleFunction.getAction());
- }
- domainCentralRoleFunction.setAppId(app.getId());
- dataAccessService.saveDomainObject(domainCentralRoleFunction, null);
- saveOrUpdateFunction = true;
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "saveCentralRoleFunction: failed", e);
- throw e;
- }
- return saveOrUpdateFunction;
- }
-
- /**
- * It creates application permission in external auth system
- *
- * @param domainCentralRoleFunction
- * @param app
- * @throws Exception
- */
- private void addRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
- throws Exception {
- ObjectMapper mapper = new ObjectMapper();
- ExternalAccessPerms extPerms = new ExternalAccessPerms();
- HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
- String type = "";
- String instance = "";
- String action = "";
- if ((domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null)
- || domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)) {
- type = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)
- ? EcompPortalUtils.getFunctionType(domainCentralRoleFunction.getCode())
- : domainCentralRoleFunction.getType();
- instance = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)
- ? EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode())
- : domainCentralRoleFunction.getCode();
- action = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)
- ? EcompPortalUtils.getFunctionAction(domainCentralRoleFunction.getCode())
- : domainCentralRoleFunction.getAction();
- } else {
- type = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url";
- instance = domainCentralRoleFunction.getCode();
- action = "*";
- }
- // get Permissions from External Auth System
- JSONArray extPermsList = getExtAuthPermissions(app);
- List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPermsList);
- String requestedPerm = type + FUNCTION_PIPE + instance + FUNCTION_PIPE + action;
- boolean checkIfFunctionsExits =
- permsDetailList.stream().anyMatch(permsDetail -> permsDetail.getInstance().equals(requestedPerm));
- if (!checkIfFunctionsExits) {
- try {
- extPerms.setAction(action);
- extPerms.setInstance(instance);
- extPerms.setType(app.getNameSpace() + "." + type);
- extPerms.setDescription(domainCentralRoleFunction.getName());
- String addFunction = mapper.writeValueAsString(extPerms);
- HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
- logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for POST: {}",
- CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
- ResponseEntity<String> addPermResponse = template.exchange(
- SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
- HttpMethod.POST, entity, String.class);
- logger.debug(EELFLoggerDelegate.debugLogger,
- "addRoleFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ",
- addPermResponse.getStatusCode().value(), addFunction);
- } catch (HttpClientErrorException e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "HttpClientErrorException - Failed to add function in external central auth system", e);
- EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
- throw e;
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "addRoleFunctionInExternalSystem: Failed to add fucntion in external central auth system", e);
- throw e;
- }
- } else {
- try {
- extPerms.setAction(action);
- extPerms.setInstance(instance);
- extPerms.setType(app.getNameSpace() + "." + type);
- extPerms.setDescription(domainCentralRoleFunction.getName());
- String updateRoleFunction = mapper.writeValueAsString(extPerms);
- HttpEntity<String> entity = new HttpEntity<>(updateRoleFunction, headers);
- logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for PUT: {}",
- CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRoleFunction);
- ResponseEntity<String> updatePermResponse = template.exchange(
- SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
- HttpMethod.PUT, entity, String.class);
- logger.debug(EELFLoggerDelegate.debugLogger,
- "addRoleFunctionInExternalSystem: Finished updating permission in External Auth system {} and response: {} ",
- updateRoleFunction, updatePermResponse.getStatusCode().value());
- } catch (HttpClientErrorException e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "HttpClientErrorException - Failed to add function in external central auth system", e);
- EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
- throw e;
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "addRoleFunctionInExternalSystem: Failed to update function in external central auth system",
- e);
- throw e;
- }
- }
- }
-
- @SuppressWarnings("unchecked")
- @Override
- @Transactional(rollbackFor = Exception.class)
- public boolean deleteCentralRoleFunction(String code, EPApp app) {
- boolean deleteFunctionResponse = false;
- try {
- final Map<String, String> params = new HashMap<>();
- params.put(FUNCTION_CODE_PARAMS, code);
- params.put(APP_ID, String.valueOf(app.getId()));
- List<CentralV2RoleFunction> domainCentralRoleFunction =
- dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
- CentralV2RoleFunction appFunctionCode = appFunctionListFilter(code, domainCentralRoleFunction);
- if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
- deleteRoleFunctionInExternalSystem(appFunctionCode, app);
- // Delete role function dependency records
- deleteAppRoleFunctions(appFunctionCode.getCode(), app);
- }
- dataAccessService.deleteDomainObject(appFunctionCode, null);
- deleteFunctionResponse = true;
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "deleteCentralRoleFunction: failed", e);
- }
- return deleteFunctionResponse;
- }
-
- /**
- * It deletes app function record in portal
- *
- * @param code
- * @param app
- */
- private void deleteAppRoleFunctions(String code, EPApp app) {
- dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
- APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + code + "'", null);
- }
-
- /**
- *
- * It deletes permission in the external auth system
- *
- * @param domainCentralRoleFunction
- * @param app
- * @throws Exception
- */
- private void deleteRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
- throws Exception {
- try {
- ObjectMapper mapper = new ObjectMapper();
- ExternalAccessPerms extPerms = new ExternalAccessPerms();
- String instanceValue = EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode());
- String checkType = getFunctionCodeType(domainCentralRoleFunction.getCode());
- String actionValue = getFunctionCodeAction(domainCentralRoleFunction.getCode());
- HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
- extPerms.setAction(actionValue);
- extPerms.setInstance(instanceValue);
- extPerms.setType(app.getNameSpace() + "." + checkType);
- extPerms.setDescription(domainCentralRoleFunction.getName());
- String deleteRoleFunction = mapper.writeValueAsString(extPerms);
- HttpEntity<String> entity = new HttpEntity<>(deleteRoleFunction, headers);
- logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleFunctionInExternalSystem: {} for DELETE: {} ",
- CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, deleteRoleFunction);
- ResponseEntity<String> delPermResponse =
- template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
- + "perm?force=true", HttpMethod.DELETE, entity, String.class);
- logger.debug(EELFLoggerDelegate.debugLogger,
- "deleteRoleFunctionInExternalSystem: Finished deleting permission in External Auth system {} and status code: {} ",
- deleteRoleFunction, delPermResponse.getStatusCode().value());
- } catch (HttpClientErrorException e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "HttpClientErrorException - Failed to delete functions in External System", e);
- EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
- } catch (Exception e) {
- if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
- logger.debug(EELFLoggerDelegate.debugLogger,
- " deleteRoleFunctionInExternalSystem: It seems like function is already deleted in external central auth system but exists in local DB",
- e.getMessage());
- } else {
- logger.error(EELFLoggerDelegate.errorLogger,
- "deleteRoleFunctionInExternalSystem: Failed to delete functions in External System", e);
- }
- }
- }
-
- @Override
- public ExternalRequestFieldsValidator saveRoleForApplication(Role saveRole, String uebkey) throws Exception {
- boolean response = false;
- String message = "";
- try {
- EPApp app = getApp(uebkey).get(0);
- addRoleInEcompDB(saveRole, app);
- response = true;
- } catch (Exception e) {
- message = e.getMessage();
- logger.error(EELFLoggerDelegate.errorLogger, "saveRoleForApplication failed", e);
- }
- return new ExternalRequestFieldsValidator(response, message);
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public boolean deleteRoleForApplication(String deleteRole, String uebkey) throws Exception {
- Session localSession = sessionFactory.openSession();
- Transaction transaction = null;
- boolean result = false;
- try {
- List<EPRole> epRoleList = null;
- EPApp app = getApp(uebkey).get(0);
- final Map<String, String> deleteRoleParams = new HashMap<>();
- deleteRoleParams.put(APP_ROLE_NAME_PARAM, deleteRole);
- if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
- epRoleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, deleteRoleParams, null);
- } else {
- deleteRoleParams.put(APP_ID, String.valueOf(app.getId()));
- epRoleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
- deleteRoleParams, null);
- }
- if (!epRoleList.isEmpty()) {
- transaction = localSession.beginTransaction();
- // Delete app role functions before deleting role
- deleteRoleFunction(app, epRoleList);
- if (app.getId() == 1) {
- // Delete fn_user_ role
- dataAccessService.deleteDomainObjects(EPUserApp.class,
- APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
- boolean isPortalRequest = false;
- deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest);
- }
- deleteRoleInExternalAuthSystem(epRoleList, app);
- transaction.commit();
- logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: committed the transaction");
- dataAccessService.deleteDomainObject(epRoleList.get(0), null);
- }
- result = true;
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleForApplication: failed", e);
- result = false;
- } finally {
- localSession.close();
- }
- return result;
- }
-
- /**
- *
- * It deletes role for application in external auth system
- *
- * @param epRoleList contains role information
- * @param app contains application information
- * @throws Exception
- */
- private void deleteRoleInExternalAuthSystem(List<EPRole> epRoleList, EPApp app) throws Exception {
- ResponseEntity<String> deleteResponse;
- ResponseEntity<String> res = getNameSpaceIfExists(app);
- if (res.getStatusCode() == HttpStatus.OK) {
- // Delete Role in External System
- String deleteRoleKey = "{\"name\":\"" + app.getNameSpace() + "." + epRoleList.get(0).getName()
- .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_") + "\"}";
- deleteResponse = deleteRoleInExternalSystem(deleteRoleKey);
- if (deleteResponse.getStatusCode().value() != 200 && deleteResponse.getStatusCode().value() != 404) {
- EPLogUtil.logExternalAuthAccessAlarm(logger, deleteResponse.getStatusCode());
- logger.error(EELFLoggerDelegate.errorLogger,
- "deleteRoleForApplication: Failed to delete role in external auth system! due to {} ",
- deleteResponse.getBody());
- }
- logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: about to commit the transaction");
- }
- }
-
- /**
- *
- * It deletes application user role in external auth system
- *
- * @param role
- * @param app
- * @param LoginId
- * @throws Exception
- */
- private void deleteUserRoleInExternalSystem(EPRole role, EPApp app, String LoginId) throws Exception {
- HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
- HttpEntity<String> entity = new HttpEntity<>(headers);
- getNameSpaceIfExists(app);
- logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} ",
- CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
- ResponseEntity<String> getResponse = template.exchange(
- SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
- + LoginId
- + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
- + "/" + app.getNameSpace() + "."
- + role.getName()
- .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
- HttpMethod.GET, entity, String.class);
- logger.debug(EELFLoggerDelegate.debugLogger,
- "deleteUserRoleInExternalSystem: Finished GET user roles from External Auth system and response: {} ",
- getResponse.getBody());
- if (getResponse.getStatusCode().value() != 200) {
- throw new ExternalAuthSystemException(getResponse.getBody());
- }
- String res = getResponse.getBody();
- if (!res.equals(IS_EMPTY_JSON_STRING)) {
- HttpEntity<String> userRoleentity = new HttpEntity<>(headers);
- logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} ",
- CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
- ResponseEntity<String> deleteResponse = template.exchange(
- SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
- + LoginId
- + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
- + "/" + app.getNameSpace() + "."
- + role.getName().replaceAll(
- EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
- HttpMethod.DELETE, userRoleentity, String.class);
- if (deleteResponse.getStatusCode().value() != 200) {
- throw new ExternalAuthSystemException("Failed to delete user role");
- }
- logger.debug(EELFLoggerDelegate.debugLogger,
- "deleteUserRoleInExternalSystem: Finished deleting user role in External Auth system and status code: {} ",
- deleteResponse.getStatusCode().value());
- }
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public List<CentralV2Role> getActiveRoles(String uebkey) throws Exception {
- List<CentralV2Role> roleList = new ArrayList<>();
- try {
- List<EPApp> app = getApp(uebkey);
- final Map<String, Long> params = new HashMap<>();
- // check if portal
- Long appId = null;
- if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
- appId = app.get(0).getId();
- }
- List<Criterion> restrictionsList = new ArrayList<Criterion>();
- Criterion active_ynCrt = Restrictions.eq("active", Boolean.TRUE);
- Criterion appIdCrt;
- if (appId == null)
- appIdCrt = Restrictions.isNull("appId");
- else
- appIdCrt = Restrictions.eq("appId", appId);
- Criterion andCrit = Restrictions.and(active_ynCrt, appIdCrt);
- restrictionsList.add(andCrit);
- List<EPRole> epRole = (List<EPRole>) dataAccessService.getList(EPRole.class, null, restrictionsList, null);
- roleList = createCentralRoleObject(app, epRole, roleList, params);
- List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
- if (globalRoleList.size() > 0)
- roleList.addAll(globalRoleList);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles: failed", e);
- throw e;
- }
- return roleList;
- }
-
- @Override
- @Transactional(rollbackFor = Exception.class)
- public ExternalRequestFieldsValidator deleteDependencyRoleRecord(Long roleId, String uebkey, String LoginId)
- throws Exception {
- Session localSession = sessionFactory.openSession();
- String message = "";
- Transaction transaction = null;
- boolean response = false;
- EPApp app = null;
- try {
- transaction = localSession.beginTransaction();
- List<EPRole> epRoleList = null;
- app = getApp(uebkey).get(0);
- if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
- epRoleList = getPortalAppRoleInfo(roleId);
- } else {
- epRoleList = getPartnerAppRoleInfo(roleId, app);
- }
- if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
- // Delete User Role in External System before deleting role
- deleteUserRoleInExternalSystem(epRoleList.get(0), app, LoginId);
- }
- // Delete user app roles
- dataAccessService.deleteDomainObjects(EPUserApp.class,
- APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
- boolean isPortalRequest = false;
- deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest);
- transaction.commit();
- if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
- // Final call to delete role once all dependencies has been
- // deleted
- deleteRoleInExternalAuthSystem(epRoleList, app);
- }
- dataAccessService.deleteDomainObjects(EPRole.class, " role_id = " + epRoleList.get(0).getId(), null);
- logger.debug(EELFLoggerDelegate.debugLogger, "deleteDependencyRoleRecord: committed the transaction");
- response = true;
- } catch (HttpClientErrorException e) {
- logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord: HttpClientErrorException", e);
- EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
- message = e.getMessage();
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord failed", e);
- EcompPortalUtils.rollbackTransaction(transaction,
- "deleteDependencyRoleRecord rollback, exception = " + e.toString());
- message = e.getMessage();
- } finally {
- localSession.close();
- }
- return new ExternalRequestFieldsValidator(response, message);
- }
-
- @Override
- @SuppressWarnings("unchecked")
- @Transactional
- public void syncRoleFunctionFromExternalAccessSystem(EPApp app) {
- try {
- // get Permissions from External Auth System
- JSONArray extPerms = getExtAuthPermissions(app);
- List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);
- // get functions in DB
- final Map<String, Long> params = new HashMap<>();
- final Map<String, CentralV2RoleFunction> roleFuncMap = new HashMap<>();
- params.put(APP_ID, app.getId());
- List<CentralV2RoleFunction> appFunctions =
- dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null);
- if (!appFunctions.isEmpty()) {
- for (CentralV2RoleFunction roleFunc : appFunctions) {
- roleFuncMap.put(roleFunc.getCode(), roleFunc);
- }
- }
- // get Roles for portal in DB
- List<EPRole> portalRoleList = getGlobalRolesOfPortal();
- final Map<String, EPRole> existingPortalRolesMap = new HashMap<>();
- for (EPRole epRole : portalRoleList) {
- existingPortalRolesMap.put(epRole.getName().replaceAll(
- EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), epRole);
- }
- // get Roles in DB
- final Map<String, EPRole> currentRolesInDB = getAppRoleNamesWithUnderscoreMap(app);
- // store External Permissions with Pipe and without Pipe (just
- // instance)
- final Map<String, ExternalAccessPermsDetail> extAccessPermsContainsPipeMap = new HashMap<>();
- final Map<String, ExternalAccessPermsDetail> extAccessPermsMap = new HashMap<>();
- for (ExternalAccessPermsDetail permsDetailInfoWithPipe : permsDetailList) {
- extAccessPermsContainsPipeMap.put(permsDetailInfoWithPipe.getInstance(), permsDetailInfoWithPipe);
- String finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetailInfoWithPipe.getInstance());
- extAccessPermsMap.put(finalFunctionCodeVal, permsDetailInfoWithPipe);
- }
- // Add if new functions and app role functions were added in
- // external auth system
- for (ExternalAccessPermsDetail permsDetail : permsDetailList) {
- String code = permsDetail.getInstance();
- CentralV2RoleFunction getFunctionCodeKey = roleFuncMap.get(permsDetail.getInstance());
- List<CentralV2RoleFunction> roleFunctionList =
- addGetLocalFunction(app, roleFuncMap, permsDetail, code, getFunctionCodeKey);
- List<String> roles = permsDetail.getRoles();
- if (roles != null) {
- // Check if function has any roles and which does not exist
- // in External Auth System. If exists delete in local
- addRemoveIfFunctionsRolesIsSyncWithExternalAuth(app, currentRolesInDB, roleFunctionList, roles,
- existingPortalRolesMap);
- }
- }
- // Check if function does exits in External Auth System but exits in
- // local then delete function and its dependencies
- for (CentralV2RoleFunction roleFunc : appFunctions) {
- try {
- ExternalAccessPermsDetail getFunctionCodeContainsPipeKey =
- extAccessPermsContainsPipeMap.get(roleFunc.getCode());
- if (null == getFunctionCodeContainsPipeKey) {
- ExternalAccessPermsDetail getFunctionCodeKey = extAccessPermsMap.get(roleFunc.getCode());
- if (null == getFunctionCodeKey) {
- deleteAppRoleFuncDoesNotExitsInExtSystem(app, roleFunc);
- }
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "syncRoleFunctionFromExternalAccessSystem: Failed to delete function", e);
- }
- }
- logger.debug(EELFLoggerDelegate.debugLogger,
- "syncRoleFunctionFromExternalAccessSystem: Finished syncRoleFunctionFromExternalAccessSystem");
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "syncRoleFunctionFromExternalAccessSystem: Failed syncRoleFunctionFromExternalAccessSystem", e);
- }
- }
-
- @SuppressWarnings("unchecked")
- private void addRemoveIfFunctionsRolesIsSyncWithExternalAuth(EPApp app, final Map<String, EPRole> currentRolesInDB,
- List<CentralV2RoleFunction> roleFunctionList, List<String> roles,
- Map<String, EPRole> existingPortalRolesMap) throws Exception {
- if (!roleFunctionList.isEmpty()) {
- final Map<String, String> appRoleFuncParams = new HashMap<>();
- final Map<String, LocalRole> currentAppRoleFunctionsMap = new HashMap<>();
- final Map<String, String> currentRolesInExtSystem = new HashMap<>();
- appRoleFuncParams.put("functionCd", roleFunctionList.get(0).getCode());
- appRoleFuncParams.put("appId", String.valueOf(app.getId()));
- List<LocalRole> localRoleList =
- dataAccessService.executeNamedQuery("getCurrentAppRoleFunctions", appRoleFuncParams, null);
- for (LocalRole localRole : localRoleList) {
- currentAppRoleFunctionsMap.put(localRole.getRolename().replaceAll(
- EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), localRole);
- }
- for (String addRole : roles) {
- currentRolesInExtSystem.put(addRole.substring(addRole.indexOf(FUNCTION_PIPE) + 1), addRole);
- }
- for (String extAuthrole : roles) {
- String roleNameSpace = extAuthrole.substring(0, extAuthrole.indexOf(FUNCTION_PIPE));
- boolean isNameSpaceMatching =
- EcompPortalUtils.checkNameSpaceMatching(roleNameSpace, app.getNameSpace());
- if (isNameSpaceMatching) {
- if (!currentAppRoleFunctionsMap
- .containsKey(extAuthrole.substring(app.getNameSpace().length() + 1))) {
- EPRole localAddFuntionRole =
- currentRolesInDB.get(extAuthrole.substring(app.getNameSpace().length() + 1));
- if (localAddFuntionRole == null) {
- checkAndAddRoleInDB(app, currentRolesInDB, roleFunctionList, extAuthrole);
- } else {
- EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
- addAppRoleFunc.setAppId(app.getId());
- addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
- addAppRoleFunc.setRoleId(localAddFuntionRole.getId());
- dataAccessService.saveDomainObject(addAppRoleFunc, null);
- }
- }
- // This block is to save global role function if exists
- } else {
- String extAuthAppRoleName = extAuthrole.substring(extAuthrole.indexOf(FUNCTION_PIPE) + 1);
- boolean checkIfGlobalRoleExists = existingPortalRolesMap.containsKey(extAuthAppRoleName);
- if (checkIfGlobalRoleExists) {
- final Map<String, Long> params = new HashMap<>();
- EPRole role = existingPortalRolesMap.get(extAuthAppRoleName);
- EPAppRoleFunction addGlobalRoleFunctions = new EPAppRoleFunction();
- params.put("appId", app.getId());
- params.put("roleId", role.getId());
- List<EPAppRoleFunction> currentGlobalRoleFunctionsList =
- dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", params, null);
- boolean checkIfRoleFunctionExists = currentGlobalRoleFunctionsList.stream()
- .anyMatch(currentGlobalRoleFunction -> currentGlobalRoleFunction.getCode()
- .equals(roleFunctionList.get(0).getCode()));
- if (role != null && !checkIfRoleFunctionExists) {
- addGlobalRoleFunctions.setAppId(app.getId());
- addGlobalRoleFunctions.setRoleId(role.getId());
- if (!app.getId().equals(role.getAppRoleId())) {
- addGlobalRoleFunctions.setRoleAppId((PortalConstants.PORTAL_APP_ID).toString());
- } else {
- addGlobalRoleFunctions.setRoleAppId(null);
- }
- addGlobalRoleFunctions.setCode(roleFunctionList.get(0).getCode());
- dataAccessService.saveDomainObject(addGlobalRoleFunctions, null);
- }
- }
- }
- }
- for (LocalRole localRoleDelete : localRoleList) {
- if (!currentRolesInExtSystem.containsKey(localRoleDelete.getRolename()
- .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
- dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
- APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunctionList.get(0).getCode()
- + "'" + " and role_id = " + localRoleDelete.getRoleId().longValue(),
- null);
- }
- }
- }
- }
-
- private void deleteAppRoleFuncDoesNotExitsInExtSystem(EPApp app, CentralV2RoleFunction roleFunc) {
- logger.debug(EELFLoggerDelegate.debugLogger,
- "syncRoleFunctionFromExternalAccessSystem: Deleting app role function {}", roleFunc.getCode());
- dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
- APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() + "'", null);
- logger.debug(EELFLoggerDelegate.debugLogger,
- "syncRoleFunctionFromExternalAccessSystem: Deleted app role function {}", roleFunc.getCode());
- logger.debug(EELFLoggerDelegate.debugLogger,
- "syncRoleFunctionFromExternalAccessSystem: Deleting app function {}", roleFunc.getCode());
- dataAccessService.deleteDomainObjects(CentralV2RoleFunction.class,
- APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() + "'", null);
- logger.debug(EELFLoggerDelegate.debugLogger,
- "syncRoleFunctionFromExternalAccessSystem: Deleted app function {}", roleFunc.getCode());
- }
-
- private void checkAndAddRoleInDB(EPApp app, final Map<String, EPRole> currentRolesInDB,
- List<CentralV2RoleFunction> roleFunctionList, String roleList) throws Exception {
- if (!currentRolesInDB.containsKey(roleList.substring(app.getNameSpace().length() + 1))) {
- Role role = addRoleInDBIfDoesNotExists(app, roleList.substring(app.getNameSpace().length() + 1));
- addRoleDescriptionInExtSystem(role, app);
- if (!roleFunctionList.isEmpty()) {
- try {
- if (!roleFunctionList.isEmpty()) {
- EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
- addAppRoleFunc.setAppId(app.getId());
- addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
- addAppRoleFunc.setRoleId(role.getId());
- dataAccessService.saveDomainObject(addAppRoleFunc, null);
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "syncRoleFunctionFromExternalAccessSystem: Failed to save app role function ", e);
- }
- }
- }
- }
-
- @SuppressWarnings("unchecked")
- private List<CentralV2RoleFunction> addGetLocalFunction(EPApp app,
- final Map<String, CentralV2RoleFunction> roleFuncMap, ExternalAccessPermsDetail permsDetail, String code,
- CentralV2RoleFunction getFunctionCodeKey) {
- String finalFunctionCodeVal =
- addToLocalIfFunctionNotExists(app, roleFuncMap, permsDetail, code, getFunctionCodeKey);
- final Map<String, String> appSyncFuncsParams = new HashMap<>();
- appSyncFuncsParams.put("appId", String.valueOf(app.getId()));
- appSyncFuncsParams.put("functionCd", finalFunctionCodeVal);
- List<CentralV2RoleFunction> roleFunctionList = null;
- roleFunctionList =
- dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams, null);
- if (roleFunctionList.isEmpty()) {
- appSyncFuncsParams.put("functionCd", code);
- roleFunctionList =
- dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams, null);
- }
- return roleFunctionList;
- }
-
- private String addToLocalIfFunctionNotExists(EPApp app, final Map<String, CentralV2RoleFunction> roleFuncMap,
- ExternalAccessPermsDetail permsDetail, String code, CentralV2RoleFunction getFunctionCodeKey) {
- String finalFunctionCodeVal = "";
- if (null == getFunctionCodeKey) {
- finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetail.getInstance());
- CentralV2RoleFunction checkIfCodeStillExits = roleFuncMap.get(finalFunctionCodeVal);
- // If function does not exist in local then add!
- if (null == checkIfCodeStillExits) {
- logger.debug(EELFLoggerDelegate.debugLogger,
- "syncRoleFunctionFromExternalAccessSystem: Adding function: {} ", code);
- addFunctionInEcompDB(app, permsDetail, code);
- logger.debug(EELFLoggerDelegate.debugLogger,
- "syncRoleFunctionFromExternalAccessSystem: Finished adding function: {} ", code);
- }
- }
- return finalFunctionCodeVal;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public Map<String, EPRole> getAppRoleNamesWithUnderscoreMap(EPApp app) {
- final Map<String, EPRole> currentRolesInDB = new HashMap<>();
- List<EPRole> getCurrentRoleList = null;
- final Map<String, Long> appParams = new HashMap<>();
- if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
- getCurrentRoleList = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
- } else {
- appParams.put("appId", app.getId());
- getCurrentRoleList = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
- }
- for (EPRole role : getCurrentRoleList) {
- currentRolesInDB.put(role.getName()
- .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), role);
- }
- return currentRolesInDB;
- }
-
- @SuppressWarnings("unchecked")
- private Map<String, EPRole> getAppRoleNamesMap(EPApp app) {
- final Map<String, EPRole> currentRolesInDB = new HashMap<>();
- List<EPRole> getCurrentRoleList = null;
- final Map<String, Long> appParams = new HashMap<>();
- if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
- getCurrentRoleList = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
- } else {
- appParams.put("appId", app.getId());
- getCurrentRoleList = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
- }
- for (EPRole role : getCurrentRoleList) {
- currentRolesInDB.put(role.getName(), role);
- }
- return currentRolesInDB;
- }
-
- private List<ExternalAccessPermsDetail> getExtAuthPerrmissonList(EPApp app, JSONArray extPerms) throws IOException {
- ExternalAccessPermsDetail permDetails = null;
- List<ExternalAccessPermsDetail> permsDetailList = new ArrayList<>();
- for (int i = 0; i < extPerms.length(); i++) {
- String description = null;
- if (extPerms.getJSONObject(i).has("description")) {
- description = extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
- } else {
- description = extPerms.getJSONObject(i).getString("type") + "|"
- + extPerms.getJSONObject(i).getString("instance") + "|"
- + extPerms.getJSONObject(i).getString("action");
- }
- if (extPerms.getJSONObject(i).has("roles")) {
- ObjectMapper rolesListMapper = new ObjectMapper();
- JSONArray resRoles = extPerms.getJSONObject(i).getJSONArray("roles");
- List<String> list = rolesListMapper.readValue(resRoles.toString(),
- TypeFactory.defaultInstance().constructCollectionType(List.class, String.class));
- permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
- extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
- + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
- + extPerms.getJSONObject(i).getString("action"),
- extPerms.getJSONObject(i).getString("action"), list, description);
- permsDetailList.add(permDetails);
- } else {
- permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
- extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
- + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
- + extPerms.getJSONObject(i).getString("action"),
- extPerms.getJSONObject(i).getString("action"), description);
- permsDetailList.add(permDetails);
- }
- }
- return permsDetailList;
- }
-
- private JSONArray getExtAuthPermissions(EPApp app) throws Exception {
- ResponseEntity<String> response = null;
- HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
- HttpEntity<String> entity = new HttpEntity<>(headers);
- logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: {} ",
- CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
- response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
- + "perms/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
- String res = response.getBody();
- logger.debug(EELFLoggerDelegate.debugLogger,
- "syncRoleFunctionFromExternalAccessSystem: Finished GET permissions from External Auth system and response: {} ",
- response.getBody());
- JSONObject jsonObj = new JSONObject(res);
- JSONArray extPerms = jsonObj.getJSONArray("perm");
- for (int i = 0; i < extPerms.length(); i++) {
- if (extPerms.getJSONObject(i).getString("type").equals(app.getNameSpace() + ".access")) {
- extPerms.remove(i);
- i--;
- }
- }
- return extPerms;
- }
-
- /**
- *
- * Add function into local DB
- *
- * @param app
- * @param permsDetail
- * @param code
- */
- private void addFunctionInEcompDB(EPApp app, ExternalAccessPermsDetail permsDetail, String code) {
- try {
- CentralV2RoleFunction addFunction = new CentralV2RoleFunction();
- addFunction.setAppId(app.getId());
- addFunction.setCode(code);
- addFunction.setName(permsDetail.getDescription());
- dataAccessService.saveDomainObject(addFunction, null);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "addFunctionInEcompDB: Failed to add function", e);
- }
- }
-
- /**
- *
- * It updates description of a role in external auth system
- *
- * @param role
- * @param app
- * @throws Exception
- */
- private boolean addRoleDescriptionInExtSystem(Role role, EPApp app) throws Exception {
- boolean status = false;
- try {
- String addRoleNew = updateExistingRoleInExternalSystem(role, app);
- HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
- HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
- template.exchange(
- SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
- HttpMethod.PUT, entity, String.class);
- status = true;
- } catch (HttpClientErrorException e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "HttpClientErrorException - Failed to addRoleDescriptionInExtSystem", e);
- EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "addRoleDescriptionInExtSystem: Failed", e);
- }
- return status;
- }
-
- /**
- *
- * While sync functions form external auth system if new role found we should add in local and
- * return Role.class object
- *
- * @param app
- * @param role
- * @return
- */
- @SuppressWarnings("unchecked")
- private Role addRoleInDBIfDoesNotExists(EPApp app, String role) {
- Role setNewRole = new Role();
- try {
- // functions can have new role created in External Auth System
- // prevent
- // duplication here
- boolean isCreated = checkIfRoleExitsElseCreateInSyncFunctions(role, app);
- final Map<String, String> getRoleByNameParams = new HashMap<>();
- List<EPRole> getRoleCreated = null;
- getRoleByNameParams.put(APP_ROLE_NAME_PARAM, role);
- if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
- getRoleByNameParams.put("appId", String.valueOf(app.getId()));
- List<EPRole> roleCreated = dataAccessService
- .executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, getRoleByNameParams, null);
- if (!isCreated) {
- EPRole epUpdateRole = roleCreated.get(0);
- epUpdateRole.setAppRoleId(epUpdateRole.getId());
- dataAccessService.saveDomainObject(epUpdateRole, null);
- getRoleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
- getRoleByNameParams, null);
- } else {
- getRoleCreated = roleCreated;
- }
- } else {
- getRoleCreated =
- dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, getRoleByNameParams, null);
- }
- if (getRoleCreated != null && !getRoleCreated.isEmpty()) {
- EPRole roleObject = getRoleCreated.get(0);
- setNewRole.setId(roleObject.getId());
- setNewRole.setName(roleObject.getName());
- setNewRole.setActive(roleObject.getActive());
- setNewRole.setPriority(roleObject.getPriority());
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "addRoleInDBIfDoesNotExists: Failed", e);
- }
- return setNewRole;
- }
-
- @SuppressWarnings("unchecked")
- private boolean checkIfRoleExitsElseCreateInSyncFunctions(String role, EPApp app) {
- boolean isCreated = false;
- final Map<String, String> roleParams = new HashMap<>();
- roleParams.put(APP_ROLE_NAME_PARAM, role);
- List<EPRole> roleCreated = null;
- if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
- roleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, roleParams, null);
- } else {
- roleParams.put("appId", String.valueOf(app.getId()));
- roleCreated =
- dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams, null);
- }
- if (roleCreated == null || roleCreated.isEmpty()) {
- roleParams.put("appId", String.valueOf(app.getId()));
- EPRole epRoleNew = new EPRole();
- epRoleNew.setActive(true);
- epRoleNew.setName(role);
- if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
- epRoleNew.setAppId(null);
- } else {
- epRoleNew.setAppId(app.getId());
- }
- dataAccessService.saveDomainObject(epRoleNew, null);
- isCreated = false;
- } else {
- isCreated = true;
- }
- return isCreated;
- }
-
- @Override
- @SuppressWarnings("unchecked")
- public Integer bulkUploadFunctions(String uebkey) throws Exception {
- EPApp app = getApp(uebkey).get(0);
- List<RoleFunction> roleFuncList = dataAccessService.executeNamedQuery("getAllFunctions", null, null);
- CentralV2RoleFunction cenRoleFunc = null;
- Integer functionsAdded = 0;
- try {
- for (RoleFunction roleFunc : roleFuncList) {
- cenRoleFunc = new CentralV2RoleFunction(roleFunc.getCode(), roleFunc.getName());
- addRoleFunctionInExternalSystem(cenRoleFunc, app);
- functionsAdded++;
- }
- } catch (HttpClientErrorException e) {
- logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadFunctions failed", e);
- EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions: failed", e.getMessage(), e);
- }
- return functionsAdded;
- }
-
- @Override
- public Integer bulkUploadRoles(String uebkey) throws Exception {
- List<EPApp> app = getApp(uebkey);
- List<EPRole> roles = getAppRoles(app.get(0).getId());
- List<CentralV2Role> cenRoleList = new ArrayList<>();
- final Map<String, Long> params = new HashMap<>();
- Integer rolesListAdded = 0;
- try {
- cenRoleList = createCentralRoleObject(app, roles, cenRoleList, params);
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
- String roleList = mapper.writeValueAsString(cenRoleList);
- List<Role> roleObjectList = mapper.readValue(roleList,
- TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
- for (Role role : roleObjectList) {
- addRoleInExternalSystem(role, app.get(0));
- rolesListAdded++;
- }
- if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
- // Add Account Admin role in External AUTH System
- try {
- String addAccountAdminRole = "";
- ExternalAccessRole extRole = new ExternalAccessRole();
- extRole.setName(app.get(0).getNameSpace() + "." + PortalConstants.ADMIN_ROLE
- .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
- addAccountAdminRole = mapper.writeValueAsString(extRole);
- HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
- HttpEntity<String> entity = new HttpEntity<>(addAccountAdminRole, headers);
- template.exchange(
- SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
- HttpMethod.POST, entity, String.class);
- rolesListAdded++;
- } catch (HttpClientErrorException e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "HttpClientErrorException - Failed to create Account Admin role", e);
- EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
- } catch (Exception e) {
- if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "bulkUploadRoles: Account Admin Role already exits but does not break functionality",
- e);
- } else {
- logger.error(EELFLoggerDelegate.errorLogger,
- "bulkUploadRoles: Failed to create Account Admin role", e.getMessage());
- }
- }
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles: failed", e);
- throw e;
- }
- return rolesListAdded;
- }
-
- /**
- * It creating new role in external auth system while doing bulk upload
- *
- * @param role
- * @param app
- * @throws Exception
- */
- private void addRoleInExternalSystem(Role role, EPApp app) throws Exception {
- String addRoleNew = updateExistingRoleInExternalSystem(role, app);
- HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
- try {
- HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
- template.exchange(
- SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
- HttpMethod.POST, entity, String.class);
- } catch (HttpClientErrorException e) {
- logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addRoleInExternalSystem",
- e);
- EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
- } catch (Exception e) {
- if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "addRoleInExternalSystem: Role already exits but does not break functionality", e);
- } else {
- logger.error(EELFLoggerDelegate.errorLogger,
- "addRoleInExternalSystem: Failed to addRoleInExternalSystem", e.getMessage());
- }
- }
- }
-
- @Override
- @SuppressWarnings("unchecked")
- public Integer bulkUploadRolesFunctions(String uebkey) throws Exception {
- EPApp app = getApp(uebkey).get(0);
- List<EPRole> roles = getAppRoles(app.getId());
- final Map<String, Long> params = new HashMap<>();
- Integer roleFunctions = 0;
- try {
- for (EPRole role : roles) {
- params.put("roleId", role.getId());
- List<BulkUploadRoleFunction> appRoleFunc =
- dataAccessService.executeNamedQuery("uploadAllRoleFunctions", params, null);
- if (!appRoleFunc.isEmpty()) {
- for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
- addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
- roleFunctions++;
- }
- }
- }
- } catch (HttpClientErrorException e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
- EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
- }
- return roleFunctions;
- }
-
- /**
- * Its adding a role function while doing bulk upload
- *
- * @param addRoleFunc
- * @param role
- * @param app
- */
- private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, EPRole role, EPApp app) {
- String type = "";
- String instance = "";
- String action = "";
- if (addRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
- type = EcompPortalUtils.getFunctionType(addRoleFunc.getFunctionCd());
- instance = EcompPortalUtils.getFunctionCode(addRoleFunc.getFunctionCd());
- action = EcompPortalUtils.getFunctionAction(addRoleFunc.getFunctionCd());
- } else {
- type = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
- instance = addRoleFunc.getFunctionCd();
- action = "*";
- }
- ExternalAccessRolePerms extRolePerms = null;
- ExternalAccessPerms extPerms = null;
- ObjectMapper mapper = new ObjectMapper();
- try {
- HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
- extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, instance, action,
- addRoleFunc.getFunctionName());
- extRolePerms = new ExternalAccessRolePerms(extPerms, app.getNameSpace() + "." + role.getName()
- .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
- String updateRolePerms = mapper.writeValueAsString(extRolePerms);
- HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
- template.exchange(
- SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
- HttpMethod.POST, entity, String.class);
- } catch (Exception e) {
- if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "addRoleFunctionsInExternalSystem: RoleFunction already exits but does not break functionality",
- e);
- } else {
- logger.error(EELFLoggerDelegate.errorLogger,
- "addRoleFunctionsInExternalSystem: Failed to addRoleFunctionsInExternalSystem", e.getMessage());
- }
- }
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public Integer bulkUploadPartnerFunctions(String uebkey) throws Exception {
- EPApp app = getApp(uebkey).get(0);
- final Map<String, Long> params = new HashMap<>();
- params.put("appId", app.getId());
- List<CentralV2RoleFunction> roleFuncList =
- dataAccessService.executeNamedQuery("getPartnerAppFunctions", params, null);
- Integer functionsAdded = 0;
- try {
- for (CentralV2RoleFunction roleFunc : roleFuncList) {
- addFunctionInExternalSystem(roleFunc, app);
- functionsAdded++;
- }
- } catch (HttpClientErrorException e) {
- logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadPartnerFunctions failed",
- e);
- EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerFunctions: failed", e.getMessage(), e);
- }
- return functionsAdded;
- }
-
- private void addFunctionInExternalSystem(CentralV2RoleFunction roleFunc, EPApp app) throws Exception {
- ObjectMapper mapper = new ObjectMapper();
- ExternalAccessPerms extPerms = new ExternalAccessPerms();
- HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
- String type = "";
- String instance = "";
- String action = "";
- if ((roleFunc.getCode().contains(FUNCTION_PIPE))
- || (roleFunc.getType() != null && roleFunc.getAction() != null)) {
- type = EcompPortalUtils.getFunctionType(roleFunc.getCode());
- instance = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
- action = EcompPortalUtils.getFunctionAction(roleFunc.getCode());
- } else {
- type = roleFunc.getCode().contains("menu") ? "menu" : "url";
- instance = roleFunc.getCode();
- action = "*";
- }
- try {
- extPerms.setAction(action);
- extPerms.setInstance(instance);
- extPerms.setType(app.getNameSpace() + "." + type);
- extPerms.setDescription(roleFunc.getName());
- String addFunction = mapper.writeValueAsString(extPerms);
- HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
- logger.debug(EELFLoggerDelegate.debugLogger, "addFunctionInExternalSystem: {} for POST: {}",
- CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
- ResponseEntity<String> addPermResponse = template.exchange(
- SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
- HttpMethod.POST, entity, String.class);
- logger.debug(EELFLoggerDelegate.debugLogger,
- "addFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ",
- addPermResponse.getStatusCode().value(), addFunction);
- } catch (HttpClientErrorException e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "HttpClientErrorException - Failed to add function in external central auth system", e);
- EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
- throw e;
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "addFunctionInExternalSystem: Failed to add fucntion in external central auth system", e);
- throw e;
- }
- }
-
- @Override
- public void bulkUploadPartnerRoles(String uebkey, List<Role> roleList) throws Exception {
- EPApp app = getApp(uebkey).get(0);
- for (Role role : roleList) {
- addRoleInExternalSystem(role, app);
- }
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public Integer bulkUploadPartnerRoleFunctions(String uebkey) throws Exception {
- EPApp app = getApp(uebkey).get(0);
- List<EPRole> roles = getAppRoles(app.getId());
- final Map<String, Long> params = new HashMap<>();
- Integer roleFunctions = 0;
- try {
- for (EPRole role : roles) {
- params.put("roleId", role.getId());
- List<BulkUploadRoleFunction> appRoleFunc =
- dataAccessService.executeNamedQuery("uploadPartnerRoleFunctions", params, null);
- if (!appRoleFunc.isEmpty()) {
- for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
- addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
- roleFunctions++;
- }
- }
- }
- // upload global role functions to ext auth system
- if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
- roleFunctions = bulkUploadGlobalRoleFunctions(app, roleFunctions);
- }
- } catch (HttpClientErrorException e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
- EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
- }
- return roleFunctions;
- }
-
- @SuppressWarnings("unchecked")
- private Integer bulkUploadGlobalRoleFunctions(EPApp app, Integer roleFunctions) throws Exception {
- try {
- EPApp portalApp = epAppService.getApp(1l);
- final Map<String, Long> params = new HashMap<>();
- params.put("appId", app.getId());
- List<GlobalRoleWithApplicationRoleFunction> globalRoleFuncs =
- dataAccessService.executeNamedQuery("getBulkUploadPartnerGlobalRoleFunctions", params, null);
- ObjectMapper mapper = new ObjectMapper();
- HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
- for (GlobalRoleWithApplicationRoleFunction globalRoleFunc : globalRoleFuncs) {
- ExternalAccessRolePerms extRolePerms;
- ExternalAccessPerms extPerms;
- String type = "";
- String instance = "";
- String action = "";
- if (globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
- type = EcompPortalUtils.getFunctionType(globalRoleFunc.getFunctionCd());
- instance = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd());
- action = EcompPortalUtils.getFunctionAction(globalRoleFunc.getFunctionCd());
- } else {
- type = globalRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
- instance = globalRoleFunc.getFunctionCd();
- action = "*";
- }
- extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, instance, action);
- extRolePerms = new ExternalAccessRolePerms(extPerms,
- portalApp.getNameSpace() + "." + globalRoleFunc.getRoleName().replaceAll(
- EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
- String updateRolePerms = mapper.writeValueAsString(extRolePerms);
- HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
- updateRoleFunctionInExternalSystem(updateRolePerms, entity);
- roleFunctions++;
- }
- } catch (HttpClientErrorException e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "HttpClientErrorException - Failed to add role function in external central auth system", e);
- EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
- throw e;
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "bulkUploadGlobalRoleFunctions: Failed to add role fucntion in external central auth system", e);
- throw e;
- }
- return roleFunctions;
- }
-
- @Override
- @Transactional
- public void syncApplicationRolesWithEcompDB(EPApp app) {
- try {
- logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Started");
- // Sync functions and roles assigned to it which also creates new roles if does
- // not exits in portal
- syncRoleFunctionFromExternalAccessSystem(app);
- logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Finished");
- ObjectMapper mapper = new ObjectMapper();
- logger.debug(EELFLoggerDelegate.debugLogger, "Entering to getAppRolesJSONFromExtAuthSystem");
- // Get Permissions from External Auth System
- JSONArray extRole = getAppRolesJSONFromExtAuthSystem(app);
- logger.debug(EELFLoggerDelegate.debugLogger, "Entering into getExternalRoleDetailsList");
- // refactoring done
- List<ExternalRoleDetails> externalRoleDetailsList = getExternalRoleDetailsList(app, mapper, extRole);
- List<EPRole> finalRoleList = new ArrayList<>();
- for (ExternalRoleDetails externalRole : externalRoleDetailsList) {
- EPRole ecompRole = convertExternalRoleDetailstoEpRole(externalRole);
- finalRoleList.add(ecompRole);
- }
- List<EPRole> applicationRolesList;
- applicationRolesList = getAppRoles(app.getId());
- List<String> applicationRoleIdList = new ArrayList<>();
- for (EPRole applicationRole : applicationRolesList) {
- applicationRoleIdList.add(applicationRole.getName());
- }
- List<EPRole> roleListToBeAddInEcompDB = new ArrayList<>();
- for (EPRole aafRole : finalRoleList) {
- if (!applicationRoleIdList.contains(aafRole.getName())) {
- roleListToBeAddInEcompDB.add(aafRole);
- }
- }
- logger.debug(EELFLoggerDelegate.debugLogger, "Entering into inactiveRolesNotInExternalAuthSystem");
- // Check if roles exits in external Access system and if not make inactive in DB
- inactiveRolesNotInExternalAuthSystem(app, finalRoleList, applicationRolesList);
- logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addNewRoleInEcompDBUpdateDescInExtAuthSystem");
- // Add new roles in DB and updates role description in External Auth System
- addNewRoleInEcompDBUpdateDescInExtAuthSystem(app, roleListToBeAddInEcompDB);
- logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: Finished");
- } catch (HttpClientErrorException e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "syncApplicationRolesWithEcompDB: Failed due to the External Auth System", e);
- EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed ", e);
- }
- }
-
- /**
- *
- * It adds new roles in DB and updates description in External Auth System
- *
- * @param app
- * @param roleListToBeAddInEcompDB
- */
- @SuppressWarnings("unchecked")
- private void addNewRoleInEcompDBUpdateDescInExtAuthSystem(EPApp app, List<EPRole> roleListToBeAddInEcompDB) {
- EPRole roleToBeAddedInEcompDB;
- for (int i = 0; i < roleListToBeAddInEcompDB.size(); i++) {
- try {
- roleToBeAddedInEcompDB = roleListToBeAddInEcompDB.get(i);
- if (app.getId() == 1) {
- roleToBeAddedInEcompDB.setAppRoleId(null);
- }
- dataAccessService.saveDomainObject(roleToBeAddedInEcompDB, null);
- List<EPRole> getRoleCreatedInSync = null;
- if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
- final Map<String, String> globalRoleParams = new HashMap<>();
- globalRoleParams.put("appId", String.valueOf(app.getId()));
- globalRoleParams.put("appRoleName", roleToBeAddedInEcompDB.getName());
- getRoleCreatedInSync = dataAccessService
- .executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, globalRoleParams, null);
- EPRole epUpdateRole = getRoleCreatedInSync.get(0);
- epUpdateRole.setAppRoleId(epUpdateRole.getId());
- dataAccessService.saveDomainObject(epUpdateRole, null);
- }
- List<EPRole> roleList = new ArrayList<>();
- final Map<String, String> params = new HashMap<>();
- params.put(APP_ROLE_NAME_PARAM, roleToBeAddedInEcompDB.getName());
- boolean isPortalRole = false;
- if (app.getId() == 1) {
- isPortalRole = true;
- roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, params, null);
- } else {
- isPortalRole = false;
- params.put(APP_ID, app.getId().toString());
- roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, params,
- null);
- }
- EPRole role = roleList.get(0);
- Role aaFrole = new Role();
- aaFrole.setId(role.getId());
- aaFrole.setActive(role.getActive());
- aaFrole.setPriority(role.getPriority());
- aaFrole.setName(role.getName());
- updateRoleInExternalSystem(aaFrole, app, isPortalRole);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "SyncApplicationRolesWithEcompDB: Failed to add or update role in external auth system", e);
- }
- }
- }
-
- /**
- *
- * It checks description in External Auth System if found any changes updates in DB
- *
- * @param app
- * @param finalRoleList contains list of External Auth System roles list which is converted to
- * EPRole
- */
- @SuppressWarnings("unchecked")
- private void checkAndUpdateRoleInDB(EPApp app, List<EPRole> finalRoleList) {
- for (EPRole roleItem : finalRoleList) {
- final Map<String, String> roleParams = new HashMap<>();
- List<EPRole> currentList = null;
- roleParams.put(APP_ROLE_NAME_PARAM, roleItem.getName());
- if (app.getId() == 1) {
- currentList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, roleParams, null);
- } else {
- roleParams.put(APP_ID, app.getId().toString());
- currentList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
- roleParams, null);
- }
- if (!currentList.isEmpty()) {
- try {
- Boolean aafRoleActive;
- Boolean localRoleActive;
- boolean result;
- aafRoleActive = Boolean.valueOf(roleItem.getActive());
- localRoleActive = Boolean.valueOf(currentList.get(0).getActive());
- result = aafRoleActive.equals(localRoleActive);
- EPRole updateRole = currentList.get(0);
- if (!result) {
- updateRole.setActive(roleItem.getActive());
- dataAccessService.saveDomainObject(updateRole, null);
- }
- if (roleItem.getPriority() != null
- && !currentList.get(0).getPriority().equals(roleItem.getPriority())) {
- updateRole.setPriority(roleItem.getPriority());
- dataAccessService.saveDomainObject(updateRole, null);
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "syncApplicationRolesWithEcompDB: Failed to update role ", e);
- }
- }
- }
- }
-
- /**
- *
- * It de-activates application roles in DB if not present in External Auth system
- *
- * @param app
- * @param finalRoleList contains list of current roles present in External Auth System
- * @param applicationRolesList contains list of current roles present in DB
- */
- @SuppressWarnings("unchecked")
- private void inactiveRolesNotInExternalAuthSystem(EPApp app, List<EPRole> finalRoleList,
- List<EPRole> applicationRolesList) {
- final Map<String, EPRole> checkRolesInactive = new HashMap<>();
- for (EPRole extrole : finalRoleList) {
- checkRolesInactive.put(extrole.getName(), extrole);
- }
- for (EPRole role : applicationRolesList) {
- try {
- final Map<String, String> extRoleParams = new HashMap<>();
- List<EPRole> roleList = null;
- extRoleParams.put(APP_ROLE_NAME_PARAM, role.getName());
- if (!checkRolesInactive.containsKey(role.getName()
- .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
- if (app.getId() == 1) {
- roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, extRoleParams, null);
- } else {
- extRoleParams.put(APP_ID, app.getId().toString());
- roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
- extRoleParams, null);
- }
- if (!roleList.isEmpty()) {
- EPRole updateRoleInactive = roleList.get(0);
- updateRoleInactive.setActive(false);
- dataAccessService.saveDomainObject(updateRoleInactive, null);
- }
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "syncApplicationRolesWithEcompDB: Failed to de-activate role ", e);
- }
- }
- }
-
- @Override
- @SuppressWarnings("unchecked")
- public List<ExternalRoleDetails> getExternalRoleDetailsList(EPApp app, ObjectMapper mapper, JSONArray extRole)
- throws IOException {
- List<ExternalRoleDetails> externalRoleDetailsList = new ArrayList<>();
- ExternalAccessPerms externalAccessPerms = new ExternalAccessPerms();
- List<String> functionCodelist = new ArrayList<>();
- Map<String, EPRole> curRolesMap = getAppRoleNamesMap(app);
- Map<String, EPRole> curRolesUnderscoreMap = getAppRoleNamesWithUnderscoreMap(app);
- for (int i = 0; i < extRole.length(); i++) {
- ExternalRoleDetails externalRoleDetail = new ExternalRoleDetails();
- EPAppRoleFunction ePAppRoleFunction = new EPAppRoleFunction();
- JSONObject Role = (JSONObject) extRole.get(i);
- String name = extRole.getJSONObject(i).getString(ROLE_NAME);
- String actualRoleName = name.substring(app.getNameSpace().length() + 1);
- if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
- actualRoleName = extRole.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
- }
- SortedSet<ExternalAccessPerms> externalAccessPermsOfRole = new TreeSet<>();
- if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_PERMS)) {
- JSONArray extPerm = (JSONArray) Role.get(EXTERNAL_AUTH_PERMS);
- for (int j = 0; j < extPerm.length(); j++) {
- JSONObject perms = extPerm.getJSONObject(j);
- boolean isNamespaceMatching =
- EcompPortalUtils.checkNameSpaceMatching(perms.getString("type"), app.getNameSpace());
- if (isNamespaceMatching) {
- externalAccessPerms = new ExternalAccessPerms(perms.getString("type"),
- perms.getString("instance"), perms.getString("action"));
- ePAppRoleFunction.setCode(externalAccessPerms.getInstance());
- functionCodelist.add(ePAppRoleFunction.getCode());
- externalAccessPermsOfRole.add(externalAccessPerms);
- }
- }
- }
- externalRoleDetail.setActive(true);
- externalRoleDetail.setName(actualRoleName);
- if (app.getId() == 1) {
- externalRoleDetail.setAppId(null);
- } else {
- externalRoleDetail.setAppId(app.getId());
- }
- EPRole currRole = null;
- currRole = (!extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION))
- ? curRolesUnderscoreMap.get(actualRoleName)
- : curRolesMap.get(actualRoleName);
- Long roleId = null;
- if (currRole != null)
- roleId = currRole.getId();
- final Map<String, EPAppRoleFunction> roleFunctionsMap = new HashMap<>();
- final Map<String, Long> appRoleFuncsParams = new HashMap<>();
- if (roleId != null) {
- appRoleFuncsParams.put("appId", app.getId());
- appRoleFuncsParams.put("roleId", roleId);
- // get role functions from DB
- List<EPAppRoleFunction> appRoleFunctions = dataAccessService
- .executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null);
- if (!appRoleFunctions.isEmpty()) {
- for (EPAppRoleFunction roleFunc : appRoleFunctions) {
- roleFunctionsMap.put(roleFunc.getCode(), roleFunc);
- }
- }
- }
- if (!externalAccessPermsOfRole.isEmpty()) {
- // Adding functions to role
- for (ExternalAccessPerms externalpermission : externalAccessPermsOfRole) {
- EPAppRoleFunction checkRoleFunctionExits = roleFunctionsMap.get(externalpermission.getInstance());
- if (checkRoleFunctionExits == null) {
- String funcCode = externalpermission.getType().substring(app.getNameSpace().length() + 1)
- + FUNCTION_PIPE + externalpermission.getInstance() + FUNCTION_PIPE
- + externalpermission.getAction();
- EPAppRoleFunction checkRoleFunctionPipeExits = roleFunctionsMap.get(funcCode);
- if (checkRoleFunctionPipeExits == null) {
- try {
- final Map<String, String> appFuncsParams = new HashMap<>();
- appFuncsParams.put("appId", String.valueOf(app.getId()));
- appFuncsParams.put("functionCd", externalpermission.getInstance());
- logger.debug(EELFLoggerDelegate.debugLogger,
- "SyncApplicationRolesWithEcompDB: Adding function to the role: {}",
- externalpermission.getInstance());
- List<CentralV2RoleFunction> roleFunction = null;
- roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId",
- appFuncsParams, null);
- if (roleFunction.isEmpty()) {
- appFuncsParams.put("functionCd", funcCode);
- roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId",
- appFuncsParams, null);
- }
- if (!roleFunction.isEmpty()) {
- EPAppRoleFunction apRoleFunction = new EPAppRoleFunction();
- apRoleFunction.setAppId(app.getId());
- apRoleFunction.setRoleId(roleId);
- apRoleFunction.setCode(roleFunction.get(0).getCode());
- dataAccessService.saveDomainObject(apRoleFunction, null);
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "SyncApplicationRolesWithEcompDB: Failed to add role function", e);
- }
- }
- }
- }
- }
- externalRoleDetailsList.add(externalRoleDetail);
- }
- return externalRoleDetailsList;
- }
-
- @Override
- public JSONArray getAppRolesJSONFromExtAuthSystem(EPApp app) throws Exception {
- ResponseEntity<String> response = null;
- HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
- HttpEntity<String> entity = new HttpEntity<>(headers);
- logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: {} ",
- CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
- response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
- + "roles/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
- String res = response.getBody();
- logger.debug(EELFLoggerDelegate.debugLogger,
- "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
- res);
- JSONObject jsonObj = new JSONObject(res);
- JSONArray extRole = jsonObj.getJSONArray("role");
- for (int i = 0; i < extRole.length(); i++) {
- if (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ADMIN)
- || extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + OWNER)
- || (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ACCOUNT_ADMINISTRATOR)
- && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
- extRole.remove(i);
- i--;
- }
- }
- return extRole;
- }
-
- @Override
- public JSONArray getAllUsersByRole(String roleName) throws Exception {
- ResponseEntity<String> response = null;
- HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
- HttpEntity<String> entity = new HttpEntity<>(headers);
- logger.debug(EELFLoggerDelegate.debugLogger, "getAllUsersByRole: {} ",
- CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
- response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
- + "userRoles/role/" + roleName, HttpMethod.GET, entity, String.class);
- String res = response.getBody();
- logger.debug(EELFLoggerDelegate.debugLogger,
- "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
- res);
- if (res == null || res.trim().isEmpty())
- return null;
- JSONObject jsonObj = new JSONObject(res);
- JSONArray extRole = jsonObj.getJSONArray("userRole");
- return extRole;
- }
-
- /**
- *
- * It converts from ExternalRoleDetails.class object to EPRole.class object
- *
- * @param externalRoleDetails
- * @return EPRole object
- */
- private EPRole convertExternalRoleDetailstoEpRole(ExternalRoleDetails externalRoleDetails) {
- EPRole role = new EPRole();
- role.setActive(true);
- role.setAppId(externalRoleDetails.getAppId());
- role.setAppRoleId(externalRoleDetails.getAppRoleId());
- role.setName(externalRoleDetails.getName());
- role.setPriority(externalRoleDetails.getPriority());
- return role;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public Integer bulkUploadUserRoles(String uebkey) throws Exception {
- EPApp app = getApp(uebkey).get(0);
- final Map<String, String> params = new HashMap<>();
- params.put("uebKey", app.getUebKey());
- List<BulkUploadUserRoles> userRolesList = null;
- Integer userRolesAdded = 0;
- if (app.getCentralAuth()) {
- userRolesList = dataAccessService.executeNamedQuery("getBulkUserRoles", params, null);
- for (BulkUploadUserRoles userRolesUpload : userRolesList) {
- if (!userRolesUpload.getOrgUserId().equals("su1234")) {
- addUserRoleInExternalSystem(userRolesUpload);
- userRolesAdded++;
- }
- }
- }
- return userRolesAdded;
- }
-
- /**
- * Its adding a user role in external auth system while doing bulk upload
- *
- * @param userRolesUpload
- */
- private void addUserRoleInExternalSystem(BulkUploadUserRoles userRolesUpload) {
- try {
- String name = "";
- ObjectMapper mapper = new ObjectMapper();
- if (EPCommonSystemProperties
- .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
- name = userRolesUpload.getOrgUserId()
- + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
- }
- ExternalAccessUser extUser =
- new ExternalAccessUser(name, userRolesUpload.getAppNameSpace() + "." + userRolesUpload.getRoleName()
- .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
- String userRole = mapper.writeValueAsString(extUser);
- HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
- HttpEntity<String> entity = new HttpEntity<>(userRole, headers);
- template.exchange(
- SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
- HttpMethod.POST, entity, String.class);
- } catch (HttpClientErrorException e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "HttpClientErrorException - Failed to addUserRoleInExternalSystem", e);
- EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
- } catch (Exception e) {
- if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "addUserRoleInExternalSystem: UserRole already exits but does not break functionality");
- } else {
- logger.error(EELFLoggerDelegate.errorLogger,
- "addUserRoleInExternalSystem: Failed to addUserRoleInExternalSystem", e);
- }
- }
- }
-
- @Override
- public void deleteRoleDependencyRecords(Session localSession, Long roleId, Long appId, boolean isPortalRequest)
- throws Exception {
- try {
- String sql = "";
- Query query = null;
- // It should delete only when it portal's roleId
- if (appId.equals(PortalConstants.PORTAL_APP_ID)) {
- // Delete from fn_role_function
- sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
- logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
- query = localSession.createSQLQuery(sql);
- query.executeUpdate();
- // Delete from fn_role_composite
- sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId;
- logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
- query = localSession.createSQLQuery(sql);
- query.executeUpdate();
- }
- // Delete from ep_app_role_function
- sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId;
- logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
- query = localSession.createSQLQuery(sql);
- query.executeUpdate();
- // Delete from ep_role_notification
- sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
- logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
- query = localSession.createSQLQuery(sql);
- query.executeUpdate();
- // Delete from fn_user_pseudo_role
- sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
- logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
- query = localSession.createSQLQuery(sql);
- query.executeUpdate();
- // Delete form EP_WIDGET_CATALOG_ROLE
- sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId;
- logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
- query = localSession.createSQLQuery(sql);
- query.executeUpdate();
- // Delete form EP_WIDGET_CATALOG_ROLE
- sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId;
- logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
- query = localSession.createSQLQuery(sql);
- query.executeUpdate();
- if (!isPortalRequest) {
- // Delete form fn_menu_functional_roles
- sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
- logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
- query = localSession.createSQLQuery(sql);
- query.executeUpdate();
- }
- } catch (Exception e) {
- logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e);
- throw new DeleteDomainObjectFailedException("delete Failed" + e.getMessage());
- }
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public List<String> getMenuFunctionsList(String uebkey) throws Exception {
- List<String> appMenuFunctionsList = null;
- List<String> appMenuFunctionsFinalList = new ArrayList<>();
- try {
- EPApp app = getApp(uebkey).get(0);
- final Map<String, Long> appParams = new HashMap<>();
- appParams.put(APP_ID, app.getId());
- appMenuFunctionsList = dataAccessService.executeNamedQuery("getMenuFunctions", appParams, null);
- for (String appMenuFunction : appMenuFunctionsList) {
- if (appMenuFunction.contains(FUNCTION_PIPE)) {
- appMenuFunctionsFinalList.add(EcompPortalUtils.getFunctionCode(appMenuFunction));
- } else {
- appMenuFunctionsFinalList.add(appMenuFunction);
- }
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getMenuFunctionsList: Failed", e);
- return appMenuFunctionsFinalList;
- }
- return appMenuFunctionsFinalList;
- }
-
- @SuppressWarnings({"unchecked"})
- @Override
- public List<EcompUser> getAllAppUsers(String uebkey) throws Exception {
- List<String> usersList = new ArrayList<>();
- List<EcompUser> usersfinalList = new ArrayList<>();
- try {
- EPApp app = getApp(uebkey).get(0);
- final Map<String, Long> appParams = new HashMap<>();
- appParams.put("appId", app.getId());
- List<EcompUserRoles> userList =
- (List<EcompUserRoles>) dataAccessService.executeNamedQuery("ApplicationUserRoles", appParams, null);
- for (EcompUserRoles ecompUserRole : userList) {
- boolean found = false;
- Set<EcompRole> roles = null;
- for (EcompUser user : usersfinalList) {
- if (user.getOrgUserId().equals(ecompUserRole.getOrgUserId())) {
- EcompRole ecompRole = new EcompRole();
- ecompRole.setId(ecompUserRole.getRoleId());
- ecompRole.setName(ecompUserRole.getRoleName());
- roles = user.getRoles();
- EcompRole role = roles.stream().filter(x -> x.getName().equals(ecompUserRole.getRoleName()))
- .findAny().orElse(null);
- SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
- if (role != null) {
- roleFunctionSet = (SortedSet<EcompRoleFunction>) role.getRoleFunctions();
- }
- String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
- functionCode = EPUserUtils.decodeFunctionCode(functionCode);
- EcompRoleFunction epRoleFunction = new EcompRoleFunction();
- epRoleFunction.setName(ecompUserRole.getFunctionName());
- epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
- epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
- epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
- roleFunctionSet.add(epRoleFunction);
- ecompRole.setRoleFunctions(roleFunctionSet);
- roles.add(ecompRole);
- user.setRoles(roles);
- found = true;
- break;
- }
- }
- if (!found) {
- EcompUser epUser = new EcompUser();
- epUser.setOrgId(ecompUserRole.getOrgId());
- epUser.setManagerId(ecompUserRole.getManagerId());
- epUser.setFirstName(ecompUserRole.getFirstName());
- epUser.setLastName(ecompUserRole.getLastName());
- epUser.setPhone(ecompUserRole.getPhone());
- epUser.setEmail(ecompUserRole.getEmail());
- epUser.setOrgUserId(ecompUserRole.getOrgUserId());
- epUser.setOrgCode(ecompUserRole.getOrgCode());
- epUser.setOrgManagerUserId(ecompUserRole.getOrgManagerUserId());
- epUser.setJobTitle(ecompUserRole.getJobTitle());
- epUser.setLoginId(ecompUserRole.getLoginId());
- epUser.setActive(true);
- roles = new HashSet<>();
- EcompRole ecompRole = new EcompRole();
- ecompRole.setId(ecompUserRole.getRoleId());
- ecompRole.setName(ecompUserRole.getRoleName());
- SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
- String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
- functionCode = EPUserUtils.decodeFunctionCode(functionCode);
- EcompRoleFunction epRoleFunction = new EcompRoleFunction();
- epRoleFunction.setName(ecompUserRole.getFunctionName());
- epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
- epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
- epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
- roleFunctionSet.add(epRoleFunction);
- ecompRole.setRoleFunctions(roleFunctionSet);
- roles.add(ecompRole);
- epUser.setRoles(roles);
- usersfinalList.add(epUser);
- }
- }
- ObjectMapper mapper = new ObjectMapper();
- for (EcompUser u1 : usersfinalList) {
- String str = mapper.writeValueAsString(u1);
- usersList.add(str);
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getAllUsers failed", e);
- throw e;
- }
- return usersfinalList;
- }
-
- @Override
- public Role ConvertCentralRoleToRole(String result) {
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- Role newRole = new Role();
- try {
- newRole = mapper.readValue(result, Role.class);
- } catch (IOException e) {
- logger.error(EELFLoggerDelegate.errorLogger, "Failed to convert the result to Role Object", e);
- }
- if (newRole.getRoleFunctions() != null) {
- @SuppressWarnings("unchecked")
- Set<RoleFunction> roleFunctionList = newRole.getRoleFunctions();
- Set<RoleFunction> roleFunctionListNew = new HashSet<>();
- Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
- while (itetaror.hasNext()) {
- Object nextValue = itetaror.next();
- RoleFunction roleFun = mapper.convertValue(nextValue, RoleFunction.class);
- roleFunctionListNew.add(roleFun);
- }
- newRole.setRoleFunctions(roleFunctionListNew);
- }
- return newRole;
- }
-
- @Override
- @SuppressWarnings("unchecked")
- public List<CentralizedApp> getCentralizedAppsOfUser(String userId) {
- Map<String, String> params = new HashMap<>();
- params.put("userId", userId);
- List<CentralizedApp> centralizedAppsList = new ArrayList<>();
- try {
- centralizedAppsList = dataAccessService.executeNamedQuery("getCentralizedAppsOfUser", params, null);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
- }
- return centralizedAppsList;
- }
-
- @SuppressWarnings("unchecked")
- public List<CentralV2Role> getGlobalRolesOfApplication(Long appId) {
- Map<String, Long> params = new HashMap<>();
- params.put("appId", appId);
- List<GlobalRoleWithApplicationRoleFunction> globalRoles = new ArrayList<>();
- try {
- globalRoles =
- dataAccessService.executeNamedQuery("getGlobalRoleWithApplicationRoleFunctions", params, null);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
- }
- List<CentralV2Role> rolesfinalList = new ArrayList<>();
- if (globalRoles.size() > 0)
- rolesfinalList = finalListOfCentralRoles(globalRoles);
- return rolesfinalList;
- }
-
- @SuppressWarnings("unchecked")
- private CentralV2Role getGlobalRoleForRequestedApp(long requestedAppId, long roleId) {
- CentralV2Role finalGlobalrole = null;
- List<GlobalRoleWithApplicationRoleFunction> roleWithApplicationRoleFucntions = new ArrayList<>();
- Map<String, Long> params = new HashMap<>();
- params.put("roleId", roleId);
- params.put("requestedAppId", requestedAppId);
- try {
- roleWithApplicationRoleFucntions =
- dataAccessService.executeNamedQuery("getGlobalRoleForRequestedApp", params, null);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRoleForRequestedApp failed", e);
- }
- if (roleWithApplicationRoleFucntions.size() > 0) {
- List<CentralV2Role> rolesfinalList = finalListOfCentralRoles(roleWithApplicationRoleFucntions);
- finalGlobalrole = rolesfinalList.get(0);
- } else {
- List<EPRole> roleList = getPortalAppRoleInfo(roleId);
- finalGlobalrole = convertRoleToCentralV2Role(roleList.get(0));
- }
- return finalGlobalrole;
- }
-
- private List<CentralV2Role> finalListOfCentralRoles(List<GlobalRoleWithApplicationRoleFunction> globalRoles) {
- List<CentralV2Role> rolesfinalList = new ArrayList<>();
- for (GlobalRoleWithApplicationRoleFunction role : globalRoles) {
- boolean found = false;
- for (CentralV2Role cenRole : rolesfinalList) {
- if (role.getRoleId().equals(cenRole.getId())) {
- SortedSet<CentralV2RoleFunction> roleFunctions = cenRole.getRoleFunctions();
- CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
- roleFunctions.add(cenRoleFun);
- cenRole.setRoleFunctions(roleFunctions);
- found = true;
- break;
- }
- }
- if (!found) {
- CentralV2Role cenrole = new CentralV2Role();
- cenrole.setName(role.getRoleName());
- cenrole.setId(role.getRoleId());
- cenrole.setActive(role.isActive());
- cenrole.setPriority(role.getPriority());
- SortedSet<CentralV2RoleFunction> roleFunctions = new TreeSet<>();
- CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
- roleFunctions.add(cenRoleFun);
- cenrole.setRoleFunctions(roleFunctions);
- rolesfinalList.add(cenrole);
- }
- }
- return rolesfinalList;
- }
-
- private CentralV2RoleFunction createCentralRoleFunctionForGlobalRole(GlobalRoleWithApplicationRoleFunction role) {
- String instance;
- String type;
- String action;
- CentralV2RoleFunction cenRoleFun;
- if (role.getFunctionCd().contains(FUNCTION_PIPE)) {
- instance = EcompPortalUtils.getFunctionCode(role.getFunctionCd());
- type = EcompPortalUtils.getFunctionType(role.getFunctionCd());
- action = EcompPortalUtils.getFunctionAction(role.getFunctionCd());
- cenRoleFun = new CentralV2RoleFunction(null, instance, role.getFunctionName(), null, type, action, null);
- } else {
- type = getFunctionCodeType(role.getFunctionCd());
- action = getFunctionCodeAction(role.getFunctionCd());
- cenRoleFun = new CentralV2RoleFunction(null, role.getFunctionCd(), role.getFunctionName(), null, type,
- action, null);
- }
- return cenRoleFun;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public List<EPRole> getGlobalRolesOfPortal() {
- List<EPRole> globalRoles = new ArrayList<>();
- try {
- globalRoles = dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRolesOfPortal failed", e);
- }
- return globalRoles;
- }
-
- private CentralV2Role convertRoleToCentralV2Role(EPRole role) {
- return new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
- role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
- new TreeSet<>(), new TreeSet<>(), new TreeSet<>());
- }
-
- @Override
- public List<CentralRoleFunction> convertCentralRoleFunctionToRoleFunctionObject(
- List<CentralV2RoleFunction> answer) {
- List<CentralRoleFunction> addRoleFuncList = new ArrayList<>();
- for (CentralV2RoleFunction cenRoleFunc : answer) {
- CentralRoleFunction setRoleFunc = new CentralRoleFunction();
- setRoleFunc.setCode(cenRoleFunc.getCode());
- setRoleFunc.setName(cenRoleFunc.getName());
- addRoleFuncList.add(setRoleFunc);
- }
- return addRoleFuncList;
- }
-
- @Override
- public CentralUser getUserRoles(String loginId, String uebkey) throws Exception {
- CentralUser sendUserRoles = null;
- try {
- CentralV2User cenV2User = getV2UserAppRoles(loginId, uebkey);
- sendUserRoles = convertV2UserRolesToOlderVersion(cenV2User);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getUserRoles: failed", e);
- throw e;
- }
- return sendUserRoles;
- }
-
- /**
- *
- * It returns V2 CentralUser object if user has any roles and permissions
- *
- * @param loginId
- * @param uebkey
- * @return CentralUser object
- * @throws Exception
- */
- private CentralV2User getV2UserAppRoles(String loginId, String uebkey) throws Exception {
- EPApp app;
- List<EPUser> epUserList;
- List<EPApp> appList = getApp(uebkey);
- app = appList.get(0);
- epUserList = getUser(loginId);
- EPUser user = epUserList.get(0);
- Set<EPUserApp> userAppSet = user.getEPUserApps();
- return createEPUser(user, userAppSet, app);
- }
-
- private List<EcompRole> getUserAppRoles(EPApp app, EPUser user) {
- final Map<String, Long> userParams = new HashMap<>();
- userParams.put("appId", app.getId());
- userParams.put("userId", user.getId());
- @SuppressWarnings("unchecked")
- List<EPUserAppCurrentRoles> userAppsRolesList =
- dataAccessService.executeNamedQuery("getUserAppCurrentRoles", userParams, null);
- List<EcompRole> setUserRoles = new ArrayList<>();
- for (EPUserAppCurrentRoles role : userAppsRolesList) {
- logger.debug(EELFLoggerDelegate.debugLogger, "In getUserAppRoles()- get userRolename = {}",
- role.getRoleName());
- EcompRole ecompRole = new EcompRole();
- ecompRole.setId(role.getRoleId());
- ecompRole.setName(role.getRoleName());
- setUserRoles.add(ecompRole);
- }
- logger.debug(EELFLoggerDelegate.debugLogger, "In getUserAppRoles()- get userrole list size = {}",
- setUserRoles.size());
- return setUserRoles;
- }
-
- @Override
- public List<EcompRole> missingUserApplicationRoles(String uebkey, String loginId, Set<EcompRole> CurrentUserRoles)
- throws Exception {
- List<EPApp> appList = getApp(uebkey);
- EPApp app = appList.get(0);
- List<EPUser> epUserList;
- epUserList = getUser(loginId);
- List<EcompRole> missingUserAppRoles = new ArrayList<>();
- List<String> roleNamesList = CurrentUserRoles.stream().map(EcompRole::getName).collect(Collectors.toList());
- logger.debug(EELFLoggerDelegate.debugLogger, "Roles of User from hibernate :" + roleNamesList);
- List<EcompRole> userApplicationsRolesfromDB = getUserAppRoles(app, epUserList.get(0));
- if (userApplicationsRolesfromDB.size() > 0) {
- missingUserAppRoles = userApplicationsRolesfromDB.stream().filter(x -> !roleNamesList.contains(x.getName()))
- .collect(Collectors.toList());
- }
- List<String> MissingroleNamesList =
- missingUserAppRoles.stream().map(EcompRole::getName).collect(Collectors.toList());
- logger.debug(EELFLoggerDelegate.debugLogger, "MissingUserAppRoles():" + MissingroleNamesList);
-
- List<EcompRole> finalMissingRoleList = new ArrayList<>();
- if (missingUserAppRoles.size() > 0) {
- final Map<String, Long> params = new HashMap<>();
- for (EcompRole role : missingUserAppRoles) {
- params.put("roleId", role.getId());
- params.put(APP_ID, app.getId());
-
- EcompRole epRole = new EcompRole();
- epRole.setId(role.getId());
- epRole.setName(role.getName());
- @SuppressWarnings("unchecked")
- List<CentralV2RoleFunction> appRoleFunctionList =
- dataAccessService.executeNamedQuery("getAppRoleFunctionList", params, null);
- SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
- for (CentralV2RoleFunction roleFunc : appRoleFunctionList) {
- String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
- String type = getFunctionCodeType(roleFunc.getCode());
- String action = getFunctionCodeAction(roleFunc.getCode());
- EcompRoleFunction fun = new EcompRoleFunction();
- fun.setAction(action);
- fun.setCode(functionCode);
- fun.setType(type);
- fun.setName(roleFunc.getName());
- roleFunctionSet.add(fun);
-
- }
- epRole.setRoleFunctions(roleFunctionSet);
- finalMissingRoleList.add(epRole);
- }
- }
-
- return finalMissingRoleList;
- }
-
- /**
- * It converts V2 CentralUser object to old version CentralUser object
- *
- * @param cenV2User
- * @return EPUser object
- */
- private CentralUser convertV2UserRolesToOlderVersion(CentralV2User cenV2User) {
- Set<CentralV2UserApp> userV2Apps = cenV2User.getUserApps();
- Set<CentralUserApp> userApps = new TreeSet<>();
- for (CentralV2UserApp userApp : userV2Apps) {
- CentralApp app = userApp.getApp();
- CentralUserApp cua = new CentralUserApp();
- cua.setUserId(null);
- cua.setApp(app);
- SortedSet<CentralRoleFunction> cenRoleFunction = new TreeSet<>();
- for (CentralV2RoleFunction cenV2RoleFunc : userApp.getRole().getRoleFunctions()) {
- CentralRoleFunction cenRoleFunc =
- new CentralRoleFunction(cenV2RoleFunc.getCode(), cenV2RoleFunc.getName());
- cenRoleFunction.add(cenRoleFunc);
- }
- CentralRole role = new CentralRole.CentralRoleBuilder().setId(userApp.getRole().getId())
- .setName(userApp.getRole().getName()).setActive(userApp.getRole().getActive())
- .setPriority(userApp.getRole().getPriority()).setRoleFunctions(cenRoleFunction).createCentralRole();
- cua.setRole(role);
- userApps.add(cua);
- }
- return new CentralUser(cenV2User.getId(), cenV2User.getCreated(), cenV2User.getModified(),
- cenV2User.getCreatedId(), cenV2User.getModifiedId(), cenV2User.getRowNum(), cenV2User.getOrgId(),
- cenV2User.getManagerId(), cenV2User.getFirstName(), cenV2User.getMiddleInitial(),
- cenV2User.getLastName(), cenV2User.getPhone(), cenV2User.getFax(), cenV2User.getCellular(),
- cenV2User.getEmail(), cenV2User.getAddressId(), cenV2User.getAlertMethodCd(), cenV2User.getHrid(),
- cenV2User.getOrgUserId(), cenV2User.getOrgCode(), cenV2User.getAddress1(), cenV2User.getAddress2(),
- cenV2User.getCity(), cenV2User.getState(), cenV2User.getZipCode(), cenV2User.getCountry(),
- cenV2User.getOrgManagerUserId(), cenV2User.getLocationClli(), cenV2User.getBusinessCountryCode(),
- cenV2User.getBusinessCountryName(), cenV2User.getBusinessUnit(), cenV2User.getBusinessUnitName(),
- cenV2User.getDepartment(), cenV2User.getDepartmentName(), cenV2User.getCompanyCode(),
- cenV2User.getCompany(), cenV2User.getZipCodeSuffix(), cenV2User.getJobTitle(),
- cenV2User.getCommandChain(), cenV2User.getSiloStatus(), cenV2User.getCostCenter(),
- cenV2User.getFinancialLocCode(), cenV2User.getLoginId(), cenV2User.getLoginPwd(),
- cenV2User.getLastLoginDate(), cenV2User.isActive(), cenV2User.isInternal(),
- cenV2User.getSelectedProfileId(), cenV2User.getTimeZoneId(), cenV2User.isOnline(),
- cenV2User.getChatId(), userApps);
- }
-
- @Override
- public List<CentralRole> convertV2CentralRoleListToOldVerisonCentralRoleList(List<CentralV2Role> v2CenRoleList) {
- List<CentralRole> cenRoleList = new ArrayList<>();
- for (CentralV2Role v2CenRole : v2CenRoleList) {
- SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
- for (CentralV2RoleFunction v2CenRoleFunc : v2CenRole.getRoleFunctions()) {
- CentralRoleFunction roleFunc =
- new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName());
- cenRoleFuncList.add(roleFunc);
- }
- CentralRole role = new CentralRole.CentralRoleBuilder().setId(v2CenRole.getId())
- .setName(v2CenRole.getName()).setActive(v2CenRole.getActive()).setPriority(v2CenRole.getPriority())
- .setRoleFunctions(cenRoleFuncList).createCentralRole();
- cenRoleList.add(role);
- }
- return cenRoleList;
- }
-
- @Override
- public ResponseEntity<String> getNameSpaceIfExists(EPApp app) throws Exception {
- HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
- HttpEntity<String> entity = new HttpEntity<>(headers);
- logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Connecting to External Auth system");
- ResponseEntity<String> response = null;
- try {
- response =
- template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
- + "nss/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
- logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Finished ",
- response.getStatusCode().value());
- } catch (HttpClientErrorException e) {
- logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e);
- EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
- if (e.getStatusCode() == HttpStatus.NOT_FOUND)
- throw new InvalidApplicationException("Invalid NameSpace");
- else
- throw e;
- }
- return response;
- }
-
- @Override
- public CentralRole convertV2CentralRoleToOldVerisonCentralRole(CentralV2Role v2CenRole) {
- SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
- for (CentralV2RoleFunction v2CenRoleFunc : v2CenRole.getRoleFunctions()) {
- CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName());
- cenRoleFuncList.add(roleFunc);
- }
- return new CentralRole.CentralRoleBuilder().setId(v2CenRole.getId()).setName(v2CenRole.getName())
- .setActive(v2CenRole.getActive()).setPriority(v2CenRole.getPriority()).setRoleFunctions(cenRoleFuncList)
- .createCentralRole();
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public Integer bulkUploadUsersSingleRole(String uebkey, Long roleId, String modifiedRoleName) throws Exception {
- EPApp app = getApp(uebkey).get(0);
- final Map<String, String> params = new HashMap<>();
- params.put("uebKey", app.getUebKey());
- params.put("roleId", String.valueOf(roleId));
- List<BulkUploadUserRoles> userRolesList = null;
- Integer userRolesAdded = 0;
- if (app.getCentralAuth()) {
- userRolesList = dataAccessService.executeNamedQuery("getBulkUsersForSingleRole", params, null);
- for (BulkUploadUserRoles userRolesUpload : userRolesList) {
- userRolesUpload.setRoleName(modifiedRoleName);
- if (!userRolesUpload.getOrgUserId().equals("su1234")) {
- addUserRoleInExternalSystem(userRolesUpload);
- userRolesAdded++;
- }
- }
- }
- return userRolesAdded;
- }
-
- @Override
- public String encodeFunctionCode(String funCode) {
- String encodedString = funCode;
- List<Pattern> encodingList = new ArrayList<>();
- encodingList.add(Pattern.compile("/"));
- encodingList.add(Pattern.compile("-"));
- for (Pattern xssInputPattern : encodingList) {
- encodedString = xssInputPattern.matcher(encodedString)
- .replaceAll("%" + Hex.encodeHexString(xssInputPattern.toString().getBytes()));
- }
- encodedString = encodedString.replaceAll("\\*", "%" + Hex.encodeHexString("*".getBytes()));
- return encodedString;
- }
-
- @Override
- public void bulkUploadRoleFunc(UploadRoleFunctionExtSystem data, EPApp app) throws Exception {
- ObjectMapper mapper = new ObjectMapper();
- HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
- try {
- ExternalAccessRolePerms extRolePerms;
- ExternalAccessPerms extPerms;
- extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + data.getType(),
- encodeFunctionCode(data.getInstance()), data.getAction());
- String appNameSpace = "";
- if (data.getIsGlobalRolePartnerFunc()) {
- appNameSpace = epAppService.getApp(1l).getNameSpace();
- } else {
- appNameSpace = app.getNameSpace();
- }
- extRolePerms = new ExternalAccessRolePerms(extPerms, appNameSpace + "." + data.getRoleName()
- .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
- String updateRolePerms = mapper.writeValueAsString(extRolePerms);
- HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
- updateRoleFunctionInExternalSystem(updateRolePerms, entity);
- } catch (HttpClientErrorException e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "HttpClientErrorException - Failed to add role function in external central auth system", e);
- EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
- throw e;
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "addFunctionInExternalSystem: Failed to add role fucntion in external central auth system", e);
- throw e;
- }
- }
-
- private void updateRoleFunctionInExternalSystem(String updateRolePerms, HttpEntity<String> entity) {
- logger.debug(EELFLoggerDelegate.debugLogger, "bulkUploadRoleFunc: {} for POST: {}",
- CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
- ResponseEntity<String> addPermResponse = template.exchange(
- SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
- HttpMethod.POST, entity, String.class);
- logger.debug(EELFLoggerDelegate.debugLogger,
- "bulkUploadRoleFunc: Finished adding permission for POST: {} and status code: {} ",
- addPermResponse.getStatusCode().value(), updateRolePerms);
- }
-
- @Override
- public void syncApplicationUserRolesFromExtAuthSystem(String loginId) throws Exception {
- String name = "";
- if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
- name = loginId + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
- }
- HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
- HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
- ResponseEntity<String> getResponse = getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
- List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
- String res = getResponse.getBody();
- JSONObject jsonObj = null;
- JSONArray extRoles = null;
- if (!res.equals("{}")) {
- jsonObj = new JSONObject(res);
- extRoles = jsonObj.getJSONArray("role");
- }
- updateUserRolesInLocal(userRoleDetailList, extRoles, loginId);
- }
-
- @SuppressWarnings("unchecked")
- private void updateUserRolesInLocal(List<ExternalAccessUserRoleDetail> userRoleDetailList, JSONArray extRoles,
- String loginId) throws InvalidUserException {
- HashMap<String, String> userParams = new HashMap<>();
- userParams.put("orgUserId", loginId);
- // Get all centralized applications existing user roles from local
- List<CentralizedAppRoles> currentUserAppRoles =
- dataAccessService.executeNamedQuery("getUserCentralizedAppRoles", userParams, null);
- EPUser user = getUser(loginId).get(0);
- // Get all centralized applications roles from local
- HashMap<String, CentralizedAppRoles> cenAppRolesMap = getCentralizedAppRoleList();
- HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap =
- getCurrentUserCentralizedAppRoles(currentUserAppRoles);
- // Get all centralized applications + admin role from local
- HashMap<String, EPApp> centralisedAppsMap = getCentralizedAdminAppsInfo();
- if (extRoles != null) {
- ExternalAccessUserRoleDetail userRoleDetail = null;
- for (int i = 0; i < extRoles.length(); i++) {
- if (!extRoles.getJSONObject(i).getString("name").endsWith(ADMIN)
- && !extRoles.getJSONObject(i).getString("name").endsWith(OWNER)) {
- userRoleDetail =
- new ExternalAccessUserRoleDetail(extRoles.getJSONObject(i).getString("name"), null);
- userRoleDetailList.add(userRoleDetail);
- }
- }
- addUserRolesInLocal(userRoleDetailList, user, cenAppRolesMap, currentCentralizedUserAppRolesMap,
- centralisedAppsMap);
- }
- }
-
- private void addUserRolesInLocal(List<ExternalAccessUserRoleDetail> userRoleDetailList, EPUser user,
- HashMap<String, CentralizedAppRoles> cenAppRolesMap,
- HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap,
- HashMap<String, EPApp> centralisedAppsMap) {
- for (ExternalAccessUserRoleDetail extUserRoleDetail : userRoleDetailList) {
- try {
- // check if user already has role in local
- if (!currentCentralizedUserAppRolesMap.containsKey(extUserRoleDetail.getName())) {
- CentralizedAppRoles getCenAppRole = cenAppRolesMap.get(extUserRoleDetail.getName());
- if (getCenAppRole != null) {
- logger.debug(EELFLoggerDelegate.debugLogger,
- "addUserRolesInLocal: Adding user role from external auth system {}",
- extUserRoleDetail.toString());
- EPUserApp userApp = new EPUserApp();
- EPApp app = new EPApp();
- app.setId(getCenAppRole.getAppId());
- EPRole epRole = new EPRole();
- epRole.setId(getCenAppRole.getRoleId());
- userApp.setApp(app);
- userApp.setUserId(user.getId());
- userApp.setRole(epRole);
- dataAccessService.saveDomainObject(userApp, null);
- logger.debug(EELFLoggerDelegate.debugLogger,
- "addUserRolesInLocal: Finished user role from external auth system {}",
- extUserRoleDetail.toString());
- } else if (getCenAppRole == null // check if user has app
- // account admin role
- && extUserRoleDetail.getName().endsWith(PortalConstants.ADMIN_ROLE.replaceAll(
- EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
- EPApp app = centralisedAppsMap.get(extUserRoleDetail.getName());
- if (app != null) {
- logger.debug(EELFLoggerDelegate.debugLogger,
- "addUserRolesInLocal: Adding user role from external auth system {}",
- extUserRoleDetail.toString());
- EPUserApp userApp = new EPUserApp();
- EPRole epRole = new EPRole();
- epRole.setId(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
- userApp.setApp(app);
- userApp.setUserId(user.getId());
- userApp.setRole(epRole);
- dataAccessService.saveDomainObject(userApp, null);
- logger.debug(EELFLoggerDelegate.debugLogger,
- "addUserRolesInLocal: Finished user role from external auth system {}",
- extUserRoleDetail.toString());
- }
- }
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "addUserRolesInLocal - Failed to update user role in local from external auth system {} ",
- extUserRoleDetail.toString(), e);
- }
- }
- }
-
- @SuppressWarnings("unchecked")
- private HashMap<String, EPApp> getCentralizedAdminAppsInfo() {
- List<EPApp> centralizedApps = dataAccessService.executeNamedQuery("getCentralizedApps", null, null);
- HashMap<String, EPApp> centralisedAppsMap = new HashMap<>();
- for (EPApp cenApp : centralizedApps) {
- centralisedAppsMap.put(
- cenApp.getNameSpace() + "."
- + PortalConstants.ADMIN_ROLE.replaceAll(
- EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
- cenApp);
- }
- return centralisedAppsMap;
- }
-
- private HashMap<String, CentralizedAppRoles> getCurrentUserCentralizedAppRoles(
- List<CentralizedAppRoles> currentUserAppRoles) {
- HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap = new HashMap<>();
- for (CentralizedAppRoles cenAppUserRole : currentUserAppRoles) {
- currentCentralizedUserAppRolesMap.put(
- cenAppUserRole.getAppNameSpace() + "."
- + cenAppUserRole.getRoleName().replaceAll(
- EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
- cenAppUserRole);
- }
- return currentCentralizedUserAppRolesMap;
- }
-
- @SuppressWarnings("unchecked")
- private HashMap<String, CentralizedAppRoles> getCentralizedAppRoleList() {
- List<CentralizedAppRoles> centralizedAppRoles =
- dataAccessService.executeNamedQuery("getAllCentralizedAppsRoles", null, null);
- HashMap<String, CentralizedAppRoles> cenAppRolesMap = new HashMap<>();
- for (CentralizedAppRoles CentralizedAppRole : centralizedAppRoles) {
- cenAppRolesMap.put(
- CentralizedAppRole.getAppNameSpace() + "."
- + CentralizedAppRole.getRoleName().replaceAll(
- EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
- CentralizedAppRole);
- }
- return cenAppRolesMap;
- }
-
- @Override
- public ResponseEntity<String> getUserRolesFromExtAuthSystem(String name, HttpEntity<String> getUserRolesEntity) {
- logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles");
- ResponseEntity<String> getResponse =
- template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
- + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class);
- if (getResponse.getStatusCode().value() == 200) {
- logger.debug(EELFLoggerDelegate.debugLogger,
- "getAllUserRoleFromExtAuthSystem: Finished GET user roles from external system and received user roles {}",
- getResponse.getBody());
- } else {
- logger.error(EELFLoggerDelegate.errorLogger,
- "getAllUserRoleFromExtAuthSystem: Failed GET user roles from external system and received user roles {}",
- getResponse.getBody());
- EPLogUtil.logExternalAuthAccessAlarm(logger, getResponse.getStatusCode());
- }
- return getResponse;
- }
-
- @Override
- public Integer updateAppRoleDescription(String uebkey) {
- Integer roleDescUpdated = 0;
- EPApp app;
- try {
- app = getApp(uebkey).get(0);
- List<EPRole> roles = getAppRoles(app.getId());
- for (EPRole epRole : roles) {
- Role role = new Role();
- role.setName(epRole.getName());
- boolean status = addRoleDescriptionInExtSystem(role, app);
- if (status)
- roleDescUpdated++;
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "updateAppRoleDescription: Failed! ", e);
- }
- return roleDescUpdated;
- }
+ private static final String APP_ROLE_NAME_PARAM = "appRoleName";
+ private static final String GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM = "getRoletoUpdateInExternalAuthSystem";
+ private static final String GET_PORTAL_APP_ROLES_QUERY = "getPortalAppRoles";
+ private static final String GET_ROLE_FUNCTION_QUERY = "getRoleFunction";
+ private static final String FUNCTION_CODE_PARAMS = "functionCode";
+ private static final String AND_FUNCTION_CD_EQUALS = " and function_cd = '";
+ private static final String OWNER = ".owner";
+ private static final String ADMIN = ".admin";
+ private static final String ACCOUNT_ADMINISTRATOR = ".Account_Administrator";
+ private static final String FUNCTION_PIPE = "|";
+ private static final String EXTERNAL_AUTH_PERMS = "perms";
+ private static final String EXTERNAL_AUTH_ROLE_DESCRIPTION = "description";
+ private static final String IS_EMPTY_JSON_STRING = "{}";
+ private static final String CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE = "Connecting to External Auth system";
+ private static final String APP_ID = "appId";
+ private static final String ROLE_NAME = "name";
+ private static final String APP_ID_EQUALS = " app_id = ";
+ private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesServiceImpl.class);
+ @Autowired
+ private DataAccessService dataAccessService;
+ @Autowired
+ private EPAppService epAppService;
+ @Autowired
+ private SessionFactory sessionFactory;
+ @Autowired
+ EPRoleService ePRoleService;
+ RestTemplate template = new RestTemplate();
+ // These decode values are based on HexDecoder
+ static final String decodeValueOfForwardSlash = "2f";
+ static final String decodeValueOfHiphen = "2d";
+ static final String decodeValueOfStar = "2a";
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<EPRole> getAppRoles(Long appId) throws Exception {
+ List<EPRole> applicationRoles = null;
+ final Map<String, Long> appParams = new HashMap<>();
+ try {
+ if (appId == 1) {
+ applicationRoles = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
+ } else {
+ appParams.put("appId", appId);
+ applicationRoles = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getAppRoles: failed", e);
+ throw e;
+ }
+ return applicationRoles;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<EPApp> getApp(String uebkey) throws Exception {
+ List<EPApp> app = null;
+ try {
+ final Map<String, String> appUebkeyParams = new HashMap<>();
+ appUebkeyParams.put("appKey", uebkey);
+ app = dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null);
+ if (!app.isEmpty() && !app.get(0).getEnabled()
+ && !app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
+ throw new InactiveApplicationException("Application:" + app.get(0).getName() + " is Unavailable");
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getApp: failed", e);
+ throw e;
+ }
+ return app;
+ }
+
+ /**
+ * It returns single application role from external auth system
+ *
+ * @param addRole
+ * @param app
+ * @return JSON string which contains application role details
+ * @throws Exception
+ */
+ private String getSingleAppRole(String addRole, EPApp app) throws Exception {
+ HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+ HttpEntity<String> entity = new HttpEntity<>(headers);
+ ResponseEntity<String> response = null;
+ logger.debug(EELFLoggerDelegate.debugLogger, "getSingleAppRole: Connecting to External Auth system");
+ response = template.exchange(
+ SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
+ + app.getNameSpace() + "." + addRole
+ .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
+ HttpMethod.GET, entity, String.class);
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "getSingleAppRole: Finished GET app role from External Auth system and status code: {} ",
+ response.getStatusCode().value());
+ return response.getBody();
+ }
+
+ @Override
+ public boolean addRole(Role addRole, String uebkey) throws Exception {
+ boolean response = false;
+ ResponseEntity<String> addResponse = null;
+ HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+ EPApp app = getApp(uebkey).get(0);
+ String newRole = updateExistingRoleInExternalSystem(addRole, app);
+ HttpEntity<String> entity = new HttpEntity<>(newRole, headers);
+ logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Connecting to External Auth system");
+ addResponse = template.exchange(
+ SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
+ HttpMethod.POST, entity, String.class);
+ if (addResponse.getStatusCode().value() == 201) {
+ response = true;
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "addRole: Finished adding role in the External Auth system and response code: {} ",
+ addResponse.getStatusCode().value());
+ }
+ if (addResponse.getStatusCode().value() == 406) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "addRole: Failed to add in the External Auth system due to {} and status code: {}",
+ addResponse.getBody(), addResponse.getStatusCode().value());
+ }
+ return response;
+ }
+
+ /**
+ *
+ * It deletes record in external auth system
+ *
+ * @param delRole
+ * @return JSON String which has status code and response body
+ * @throws Exception
+ */
+ private ResponseEntity<String> deleteRoleInExternalSystem(String delRole) throws Exception {
+ ResponseEntity<String> delResponse = null;
+ HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+ HttpEntity<String> entity = new HttpEntity<>(delRole, headers);
+ logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: {} for DELETE: {}",
+ CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, delRole);
+ delResponse = template.exchange(
+ SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role?force=true",
+ HttpMethod.DELETE, entity, String.class);
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "deleteRoleInExternalSystem: Finished DELETE operation in the External Auth system {} and status code: {} ",
+ delRole, delResponse.getStatusCode().value());
+ return delResponse;
+ }
+
+ /**
+ * It updates role in external auth system
+ *
+ * @param updateExtRole
+ * @param app
+ * @return true if success else false
+ * @throws Exception If updateRoleInExternalSystem fails we catch it in logger
+ * for detail message
+ */
+ private boolean updateRoleInExternalSystem(Role updateExtRole, EPApp app, boolean isGlobalRole) throws Exception {
+ boolean response = false;
+ ObjectMapper mapper = new ObjectMapper();
+ ResponseEntity<String> deleteResponse = null;
+ List<EPRole> epRoleList = null;
+ if (app.getId().equals(PortalConstants.PORTAL_APP_ID)
+ || (isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
+ epRoleList = getPortalAppRoleInfo(updateExtRole.getId());
+ } else {
+ epRoleList = getPartnerAppRoleInfo(updateExtRole.getId(), app);
+ }
+ // Assigning functions to global role
+ if ((isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
+ List<RoleFunction> globalRoleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole);
+ EPApp portalAppInfo = epAppService.getApp(PortalConstants.PORTAL_APP_ID);
+ addFunctionsTOGlobalRole(epRoleList, updateExtRole, globalRoleFunctionListNew, mapper, app, portalAppInfo);
+ response = true;
+ } else {
+ String appRole = getSingleAppRole(epRoleList.get(0).getName(), app);
+ List<RoleFunction> roleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole);
+ if (!appRole.equals(IS_EMPTY_JSON_STRING)) {
+ JSONObject jsonObj = new JSONObject(appRole);
+ JSONArray extRole = jsonObj.getJSONArray("role");
+ if (!extRole.getJSONObject(0).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
+ String roleName = extRole.getJSONObject(0).getString(ROLE_NAME);
+ Map<String, String> delRoleKeyMapper = new HashMap<>();
+ delRoleKeyMapper.put(ROLE_NAME, roleName);
+ String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
+ deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
+ if (deleteResponse.getStatusCode().value() != 200) {
+ throw new ExternalAuthSystemException(deleteResponse.getBody());
+ }
+ addRole(updateExtRole, app.getUebKey());
+ } else {
+ String desc = extRole.getJSONObject(0).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
+ String name = extRole.getJSONObject(0).getString(ROLE_NAME);
+ List<ExternalAccessPerms> list = new ArrayList<>();
+ if (extRole.getJSONObject(0).has(EXTERNAL_AUTH_PERMS)) {
+ JSONArray perms = extRole.getJSONObject(0).getJSONArray(EXTERNAL_AUTH_PERMS);
+ list = mapper.readValue(perms.toString(), TypeFactory.defaultInstance()
+ .constructCollectionType(List.class, ExternalAccessPerms.class));
+ }
+ // If role name or role functions are updated then delete
+ // record in External System and add new record to avoid
+ // conflicts
+ boolean isRoleNameChanged = false;
+ if (!desc.equals(updateExtRole.getName())) {
+ isRoleNameChanged = true;
+ deleteRoleInExtSystem(mapper, name);
+ addRole(updateExtRole, app.getUebKey());
+ // add partner functions to the global role in External
+ // Auth System
+ if (!list.isEmpty() && isGlobalRole) {
+ addPartnerHasRoleFunctionsToGlobalRole(list, mapper, app, updateExtRole);
+ }
+ list.removeIf(
+ perm -> EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace()));
+ // if role name is changes please ignore the previous
+ // functions in External Auth
+ // and update with user requested functions
+ addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name, list);
+ }
+ // Delete role in External System if role is inactive
+ if (!updateExtRole.getActive()) {
+ deleteRoleInExtSystem(mapper, name);
+ }
+ if (!isRoleNameChanged) {
+ response = addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name,
+ list);
+ }
+ }
+ } else {
+ // It seems like role exists in local DB but not in External
+ // Access system
+ if (updateExtRole.getActive()) {
+ addRole(updateExtRole, app.getUebKey());
+ ExternalAccessRolePerms extAddRolePerms = null;
+ ExternalAccessPerms extAddPerms = null;
+ List<RoleFunction> roleFunctionListAdd = convertSetToListOfRoleFunctions(updateExtRole);
+ HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+ for (RoleFunction roleFunc : roleFunctionListAdd) {
+ extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + roleFunc.getType(),
+ roleFunc.getCode(), roleFunc.getAction());
+ extAddRolePerms = new ExternalAccessRolePerms(extAddPerms,
+ app.getNameSpace() + "." + updateExtRole.getName().replaceAll(
+ EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
+ response = addRoleFuncExtSysRestAPI(mapper, extAddRolePerms, headers);
+ }
+ }
+ }
+ }
+ return response;
+ }
+
+ private void deleteRoleInExtSystem(ObjectMapper mapper, String name)
+ throws JsonProcessingException, Exception, ExternalAuthSystemException {
+ ResponseEntity<String> deleteResponse;
+ Map<String, String> delRoleKeyMapper = new HashMap<>();
+ delRoleKeyMapper.put(ROLE_NAME, name);
+ String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
+ deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
+ if (deleteResponse.getStatusCode().value() != 200) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "updateRoleInExternalSystem: Failed to delete role in external system due to {} ",
+ deleteResponse.getBody());
+ throw new ExternalAuthSystemException(deleteResponse.getBody());
+ }
+ }
+
+ private boolean addRemoveFunctionsToRole(Role updateExtRole, EPApp app, ObjectMapper mapper,
+ List<RoleFunction> roleFunctionListNew, String name, List<ExternalAccessPerms> list) throws Exception {
+ boolean response;
+ Map<String, RoleFunction> updateRoleFunc = new HashMap<>();
+ for (RoleFunction addPerm : roleFunctionListNew) {
+ updateRoleFunc.put(addPerm.getCode(), addPerm);
+ }
+ final Map<String, ExternalAccessPerms> extRolePermMap = new HashMap<>();
+ final Map<String, ExternalAccessPerms> extRolePermMapPipes = new HashMap<>();
+ list.removeIf(perm -> !EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace()));
+ // Update permissions in the ExternalAccess System
+ HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+ if (!list.isEmpty()) {
+ for (ExternalAccessPerms perm : list) {
+ RoleFunction roleFunc = updateRoleFunc.get(perm.getType().substring(app.getNameSpace().length() + 1)
+ + FUNCTION_PIPE + perm.getInstance() + FUNCTION_PIPE + perm.getAction());
+ if (roleFunc == null) {
+ RoleFunction roleFuncPipeFilter = updateRoleFunc.get(perm.getInstance());
+ if (roleFuncPipeFilter == null)
+ removePermForRole(perm, mapper, name, headers);
+ }
+ extRolePermMap.put(perm.getInstance(), perm);
+ extRolePermMapPipes.put(perm.getType().substring(app.getNameSpace().length() + 1) + FUNCTION_PIPE
+ + perm.getInstance() + FUNCTION_PIPE + perm.getAction(), perm);
+ }
+ }
+ response = true;
+ if (!roleFunctionListNew.isEmpty()) {
+ for (RoleFunction roleFunc : roleFunctionListNew) {
+ if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
+ ExternalAccessPerms perm = extRolePermMapPipes.get(roleFunc.getCode());
+ if (perm == null) {
+ response = addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers,
+ roleFunc);
+ }
+ } else {
+ if (!extRolePermMap.containsKey(EcompPortalUtils.getFunctionCode(roleFunc.getCode()))) {
+ response = addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers,
+ roleFunc);
+ }
+ }
+ }
+ }
+ return response;
+ }
+
+ /*
+ * Adds function to the role in the external auth system while editing a role or
+ * updating new functions to a role
+ *
+ */
+ private boolean addFunctionsToRoleInExternalAuthSystem(Role updateExtRole, EPApp app, ObjectMapper mapper,
+ HttpHeaders headers, RoleFunction roleFunc) throws JsonProcessingException {
+ boolean response;
+ ExternalAccessRolePerms extRolePerms;
+ ExternalAccessPerms extPerms;
+ String code = "";
+ String type = "";
+ String action = "";
+ if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
+ code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
+ type = EcompPortalUtils.getFunctionType(roleFunc.getCode());
+ action = getFunctionCodeAction(roleFunc.getCode());
+ } else {
+ code = roleFunc.getCode();
+ type = roleFunc.getCode().contains("menu") ? "menu" : "url";
+ action = "*";
+ }
+ extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, code, action);
+ extRolePerms = new ExternalAccessRolePerms(extPerms, app.getNameSpace() + "." + updateExtRole.getName()
+ .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
+ String updateRolePerms = mapper.writeValueAsString(extRolePerms);
+ HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
+ logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: {} for POST: {}",
+ CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
+ ResponseEntity<String> addResponse = template.exchange(
+ SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
+ HttpMethod.POST, entity, String.class);
+ if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 409) {
+ response = false;
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "updateRoleInExternalSystem: Connected to External Auth system but something went wrong! due to {} and statuscode: {}",
+ addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
+ } else {
+ response = true;
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "updateRoleInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ",
+ updateRolePerms, addResponse.getStatusCode().value());
+ }
+ return response;
+ }
+
+ private void addPartnerHasRoleFunctionsToGlobalRole(List<ExternalAccessPerms> permslist, ObjectMapper mapper,
+ EPApp app, Role updateExtRole) throws Exception {
+ for (ExternalAccessPerms perm : permslist) {
+ if (!EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace())) {
+ ExternalAccessRolePerms extAddGlobalRolePerms = null;
+ ExternalAccessPerms extAddPerms = null;
+ extAddPerms = new ExternalAccessPerms(perm.getType(), perm.getInstance(), perm.getAction());
+ extAddGlobalRolePerms = new ExternalAccessRolePerms(extAddPerms,
+ app.getNameSpace() + "." + updateExtRole.getName().replaceAll(
+ EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
+ String addPerms = mapper.writeValueAsString(extAddGlobalRolePerms);
+ HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+ HttpEntity<String> entity = new HttpEntity<>(addPerms, headers);
+ logger.debug(EELFLoggerDelegate.debugLogger, "addPartnerHasRoleFunctionsToGlobalRole: {} ",
+ CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
+ try {
+ ResponseEntity<String> addResponse = template
+ .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
+ + "role/perm", HttpMethod.POST, entity, String.class);
+ if (addResponse.getStatusCode().value() != 201) {
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "addPartnerHasRoleFunctionsToGlobalRole: While adding permission to the role in External Auth system something went wrong! due to {} and statuscode: {}",
+ addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
+ } else {
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "addPartnerHasRoleFunctionsToGlobalRole: Finished adding permissions to roles in External Auth system and status code: {} ",
+ addResponse.getStatusCode().value());
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "addPartnerHasRoleFunctionsToGlobalRole: Failed for POST request: {} due to ", addPerms, e);
+ }
+ }
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private void addFunctionsTOGlobalRole(List<EPRole> epRoleList, Role updateExtRole,
+ List<RoleFunction> roleFunctionListNew, ObjectMapper mapper, EPApp app, EPApp portalAppInfo)
+ throws Exception {
+ try {
+ logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addFunctionsTOGlobalRole");
+ // GET Permissions from External Auth System
+ JSONArray extPerms = getExtAuthPermissions(app);
+ List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);
+ final Map<String, ExternalAccessPermsDetail> existingPermsWithRoles = new HashMap<>();
+ final Map<String, ExternalAccessPermsDetail> existingPermsWithRolesWithPipes = new HashMap<>();
+ final Map<String, RoleFunction> userRquestedFunctionsMap = new HashMap<>();
+ final Map<String, RoleFunction> userRquestedFunctionsMapPipesFilter = new HashMap<>();
+ for (ExternalAccessPermsDetail permDetail : permsDetailList) {
+ existingPermsWithRoles.put(EcompPortalUtils.getFunctionCode(permDetail.getInstance()), permDetail);
+ existingPermsWithRolesWithPipes.put(permDetail.getInstance(), permDetail);
+ }
+ // Add If function does not exists for role in External Auth System
+ for (RoleFunction roleFunc : roleFunctionListNew) {
+ String roleFuncCode = "";
+ ExternalAccessPermsDetail permsDetail;
+ if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
+ roleFuncCode = roleFunc.getCode();
+ permsDetail = existingPermsWithRolesWithPipes.get(roleFunc.getCode());
+ } else {
+ roleFuncCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
+ permsDetail = existingPermsWithRoles.get(roleFuncCode);
+ }
+ if (null == permsDetail.getRoles()
+ || !permsDetail.getRoles()
+ .contains(portalAppInfo.getNameSpace() + FUNCTION_PIPE
+ + epRoleList.get(0).getName().replaceAll(
+ EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
+ "_"))) {
+ addRoleFunctionsToGlobalRoleInExternalSystem(roleFunc, updateExtRole, mapper, app, portalAppInfo);
+ }
+ userRquestedFunctionsMap.put(roleFuncCode, roleFunc);
+ userRquestedFunctionsMapPipesFilter.put(EcompPortalUtils.getFunctionCode(roleFuncCode), roleFunc);
+ }
+ // Delete functions if exists in External Auth System but not in
+ // incoming
+ // request
+ final Map<String, Long> epAppRoleFuncParams = new HashMap<>();
+ epAppRoleFuncParams.put("requestedAppId", app.getId());
+ epAppRoleFuncParams.put("roleId", updateExtRole.getId());
+ List<GlobalRoleWithApplicationRoleFunction> globalRoleFunctionList = dataAccessService
+ .executeNamedQuery("getGlobalRoleForRequestedApp", epAppRoleFuncParams, null);
+ for (GlobalRoleWithApplicationRoleFunction globalRoleFunc : globalRoleFunctionList) {
+ String globalRoleFuncWithoutPipes = "";
+ RoleFunction roleFunc = null;
+ if (globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
+ globalRoleFuncWithoutPipes = globalRoleFunc.getFunctionCd();
+ roleFunc = userRquestedFunctionsMap.get(globalRoleFuncWithoutPipes);
+ } else {
+ globalRoleFuncWithoutPipes = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd());
+ roleFunc = userRquestedFunctionsMapPipesFilter.get(globalRoleFuncWithoutPipes);
+ }
+ if (roleFunc == null) {
+ ExternalAccessPermsDetail permDetailFromMap = globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)
+ ? existingPermsWithRolesWithPipes.get(globalRoleFuncWithoutPipes)
+ : existingPermsWithRoles.get(globalRoleFuncWithoutPipes);
+ ExternalAccessPerms perm = new ExternalAccessPerms(permDetailFromMap.getType(),
+ EcompPortalUtils.getFunctionCode(permDetailFromMap.getInstance()),
+ permDetailFromMap.getAction());
+ String roleName = portalAppInfo.getNameSpace() + "." + globalRoleFunc.getRoleName()
+ .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_");
+ HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+ removePermForRole(perm, mapper, roleName, headers);
+ }
+ }
+ logger.debug(EELFLoggerDelegate.debugLogger, "Finished addFunctionsTOGlobalRole");
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "addFunctionsTOGlobalRole: Failed", e);
+ throw e;
+ }
+ }
+
+ private void addRoleFunctionsToGlobalRoleInExternalSystem(RoleFunction addFunction, Role globalRole,
+ ObjectMapper mapper, EPApp app, EPApp portalAppInfo) throws Exception {
+ try {
+ logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addRoleFunctionsToGlobalRoleInExternalSystem");
+ ExternalAccessRolePerms extAddRolePerms = null;
+ ExternalAccessPerms extAddPerms = null;
+ HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+ String code = "";
+ String type = "";
+ String action = "";
+ if (addFunction.getCode().contains(FUNCTION_PIPE)) {
+ code = EcompPortalUtils.getFunctionCode(addFunction.getCode());
+ type = getFunctionCodeType(addFunction.getCode());
+ action = getFunctionCodeAction(addFunction.getCode());
+ } else {
+ code = addFunction.getCode();
+ type = addFunction.getCode().contains("menu") ? "menu" : "url";
+ action = "*";
+ }
+ extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, code, action);
+ extAddRolePerms = new ExternalAccessRolePerms(extAddPerms, portalAppInfo.getNameSpace() + "." + globalRole
+ .getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
+ String updateRolePerms = mapper.writeValueAsString(extAddRolePerms);
+ HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
+ logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} ",
+ CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
+ ResponseEntity<String> addResponse = template.exchange(
+ SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
+ HttpMethod.POST, entity, String.class);
+ if (addResponse.getStatusCode().value() != 201) {
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "addRoleFunctionsInExternalSystem: While adding permission to the role in External Auth system something went wrong! due to {} and statuscode: {}",
+ addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
+ } else {
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system and status code: {} ",
+ addResponse.getStatusCode().value());
+ }
+ logger.debug(EELFLoggerDelegate.debugLogger, "Finished addRoleFunctionsToGlobalRoleInExternalSystem");
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionsToGlobalRoleInExternalSystem: Failed", e);
+ throw e;
+ }
+ }
+
+ private boolean addRoleFuncExtSysRestAPI(ObjectMapper addPermsMapper, ExternalAccessRolePerms extAddRolePerms,
+ HttpHeaders headers) throws JsonProcessingException {
+ boolean response;
+ String updateRolePerms = addPermsMapper.writeValueAsString(extAddRolePerms);
+ HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
+ logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} for POST: {} ",
+ CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
+ ResponseEntity<String> addResponse = template.exchange(
+ SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
+ HttpMethod.POST, entity, String.class);
+ if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 409) {
+ response = false;
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "addRoleFunctionsInExternalSystem: While adding permission to the role in External Auth system something went wrong! due to {} and statuscode: {}",
+ addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
+ } else {
+ response = true;
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ",
+ updateRolePerms, addResponse.getStatusCode().value());
+ }
+ return response;
+ }
+
+ /**
+ *
+ * It converts list of functions in updateExtRole parameter to the RoleFunction
+ * object
+ *
+ * @param updateExtRole
+ * @return list of functions
+ */
+ @SuppressWarnings("unchecked")
+ private List<RoleFunction> convertSetToListOfRoleFunctions(Role updateExtRole) {
+ Set<RoleFunction> roleFunctionSetList = updateExtRole.getRoleFunctions();
+ List<RoleFunction> roleFunctionList = new ArrayList<>();
+ ObjectMapper roleFuncMapper = new ObjectMapper();
+ Iterator<RoleFunction> itetaror = roleFunctionSetList.iterator();
+ while (itetaror.hasNext()) {
+ Object nextValue = itetaror.next();
+ RoleFunction roleFunction = roleFuncMapper.convertValue(nextValue, RoleFunction.class);
+ roleFunctionList.add(roleFunction);
+ }
+ return roleFunctionList.stream().distinct().collect(Collectors.toList());
+ }
+
+ /**
+ * It delete permissions/functions in the external auth system
+ *
+ * @param perm
+ * @param permMapper
+ * @param name
+ * @param headers
+ * @throws JsonProcessingException
+ * @throws Exception
+ */
+ private void removePermForRole(ExternalAccessPerms perm, ObjectMapper permMapper, String name, HttpHeaders headers)
+ throws ExternalAuthSystemException, JsonProcessingException {
+ ExternalAccessRolePerms extAccessRolePerms = new ExternalAccessRolePerms(perm, name);
+ String permDetails = permMapper.writeValueAsString(extAccessRolePerms);
+ try {
+ HttpEntity<String> deleteEntity = new HttpEntity<>(permDetails, headers);
+ logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: {} for DELETE: {} ",
+ CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, permDetails);
+ ResponseEntity<String> deletePermResponse = template
+ .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
+ + "role/" + name + "/perm", HttpMethod.DELETE, deleteEntity, String.class);
+ if (deletePermResponse.getStatusCode().value() != 200) {
+ throw new ExternalAuthSystemException(deletePermResponse.getBody());
+ }
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "removePermForRole: Finished deleting permission to role in External Auth system: {} and status code: {}",
+ permDetails, deletePermResponse.getStatusCode().value());
+ } catch (Exception e) {
+ if (e.getMessage().contains("404")) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Failed to add role for DELETE request: {} due to {}",
+ permDetails, e.getMessage());
+ } else {
+ throw e;
+ }
+ }
+ }
+
+ /**
+ * It will create new role in the External Auth System
+ *
+ * @param newRole
+ * @param app
+ * @return true if successfully added in the system else false
+ * @throws Exception If fails to add role in the system
+ */
+ private void addNewRoleInExternalSystem(List<EPRole> newRole, EPApp app)
+ throws Exception, HttpClientErrorException {
+ try {
+ HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+ ObjectMapper mapper = new ObjectMapper();
+ String addNewRole = "";
+ ExternalAccessRole extRole = new ExternalAccessRole();
+ extRole.setName(app.getNameSpace() + "." + newRole.get(0).getName()
+ .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
+ extRole.setDescription(String.valueOf(newRole.get(0).getName()));
+ addNewRole = mapper.writeValueAsString(extRole);
+ HttpEntity<String> postEntity = new HttpEntity<>(addNewRole, headers);
+ logger.debug(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: {} for POST: {} ",
+ CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addNewRole);
+ ResponseEntity<String> addNewRoleInExternalSystem = template.exchange(
+ SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
+ HttpMethod.POST, postEntity, String.class);
+ if (addNewRoleInExternalSystem.getStatusCode().value() == 201) {
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "addNewRoleInExternalSystem: Finished adding into External Auth system for POST: {} and status code: {}",
+ addNewRole, addNewRoleInExternalSystem.getStatusCode().value());
+ }
+ } catch (HttpClientErrorException ht) {
+ dataAccessService.deleteDomainObjects(EPRole.class, " role_id = " + newRole.get(0).getId(), null);
+ logger.error(EELFLoggerDelegate.debugLogger,
+ "addNewRoleInExternalSystem: Failed to add in External Auth system and status code: {}", ht);
+ throw new HttpClientErrorException(ht.getStatusCode());
+ }
+ }
+
+ /**
+ *
+ * It updates existing role in the External Auth System
+ *
+ * @param addRole It Contains role information
+ * @param app
+ * @return string which is formatted to match with the external auth system
+ * @throws JsonProcessingException
+ */
+ private String updateExistingRoleInExternalSystem(Role addRole, EPApp app) throws JsonProcessingException {
+ ObjectMapper mapper = new ObjectMapper();
+ String addNewRole = "";
+ ExternalAccessRole extRole = new ExternalAccessRole();
+ extRole.setName(app.getNameSpace() + "." + addRole.getName()
+ .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
+ extRole.setDescription(String.valueOf(addRole.getName()));
+ addNewRole = mapper.writeValueAsString(extRole);
+ return addNewRole;
+ }
+
+ /**
+ * It create a role in the external auth system and then in our local
+ *
+ * @param addRoleInDB
+ * @param app
+ * @return true else false
+ * @throws Exception
+ */
+ @SuppressWarnings("unchecked")
+ @Transactional(rollbackFor = Exception.class)
+ public boolean addRoleInEcompDB(Role addRoleInDB, EPApp app) throws Exception {
+ boolean result = false;
+ EPRole epRole = null;
+ Set<RoleFunction> roleFunctionList = addRoleInDB.getRoleFunctions();
+ List<RoleFunction> roleFunctionListNew = new ArrayList<>();
+ ObjectMapper mapper = new ObjectMapper();
+ Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
+ while (itetaror.hasNext()) {
+ Object nextValue = itetaror.next();
+ RoleFunction roleFunction = mapper.convertValue(nextValue, RoleFunction.class);
+ roleFunctionListNew.add(roleFunction);
+ }
+ List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct().collect(Collectors.toList());
+ try {
+ if (addRoleInDB.getId() == null) { // check if it is new role
+ if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
+ checkIfRoleExitsInExternalSystem(addRoleInDB, app);
+ }
+ EPRole epRoleNew = new EPRole();
+ epRoleNew.setActive(addRoleInDB.getActive());
+ epRoleNew.setName(addRoleInDB.getName());
+ epRoleNew.setPriority(addRoleInDB.getPriority());
+ if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
+ epRoleNew.setAppId(null);
+ } else {
+ epRoleNew.setAppId(app.getId());
+ }
+ dataAccessService.saveDomainObject(epRoleNew, null);
+ List<EPRole> getRoleCreated = null;
+ final Map<String, String> epAppRoleParams = new HashMap<>();
+ final Map<String, String> epAppPortalRoleParams = new HashMap<>();
+ if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
+ epAppRoleParams.put("appId", String.valueOf(app.getId()));
+ epAppRoleParams.put(APP_ROLE_NAME_PARAM, addRoleInDB.getName());
+ List<EPRole> roleCreated = dataAccessService
+ .executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, epAppRoleParams, null);
+ EPRole epUpdateRole = roleCreated.get(0);
+ epUpdateRole.setAppRoleId(epUpdateRole.getId());
+ dataAccessService.saveDomainObject(epUpdateRole, null);
+ getRoleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
+ epAppRoleParams, null);
+ } else {
+ epAppPortalRoleParams.put(APP_ROLE_NAME_PARAM, addRoleInDB.getName());
+ getRoleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY,
+ epAppPortalRoleParams, null);
+ }
+ // Add role in External Auth system
+ if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
+ addNewRoleInExternalSystem(getRoleCreated, app);
+ }
+ result = true;
+ } else { // if role already exists then update it
+ EPRole globalRole = null;
+ List<EPRole> applicationRoles;
+ List<EPRole> globalRoleList = getGlobalRolesOfPortal();
+ boolean isGlobalRole = false;
+ if (!globalRoleList.isEmpty()) {
+ EPRole role = globalRoleList.stream().filter(x -> addRoleInDB.getId().equals(x.getId())).findAny()
+ .orElse(null);
+ if (role != null) {
+ globalRole = role;
+ isGlobalRole = true;
+ }
+ }
+ if (app.getId().equals(PortalConstants.PORTAL_APP_ID)
+ || (globalRole != null && app.getId() != globalRole.getAppId())) {
+ applicationRoles = getPortalAppRoleInfo(addRoleInDB.getId());
+ } else {
+ applicationRoles = getPartnerAppRoleInfo(addRoleInDB.getId(), app);
+ }
+ if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
+ updateRoleInExternalSystem(addRoleInDB, app, isGlobalRole);
+ // Add all user to the re-named role in external auth system
+ if (!applicationRoles.isEmpty()
+ && !addRoleInDB.getName().equals(applicationRoles.get(0).getName())) {
+ bulkUploadUsersSingleRole(app.getUebKey(), applicationRoles.get(0).getId(),
+ addRoleInDB.getName());
+ }
+ }
+ deleteRoleFunction(app, applicationRoles);
+ if (!applicationRoles.isEmpty()) {
+ epRole = applicationRoles.get(0);
+ epRole.setName(addRoleInDB.getName());
+ epRole.setPriority(addRoleInDB.getPriority());
+ epRole.setActive(addRoleInDB.getActive());
+ if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
+ epRole.setAppId(null);
+ epRole.setAppRoleId(null);
+ } else if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)
+ && applicationRoles.get(0).getAppRoleId() == null) {
+ epRole.setAppRoleId(epRole.getId());
+ }
+ dataAccessService.saveDomainObject(epRole, null);
+ }
+ Long roleAppId = null;
+ if (globalRole != null && !app.getId().equals(globalRole.getAppId()))
+ roleAppId = PortalConstants.PORTAL_APP_ID;
+ saveRoleFunction(listWithoutDuplicates, app, applicationRoles, roleAppId);
+ result = true;
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "addRoleInEcompDB is failed", e);
+ throw e;
+ }
+ return result;
+ }
+
+ /**
+ *
+ * It validates whether role exists in external auth system
+ *
+ * @param checkRole
+ * @param app
+ * @throws Exception If role exits
+ */
+ private void checkIfRoleExitsInExternalSystem(Role checkRole, EPApp app) throws Exception {
+ getNameSpaceIfExists(app);
+ HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+ String roleName = app.getNameSpace() + "." + checkRole.getName()
+ .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_");
+ HttpEntity<String> checkRoleEntity = new HttpEntity<>(headers);
+ logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRoleExitsInExternalSystem: {} ",
+ CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
+ ResponseEntity<String> checkRoleInExternalSystem = template
+ .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
+ + roleName, HttpMethod.GET, checkRoleEntity, String.class);
+ if (!checkRoleInExternalSystem.getBody().equals(IS_EMPTY_JSON_STRING)) {
+ logger.debug(
+ "checkIfRoleExitsInExternalSystem: Role already exists in external system {} and status code: {} ",
+ checkRoleInExternalSystem.getBody(), checkRoleInExternalSystem.getStatusCode().value());
+ throw new ExternalAuthSystemException(" Role already exists in external system");
+ }
+ }
+
+ /**
+ * It saves list of functions to the role in portal
+ *
+ * @param roleFunctionListNew
+ * @param app
+ * @param applicationRoles
+ * @throws Exception
+ */
+ @SuppressWarnings("unchecked")
+ private void saveRoleFunction(List<RoleFunction> roleFunctionListNew, EPApp app, List<EPRole> applicationRoles,
+ Long roleAppId) throws Exception {
+ final Map<String, String> getAppFunctionParams = new HashMap<>();
+ for (RoleFunction roleFunc : roleFunctionListNew) {
+ String code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
+ EPAppRoleFunction appRoleFunc = new EPAppRoleFunction();
+ appRoleFunc.setAppId(app.getId());
+ appRoleFunc.setRoleId(applicationRoles.get(0).getId());
+ appRoleFunc.setRoleAppId(String.valueOf(roleAppId));
+ getAppFunctionParams.put("appId", String.valueOf(app.getId()));
+ getAppFunctionParams.put(FUNCTION_CODE_PARAMS, roleFunc.getCode());
+ // query to check if function code has pipes
+ List<CentralV2RoleFunction> roleFunction = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY,
+ getAppFunctionParams, null);
+ if (roleFunction.isEmpty()) {
+ getAppFunctionParams.put(FUNCTION_CODE_PARAMS, code);
+ roleFunction = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null);
+ }
+ if (roleFunction.size() > 1) {
+ CentralV2RoleFunction getExactFunctionCode = appFunctionListFilter(code, roleFunction);
+ appRoleFunc.setCode(getExactFunctionCode.getCode());
+ } else {
+ appRoleFunc.setCode(roleFunction.get(0).getCode());
+ }
+ dataAccessService.saveDomainObject(appRoleFunc, null);
+ }
+ }
+
+ /**
+ *
+ * It filters the app functions which starts with similar name in the result set
+ *
+ * @param roleFunc
+ * @param roleFunction
+ * @return CentralRoleFunction
+ */
+ private CentralV2RoleFunction appFunctionListFilter(String roleFuncCode, List<CentralV2RoleFunction> roleFunction) {
+ final Map<String, CentralV2RoleFunction> appFunctionsFilter = new HashMap<>();
+ final Map<String, CentralV2RoleFunction> appFunctionsFilterPipes = new HashMap<>();
+ CentralV2RoleFunction getExactFunctionCode = null;
+ for (CentralV2RoleFunction cenRoleFunction : roleFunction) {
+ appFunctionsFilter.put(cenRoleFunction.getCode(), cenRoleFunction);
+ appFunctionsFilterPipes.put(EcompPortalUtils.getFunctionCode(cenRoleFunction.getCode()), cenRoleFunction);
+ }
+ getExactFunctionCode = appFunctionsFilter.get(roleFuncCode);
+ if (getExactFunctionCode == null) {
+ getExactFunctionCode = appFunctionsFilterPipes.get(roleFuncCode);
+ }
+ return getExactFunctionCode;
+ }
+
+ /**
+ * It deletes all EPAppRoleFunction records in the portal
+ *
+ * @param app
+ * @param role
+ */
+ @SuppressWarnings("unchecked")
+ private void deleteRoleFunction(EPApp app, List<EPRole> role) {
+ final Map<String, Long> appRoleFuncsParams = new HashMap<>();
+ appRoleFuncsParams.put("appId", app.getId());
+ appRoleFuncsParams.put("roleId", role.get(0).getId());
+ List<EPAppRoleFunction> appRoleFunctionList = dataAccessService
+ .executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null);
+ if (!appRoleFunctionList.isEmpty()) {
+ for (EPAppRoleFunction approleFunction : appRoleFunctionList) {
+ dataAccessService.deleteDomainObject(approleFunction, null);
+ }
+ }
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public List<EPUser> getUser(String loginId) throws InvalidUserException {
+ final Map<String, String> userParams = new HashMap<>();
+ userParams.put("org_user_id", loginId);
+ List<EPUser> userList = dataAccessService.executeNamedQuery("getEPUserByOrgUserId", userParams, null);
+ if (userList.isEmpty()) {
+ throw new InvalidUserException("User not found");
+ }
+ return userList;
+ }
+
+ @Override
+ public String getV2UserWithRoles(String loginId, String uebkey) throws Exception {
+ final Map<String, String> params = new HashMap<>();
+ List<EPUser> userList = null;
+ CentralV2User cenV2User = null;
+ String result = null;
+ try {
+ params.put("orgUserIdValue", loginId);
+ List<EPApp> appList = getApp(uebkey);
+ if (!appList.isEmpty()) {
+ userList = getUser(loginId);
+ if (!userList.isEmpty()) {
+ ObjectMapper mapper = new ObjectMapper();
+ cenV2User = getV2UserAppRoles(loginId, uebkey);
+ result = mapper.writeValueAsString(cenV2User);
+ } else if (userList.isEmpty()) {
+ throw new InvalidUserException("User not found");
+ }
+ } else {
+ throw new InactiveApplicationException("Application not found");
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getUser: failed", e);
+ throw e;
+ }
+ return result;
+ }
+
+ @Override
+ public List<CentralV2Role> getRolesForApp(String uebkey) throws Exception {
+ logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Entering into getRolesForApp");
+ List<CentralV2Role> roleList = new ArrayList<>();
+ final Map<String, Long> params = new HashMap<>();
+ try {
+ List<EPApp> app = getApp(uebkey);
+ List<EPRole> appRolesList = getAppRoles(app.get(0).getId());
+ roleList = createCentralRoleObject(app, appRolesList, roleList, params);
+ if (app.get(0).getId() != PortalConstants.PORTAL_APP_ID) {
+ List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
+ List<EPRole> globalRolesList = getGlobalRolesOfPortal();
+ List<CentralV2Role> portalsGlobalRolesFinlaList = new ArrayList<>();
+ if (!globalRolesList.isEmpty()) {
+ for (EPRole eprole : globalRolesList) {
+ CentralV2Role cenRole = convertRoleToCentralV2Role(eprole);
+ portalsGlobalRolesFinlaList.add(cenRole);
+ }
+ roleList.addAll(globalRoleList);
+ for (CentralV2Role role : portalsGlobalRolesFinlaList) {
+ CentralV2Role result = roleList.stream().filter(x -> role.getId().equals(x.getId())).findAny()
+ .orElse(null);
+ if (result == null)
+ roleList.add(role);
+ }
+ } else {
+ for (EPRole role : globalRolesList) {
+ CentralV2Role cenRole = convertRoleToCentralV2Role(role);
+ roleList.add(cenRole);
+ }
+ }
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getRolesForApp: Failed!", e);
+ throw e;
+ }
+ logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Finished!");
+ return roleList.stream().distinct().collect(Collectors.toList());
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<CentralV2RoleFunction> getRoleFuncList(String uebkey) throws Exception {
+ EPApp app = getApp(uebkey).get(0);
+ List<CentralV2RoleFunction> finalRoleList = new ArrayList<>();
+ final Map<String, Long> params = new HashMap<>();
+ params.put(APP_ID, app.getId());
+ List<CentralV2RoleFunction> getRoleFuncList = dataAccessService.executeNamedQuery("getAllRoleFunctions", params,
+ null);
+ for (CentralV2RoleFunction roleFuncItem : getRoleFuncList) {
+ String code = EcompPortalUtils.getFunctionCode(roleFuncItem.getCode());
+ String type = "";
+ if (roleFuncItem.getCode().contains("|"))
+ type = EcompPortalUtils.getFunctionType(roleFuncItem.getCode());
+ else
+ type = getFunctionCodeType(roleFuncItem.getCode());
+ String action = getFunctionCodeAction(roleFuncItem.getCode());
+ roleFuncItem.setCode(EPUserUtils.decodeFunctionCode(code));
+ roleFuncItem.setType(type);
+ roleFuncItem.setAction(action);
+ finalRoleList.add(roleFuncItem);
+ }
+ return finalRoleList;
+ }
+
+ @Override
+ public String getFunctionCodeAction(String roleFuncItem) {
+ return (!roleFuncItem.contains(FUNCTION_PIPE)) ? "*" : EcompPortalUtils.getFunctionAction(roleFuncItem);
+ }
+
+ @Override
+ public String getFunctionCodeType(String roleFuncItem) {
+ String type = null;
+ if ((roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))
+ || (!roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))) {
+ type = "menu";
+ } else if (checkIfCodeHasNoPipesAndHasTypeUrl(roleFuncItem) || checkIfCodeHasPipesAndHasTypeUrl(roleFuncItem)
+ || checkIfCodeHasNoPipesAndHasNoTypeUrl(roleFuncItem)) {
+ type = "url";
+ } else if (roleFuncItem.contains(FUNCTION_PIPE)
+ && (!roleFuncItem.contains("menu") || roleFuncItem.contains("url"))) {
+ type = EcompPortalUtils.getFunctionType(roleFuncItem);
+ }
+ return type;
+ }
+
+ /**
+ *
+ * It check whether function code has no pipes and no url string in it
+ *
+ * @param roleFuncItem
+ * @return true or false
+ */
+ private boolean checkIfCodeHasNoPipesAndHasNoTypeUrl(String roleFuncItem) {
+ return !roleFuncItem.contains(FUNCTION_PIPE) && !roleFuncItem.contains("url");
+ }
+
+ /**
+ *
+ * It check whether function code has pipes and url string in it
+ *
+ * @param roleFuncItem
+ * @return true or false
+ */
+ private boolean checkIfCodeHasPipesAndHasTypeUrl(String roleFuncItem) {
+ return roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
+ }
+
+ /**
+ *
+ * It check whether function code has no pipes and has url string in it
+ *
+ * @param roleFuncItem
+ * @return true or false
+ */
+ private boolean checkIfCodeHasNoPipesAndHasTypeUrl(String roleFuncItem) {
+ return !roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
+ }
+
+ /**
+ * It returns user detail information which is deep copy of EPUser.class object
+ *
+ * @param userInfo
+ * @param userAppSet
+ * @param app
+ * @return
+ * @throws Exception
+ */
+ @SuppressWarnings("unchecked")
+ private CentralV2User createEPUser(EPUser userInfo, Set<EPUserApp> userAppSet, EPApp app) throws Exception {
+ final Map<String, Long> params = new HashMap<>();
+ CentralV2User userAppList = new CentralV2User();
+ CentralV2User user1 = null;
+ final Map<String, Long> params1 = new HashMap<>();
+ List<EPRole> globalRoleList = new ArrayList<>();
+ try {
+ if (app.getId() != PortalConstants.PORTAL_APP_ID) {
+ params1.put("userId", userInfo.getId());
+ params1.put("appId", app.getId());
+ globalRoleList = dataAccessService.executeNamedQuery("userAppGlobalRoles", params1, null);
+ }
+ userAppList.setUserApps(new TreeSet<CentralV2UserApp>());
+ for (EPUserApp userApp : userAppSet) {
+ if (userApp.getRole().getActive()) {
+ EPApp epApp = userApp.getApp();
+ String globalRole = userApp.getRole().getName().toLowerCase();
+ if (((epApp.getId().equals(app.getId()))
+ && (!userApp.getRole().getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)))
+ || ((epApp.getId().equals(PortalConstants.PORTAL_APP_ID))
+ && (globalRole.toLowerCase().startsWith("global_")))) {
+ CentralV2UserApp cua = new CentralV2UserApp();
+ cua.setUserId(null);
+ CentralApp cenApp = new CentralApp(1L, epApp.getCreated(), epApp.getModified(),
+ epApp.getCreatedId(), epApp.getModifiedId(), epApp.getRowNum(), epApp.getName(),
+ epApp.getImageUrl(), epApp.getDescription(), epApp.getNotes(), epApp.getUrl(),
+ epApp.getAlternateUrl(), epApp.getAppRestEndpoint(), epApp.getMlAppName(),
+ epApp.getMlAppAdminId(), String.valueOf(epApp.getMotsId()), epApp.getAppPassword(),
+ String.valueOf(epApp.getOpen()), String.valueOf(epApp.getEnabled()),
+ epApp.getThumbnail(), epApp.getUsername(), epApp.getUebKey(), epApp.getUebSecret(),
+ epApp.getUebTopicName());
+ cenApp.setAppPassword(EPCommonSystemProperties.APP_DISPLAY_PASSWORD);
+ cua.setApp(cenApp);
+ Long appId = null;
+ if (globalRole.toLowerCase().startsWith("global_")
+ && epApp.getId().equals(PortalConstants.PORTAL_APP_ID)
+ && !epApp.getId().equals(app.getId())) {
+ appId = app.getId();
+ EPRole result = null;
+ if (globalRoleList.size() > 0)
+ result = globalRoleList.stream()
+ .filter(x -> userApp.getRole().getId().equals(x.getId())).findAny()
+ .orElse(null);
+ if (result == null)
+ continue;
+ } else {
+ appId = userApp.getApp().getId();
+ }
+ params.put("roleId", userApp.getRole().getId());
+ params.put(APP_ID, appId);
+ List<CentralV2RoleFunction> appRoleFunctionList = dataAccessService
+ .executeNamedQuery("getAppRoleFunctionList", params, null);
+ SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>();
+ for (CentralV2RoleFunction roleFunc : appRoleFunctionList) {
+ String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
+ String type = getFunctionCodeType(roleFunc.getCode());
+ String action = getFunctionCodeAction(roleFunc.getCode());
+ CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(roleFunc.getId(),
+ functionCode, roleFunc.getName(), null, type, action, null);
+ roleFunctionSet.add(cenRoleFunc);
+ }
+ Long userRoleId = null;
+ if (globalRole.toLowerCase().startsWith("global_")
+ || epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) {
+ userRoleId = userApp.getRole().getId();
+ } else {
+ userRoleId = userApp.getRole().getAppRoleId();
+ }
+ CentralV2Role cenRole = new CentralV2Role(userRoleId, userApp.getRole().getCreated(),
+ userApp.getRole().getModified(), userApp.getRole().getCreatedId(),
+ userApp.getRole().getModifiedId(), userApp.getRole().getRowNum(),
+ userApp.getRole().getName(), userApp.getRole().getActive(),
+ userApp.getRole().getPriority(), roleFunctionSet, null, null);
+ cua.setRole(cenRole);
+ userAppList.getUserApps().add(cua);
+ }
+ }
+ }
+ user1 = new CentralV2User(null, userInfo.getCreated(), userInfo.getModified(), userInfo.getCreatedId(),
+ userInfo.getModifiedId(), userInfo.getRowNum(), userInfo.getOrgId(), userInfo.getManagerId(),
+ userInfo.getFirstName(), userInfo.getMiddleInitial(), userInfo.getLastName(), userInfo.getPhone(),
+ userInfo.getFax(), userInfo.getCellular(), userInfo.getEmail(), userInfo.getAddressId(),
+ userInfo.getAlertMethodCd(), userInfo.getHrid(), userInfo.getOrgUserId(), userInfo.getOrgCode(),
+ userInfo.getAddress1(), userInfo.getAddress2(), userInfo.getCity(), userInfo.getState(),
+ userInfo.getZipCode(), userInfo.getCountry(), userInfo.getOrgManagerUserId(),
+ userInfo.getLocationClli(), userInfo.getBusinessCountryCode(), userInfo.getBusinessCountryName(),
+ userInfo.getBusinessUnit(), userInfo.getBusinessUnitName(), userInfo.getDepartment(),
+ userInfo.getDepartmentName(), userInfo.getCompanyCode(), userInfo.getCompany(),
+ userInfo.getZipCodeSuffix(), userInfo.getJobTitle(), userInfo.getCommandChain(),
+ userInfo.getSiloStatus(), userInfo.getCostCenter(), userInfo.getFinancialLocCode(),
+ userInfo.getLoginId(), userInfo.getLoginPwd(), userInfo.getLastLoginDate(), userInfo.getActive(),
+ userInfo.getInternal(), userInfo.getSelectedProfileId(), userInfo.getTimeZoneId(),
+ userInfo.isOnline(), userInfo.getChatId(), userAppList.getUserApps(), null);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "createEPUser: createEPUser failed", e);
+ throw e;
+ }
+ return user1;
+ }
+
+ @Override
+ public CentralV2Role getRoleInfo(Long roleId, String uebkey) throws Exception {
+ final Map<String, Long> params = new HashMap<>();
+ List<CentralV2Role> roleList = new ArrayList<>();
+ CentralV2Role cenRole = new CentralV2Role();
+ List<EPRole> roleInfo = null;
+ List<EPApp> app = null;
+ try {
+ app = getApp(uebkey);
+ if (app.isEmpty()) {
+ throw new InactiveApplicationException("Application not found");
+ }
+ if (app.get(0).getId() != PortalConstants.PORTAL_APP_ID) {
+ List<EPRole> globalRoleList = new ArrayList<>();
+ globalRoleList = getGlobalRolesOfPortal();
+ if (globalRoleList.size() > 0) {
+ EPRole result = globalRoleList.stream().filter(x -> roleId.equals(x.getId())).findAny()
+ .orElse(null);
+ if (result != null)
+ return getGlobalRoleForRequestedApp(app.get(0).getId(), roleId);
+ }
+ }
+ if (app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
+ roleInfo = getPortalAppRoleInfo(roleId);
+ } else {
+ roleInfo = getPartnerAppRoleInfo(roleId, app.get(0));
+ }
+ roleList = createCentralRoleObject(app, roleInfo, roleList, params);
+ if (roleList.isEmpty()) {
+ return cenRole;
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo: failed", e);
+ throw e;
+ }
+ return roleList.get(0);
+ }
+
+ @SuppressWarnings("unchecked")
+ private List<EPRole> getPartnerAppRoleInfo(Long roleId, EPApp app) {
+ List<EPRole> roleInfo;
+ final Map<String, Long> getPartnerAppRoleParams = new HashMap<>();
+ getPartnerAppRoleParams.put("appRoleId", roleId);
+ getPartnerAppRoleParams.put("appId", app.getId());
+ roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams, null);
+ if (roleInfo.isEmpty()) {
+ getPartnerAppRoleParams.put("appRoleId", roleId);
+ roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleById", getPartnerAppRoleParams, null);
+ }
+ return roleInfo;
+ }
+
+ @SuppressWarnings("unchecked")
+ private List<EPRole> getPortalAppRoleInfo(Long roleId) {
+ List<EPRole> roleInfo;
+ final Map<String, Long> getPortalAppRoleParams = new HashMap<>();
+ getPortalAppRoleParams.put("roleId", roleId);
+ roleInfo = dataAccessService.executeNamedQuery("getPortalAppRoleByRoleId", getPortalAppRoleParams, null);
+ return roleInfo;
+ }
+
+ /**
+ *
+ * It returns list of app roles along with role functions and which went through
+ * deep copy
+ *
+ * @param app
+ * @param roleInfo
+ * @param roleList
+ * @param params
+ * @return
+ * @throws DecoderException
+ */
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<CentralV2Role> createCentralRoleObject(List<EPApp> app, List<EPRole> roleInfo,
+ List<CentralV2Role> roleList, Map<String, Long> params) throws RoleFunctionException {
+ for (EPRole role : roleInfo) {
+ params.put("roleId", role.getId());
+ params.put(APP_ID, app.get(0).getId());
+ List<CentralV2RoleFunction> cenRoleFuncList = dataAccessService.executeNamedQuery("getAppRoleFunctionList",
+ params, null);
+ SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>();
+ for (CentralV2RoleFunction roleFunc : cenRoleFuncList) {
+ String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
+ functionCode = EPUserUtils.decodeFunctionCode(functionCode);
+ String type = getFunctionCodeType(roleFunc.getCode());
+ String action = getFunctionCodeAction(roleFunc.getCode());
+ CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(role.getId(), functionCode,
+ roleFunc.getName(), null, type, action, null);
+ roleFunctionSet.add(cenRoleFunc);
+ }
+ SortedSet<CentralV2Role> childRoles = new TreeSet<>();
+ SortedSet<CentralV2Role> parentRoles = new TreeSet<>();
+ CentralV2Role cenRole = null;
+ if (role.getAppRoleId() == null) {
+ cenRole = new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
+ role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
+ roleFunctionSet, childRoles, parentRoles);
+ } else {
+ cenRole = new CentralV2Role(role.getAppRoleId(), role.getCreated(), role.getModified(),
+ role.getCreatedId(), role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(),
+ role.getPriority(), roleFunctionSet, childRoles, parentRoles);
+ }
+ roleList.add(cenRole);
+ }
+ return roleList;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public CentralV2RoleFunction getRoleFunction(String functionCode, String uebkey) throws Exception {
+ String code = EcompPortalUtils.getFunctionCode(functionCode);
+ String encodedCode = EcompPortalUtils.encodeFunctionCode(code);
+ CentralV2RoleFunction roleFunc = null;
+ EPApp app = getApp(uebkey).get(0);
+ List<CentralV2RoleFunction> getRoleFuncList = null;
+ final Map<String, String> params = new HashMap<>();
+ try {
+ params.put(FUNCTION_CODE_PARAMS, functionCode);
+ params.put(APP_ID, String.valueOf(app.getId()));
+ getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
+ if (getRoleFuncList.isEmpty()) {
+ params.put(FUNCTION_CODE_PARAMS, encodedCode);
+ getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
+ if (getRoleFuncList.isEmpty()) {
+ return roleFunc;
+ }
+ }
+ if (getRoleFuncList.size() > 1) {
+ CentralV2RoleFunction cenV2RoleFunction = appFunctionListFilter(encodedCode, getRoleFuncList);
+ if (cenV2RoleFunction == null)
+ return roleFunc;
+ roleFunc = checkIfPipesExitsInFunctionCode(cenV2RoleFunction);
+ } else {
+ // Check even if single record have pipes
+ if (!getRoleFuncList.isEmpty() && getRoleFuncList.get(0).getCode().contains(FUNCTION_PIPE)) {
+ roleFunc = checkIfPipesExitsInFunctionCode(getRoleFuncList.get(0));
+ } else {
+ roleFunc = getRoleFuncList.get(0);
+ }
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction: failed", e);
+ throw e;
+ }
+ return roleFunc;
+ }
+
+ private CentralV2RoleFunction checkIfPipesExitsInFunctionCode(CentralV2RoleFunction getRoleFuncList) {
+ CentralV2RoleFunction roleFunc;
+ String functionCodeFormat = getRoleFuncList.getCode();
+ if (functionCodeFormat.contains(FUNCTION_PIPE)) {
+ String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(functionCodeFormat);
+ String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(functionCodeFormat);
+ String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(functionCodeFormat);
+ roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), newfunctionCodeFormat,
+ getRoleFuncList.getName(), getRoleFuncList.getAppId(), newfunctionTypeFormat,
+ newfunctionActionFormat, getRoleFuncList.getEditUrl());
+ } else {
+ roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), functionCodeFormat, getRoleFuncList.getName(),
+ getRoleFuncList.getAppId(), getRoleFuncList.getEditUrl());
+ }
+ return roleFunc;
+ }
+
+ @Override
+ public boolean saveCentralRoleFunction(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
+ throws Exception {
+ boolean saveOrUpdateFunction = false;
+ try {
+ if(EcompPortalUtils.checkFunctionCodeHasEncodePattern(domainCentralRoleFunction.getCode()))
+ domainCentralRoleFunction.setCode(EcompPortalUtils.encodeFunctionCode(domainCentralRoleFunction.getCode()));
+ final Map<String, String> functionParams = new HashMap<>();
+ functionParams.put("appId", String.valueOf(app.getId()));
+ if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
+ addRoleFunctionInExternalSystem(domainCentralRoleFunction, app);
+ }
+ if (domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null) {
+ domainCentralRoleFunction.setCode(domainCentralRoleFunction.getType() + FUNCTION_PIPE
+ + domainCentralRoleFunction.getCode() + FUNCTION_PIPE + domainCentralRoleFunction.getAction());
+ }
+ domainCentralRoleFunction.setAppId(app.getId());
+ dataAccessService.saveDomainObject(domainCentralRoleFunction, null);
+ saveOrUpdateFunction = true;
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "saveCentralRoleFunction: failed", e);
+ throw e;
+ }
+ return saveOrUpdateFunction;
+ }
+
+ /**
+ * It creates application permission in external auth system
+ *
+ * @param domainCentralRoleFunction
+ * @param app
+ * @throws Exception
+ */
+ private void addRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
+ throws Exception {
+ ObjectMapper mapper = new ObjectMapper();
+ ExternalAccessPerms extPerms = new ExternalAccessPerms();
+ HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+ String type = "";
+ String instance = "";
+ String action = "";
+ if ((domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null)
+ || domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)) {
+ type = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)
+ ? EcompPortalUtils.getFunctionType(domainCentralRoleFunction.getCode())
+ : domainCentralRoleFunction.getType();
+ instance = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)
+ ? EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode())
+ : domainCentralRoleFunction.getCode();
+ action = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)
+ ? EcompPortalUtils.getFunctionAction(domainCentralRoleFunction.getCode())
+ : domainCentralRoleFunction.getAction();
+ } else {
+ type = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url";
+ instance = domainCentralRoleFunction.getCode();
+ action = "*";
+ }
+ // get Permissions from External Auth System
+ JSONArray extPermsList = getExtAuthPermissions(app);
+ List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPermsList);
+ String requestedPerm = type + FUNCTION_PIPE + instance + FUNCTION_PIPE + action;
+ boolean checkIfFunctionsExits = permsDetailList.stream()
+ .anyMatch(permsDetail -> permsDetail.getInstance().equals(requestedPerm));
+ if (!checkIfFunctionsExits) {
+ try {
+ extPerms.setAction(action);
+ extPerms.setInstance(instance);
+ extPerms.setType(app.getNameSpace() + "." + type);
+ extPerms.setDescription(domainCentralRoleFunction.getName());
+ String addFunction = mapper.writeValueAsString(extPerms);
+ HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
+ logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for POST: {}",
+ CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
+ ResponseEntity<String> addPermResponse = template.exchange(
+ SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
+ HttpMethod.POST, entity, String.class);
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "addRoleFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ",
+ addPermResponse.getStatusCode().value(), addFunction);
+ } catch (HttpClientErrorException e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "HttpClientErrorException - Failed to add function in external central auth system", e);
+ EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+ throw e;
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "addRoleFunctionInExternalSystem: Failed to add fucntion in external central auth system", e);
+ throw e;
+ }
+ } else {
+ try {
+ extPerms.setAction(action);
+ extPerms.setInstance(instance);
+ extPerms.setType(app.getNameSpace() + "." + type);
+ extPerms.setDescription(domainCentralRoleFunction.getName());
+ String updateRoleFunction = mapper.writeValueAsString(extPerms);
+ HttpEntity<String> entity = new HttpEntity<>(updateRoleFunction, headers);
+ logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for PUT: {}",
+ CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRoleFunction);
+ ResponseEntity<String> updatePermResponse = template.exchange(
+ SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
+ HttpMethod.PUT, entity, String.class);
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "addRoleFunctionInExternalSystem: Finished updating permission in External Auth system {} and response: {} ",
+ updateRoleFunction, updatePermResponse.getStatusCode().value());
+ } catch (HttpClientErrorException e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "HttpClientErrorException - Failed to add function in external central auth system", e);
+ EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+ throw e;
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "addRoleFunctionInExternalSystem: Failed to update function in external central auth system",
+ e);
+ throw e;
+ }
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ @Transactional(rollbackFor = Exception.class)
+ public boolean deleteCentralRoleFunction(String code, EPApp app) {
+ boolean deleteFunctionResponse = false;
+ try {
+ final Map<String, String> params = new HashMap<>();
+ params.put(FUNCTION_CODE_PARAMS, code);
+ params.put(APP_ID, String.valueOf(app.getId()));
+ List<CentralV2RoleFunction> domainCentralRoleFunction = dataAccessService
+ .executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
+ CentralV2RoleFunction appFunctionCode = appFunctionListFilter(code, domainCentralRoleFunction);
+ if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
+ deleteRoleFunctionInExternalSystem(appFunctionCode, app);
+ // Delete role function dependency records
+ deleteAppRoleFunctions(appFunctionCode.getCode(), app);
+ }
+ dataAccessService.deleteDomainObject(appFunctionCode, null);
+ deleteFunctionResponse = true;
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "deleteCentralRoleFunction: failed", e);
+ }
+ return deleteFunctionResponse;
+ }
+
+ /**
+ * It deletes app function record in portal
+ *
+ * @param code
+ * @param app
+ */
+ private void deleteAppRoleFunctions(String code, EPApp app) {
+ dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
+ APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + code + "'", null);
+ }
+
+ /**
+ *
+ * It deletes permission in the external auth system
+ *
+ * @param domainCentralRoleFunction
+ * @param app
+ * @throws Exception
+ */
+ private void deleteRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
+ throws Exception {
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ ExternalAccessPerms extPerms = new ExternalAccessPerms();
+ String instanceValue = EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode());
+ String checkType = getFunctionCodeType(domainCentralRoleFunction.getCode());
+ String actionValue = getFunctionCodeAction(domainCentralRoleFunction.getCode());
+ HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+ extPerms.setAction(actionValue);
+ extPerms.setInstance(instanceValue);
+ extPerms.setType(app.getNameSpace() + "." + checkType);
+ extPerms.setDescription(domainCentralRoleFunction.getName());
+ String deleteRoleFunction = mapper.writeValueAsString(extPerms);
+ HttpEntity<String> entity = new HttpEntity<>(deleteRoleFunction, headers);
+ logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleFunctionInExternalSystem: {} for DELETE: {} ",
+ CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, deleteRoleFunction);
+ ResponseEntity<String> delPermResponse = template
+ .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
+ + "perm?force=true", HttpMethod.DELETE, entity, String.class);
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "deleteRoleFunctionInExternalSystem: Finished deleting permission in External Auth system {} and status code: {} ",
+ deleteRoleFunction, delPermResponse.getStatusCode().value());
+ } catch (HttpClientErrorException e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "HttpClientErrorException - Failed to delete functions in External System", e);
+ EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+ } catch (Exception e) {
+ if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ " deleteRoleFunctionInExternalSystem: It seems like function is already deleted in external central auth system but exists in local DB",
+ e.getMessage());
+ } else {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "deleteRoleFunctionInExternalSystem: Failed to delete functions in External System", e);
+ }
+ }
+ }
+
+ @Override
+ public ExternalRequestFieldsValidator saveRoleForApplication(Role saveRole, String uebkey) throws Exception {
+ boolean response = false;
+ String message = "";
+ try {
+ EPApp app = getApp(uebkey).get(0);
+ addRoleInEcompDB(saveRole, app);
+ response = true;
+ } catch (Exception e) {
+ message = e.getMessage();
+ logger.error(EELFLoggerDelegate.errorLogger, "saveRoleForApplication failed", e);
+ }
+ return new ExternalRequestFieldsValidator(response, message);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public boolean deleteRoleForApplication(String deleteRole, String uebkey) throws Exception {
+ Session localSession = sessionFactory.openSession();
+ Transaction transaction = null;
+ boolean result = false;
+ try {
+ List<EPRole> epRoleList = null;
+ EPApp app = getApp(uebkey).get(0);
+ final Map<String, String> deleteRoleParams = new HashMap<>();
+ deleteRoleParams.put(APP_ROLE_NAME_PARAM, deleteRole);
+ if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
+ epRoleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, deleteRoleParams, null);
+ } else {
+ deleteRoleParams.put(APP_ID, String.valueOf(app.getId()));
+ epRoleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
+ deleteRoleParams, null);
+ }
+ if (!epRoleList.isEmpty()) {
+ transaction = localSession.beginTransaction();
+ // Delete app role functions before deleting role
+ deleteRoleFunction(app, epRoleList);
+ if (app.getId() == 1) {
+ // Delete fn_user_ role
+ dataAccessService.deleteDomainObjects(EPUserApp.class,
+ APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
+ boolean isPortalRequest = false;
+ deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest);
+ }
+ deleteRoleInExternalAuthSystem(epRoleList, app);
+ transaction.commit();
+ logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: committed the transaction");
+ dataAccessService.deleteDomainObject(epRoleList.get(0), null);
+ }
+ result = true;
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleForApplication: failed", e);
+ result = false;
+ } finally {
+ localSession.close();
+ }
+ return result;
+ }
+
+ /**
+ *
+ * It deletes role for application in external auth system
+ *
+ * @param epRoleList contains role information
+ * @param app contains application information
+ * @throws Exception
+ */
+ private void deleteRoleInExternalAuthSystem(List<EPRole> epRoleList, EPApp app) throws Exception {
+ ResponseEntity<String> deleteResponse;
+ ResponseEntity<String> res = getNameSpaceIfExists(app);
+ if (res.getStatusCode() == HttpStatus.OK) {
+ // Delete Role in External System
+ String deleteRoleKey = "{\"name\":\"" + app.getNameSpace() + "." + epRoleList.get(0).getName()
+ .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_") + "\"}";
+ deleteResponse = deleteRoleInExternalSystem(deleteRoleKey);
+ if (deleteResponse.getStatusCode().value() != 200 && deleteResponse.getStatusCode().value() != 404) {
+ EPLogUtil.logExternalAuthAccessAlarm(logger, deleteResponse.getStatusCode());
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "deleteRoleForApplication: Failed to delete role in external auth system! due to {} ",
+ deleteResponse.getBody());
+ }
+ logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: about to commit the transaction");
+ }
+ }
+
+ /**
+ *
+ * It deletes application user role in external auth system
+ *
+ * @param role
+ * @param app
+ * @param LoginId
+ * @throws Exception
+ */
+ private void deleteUserRoleInExternalSystem(EPRole role, EPApp app, String LoginId) throws Exception {
+ HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+ HttpEntity<String> entity = new HttpEntity<>(headers);
+ getNameSpaceIfExists(app);
+ logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} ",
+ CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
+ ResponseEntity<String> getResponse = template.exchange(
+ SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
+ + LoginId
+ + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
+ + "/" + app.getNameSpace() + "."
+ + role.getName()
+ .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
+ HttpMethod.GET, entity, String.class);
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "deleteUserRoleInExternalSystem: Finished GET user roles from External Auth system and response: {} ",
+ getResponse.getBody());
+ if (getResponse.getStatusCode().value() != 200) {
+ throw new ExternalAuthSystemException(getResponse.getBody());
+ }
+ String res = getResponse.getBody();
+ if (!res.equals(IS_EMPTY_JSON_STRING)) {
+ HttpEntity<String> userRoleentity = new HttpEntity<>(headers);
+ logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} ",
+ CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
+ ResponseEntity<String> deleteResponse = template.exchange(
+ SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
+ + LoginId
+ + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
+ + "/" + app.getNameSpace() + "."
+ + role.getName().replaceAll(
+ EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
+ HttpMethod.DELETE, userRoleentity, String.class);
+ if (deleteResponse.getStatusCode().value() != 200) {
+ throw new ExternalAuthSystemException("Failed to delete user role");
+ }
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "deleteUserRoleInExternalSystem: Finished deleting user role in External Auth system and status code: {} ",
+ deleteResponse.getStatusCode().value());
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<CentralV2Role> getActiveRoles(String uebkey) throws Exception {
+ List<CentralV2Role> roleList = new ArrayList<>();
+ try {
+ List<EPApp> app = getApp(uebkey);
+ final Map<String, Long> params = new HashMap<>();
+ // check if portal
+ Long appId = null;
+ if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
+ appId = app.get(0).getId();
+ }
+ List<Criterion> restrictionsList = new ArrayList<Criterion>();
+ Criterion active_ynCrt = Restrictions.eq("active", Boolean.TRUE);
+ Criterion appIdCrt;
+ if (appId == null)
+ appIdCrt = Restrictions.isNull("appId");
+ else
+ appIdCrt = Restrictions.eq("appId", appId);
+ Criterion andCrit = Restrictions.and(active_ynCrt, appIdCrt);
+ restrictionsList.add(andCrit);
+ List<EPRole> epRole = (List<EPRole>) dataAccessService.getList(EPRole.class, null, restrictionsList, null);
+ roleList = createCentralRoleObject(app, epRole, roleList, params);
+ List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
+ if (globalRoleList.size() > 0)
+ roleList.addAll(globalRoleList);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles: failed", e);
+ throw e;
+ }
+ return roleList;
+ }
+
+ @Override
+ @Transactional(rollbackFor = Exception.class)
+ public ExternalRequestFieldsValidator deleteDependencyRoleRecord(Long roleId, String uebkey, String LoginId)
+ throws Exception {
+ Session localSession = sessionFactory.openSession();
+ String message = "";
+ Transaction transaction = null;
+ boolean response = false;
+ EPApp app = null;
+ try {
+ transaction = localSession.beginTransaction();
+ List<EPRole> epRoleList = null;
+ app = getApp(uebkey).get(0);
+ if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
+ epRoleList = getPortalAppRoleInfo(roleId);
+ } else {
+ epRoleList = getPartnerAppRoleInfo(roleId, app);
+ }
+ if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
+ // Delete User Role in External System before deleting role
+ deleteUserRoleInExternalSystem(epRoleList.get(0), app, LoginId);
+ }
+ // Delete user app roles
+ dataAccessService.deleteDomainObjects(EPUserApp.class,
+ APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
+ boolean isPortalRequest = false;
+ deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest);
+ transaction.commit();
+ if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
+ // Final call to delete role once all dependencies has been
+ // deleted
+ deleteRoleInExternalAuthSystem(epRoleList, app);
+ }
+ dataAccessService.deleteDomainObjects(EPRole.class, " role_id = " + epRoleList.get(0).getId(), null);
+ logger.debug(EELFLoggerDelegate.debugLogger, "deleteDependencyRoleRecord: committed the transaction");
+ response = true;
+ } catch (HttpClientErrorException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord: HttpClientErrorException", e);
+ EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+ message = e.getMessage();
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord failed", e);
+ EcompPortalUtils.rollbackTransaction(transaction,
+ "deleteDependencyRoleRecord rollback, exception = " + e.toString());
+ message = e.getMessage();
+ } finally {
+ localSession.close();
+ }
+ return new ExternalRequestFieldsValidator(response, message);
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ @Transactional
+ public void syncRoleFunctionFromExternalAccessSystem(EPApp app) {
+ try {
+ // get Permissions from External Auth System
+ JSONArray extPerms = getExtAuthPermissions(app);
+ List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);
+ // get functions in DB
+ final Map<String, Long> params = new HashMap<>();
+ final Map<String, CentralV2RoleFunction> roleFuncMap = new HashMap<>();
+ params.put(APP_ID, app.getId());
+ List<CentralV2RoleFunction> appFunctions = dataAccessService.executeNamedQuery("getAllRoleFunctions",
+ params, null);
+ if (!appFunctions.isEmpty()) {
+ for (CentralV2RoleFunction roleFunc : appFunctions) {
+ roleFuncMap.put(roleFunc.getCode(), roleFunc);
+ }
+ }
+ // get Roles for portal in DB
+ List<EPRole> portalRoleList = getGlobalRolesOfPortal();
+ final Map<String, EPRole> existingPortalRolesMap = new HashMap<>();
+ for (EPRole epRole : portalRoleList) {
+ existingPortalRolesMap.put(epRole.getName().replaceAll(
+ EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), epRole);
+ }
+ // get Roles in DB
+ final Map<String, EPRole> currentRolesInDB = getAppRoleNamesWithUnderscoreMap(app);
+ // store External Permissions with Pipe and without Pipe (just
+ // instance)
+ final Map<String, ExternalAccessPermsDetail> extAccessPermsContainsPipeMap = new HashMap<>();
+ final Map<String, ExternalAccessPermsDetail> extAccessPermsMap = new HashMap<>();
+ for (ExternalAccessPermsDetail permsDetailInfoWithPipe : permsDetailList) {
+ extAccessPermsContainsPipeMap.put(permsDetailInfoWithPipe.getInstance(), permsDetailInfoWithPipe);
+ String finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetailInfoWithPipe.getInstance());
+ extAccessPermsMap.put(finalFunctionCodeVal, permsDetailInfoWithPipe);
+ }
+ // Add if new functions and app role functions were added in
+ // external auth system
+ for (ExternalAccessPermsDetail permsDetail : permsDetailList) {
+ String code = permsDetail.getInstance();
+ CentralV2RoleFunction getFunctionCodeKey = roleFuncMap.get(permsDetail.getInstance());
+ List<CentralV2RoleFunction> roleFunctionList = addGetLocalFunction(app, roleFuncMap, permsDetail, code,
+ getFunctionCodeKey);
+ List<String> roles = permsDetail.getRoles();
+ if (roles != null) {
+ // Check if function has any roles and which does not exist
+ // in External Auth System. If exists delete in local
+ addRemoveIfFunctionsRolesIsSyncWithExternalAuth(app, currentRolesInDB, roleFunctionList, roles,
+ existingPortalRolesMap);
+ }
+ }
+ // Check if function does exits in External Auth System but exits in
+ // local then delete function and its dependencies
+ for (CentralV2RoleFunction roleFunc : appFunctions) {
+ try {
+ ExternalAccessPermsDetail getFunctionCodeContainsPipeKey = extAccessPermsContainsPipeMap
+ .get(roleFunc.getCode());
+ if (null == getFunctionCodeContainsPipeKey) {
+ ExternalAccessPermsDetail getFunctionCodeKey = extAccessPermsMap.get(roleFunc.getCode());
+ if (null == getFunctionCodeKey) {
+ deleteAppRoleFuncDoesNotExitsInExtSystem(app, roleFunc);
+ }
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "syncRoleFunctionFromExternalAccessSystem: Failed to delete function", e);
+ }
+ }
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "syncRoleFunctionFromExternalAccessSystem: Finished syncRoleFunctionFromExternalAccessSystem");
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "syncRoleFunctionFromExternalAccessSystem: Failed syncRoleFunctionFromExternalAccessSystem", e);
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private void addRemoveIfFunctionsRolesIsSyncWithExternalAuth(EPApp app, final Map<String, EPRole> currentRolesInDB,
+ List<CentralV2RoleFunction> roleFunctionList, List<String> roles,
+ Map<String, EPRole> existingPortalRolesMap) throws Exception {
+ if (!roleFunctionList.isEmpty()) {
+ final Map<String, String> appRoleFuncParams = new HashMap<>();
+ final Map<String, LocalRole> currentAppRoleFunctionsMap = new HashMap<>();
+ final Map<String, String> currentRolesInExtSystem = new HashMap<>();
+ appRoleFuncParams.put("functionCd", roleFunctionList.get(0).getCode());
+ appRoleFuncParams.put("appId", String.valueOf(app.getId()));
+ List<LocalRole> localRoleList = dataAccessService.executeNamedQuery("getCurrentAppRoleFunctions",
+ appRoleFuncParams, null);
+ for (LocalRole localRole : localRoleList) {
+ currentAppRoleFunctionsMap.put(localRole.getRolename().replaceAll(
+ EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), localRole);
+ }
+ for (String addRole : roles) {
+ currentRolesInExtSystem.put(addRole.substring(addRole.indexOf(FUNCTION_PIPE) + 1), addRole);
+ }
+ for (String extAuthrole : roles) {
+ String roleNameSpace = extAuthrole.substring(0, extAuthrole.indexOf(FUNCTION_PIPE));
+ boolean isNameSpaceMatching = EcompPortalUtils.checkNameSpaceMatching(roleNameSpace,
+ app.getNameSpace());
+ if (isNameSpaceMatching) {
+ if (!currentAppRoleFunctionsMap
+ .containsKey(extAuthrole.substring(app.getNameSpace().length() + 1))) {
+ EPRole localAddFuntionRole = currentRolesInDB
+ .get(extAuthrole.substring(app.getNameSpace().length() + 1));
+ if (localAddFuntionRole == null) {
+ checkAndAddRoleInDB(app, currentRolesInDB, roleFunctionList, extAuthrole);
+ } else {
+ EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
+ addAppRoleFunc.setAppId(app.getId());
+ addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
+ addAppRoleFunc.setRoleId(localAddFuntionRole.getId());
+ dataAccessService.saveDomainObject(addAppRoleFunc, null);
+ }
+ }
+ // This block is to save global role function if exists
+ } else {
+ String extAuthAppRoleName = extAuthrole.substring(extAuthrole.indexOf(FUNCTION_PIPE) + 1);
+ boolean checkIfGlobalRoleExists = existingPortalRolesMap.containsKey(extAuthAppRoleName);
+ if (checkIfGlobalRoleExists) {
+ final Map<String, Long> params = new HashMap<>();
+ EPRole role = existingPortalRolesMap.get(extAuthAppRoleName);
+ EPAppRoleFunction addGlobalRoleFunctions = new EPAppRoleFunction();
+ params.put("appId", app.getId());
+ params.put("roleId", role.getId());
+ List<EPAppRoleFunction> currentGlobalRoleFunctionsList = dataAccessService
+ .executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", params, null);
+ boolean checkIfRoleFunctionExists = currentGlobalRoleFunctionsList.stream()
+ .anyMatch(currentGlobalRoleFunction -> currentGlobalRoleFunction.getCode()
+ .equals(roleFunctionList.get(0).getCode()));
+ if (role != null && !checkIfRoleFunctionExists) {
+ addGlobalRoleFunctions.setAppId(app.getId());
+ addGlobalRoleFunctions.setRoleId(role.getId());
+ if (!app.getId().equals(role.getAppRoleId())) {
+ addGlobalRoleFunctions.setRoleAppId((PortalConstants.PORTAL_APP_ID).toString());
+ } else {
+ addGlobalRoleFunctions.setRoleAppId(null);
+ }
+ addGlobalRoleFunctions.setCode(roleFunctionList.get(0).getCode());
+ dataAccessService.saveDomainObject(addGlobalRoleFunctions, null);
+ }
+ }
+ }
+ }
+ for (LocalRole localRoleDelete : localRoleList) {
+ if (!currentRolesInExtSystem.containsKey(localRoleDelete.getRolename()
+ .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
+ dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
+ APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunctionList.get(0).getCode()
+ + "'" + " and role_id = " + localRoleDelete.getRoleId().longValue(),
+ null);
+ }
+ }
+ }
+ }
+
+ private void deleteAppRoleFuncDoesNotExitsInExtSystem(EPApp app, CentralV2RoleFunction roleFunc) {
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "syncRoleFunctionFromExternalAccessSystem: Deleting app role function {}", roleFunc.getCode());
+ dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
+ APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() + "'", null);
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "syncRoleFunctionFromExternalAccessSystem: Deleted app role function {}", roleFunc.getCode());
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "syncRoleFunctionFromExternalAccessSystem: Deleting app function {}", roleFunc.getCode());
+ dataAccessService.deleteDomainObjects(CentralV2RoleFunction.class,
+ APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() + "'", null);
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "syncRoleFunctionFromExternalAccessSystem: Deleted app function {}", roleFunc.getCode());
+ }
+
+ private void checkAndAddRoleInDB(EPApp app, final Map<String, EPRole> currentRolesInDB,
+ List<CentralV2RoleFunction> roleFunctionList, String roleList) throws Exception {
+ if (!currentRolesInDB.containsKey(roleList.substring(app.getNameSpace().length() + 1))) {
+ Role role = addRoleInDBIfDoesNotExists(app, roleList.substring(app.getNameSpace().length() + 1));
+ addRoleDescriptionInExtSystem(role, app);
+ if (!roleFunctionList.isEmpty()) {
+ try {
+ if (!roleFunctionList.isEmpty()) {
+ EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
+ addAppRoleFunc.setAppId(app.getId());
+ addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
+ addAppRoleFunc.setRoleId(role.getId());
+ dataAccessService.saveDomainObject(addAppRoleFunc, null);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "syncRoleFunctionFromExternalAccessSystem: Failed to save app role function ", e);
+ }
+ }
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private List<CentralV2RoleFunction> addGetLocalFunction(EPApp app,
+ final Map<String, CentralV2RoleFunction> roleFuncMap, ExternalAccessPermsDetail permsDetail, String code,
+ CentralV2RoleFunction getFunctionCodeKey) {
+ String finalFunctionCodeVal = addToLocalIfFunctionNotExists(app, roleFuncMap, permsDetail, code,
+ getFunctionCodeKey);
+ final Map<String, String> appSyncFuncsParams = new HashMap<>();
+ appSyncFuncsParams.put("appId", String.valueOf(app.getId()));
+ appSyncFuncsParams.put("functionCd", finalFunctionCodeVal);
+ List<CentralV2RoleFunction> roleFunctionList = null;
+ roleFunctionList = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams,
+ null);
+ if (roleFunctionList.isEmpty()) {
+ appSyncFuncsParams.put("functionCd", code);
+ roleFunctionList = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams,
+ null);
+ }
+ return roleFunctionList;
+ }
+
+ private String addToLocalIfFunctionNotExists(EPApp app, final Map<String, CentralV2RoleFunction> roleFuncMap,
+ ExternalAccessPermsDetail permsDetail, String code, CentralV2RoleFunction getFunctionCodeKey) {
+ String finalFunctionCodeVal = "";
+ if (null == getFunctionCodeKey) {
+ finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetail.getInstance());
+ CentralV2RoleFunction checkIfCodeStillExits = roleFuncMap.get(finalFunctionCodeVal);
+ // If function does not exist in local then add!
+ if (null == checkIfCodeStillExits) {
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "syncRoleFunctionFromExternalAccessSystem: Adding function: {} ", code);
+ addFunctionInEcompDB(app, permsDetail, code);
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "syncRoleFunctionFromExternalAccessSystem: Finished adding function: {} ", code);
+ }
+ }
+ return finalFunctionCodeVal;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public Map<String, EPRole> getAppRoleNamesWithUnderscoreMap(EPApp app) {
+ final Map<String, EPRole> currentRolesInDB = new HashMap<>();
+ List<EPRole> getCurrentRoleList = null;
+ final Map<String, Long> appParams = new HashMap<>();
+ if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
+ getCurrentRoleList = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
+ } else {
+ appParams.put("appId", app.getId());
+ getCurrentRoleList = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
+ }
+ for (EPRole role : getCurrentRoleList) {
+ currentRolesInDB.put(role.getName()
+ .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), role);
+ }
+ return currentRolesInDB;
+ }
+
+ @SuppressWarnings("unchecked")
+ private Map<String, EPRole> getAppRoleNamesMap(EPApp app) {
+ final Map<String, EPRole> currentRolesInDB = new HashMap<>();
+ List<EPRole> getCurrentRoleList = null;
+ final Map<String, Long> appParams = new HashMap<>();
+ if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
+ getCurrentRoleList = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
+ } else {
+ appParams.put("appId", app.getId());
+ getCurrentRoleList = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
+ }
+ for (EPRole role : getCurrentRoleList) {
+ currentRolesInDB.put(role.getName(), role);
+ }
+ return currentRolesInDB;
+ }
+
+ private List<ExternalAccessPermsDetail> getExtAuthPerrmissonList(EPApp app, JSONArray extPerms) throws IOException {
+ ExternalAccessPermsDetail permDetails = null;
+ List<ExternalAccessPermsDetail> permsDetailList = new ArrayList<>();
+ for (int i = 0; i < extPerms.length(); i++) {
+ String description = null;
+ if (extPerms.getJSONObject(i).has("description")) {
+ description = extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
+ } else {
+ description = extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1) + "|"
+ + extPerms.getJSONObject(i).getString("instance") + "|"
+ + extPerms.getJSONObject(i).getString("action");
+ }
+ if (extPerms.getJSONObject(i).has("roles")) {
+ ObjectMapper rolesListMapper = new ObjectMapper();
+ JSONArray resRoles = extPerms.getJSONObject(i).getJSONArray("roles");
+ List<String> list = rolesListMapper.readValue(resRoles.toString(),
+ TypeFactory.defaultInstance().constructCollectionType(List.class, String.class));
+ permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
+ extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
+ + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
+ + extPerms.getJSONObject(i).getString("action"),
+ extPerms.getJSONObject(i).getString("action"), list, description);
+ permsDetailList.add(permDetails);
+ } else {
+ permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
+ extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
+ + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
+ + extPerms.getJSONObject(i).getString("action"),
+ extPerms.getJSONObject(i).getString("action"), description);
+ permsDetailList.add(permDetails);
+ }
+ }
+ return permsDetailList;
+ }
+
+ private JSONArray getExtAuthPermissions(EPApp app) throws Exception {
+ ResponseEntity<String> response = null;
+ HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+ HttpEntity<String> entity = new HttpEntity<>(headers);
+ logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: {} ",
+ CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
+ response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
+ + "perms/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
+ String res = response.getBody();
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "syncRoleFunctionFromExternalAccessSystem: Finished GET permissions from External Auth system and response: {} ",
+ response.getBody());
+ JSONObject jsonObj = new JSONObject(res);
+ JSONArray extPerms = jsonObj.getJSONArray("perm");
+ for (int i = 0; i < extPerms.length(); i++) {
+ if (extPerms.getJSONObject(i).getString("type").equals(app.getNameSpace() + ".access")) {
+ extPerms.remove(i);
+ i--;
+ }
+ }
+ return extPerms;
+ }
+
+ /**
+ *
+ * Add function into local DB
+ *
+ * @param app
+ * @param permsDetail
+ * @param code
+ */
+ private void addFunctionInEcompDB(EPApp app, ExternalAccessPermsDetail permsDetail, String code) {
+ try {
+ CentralV2RoleFunction addFunction = new CentralV2RoleFunction();
+ addFunction.setAppId(app.getId());
+ addFunction.setCode(code);
+ addFunction.setName(permsDetail.getDescription());
+ dataAccessService.saveDomainObject(addFunction, null);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "addFunctionInEcompDB: Failed to add function", e);
+ }
+ }
+
+ /**
+ *
+ * It updates description of a role in external auth system
+ *
+ * @param role
+ * @param app
+ * @throws Exception
+ */
+ private boolean addRoleDescriptionInExtSystem(Role role, EPApp app) throws Exception {
+ boolean status = false;
+ try {
+ String addRoleNew = updateExistingRoleInExternalSystem(role, app);
+ HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+ HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
+ template.exchange(
+ SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
+ HttpMethod.PUT, entity, String.class);
+ status = true;
+ } catch (HttpClientErrorException e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "HttpClientErrorException - Failed to addRoleDescriptionInExtSystem", e);
+ EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "addRoleDescriptionInExtSystem: Failed", e);
+ }
+ return status;
+ }
+
+ /**
+ *
+ * While sync functions form external auth system if new role found we should
+ * add in local and return Role.class object
+ *
+ * @param app
+ * @param role
+ * @return
+ */
+ @SuppressWarnings("unchecked")
+ private Role addRoleInDBIfDoesNotExists(EPApp app, String role) {
+ Role setNewRole = new Role();
+ try {
+ // functions can have new role created in External Auth System
+ // prevent
+ // duplication here
+ boolean isCreated = checkIfRoleExitsElseCreateInSyncFunctions(role, app);
+ final Map<String, String> getRoleByNameParams = new HashMap<>();
+ List<EPRole> getRoleCreated = null;
+ getRoleByNameParams.put(APP_ROLE_NAME_PARAM, role);
+ if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
+ getRoleByNameParams.put("appId", String.valueOf(app.getId()));
+ List<EPRole> roleCreated = dataAccessService
+ .executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, getRoleByNameParams, null);
+ if (!isCreated) {
+ EPRole epUpdateRole = roleCreated.get(0);
+ epUpdateRole.setAppRoleId(epUpdateRole.getId());
+ dataAccessService.saveDomainObject(epUpdateRole, null);
+ getRoleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
+ getRoleByNameParams, null);
+ } else {
+ getRoleCreated = roleCreated;
+ }
+ } else {
+ getRoleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, getRoleByNameParams,
+ null);
+ }
+ if (getRoleCreated != null && !getRoleCreated.isEmpty()) {
+ EPRole roleObject = getRoleCreated.get(0);
+ setNewRole.setId(roleObject.getId());
+ setNewRole.setName(roleObject.getName());
+ setNewRole.setActive(roleObject.getActive());
+ setNewRole.setPriority(roleObject.getPriority());
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "addRoleInDBIfDoesNotExists: Failed", e);
+ }
+ return setNewRole;
+ }
+
+ @SuppressWarnings("unchecked")
+ private boolean checkIfRoleExitsElseCreateInSyncFunctions(String role, EPApp app) {
+ boolean isCreated = false;
+ final Map<String, String> roleParams = new HashMap<>();
+ roleParams.put(APP_ROLE_NAME_PARAM, role);
+ List<EPRole> roleCreated = null;
+ if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
+ roleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, roleParams, null);
+ } else {
+ roleParams.put("appId", String.valueOf(app.getId()));
+ roleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams,
+ null);
+ }
+ if (roleCreated == null || roleCreated.isEmpty()) {
+ roleParams.put("appId", String.valueOf(app.getId()));
+ EPRole epRoleNew = new EPRole();
+ epRoleNew.setActive(true);
+ epRoleNew.setName(role);
+ if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
+ epRoleNew.setAppId(null);
+ } else {
+ epRoleNew.setAppId(app.getId());
+ }
+ dataAccessService.saveDomainObject(epRoleNew, null);
+ isCreated = false;
+ } else {
+ isCreated = true;
+ }
+ return isCreated;
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public Integer bulkUploadFunctions(String uebkey) throws Exception {
+ EPApp app = getApp(uebkey).get(0);
+ List<RoleFunction> roleFuncList = dataAccessService.executeNamedQuery("getAllFunctions", null, null);
+ CentralV2RoleFunction cenRoleFunc = null;
+ Integer functionsAdded = 0;
+ try {
+ for (RoleFunction roleFunc : roleFuncList) {
+ cenRoleFunc = new CentralV2RoleFunction(roleFunc.getCode(), roleFunc.getName());
+ addRoleFunctionInExternalSystem(cenRoleFunc, app);
+ functionsAdded++;
+ }
+ } catch (HttpClientErrorException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadFunctions failed", e);
+ EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions: failed", e.getMessage(), e);
+ }
+ return functionsAdded;
+ }
+
+ @Override
+ public Integer bulkUploadRoles(String uebkey) throws Exception {
+ List<EPApp> app = getApp(uebkey);
+ List<EPRole> roles = getAppRoles(app.get(0).getId());
+ List<CentralV2Role> cenRoleList = new ArrayList<>();
+ final Map<String, Long> params = new HashMap<>();
+ Integer rolesListAdded = 0;
+ try {
+ cenRoleList = createCentralRoleObject(app, roles, cenRoleList, params);
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
+ String roleList = mapper.writeValueAsString(cenRoleList);
+ List<Role> roleObjectList = mapper.readValue(roleList,
+ TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
+ for (Role role : roleObjectList) {
+ addRoleInExternalSystem(role, app.get(0));
+ rolesListAdded++;
+ }
+ if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
+ // Add Account Admin role in External AUTH System
+ try {
+ String addAccountAdminRole = "";
+ ExternalAccessRole extRole = new ExternalAccessRole();
+ extRole.setName(app.get(0).getNameSpace() + "." + PortalConstants.ADMIN_ROLE
+ .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
+ addAccountAdminRole = mapper.writeValueAsString(extRole);
+ HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+ HttpEntity<String> entity = new HttpEntity<>(addAccountAdminRole, headers);
+ template.exchange(
+ SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
+ HttpMethod.POST, entity, String.class);
+ rolesListAdded++;
+ } catch (HttpClientErrorException e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "HttpClientErrorException - Failed to create Account Admin role", e);
+ EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+ } catch (Exception e) {
+ if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "bulkUploadRoles: Account Admin Role already exits but does not break functionality",
+ e);
+ } else {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "bulkUploadRoles: Failed to create Account Admin role", e.getMessage());
+ }
+ }
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles: failed", e);
+ throw e;
+ }
+ return rolesListAdded;
+ }
+
+ /**
+ * It creating new role in external auth system while doing bulk upload
+ *
+ * @param role
+ * @param app
+ * @throws Exception
+ */
+ private void addRoleInExternalSystem(Role role, EPApp app) throws Exception {
+ String addRoleNew = updateExistingRoleInExternalSystem(role, app);
+ HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+ try {
+ HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
+ template.exchange(
+ SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
+ HttpMethod.POST, entity, String.class);
+ } catch (HttpClientErrorException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addRoleInExternalSystem",
+ e);
+ EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+ } catch (Exception e) {
+ if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "addRoleInExternalSystem: Role already exits but does not break functionality", e);
+ } else {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "addRoleInExternalSystem: Failed to addRoleInExternalSystem", e.getMessage());
+ }
+ }
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public Integer bulkUploadRolesFunctions(String uebkey) throws Exception {
+ EPApp app = getApp(uebkey).get(0);
+ List<EPRole> roles = getAppRoles(app.getId());
+ final Map<String, Long> params = new HashMap<>();
+ Integer roleFunctions = 0;
+ try {
+ for (EPRole role : roles) {
+ params.put("roleId", role.getId());
+ List<BulkUploadRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("uploadAllRoleFunctions",
+ params, null);
+ if (!appRoleFunc.isEmpty()) {
+ for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
+ addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
+ roleFunctions++;
+ }
+ }
+ }
+ } catch (HttpClientErrorException e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
+ EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
+ }
+ return roleFunctions;
+ }
+
+ /**
+ * Its adding a role function while doing bulk upload
+ *
+ * @param addRoleFunc
+ * @param role
+ * @param app
+ */
+ private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, EPRole role, EPApp app) {
+ String type = "";
+ String instance = "";
+ String action = "";
+ if (addRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
+ type = EcompPortalUtils.getFunctionType(addRoleFunc.getFunctionCd());
+ instance = EcompPortalUtils.getFunctionCode(addRoleFunc.getFunctionCd());
+ action = EcompPortalUtils.getFunctionAction(addRoleFunc.getFunctionCd());
+ } else {
+ type = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
+ instance = addRoleFunc.getFunctionCd();
+ action = "*";
+ }
+ ExternalAccessRolePerms extRolePerms = null;
+ ExternalAccessPerms extPerms = null;
+ ObjectMapper mapper = new ObjectMapper();
+ try {
+ HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+ extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, instance, action,
+ addRoleFunc.getFunctionName());
+ extRolePerms = new ExternalAccessRolePerms(extPerms, app.getNameSpace() + "." + role.getName()
+ .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
+ String updateRolePerms = mapper.writeValueAsString(extRolePerms);
+ HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
+ template.exchange(
+ SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
+ HttpMethod.POST, entity, String.class);
+ } catch (Exception e) {
+ if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "addRoleFunctionsInExternalSystem: RoleFunction already exits but does not break functionality",
+ e);
+ } else {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "addRoleFunctionsInExternalSystem: Failed to addRoleFunctionsInExternalSystem", e.getMessage());
+ }
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public Integer bulkUploadPartnerFunctions(String uebkey) throws Exception {
+ EPApp app = getApp(uebkey).get(0);
+ final Map<String, Long> params = new HashMap<>();
+ params.put("appId", app.getId());
+ List<CentralV2RoleFunction> roleFuncList = dataAccessService.executeNamedQuery("getPartnerAppFunctions", params,
+ null);
+ Integer functionsAdded = 0;
+ try {
+ for (CentralV2RoleFunction roleFunc : roleFuncList) {
+ addFunctionInExternalSystem(roleFunc, app);
+ functionsAdded++;
+ }
+ } catch (HttpClientErrorException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadPartnerFunctions failed",
+ e);
+ EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerFunctions: failed", e.getMessage(), e);
+ }
+ return functionsAdded;
+ }
+
+ private void addFunctionInExternalSystem(CentralV2RoleFunction roleFunc, EPApp app) throws Exception {
+ ObjectMapper mapper = new ObjectMapper();
+ ExternalAccessPerms extPerms = new ExternalAccessPerms();
+ HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+ String type = "";
+ String instance = "";
+ String action = "";
+ if ((roleFunc.getCode().contains(FUNCTION_PIPE))
+ || (roleFunc.getType() != null && roleFunc.getAction() != null)) {
+ type = EcompPortalUtils.getFunctionType(roleFunc.getCode());
+ instance = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
+ action = EcompPortalUtils.getFunctionAction(roleFunc.getCode());
+ } else {
+ type = roleFunc.getCode().contains("menu") ? "menu" : "url";
+ instance = roleFunc.getCode();
+ action = "*";
+ }
+ try {
+ extPerms.setAction(action);
+ extPerms.setInstance(instance);
+ extPerms.setType(app.getNameSpace() + "." + type);
+ extPerms.setDescription(roleFunc.getName());
+ String addFunction = mapper.writeValueAsString(extPerms);
+ HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
+ logger.debug(EELFLoggerDelegate.debugLogger, "addFunctionInExternalSystem: {} for POST: {}",
+ CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
+ ResponseEntity<String> addPermResponse = template.exchange(
+ SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
+ HttpMethod.POST, entity, String.class);
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "addFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ",
+ addPermResponse.getStatusCode().value(), addFunction);
+ } catch (HttpClientErrorException e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "HttpClientErrorException - Failed to add function in external central auth system", e);
+ EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+ throw e;
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "addFunctionInExternalSystem: Failed to add fucntion in external central auth system", e);
+ throw e;
+ }
+ }
+
+ @Override
+ public void bulkUploadPartnerRoles(String uebkey, List<Role> roleList) throws Exception {
+ EPApp app = getApp(uebkey).get(0);
+ for (Role role : roleList) {
+ addRoleInExternalSystem(role, app);
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public Integer bulkUploadPartnerRoleFunctions(String uebkey) throws Exception {
+ EPApp app = getApp(uebkey).get(0);
+ List<EPRole> roles = getAppRoles(app.getId());
+ final Map<String, Long> params = new HashMap<>();
+ Integer roleFunctions = 0;
+ try {
+ for (EPRole role : roles) {
+ params.put("roleId", role.getId());
+ List<BulkUploadRoleFunction> appRoleFunc = dataAccessService
+ .executeNamedQuery("uploadPartnerRoleFunctions", params, null);
+ if (!appRoleFunc.isEmpty()) {
+ for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
+ addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
+ roleFunctions++;
+ }
+ }
+ }
+ // upload global role functions to ext auth system
+ if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
+ roleFunctions = bulkUploadGlobalRoleFunctions(app, roleFunctions);
+ }
+ } catch (HttpClientErrorException e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
+ EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
+ }
+ return roleFunctions;
+ }
+
+ @SuppressWarnings("unchecked")
+ private Integer bulkUploadGlobalRoleFunctions(EPApp app, Integer roleFunctions) throws Exception {
+ try {
+ EPApp portalApp = epAppService.getApp(1l);
+ final Map<String, Long> params = new HashMap<>();
+ params.put("appId", app.getId());
+ List<GlobalRoleWithApplicationRoleFunction> globalRoleFuncs = dataAccessService
+ .executeNamedQuery("getBulkUploadPartnerGlobalRoleFunctions", params, null);
+ ObjectMapper mapper = new ObjectMapper();
+ HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+ for (GlobalRoleWithApplicationRoleFunction globalRoleFunc : globalRoleFuncs) {
+ ExternalAccessRolePerms extRolePerms;
+ ExternalAccessPerms extPerms;
+ String type = "";
+ String instance = "";
+ String action = "";
+ if (globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
+ type = EcompPortalUtils.getFunctionType(globalRoleFunc.getFunctionCd());
+ instance = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd());
+ action = EcompPortalUtils.getFunctionAction(globalRoleFunc.getFunctionCd());
+ } else {
+ type = globalRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
+ instance = globalRoleFunc.getFunctionCd();
+ action = "*";
+ }
+ extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, instance, action);
+ extRolePerms = new ExternalAccessRolePerms(extPerms,
+ portalApp.getNameSpace() + "." + globalRoleFunc.getRoleName().replaceAll(
+ EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
+ String updateRolePerms = mapper.writeValueAsString(extRolePerms);
+ HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
+ updateRoleFunctionInExternalSystem(updateRolePerms, entity);
+ roleFunctions++;
+ }
+ } catch (HttpClientErrorException e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "HttpClientErrorException - Failed to add role function in external central auth system", e);
+ EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+ throw e;
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "bulkUploadGlobalRoleFunctions: Failed to add role fucntion in external central auth system", e);
+ throw e;
+ }
+ return roleFunctions;
+ }
+
+ @Override
+ @Transactional
+ public void syncApplicationRolesWithEcompDB(EPApp app) {
+ try {
+ logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Started");
+ // Sync functions and roles assigned to it which also creates new roles if does
+ // not exits in portal
+ syncRoleFunctionFromExternalAccessSystem(app);
+ logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Finished");
+ ObjectMapper mapper = new ObjectMapper();
+ logger.debug(EELFLoggerDelegate.debugLogger, "Entering to getAppRolesJSONFromExtAuthSystem");
+ // Get Permissions from External Auth System
+ JSONArray extRole = getAppRolesJSONFromExtAuthSystem(app);
+ logger.debug(EELFLoggerDelegate.debugLogger, "Entering into getExternalRoleDetailsList");
+ // refactoring done
+ List<ExternalRoleDetails> externalRoleDetailsList = getExternalRoleDetailsList(app, mapper, extRole);
+ List<EPRole> finalRoleList = new ArrayList<>();
+ for (ExternalRoleDetails externalRole : externalRoleDetailsList) {
+ EPRole ecompRole = convertExternalRoleDetailstoEpRole(externalRole);
+ finalRoleList.add(ecompRole);
+ }
+ List<EPRole> applicationRolesList;
+ applicationRolesList = getAppRoles(app.getId());
+ List<String> applicationRoleIdList = new ArrayList<>();
+ for (EPRole applicationRole : applicationRolesList) {
+ applicationRoleIdList.add(applicationRole.getName());
+ }
+ List<EPRole> roleListToBeAddInEcompDB = new ArrayList<>();
+ for (EPRole aafRole : finalRoleList) {
+ if (!applicationRoleIdList.contains(aafRole.getName())) {
+ roleListToBeAddInEcompDB.add(aafRole);
+ }
+ }
+ logger.debug(EELFLoggerDelegate.debugLogger, "Entering into inactiveRolesNotInExternalAuthSystem");
+ // Check if roles exits in external Access system and if not make inactive in DB
+ inactiveRolesNotInExternalAuthSystem(app, finalRoleList, applicationRolesList);
+ logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addNewRoleInEcompDBUpdateDescInExtAuthSystem");
+ // Add new roles in DB and updates role description in External Auth System
+ addNewRoleInEcompDBUpdateDescInExtAuthSystem(app, roleListToBeAddInEcompDB);
+ logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: Finished");
+ } catch (HttpClientErrorException e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "syncApplicationRolesWithEcompDB: Failed due to the External Auth System", e);
+ EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed ", e);
+ }
+ }
+
+ /**
+ *
+ * It adds new roles in DB and updates description in External Auth System
+ *
+ * @param app
+ * @param roleListToBeAddInEcompDB
+ */
+ @SuppressWarnings("unchecked")
+ private void addNewRoleInEcompDBUpdateDescInExtAuthSystem(EPApp app, List<EPRole> roleListToBeAddInEcompDB) {
+ EPRole roleToBeAddedInEcompDB;
+ for (int i = 0; i < roleListToBeAddInEcompDB.size(); i++) {
+ try {
+ roleToBeAddedInEcompDB = roleListToBeAddInEcompDB.get(i);
+ if (app.getId() == 1) {
+ roleToBeAddedInEcompDB.setAppRoleId(null);
+ }
+ dataAccessService.saveDomainObject(roleToBeAddedInEcompDB, null);
+ List<EPRole> getRoleCreatedInSync = null;
+ if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
+ final Map<String, String> globalRoleParams = new HashMap<>();
+ globalRoleParams.put("appId", String.valueOf(app.getId()));
+ globalRoleParams.put("appRoleName", roleToBeAddedInEcompDB.getName());
+ getRoleCreatedInSync = dataAccessService
+ .executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, globalRoleParams, null);
+ EPRole epUpdateRole = getRoleCreatedInSync.get(0);
+ epUpdateRole.setAppRoleId(epUpdateRole.getId());
+ dataAccessService.saveDomainObject(epUpdateRole, null);
+ }
+ List<EPRole> roleList = new ArrayList<>();
+ final Map<String, String> params = new HashMap<>();
+ params.put(APP_ROLE_NAME_PARAM, roleToBeAddedInEcompDB.getName());
+ boolean isPortalRole = false;
+ if (app.getId() == 1) {
+ isPortalRole = true;
+ roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, params, null);
+ } else {
+ isPortalRole = false;
+ params.put(APP_ID, app.getId().toString());
+ roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, params,
+ null);
+ }
+ EPRole role = roleList.get(0);
+ Role aaFrole = new Role();
+ aaFrole.setId(role.getId());
+ aaFrole.setActive(role.getActive());
+ aaFrole.setPriority(role.getPriority());
+ aaFrole.setName(role.getName());
+ updateRoleInExternalSystem(aaFrole, app, isPortalRole);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "SyncApplicationRolesWithEcompDB: Failed to add or update role in external auth system", e);
+ }
+ }
+ }
+
+ /**
+ *
+ * It de-activates application roles in DB if not present in External Auth
+ * system
+ *
+ * @param app
+ * @param finalRoleList contains list of current roles present in
+ * External Auth System
+ * @param applicationRolesList contains list of current roles present in DB
+ */
+ @SuppressWarnings("unchecked")
+ private void inactiveRolesNotInExternalAuthSystem(EPApp app, List<EPRole> finalRoleList,
+ List<EPRole> applicationRolesList) {
+ final Map<String, EPRole> checkRolesInactive = new HashMap<>();
+ for (EPRole extrole : finalRoleList) {
+ checkRolesInactive.put(extrole.getName(), extrole);
+ }
+ for (EPRole role : applicationRolesList) {
+ try {
+ final Map<String, String> extRoleParams = new HashMap<>();
+ List<EPRole> roleList = null;
+ extRoleParams.put(APP_ROLE_NAME_PARAM, role.getName());
+ if (!checkRolesInactive.containsKey(role.getName())) {
+ if (app.getId() == 1) {
+ roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, extRoleParams, null);
+ } else {
+ extRoleParams.put(APP_ID, app.getId().toString());
+ roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
+ extRoleParams, null);
+ }
+ if (!roleList.isEmpty()) {
+ EPRole updateRoleInactive = roleList.get(0);
+ updateRoleInactive.setActive(false);
+ dataAccessService.saveDomainObject(updateRoleInactive, null);
+ }
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "syncApplicationRolesWithEcompDB: Failed to de-activate role ", e);
+ }
+ }
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public List<ExternalRoleDetails> getExternalRoleDetailsList(EPApp app, ObjectMapper mapper, JSONArray extRole)
+ throws IOException {
+ List<ExternalRoleDetails> externalRoleDetailsList = new ArrayList<>();
+ ExternalAccessPerms externalAccessPerms = new ExternalAccessPerms();
+ List<String> functionCodelist = new ArrayList<>();
+ Map<String, EPRole> curRolesMap = getAppRoleNamesMap(app);
+ Map<String, EPRole> curRolesUnderscoreMap = getAppRoleNamesWithUnderscoreMap(app);
+ for (int i = 0; i < extRole.length(); i++) {
+ ExternalRoleDetails externalRoleDetail = new ExternalRoleDetails();
+ EPAppRoleFunction ePAppRoleFunction = new EPAppRoleFunction();
+ JSONObject Role = (JSONObject) extRole.get(i);
+ String name = extRole.getJSONObject(i).getString(ROLE_NAME);
+ String actualRoleName = name.substring(app.getNameSpace().length() + 1);
+ if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
+ actualRoleName = extRole.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
+ }
+ SortedSet<ExternalAccessPerms> externalAccessPermsOfRole = new TreeSet<>();
+ if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_PERMS)) {
+ JSONArray extPerm = (JSONArray) Role.get(EXTERNAL_AUTH_PERMS);
+ for (int j = 0; j < extPerm.length(); j++) {
+ JSONObject perms = extPerm.getJSONObject(j);
+ boolean isNamespaceMatching = EcompPortalUtils.checkNameSpaceMatching(perms.getString("type"),
+ app.getNameSpace());
+ if (isNamespaceMatching) {
+ externalAccessPerms = new ExternalAccessPerms(perms.getString("type"),
+ perms.getString("instance"), perms.getString("action"));
+ ePAppRoleFunction.setCode(externalAccessPerms.getInstance());
+ functionCodelist.add(ePAppRoleFunction.getCode());
+ externalAccessPermsOfRole.add(externalAccessPerms);
+ }
+ }
+ }
+ externalRoleDetail.setActive(true);
+ externalRoleDetail.setName(actualRoleName);
+ if (app.getId() == 1) {
+ externalRoleDetail.setAppId(null);
+ } else {
+ externalRoleDetail.setAppId(app.getId());
+ }
+ EPRole currRole = null;
+ currRole = (!extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION))
+ ? curRolesUnderscoreMap.get(actualRoleName)
+ : curRolesMap.get(actualRoleName);
+ Long roleId = null;
+ if (currRole != null)
+ roleId = currRole.getId();
+ final Map<String, EPAppRoleFunction> roleFunctionsMap = new HashMap<>();
+ final Map<String, Long> appRoleFuncsParams = new HashMap<>();
+ if (roleId != null) {
+ appRoleFuncsParams.put("appId", app.getId());
+ appRoleFuncsParams.put("roleId", roleId);
+ // get role functions from DB
+ List<EPAppRoleFunction> appRoleFunctions = dataAccessService
+ .executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null);
+ if (!appRoleFunctions.isEmpty()) {
+ for (EPAppRoleFunction roleFunc : appRoleFunctions) {
+ roleFunctionsMap.put(roleFunc.getCode(), roleFunc);
+ }
+ }
+ }
+ if (!externalAccessPermsOfRole.isEmpty()) {
+ // Adding functions to role
+ for (ExternalAccessPerms externalpermission : externalAccessPermsOfRole) {
+ EPAppRoleFunction checkRoleFunctionExits = roleFunctionsMap.get(externalpermission.getInstance());
+ if (checkRoleFunctionExits == null) {
+ String funcCode = externalpermission.getType().substring(app.getNameSpace().length() + 1)
+ + FUNCTION_PIPE + externalpermission.getInstance() + FUNCTION_PIPE
+ + externalpermission.getAction();
+ EPAppRoleFunction checkRoleFunctionPipeExits = roleFunctionsMap.get(funcCode);
+ if (checkRoleFunctionPipeExits == null) {
+ try {
+ final Map<String, String> appFuncsParams = new HashMap<>();
+ appFuncsParams.put("appId", String.valueOf(app.getId()));
+ appFuncsParams.put("functionCd", externalpermission.getInstance());
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "SyncApplicationRolesWithEcompDB: Adding function to the role: {}",
+ externalpermission.getInstance());
+ List<CentralV2RoleFunction> roleFunction = null;
+ roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId",
+ appFuncsParams, null);
+ if (roleFunction.isEmpty()) {
+ appFuncsParams.put("functionCd", funcCode);
+ roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId",
+ appFuncsParams, null);
+ }
+ if (!roleFunction.isEmpty()) {
+ EPAppRoleFunction apRoleFunction = new EPAppRoleFunction();
+ apRoleFunction.setAppId(app.getId());
+ apRoleFunction.setRoleId(roleId);
+ apRoleFunction.setCode(roleFunction.get(0).getCode());
+ dataAccessService.saveDomainObject(apRoleFunction, null);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "SyncApplicationRolesWithEcompDB: Failed to add role function", e);
+ }
+ }
+ }
+ }
+ }
+ externalRoleDetailsList.add(externalRoleDetail);
+ }
+ return externalRoleDetailsList;
+ }
+
+ @Override
+ public JSONArray getAppRolesJSONFromExtAuthSystem(EPApp app) throws Exception {
+ ResponseEntity<String> response = null;
+ HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+ HttpEntity<String> entity = new HttpEntity<>(headers);
+ logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: {} ",
+ CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
+ response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
+ + "roles/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
+ String res = response.getBody();
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
+ res);
+ JSONObject jsonObj = new JSONObject(res);
+ JSONArray extRole = jsonObj.getJSONArray("role");
+ for (int i = 0; i < extRole.length(); i++) {
+ if (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ADMIN)
+ || extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + OWNER)
+ || (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ACCOUNT_ADMINISTRATOR)
+ && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
+ extRole.remove(i);
+ i--;
+ }
+ }
+ return extRole;
+ }
+
+ @Override
+ public JSONArray getAllUsersByRole(String roleName) throws Exception {
+ ResponseEntity<String> response = null;
+ HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+ HttpEntity<String> entity = new HttpEntity<>(headers);
+ logger.debug(EELFLoggerDelegate.debugLogger, "getAllUsersByRole: {} ",
+ CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
+ response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
+ + "userRoles/role/" + roleName, HttpMethod.GET, entity, String.class);
+ String res = response.getBody();
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
+ res);
+ if (res == null || res.trim().isEmpty())
+ return null;
+ JSONObject jsonObj = new JSONObject(res);
+ JSONArray extRole = jsonObj.getJSONArray("userRole");
+ return extRole;
+ }
+
+ /**
+ *
+ * It converts from ExternalRoleDetails.class object to EPRole.class object
+ *
+ * @param externalRoleDetails
+ * @return EPRole object
+ */
+ private EPRole convertExternalRoleDetailstoEpRole(ExternalRoleDetails externalRoleDetails) {
+ EPRole role = new EPRole();
+ role.setActive(true);
+ role.setAppId(externalRoleDetails.getAppId());
+ role.setAppRoleId(externalRoleDetails.getAppRoleId());
+ role.setName(externalRoleDetails.getName());
+ role.setPriority(externalRoleDetails.getPriority());
+ return role;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public Integer bulkUploadUserRoles(String uebkey) throws Exception {
+ EPApp app = getApp(uebkey).get(0);
+ final Map<String, String> params = new HashMap<>();
+ params.put("uebKey", app.getUebKey());
+ List<BulkUploadUserRoles> userRolesList = null;
+ Integer userRolesAdded = 0;
+ if (app.getCentralAuth()) {
+ userRolesList = dataAccessService.executeNamedQuery("getBulkUserRoles", params, null);
+ for (BulkUploadUserRoles userRolesUpload : userRolesList) {
+ if (!userRolesUpload.getOrgUserId().equals("su1234")) {
+ addUserRoleInExternalSystem(userRolesUpload);
+ userRolesAdded++;
+ }
+ }
+ }
+ return userRolesAdded;
+ }
+
+ /**
+ * Its adding a user role in external auth system while doing bulk upload
+ *
+ * @param userRolesUpload
+ */
+ private void addUserRoleInExternalSystem(BulkUploadUserRoles userRolesUpload) {
+ try {
+ String name = "";
+ ObjectMapper mapper = new ObjectMapper();
+ if (EPCommonSystemProperties
+ .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
+ name = userRolesUpload.getOrgUserId()
+ + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
+ }
+ ExternalAccessUser extUser = new ExternalAccessUser(name,
+ userRolesUpload.getAppNameSpace() + "." + userRolesUpload.getRoleName()
+ .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
+ String userRole = mapper.writeValueAsString(extUser);
+ HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+ HttpEntity<String> entity = new HttpEntity<>(userRole, headers);
+ template.exchange(
+ SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
+ HttpMethod.POST, entity, String.class);
+ } catch (HttpClientErrorException e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "HttpClientErrorException - Failed to addUserRoleInExternalSystem", e);
+ EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+ } catch (Exception e) {
+ if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "addUserRoleInExternalSystem: UserRole already exits but does not break functionality");
+ } else {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "addUserRoleInExternalSystem: Failed to addUserRoleInExternalSystem", e);
+ }
+ }
+ }
+
+ @Override
+ public void deleteRoleDependencyRecords(Session localSession, Long roleId, Long appId, boolean isPortalRequest)
+ throws Exception {
+ try {
+ String sql = "";
+ Query query = null;
+ // It should delete only when it portal's roleId
+ if (appId.equals(PortalConstants.PORTAL_APP_ID)) {
+ // Delete from fn_role_function
+ sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
+ logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
+ query = localSession.createSQLQuery(sql);
+ query.executeUpdate();
+ // Delete from fn_role_composite
+ sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId;
+ logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
+ query = localSession.createSQLQuery(sql);
+ query.executeUpdate();
+ }
+ // Delete from ep_app_role_function
+ sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId;
+ logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
+ query = localSession.createSQLQuery(sql);
+ query.executeUpdate();
+ // Delete from ep_role_notification
+ sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
+ logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
+ query = localSession.createSQLQuery(sql);
+ query.executeUpdate();
+ // Delete from fn_user_pseudo_role
+ sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
+ logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
+ query = localSession.createSQLQuery(sql);
+ query.executeUpdate();
+ // Delete form EP_WIDGET_CATALOG_ROLE
+ sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId;
+ logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
+ query = localSession.createSQLQuery(sql);
+ query.executeUpdate();
+ // Delete form EP_WIDGET_CATALOG_ROLE
+ sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId;
+ logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
+ query = localSession.createSQLQuery(sql);
+ query.executeUpdate();
+ if (!isPortalRequest) {
+ // Delete form fn_menu_functional_roles
+ sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
+ logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
+ query = localSession.createSQLQuery(sql);
+ query.executeUpdate();
+ }
+ } catch (Exception e) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e);
+ throw new DeleteDomainObjectFailedException("delete Failed" + e.getMessage());
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<String> getMenuFunctionsList(String uebkey) throws Exception {
+ List<String> appMenuFunctionsList = null;
+ List<String> appMenuFunctionsFinalList = new ArrayList<>();
+ try {
+ EPApp app = getApp(uebkey).get(0);
+ final Map<String, Long> appParams = new HashMap<>();
+ appParams.put(APP_ID, app.getId());
+ appMenuFunctionsList = dataAccessService.executeNamedQuery("getMenuFunctions", appParams, null);
+ for (String appMenuFunction : appMenuFunctionsList) {
+ if (appMenuFunction.contains(FUNCTION_PIPE)) {
+ appMenuFunctionsFinalList.add(EcompPortalUtils.getFunctionCode(appMenuFunction));
+ } else {
+ appMenuFunctionsFinalList.add(appMenuFunction);
+ }
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getMenuFunctionsList: Failed", e);
+ return appMenuFunctionsFinalList;
+ }
+ return appMenuFunctionsFinalList;
+ }
+
+ @SuppressWarnings({ "unchecked" })
+ @Override
+ public List<EcompUser> getAllAppUsers(String uebkey) throws Exception {
+ List<String> usersList = new ArrayList<>();
+ List<EcompUser> usersfinalList = new ArrayList<>();
+ try {
+ EPApp app = getApp(uebkey).get(0);
+ final Map<String, Long> appParams = new HashMap<>();
+ appParams.put("appId", app.getId());
+ List<EcompUserRoles> userList = (List<EcompUserRoles>) dataAccessService
+ .executeNamedQuery("ApplicationUserRoles", appParams, null);
+ for (EcompUserRoles ecompUserRole : userList) {
+ boolean found = false;
+ Set<EcompRole> roles = null;
+ for (EcompUser user : usersfinalList) {
+ if (user.getOrgUserId().equals(ecompUserRole.getOrgUserId())) {
+ EcompRole ecompRole = new EcompRole();
+ ecompRole.setId(ecompUserRole.getRoleId());
+ ecompRole.setName(ecompUserRole.getRoleName());
+ roles = user.getRoles();
+ EcompRole role = roles.stream().filter(x -> x.getName().equals(ecompUserRole.getRoleName()))
+ .findAny().orElse(null);
+ SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
+ if (role != null) {
+ roleFunctionSet = (SortedSet<EcompRoleFunction>) role.getRoleFunctions();
+ }
+ String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
+ functionCode = EPUserUtils.decodeFunctionCode(functionCode);
+ EcompRoleFunction epRoleFunction = new EcompRoleFunction();
+ epRoleFunction.setName(ecompUserRole.getFunctionName());
+ epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
+ epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
+ epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
+ roleFunctionSet.add(epRoleFunction);
+ ecompRole.setRoleFunctions(roleFunctionSet);
+ roles.add(ecompRole);
+ user.setRoles(roles);
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ EcompUser epUser = new EcompUser();
+ epUser.setOrgId(ecompUserRole.getOrgId());
+ epUser.setManagerId(ecompUserRole.getManagerId());
+ epUser.setFirstName(ecompUserRole.getFirstName());
+ epUser.setLastName(ecompUserRole.getLastName());
+ epUser.setPhone(ecompUserRole.getPhone());
+ epUser.setEmail(ecompUserRole.getEmail());
+ epUser.setOrgUserId(ecompUserRole.getOrgUserId());
+ epUser.setOrgCode(ecompUserRole.getOrgCode());
+ epUser.setOrgManagerUserId(ecompUserRole.getOrgManagerUserId());
+ epUser.setJobTitle(ecompUserRole.getJobTitle());
+ epUser.setLoginId(ecompUserRole.getLoginId());
+ epUser.setActive(true);
+ roles = new HashSet<>();
+ EcompRole ecompRole = new EcompRole();
+ ecompRole.setId(ecompUserRole.getRoleId());
+ ecompRole.setName(ecompUserRole.getRoleName());
+ SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
+ String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
+ functionCode = EPUserUtils.decodeFunctionCode(functionCode);
+ EcompRoleFunction epRoleFunction = new EcompRoleFunction();
+ epRoleFunction.setName(ecompUserRole.getFunctionName());
+ epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
+ epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
+ epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
+ roleFunctionSet.add(epRoleFunction);
+ ecompRole.setRoleFunctions(roleFunctionSet);
+ roles.add(ecompRole);
+ epUser.setRoles(roles);
+ usersfinalList.add(epUser);
+ }
+ }
+ ObjectMapper mapper = new ObjectMapper();
+ for (EcompUser u1 : usersfinalList) {
+ String str = mapper.writeValueAsString(u1);
+ usersList.add(str);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getAllUsers failed", e);
+ throw e;
+ }
+ return usersfinalList;
+ }
+
+ @Override
+ public Role ConvertCentralRoleToRole(String result) {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ Role newRole = new Role();
+ try {
+ newRole = mapper.readValue(result, Role.class);
+ } catch (IOException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Failed to convert the result to Role Object", e);
+ }
+ if (newRole.getRoleFunctions() != null) {
+ @SuppressWarnings("unchecked")
+ Set<RoleFunction> roleFunctionList = newRole.getRoleFunctions();
+ Set<RoleFunction> roleFunctionListNew = new HashSet<>();
+ Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
+ while (itetaror.hasNext()) {
+ Object nextValue = itetaror.next();
+ RoleFunction roleFun = mapper.convertValue(nextValue, RoleFunction.class);
+ roleFunctionListNew.add(roleFun);
+ }
+ newRole.setRoleFunctions(roleFunctionListNew);
+ }
+ return newRole;
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public List<CentralizedApp> getCentralizedAppsOfUser(String userId) {
+ Map<String, String> params = new HashMap<>();
+ params.put("userId", userId);
+ List<CentralizedApp> centralizedAppsList = new ArrayList<>();
+ try {
+ centralizedAppsList = dataAccessService.executeNamedQuery("getCentralizedAppsOfUser", params, null);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
+ }
+ return centralizedAppsList;
+ }
+
+ @SuppressWarnings("unchecked")
+ public List<CentralV2Role> getGlobalRolesOfApplication(Long appId) {
+ Map<String, Long> params = new HashMap<>();
+ params.put("appId", appId);
+ List<GlobalRoleWithApplicationRoleFunction> globalRoles = new ArrayList<>();
+ try {
+ globalRoles = dataAccessService.executeNamedQuery("getGlobalRoleWithApplicationRoleFunctions", params,
+ null);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
+ }
+ List<CentralV2Role> rolesfinalList = new ArrayList<>();
+ if (globalRoles.size() > 0)
+ rolesfinalList = finalListOfCentralRoles(globalRoles);
+ return rolesfinalList;
+ }
+
+ @SuppressWarnings("unchecked")
+ private CentralV2Role getGlobalRoleForRequestedApp(long requestedAppId, long roleId) {
+ CentralV2Role finalGlobalrole = null;
+ List<GlobalRoleWithApplicationRoleFunction> roleWithApplicationRoleFucntions = new ArrayList<>();
+ Map<String, Long> params = new HashMap<>();
+ params.put("roleId", roleId);
+ params.put("requestedAppId", requestedAppId);
+ try {
+ roleWithApplicationRoleFucntions = dataAccessService.executeNamedQuery("getGlobalRoleForRequestedApp",
+ params, null);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRoleForRequestedApp failed", e);
+ }
+ if (roleWithApplicationRoleFucntions.size() > 0) {
+ List<CentralV2Role> rolesfinalList = finalListOfCentralRoles(roleWithApplicationRoleFucntions);
+ finalGlobalrole = rolesfinalList.get(0);
+ } else {
+ List<EPRole> roleList = getPortalAppRoleInfo(roleId);
+ finalGlobalrole = convertRoleToCentralV2Role(roleList.get(0));
+ }
+ return finalGlobalrole;
+ }
+
+ private List<CentralV2Role> finalListOfCentralRoles(List<GlobalRoleWithApplicationRoleFunction> globalRoles) {
+ List<CentralV2Role> rolesfinalList = new ArrayList<>();
+ for (GlobalRoleWithApplicationRoleFunction role : globalRoles) {
+ boolean found = false;
+ for (CentralV2Role cenRole : rolesfinalList) {
+ if (role.getRoleId().equals(cenRole.getId())) {
+ SortedSet<CentralV2RoleFunction> roleFunctions = cenRole.getRoleFunctions();
+ CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
+ roleFunctions.add(cenRoleFun);
+ cenRole.setRoleFunctions(roleFunctions);
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ CentralV2Role cenrole = new CentralV2Role();
+ cenrole.setName(role.getRoleName());
+ cenrole.setId(role.getRoleId());
+ cenrole.setActive(role.isActive());
+ cenrole.setPriority(role.getPriority());
+ SortedSet<CentralV2RoleFunction> roleFunctions = new TreeSet<>();
+ CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
+ roleFunctions.add(cenRoleFun);
+ cenrole.setRoleFunctions(roleFunctions);
+ rolesfinalList.add(cenrole);
+ }
+ }
+ return rolesfinalList;
+ }
+
+ private CentralV2RoleFunction createCentralRoleFunctionForGlobalRole(GlobalRoleWithApplicationRoleFunction role) {
+ String instance;
+ String type;
+ String action;
+ CentralV2RoleFunction cenRoleFun;
+ if (role.getFunctionCd().contains(FUNCTION_PIPE)) {
+ instance = EcompPortalUtils.getFunctionCode(role.getFunctionCd());
+ type = EcompPortalUtils.getFunctionType(role.getFunctionCd());
+ action = EcompPortalUtils.getFunctionAction(role.getFunctionCd());
+ cenRoleFun = new CentralV2RoleFunction(null, instance, role.getFunctionName(), null, type, action, null);
+ } else {
+ type = getFunctionCodeType(role.getFunctionCd());
+ action = getFunctionCodeAction(role.getFunctionCd());
+ cenRoleFun = new CentralV2RoleFunction(null, role.getFunctionCd(), role.getFunctionName(), null, type,
+ action, null);
+ }
+ return cenRoleFun;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<EPRole> getGlobalRolesOfPortal() {
+ List<EPRole> globalRoles = new ArrayList<>();
+ try {
+ globalRoles = dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRolesOfPortal failed", e);
+ }
+ return globalRoles;
+ }
+
+ private CentralV2Role convertRoleToCentralV2Role(EPRole role) {
+ return new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
+ role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
+ new TreeSet<>(), new TreeSet<>(), new TreeSet<>());
+ }
+
+ @Override
+ public List<CentralRoleFunction> convertCentralRoleFunctionToRoleFunctionObject(
+ List<CentralV2RoleFunction> answer) {
+ List<CentralRoleFunction> addRoleFuncList = new ArrayList<>();
+ for (CentralV2RoleFunction cenRoleFunc : answer) {
+ CentralRoleFunction setRoleFunc = new CentralRoleFunction();
+ setRoleFunc.setCode(cenRoleFunc.getCode());
+ setRoleFunc.setName(cenRoleFunc.getName());
+ addRoleFuncList.add(setRoleFunc);
+ }
+ return addRoleFuncList;
+ }
+
+ @Override
+ public CentralUser getUserRoles(String loginId, String uebkey) throws Exception {
+ CentralUser sendUserRoles = null;
+ try {
+ CentralV2User cenV2User = getV2UserAppRoles(loginId, uebkey);
+ sendUserRoles = convertV2UserRolesToOlderVersion(cenV2User);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getUserRoles: failed", e);
+ throw e;
+ }
+ return sendUserRoles;
+ }
+
+ /**
+ *
+ * It returns V2 CentralUser object if user has any roles and permissions
+ *
+ * @param loginId
+ * @param uebkey
+ * @return CentralUser object
+ * @throws Exception
+ */
+ private CentralV2User getV2UserAppRoles(String loginId, String uebkey) throws Exception {
+ EPApp app;
+ List<EPUser> epUserList;
+ List<EPApp> appList = getApp(uebkey);
+ app = appList.get(0);
+ epUserList = getUser(loginId);
+ EPUser user = epUserList.get(0);
+ Set<EPUserApp> userAppSet = user.getEPUserApps();
+ return createEPUser(user, userAppSet, app);
+ }
+
+ private List<EcompRole> getUserAppRoles(EPApp app, EPUser user) {
+ final Map<String, Long> userParams = new HashMap<>();
+ userParams.put("appId", app.getId());
+ userParams.put("userId", user.getId());
+ @SuppressWarnings("unchecked")
+ List<EPUserAppCurrentRoles> userAppsRolesList = dataAccessService.executeNamedQuery("getUserAppCurrentRoles",
+ userParams, null);
+ List<EcompRole> setUserRoles = new ArrayList<>();
+ for (EPUserAppCurrentRoles role : userAppsRolesList) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "In getUserAppRoles()- get userRolename = {}",
+ role.getRoleName());
+ EcompRole ecompRole = new EcompRole();
+ ecompRole.setId(role.getRoleId());
+ ecompRole.setName(role.getRoleName());
+ setUserRoles.add(ecompRole);
+ }
+ logger.debug(EELFLoggerDelegate.debugLogger, "In getUserAppRoles()- get userrole list size = {}",
+ setUserRoles.size());
+ return setUserRoles;
+ }
+
+ @Override
+ public List<EcompRole> missingUserApplicationRoles(String uebkey, String loginId, Set<EcompRole> CurrentUserRoles)
+ throws Exception {
+ List<EPApp> appList = getApp(uebkey);
+ EPApp app = appList.get(0);
+ List<EPUser> epUserList;
+ epUserList = getUser(loginId);
+ List<EcompRole> missingUserAppRoles = new ArrayList<>();
+ List<String> roleNamesList = CurrentUserRoles.stream().map(EcompRole::getName).collect(Collectors.toList());
+ logger.debug(EELFLoggerDelegate.debugLogger, "Roles of User from hibernate :" + roleNamesList);
+ List<EcompRole> userApplicationsRolesfromDB = getUserAppRoles(app, epUserList.get(0));
+ if (userApplicationsRolesfromDB.size() > 0) {
+ missingUserAppRoles = userApplicationsRolesfromDB.stream().filter(x -> !roleNamesList.contains(x.getName()))
+ .collect(Collectors.toList());
+ }
+ List<String> MissingroleNamesList = missingUserAppRoles.stream().map(EcompRole::getName)
+ .collect(Collectors.toList());
+ logger.debug(EELFLoggerDelegate.debugLogger, "MissingUserAppRoles():" + MissingroleNamesList);
+
+ List<EcompRole> finalMissingRoleList = new ArrayList<>();
+ if (missingUserAppRoles.size() > 0) {
+ final Map<String, Long> params = new HashMap<>();
+ for (EcompRole role : missingUserAppRoles) {
+ params.put("roleId", role.getId());
+ params.put(APP_ID, app.getId());
+
+ EcompRole epRole = new EcompRole();
+ epRole.setId(role.getId());
+ epRole.setName(role.getName());
+ @SuppressWarnings("unchecked")
+ List<CentralV2RoleFunction> appRoleFunctionList = dataAccessService
+ .executeNamedQuery("getAppRoleFunctionList", params, null);
+ SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
+ for (CentralV2RoleFunction roleFunc : appRoleFunctionList) {
+ String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
+ String type = getFunctionCodeType(roleFunc.getCode());
+ String action = getFunctionCodeAction(roleFunc.getCode());
+ EcompRoleFunction fun = new EcompRoleFunction();
+ fun.setAction(action);
+ fun.setCode(functionCode);
+ fun.setType(type);
+ fun.setName(roleFunc.getName());
+ roleFunctionSet.add(fun);
+
+ }
+ epRole.setRoleFunctions(roleFunctionSet);
+ finalMissingRoleList.add(epRole);
+ }
+ }
+
+ return finalMissingRoleList;
+ }
+
+ /**
+ * It converts V2 CentralUser object to old version CentralUser object
+ *
+ * @param cenV2User
+ * @return EPUser object
+ */
+ private CentralUser convertV2UserRolesToOlderVersion(CentralV2User cenV2User) {
+ Set<CentralV2UserApp> userV2Apps = cenV2User.getUserApps();
+ Set<CentralUserApp> userApps = new TreeSet<>();
+ for (CentralV2UserApp userApp : userV2Apps) {
+ CentralApp app = userApp.getApp();
+ CentralUserApp cua = new CentralUserApp();
+ cua.setUserId(null);
+ cua.setApp(app);
+ SortedSet<CentralRoleFunction> cenRoleFunction = new TreeSet<>();
+ for (CentralV2RoleFunction cenV2RoleFunc : userApp.getRole().getRoleFunctions()) {
+ CentralRoleFunction cenRoleFunc = new CentralRoleFunction(cenV2RoleFunc.getCode(),
+ cenV2RoleFunc.getName());
+ cenRoleFunction.add(cenRoleFunc);
+ }
+ CentralRole role = new CentralRole(userApp.getRole().getId(), userApp.getRole().getName(),
+ userApp.getRole().getActive(), userApp.getRole().getPriority(), cenRoleFunction);
+ cua.setRole(role);
+ userApps.add(cua);
+ }
+ return new CentralUser(cenV2User.getId(), cenV2User.getCreated(), cenV2User.getModified(),
+ cenV2User.getCreatedId(), cenV2User.getModifiedId(), cenV2User.getRowNum(), cenV2User.getOrgId(),
+ cenV2User.getManagerId(), cenV2User.getFirstName(), cenV2User.getMiddleInitial(),
+ cenV2User.getLastName(), cenV2User.getPhone(), cenV2User.getFax(), cenV2User.getCellular(),
+ cenV2User.getEmail(), cenV2User.getAddressId(), cenV2User.getAlertMethodCd(), cenV2User.getHrid(),
+ cenV2User.getOrgUserId(), cenV2User.getOrgCode(), cenV2User.getAddress1(), cenV2User.getAddress2(),
+ cenV2User.getCity(), cenV2User.getState(), cenV2User.getZipCode(), cenV2User.getCountry(),
+ cenV2User.getOrgManagerUserId(), cenV2User.getLocationClli(), cenV2User.getBusinessCountryCode(),
+ cenV2User.getBusinessCountryName(), cenV2User.getBusinessUnit(), cenV2User.getBusinessUnitName(),
+ cenV2User.getDepartment(), cenV2User.getDepartmentName(), cenV2User.getCompanyCode(),
+ cenV2User.getCompany(), cenV2User.getZipCodeSuffix(), cenV2User.getJobTitle(),
+ cenV2User.getCommandChain(), cenV2User.getSiloStatus(), cenV2User.getCostCenter(),
+ cenV2User.getFinancialLocCode(), cenV2User.getLoginId(), cenV2User.getLoginPwd(),
+ cenV2User.getLastLoginDate(), cenV2User.isActive(), cenV2User.isInternal(),
+ cenV2User.getSelectedProfileId(), cenV2User.getTimeZoneId(), cenV2User.isOnline(),
+ cenV2User.getChatId(), userApps);
+ }
+
+ @Override
+ public List<CentralRole> convertV2CentralRoleListToOldVerisonCentralRoleList(List<CentralV2Role> v2CenRoleList) {
+ List<CentralRole> cenRoleList = new ArrayList<>();
+ for (CentralV2Role v2CenRole : v2CenRoleList) {
+ SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
+ for (CentralV2RoleFunction v2CenRoleFunc : v2CenRole.getRoleFunctions()) {
+ CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(),
+ v2CenRoleFunc.getName());
+ cenRoleFuncList.add(roleFunc);
+ }
+ CentralRole role = new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.getActive(),
+ v2CenRole.getPriority(), cenRoleFuncList);
+ cenRoleList.add(role);
+ }
+ return cenRoleList;
+ }
+
+ @Override
+ public ResponseEntity<String> getNameSpaceIfExists(EPApp app) throws Exception {
+ HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+ HttpEntity<String> entity = new HttpEntity<>(headers);
+ logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Connecting to External Auth system");
+ ResponseEntity<String> response = null;
+ try {
+ response = template
+ .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
+ + "nss/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
+ logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Finished ",
+ response.getStatusCode().value());
+ } catch (HttpClientErrorException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e);
+ EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+ if (e.getStatusCode() == HttpStatus.NOT_FOUND)
+ throw new InvalidApplicationException("Invalid NameSpace");
+ else
+ throw e;
+ }
+ return response;
+ }
+
+ @Override
+ public CentralRole convertV2CentralRoleToOldVerisonCentralRole(CentralV2Role v2CenRole) {
+ SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
+ for (CentralV2RoleFunction v2CenRoleFunc : v2CenRole.getRoleFunctions()) {
+ CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName());
+ cenRoleFuncList.add(roleFunc);
+ }
+ return new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.getActive(), v2CenRole.getPriority(),
+ cenRoleFuncList);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public Integer bulkUploadUsersSingleRole(String uebkey, Long roleId, String modifiedRoleName) throws Exception {
+ EPApp app = getApp(uebkey).get(0);
+ final Map<String, String> params = new HashMap<>();
+ params.put("uebKey", app.getUebKey());
+ params.put("roleId", String.valueOf(roleId));
+ List<BulkUploadUserRoles> userRolesList = null;
+ Integer userRolesAdded = 0;
+ if (app.getCentralAuth()) {
+ userRolesList = dataAccessService.executeNamedQuery("getBulkUsersForSingleRole", params, null);
+ for (BulkUploadUserRoles userRolesUpload : userRolesList) {
+ userRolesUpload.setRoleName(modifiedRoleName);
+ if (!userRolesUpload.getOrgUserId().equals("su1234")) {
+ addUserRoleInExternalSystem(userRolesUpload);
+ userRolesAdded++;
+ }
+ }
+ }
+ return userRolesAdded;
+ }
+
+ @Override
+ public void bulkUploadRoleFunc(UploadRoleFunctionExtSystem data, EPApp app) throws Exception {
+ ObjectMapper mapper = new ObjectMapper();
+ HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+ try {
+ ExternalAccessRolePerms extRolePerms;
+ ExternalAccessPerms extPerms;
+ extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + data.getType(),
+ EcompPortalUtils.encodeFunctionCode(data.getInstance()), data.getAction());
+ String appNameSpace = "";
+ if (data.getIsGlobalRolePartnerFunc()) {
+ appNameSpace = epAppService.getApp(1l).getNameSpace();
+ } else {
+ appNameSpace = app.getNameSpace();
+ }
+ extRolePerms = new ExternalAccessRolePerms(extPerms, appNameSpace + "." + data.getRoleName()
+ .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
+ String updateRolePerms = mapper.writeValueAsString(extRolePerms);
+ HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
+ updateRoleFunctionInExternalSystem(updateRolePerms, entity);
+ } catch (HttpClientErrorException e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "HttpClientErrorException - Failed to add role function in external central auth system", e);
+ EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+ throw e;
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "addFunctionInExternalSystem: Failed to add role fucntion in external central auth system", e);
+ throw e;
+ }
+ }
+
+ private void updateRoleFunctionInExternalSystem(String updateRolePerms, HttpEntity<String> entity) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "bulkUploadRoleFunc: {} for POST: {}",
+ CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
+ ResponseEntity<String> addPermResponse = template.exchange(
+ SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
+ HttpMethod.POST, entity, String.class);
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "bulkUploadRoleFunc: Finished adding permission for POST: {} and status code: {} ",
+ addPermResponse.getStatusCode().value(), updateRolePerms);
+ }
+
+ @Override
+ public void syncApplicationUserRolesFromExtAuthSystem(String loginId) throws Exception {
+ String name = "";
+ if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
+ name = loginId + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
+ }
+ HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+ HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
+ ResponseEntity<String> getResponse = getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
+ List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
+ String res = getResponse.getBody();
+ JSONObject jsonObj = null;
+ JSONArray extRoles = null;
+ if (!res.equals("{}")) {
+ jsonObj = new JSONObject(res);
+ extRoles = jsonObj.getJSONArray("role");
+ }
+ updateUserRolesInLocal(userRoleDetailList, extRoles, loginId);
+ }
+
+ @SuppressWarnings("unchecked")
+ private void updateUserRolesInLocal(List<ExternalAccessUserRoleDetail> userRoleDetailList, JSONArray extRoles,
+ String loginId) throws InvalidUserException {
+ HashMap<String, String> userParams = new HashMap<>();
+ userParams.put("orgUserId", loginId);
+ // Get all centralized applications existing user roles from local
+ List<CentralizedAppRoles> currentUserAppRoles = dataAccessService
+ .executeNamedQuery("getUserCentralizedAppRoles", userParams, null);
+ EPUser user = getUser(loginId).get(0);
+ // Get all centralized applications roles from local
+ HashMap<String, CentralizedAppRoles> cenAppRolesMap = getCentralizedAppRoleList();
+ HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap = getCurrentUserCentralizedAppRoles(
+ currentUserAppRoles);
+ // Get all centralized applications + admin role from local
+ HashMap<String, EPApp> centralisedAppsMap = getCentralizedAdminAppsInfo();
+ if (extRoles != null) {
+ ExternalAccessUserRoleDetail userRoleDetail = null;
+ for (int i = 0; i < extRoles.length(); i++) {
+ if (!extRoles.getJSONObject(i).getString("name").endsWith(ADMIN)
+ && !extRoles.getJSONObject(i).getString("name").endsWith(OWNER)) {
+ userRoleDetail = new ExternalAccessUserRoleDetail(extRoles.getJSONObject(i).getString("name"),
+ null);
+ userRoleDetailList.add(userRoleDetail);
+ }
+ }
+ addUserRolesInLocal(userRoleDetailList, user, cenAppRolesMap, currentCentralizedUserAppRolesMap,
+ centralisedAppsMap);
+ }
+ }
+
+ private void addUserRolesInLocal(List<ExternalAccessUserRoleDetail> userRoleDetailList, EPUser user,
+ HashMap<String, CentralizedAppRoles> cenAppRolesMap,
+ HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap,
+ HashMap<String, EPApp> centralisedAppsMap) {
+ for (ExternalAccessUserRoleDetail extUserRoleDetail : userRoleDetailList) {
+ try {
+ // check if user already has role in local
+ if (!currentCentralizedUserAppRolesMap.containsKey(extUserRoleDetail.getName())) {
+ CentralizedAppRoles getCenAppRole = cenAppRolesMap.get(extUserRoleDetail.getName());
+ if (getCenAppRole != null) {
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "addUserRolesInLocal: Adding user role from external auth system {}",
+ extUserRoleDetail.toString());
+ EPUserApp userApp = new EPUserApp();
+ EPApp app = new EPApp();
+ app.setId(getCenAppRole.getAppId());
+ EPRole epRole = new EPRole();
+ epRole.setId(getCenAppRole.getRoleId());
+ userApp.setApp(app);
+ userApp.setUserId(user.getId());
+ userApp.setRole(epRole);
+ dataAccessService.saveDomainObject(userApp, null);
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "addUserRolesInLocal: Finished user role from external auth system {}",
+ extUserRoleDetail.toString());
+ } else if (getCenAppRole == null // check if user has app
+ // account admin role
+ && extUserRoleDetail.getName().endsWith(PortalConstants.ADMIN_ROLE.replaceAll(
+ EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
+ EPApp app = centralisedAppsMap.get(extUserRoleDetail.getName());
+ if (app != null) {
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "addUserRolesInLocal: Adding user role from external auth system {}",
+ extUserRoleDetail.toString());
+ EPUserApp userApp = new EPUserApp();
+ EPRole epRole = new EPRole();
+ epRole.setId(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
+ userApp.setApp(app);
+ userApp.setUserId(user.getId());
+ userApp.setRole(epRole);
+ dataAccessService.saveDomainObject(userApp, null);
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "addUserRolesInLocal: Finished user role from external auth system {}",
+ extUserRoleDetail.toString());
+ }
+ }
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "addUserRolesInLocal - Failed to update user role in local from external auth system {} ",
+ extUserRoleDetail.toString(), e);
+ }
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private HashMap<String, EPApp> getCentralizedAdminAppsInfo() {
+ List<EPApp> centralizedApps = dataAccessService.executeNamedQuery("getCentralizedApps", null, null);
+ HashMap<String, EPApp> centralisedAppsMap = new HashMap<>();
+ for (EPApp cenApp : centralizedApps) {
+ centralisedAppsMap.put(
+ cenApp.getNameSpace() + "."
+ + PortalConstants.ADMIN_ROLE.replaceAll(
+ EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
+ cenApp);
+ }
+ return centralisedAppsMap;
+ }
+
+ private HashMap<String, CentralizedAppRoles> getCurrentUserCentralizedAppRoles(
+ List<CentralizedAppRoles> currentUserAppRoles) {
+ HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap = new HashMap<>();
+ for (CentralizedAppRoles cenAppUserRole : currentUserAppRoles) {
+ currentCentralizedUserAppRolesMap.put(
+ cenAppUserRole.getAppNameSpace() + "."
+ + cenAppUserRole.getRoleName().replaceAll(
+ EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
+ cenAppUserRole);
+ }
+ return currentCentralizedUserAppRolesMap;
+ }
+
+ @SuppressWarnings("unchecked")
+ private HashMap<String, CentralizedAppRoles> getCentralizedAppRoleList() {
+ List<CentralizedAppRoles> centralizedAppRoles = dataAccessService
+ .executeNamedQuery("getAllCentralizedAppsRoles", null, null);
+ HashMap<String, CentralizedAppRoles> cenAppRolesMap = new HashMap<>();
+ for (CentralizedAppRoles CentralizedAppRole : centralizedAppRoles) {
+ cenAppRolesMap.put(
+ CentralizedAppRole.getAppNameSpace() + "."
+ + CentralizedAppRole.getRoleName().replaceAll(
+ EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
+ CentralizedAppRole);
+ }
+ return cenAppRolesMap;
+ }
+
+ @Override
+ public ResponseEntity<String> getUserRolesFromExtAuthSystem(String name, HttpEntity<String> getUserRolesEntity) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles");
+ ResponseEntity<String> getResponse = template
+ .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
+ + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class);
+ if (getResponse.getStatusCode().value() == 200) {
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "getAllUserRoleFromExtAuthSystem: Finished GET user roles from external system and received user roles {}",
+ getResponse.getBody());
+ } else {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "getAllUserRoleFromExtAuthSystem: Failed GET user roles from external system and received user roles {}",
+ getResponse.getBody());
+ EPLogUtil.logExternalAuthAccessAlarm(logger, getResponse.getStatusCode());
+ }
+ return getResponse;
+ }
+
+ @Override
+ public Integer updateAppRoleDescription(String uebkey) {
+ Integer roleDescUpdated = 0;
+ EPApp app;
+ try {
+ app = getApp(uebkey).get(0);
+ List<EPRole> roles = getAppRoles(app.getId());
+ for (EPRole epRole : roles) {
+ Role role = new Role();
+ role.setName(epRole.getName());
+ boolean status = addRoleDescriptionInExtSystem(role, app);
+ if (status)
+ roleDescUpdated++;
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "updateAppRoleDescription: Failed! ", e);
+ }
+ return roleDescUpdated;
+ }
+
}
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java
index aaaf91bd..1904d8e2 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java
@@ -114,6 +114,7 @@ import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
+import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.core.JsonProcessingException;
@@ -176,10 +177,10 @@ public class UserRolesCommonServiceImpl {
*
* @param userId
*/
- protected boolean createLocalUserIfNecessary(String userId) {
+ protected void createLocalUserIfNecessary(String userId,boolean isSystemUser) {
if (StringUtils.isEmpty(userId)) {
logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty userId!");
- return false;
+ return;
}
Session localSession = null;
Transaction transaction = null;
@@ -193,7 +194,15 @@ public class UserRolesCommonServiceImpl {
.setParameter("userId",userId)
.list();
if (userList.size() == 0) {
- EPUser client = searchService.searchUserByUserId(userId);
+ EPUser client = null;
+ if (!isSystemUser) {
+ client = searchService.searchUserByUserId(userId);
+ } else {
+ client = new EPUser();
+ client.setOrgUserId(userId);
+ client.setSystemUser(true);
+ client.setFirstName(userId.substring(0,userId.indexOf("@")));
+ }
if (client == null) {
String msg = "createLocalUserIfNecessary: cannot create user " + userId
+ ", because not found in phonebook";
@@ -205,11 +214,9 @@ public class UserRolesCommonServiceImpl {
}
}
transaction.commit();
- return true;
} catch (Exception e) {
EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
EcompPortalUtils.rollbackTransaction(transaction, "searchOrCreateUser rollback, exception = " + e);
- return false;
} finally {
EcompPortalUtils.closeLocalSession(localSession, "searchOrCreateUser");
}
@@ -630,6 +637,7 @@ public class UserRolesCommonServiceImpl {
result = new RolesInAppForUser();
result.appId = appId;
result.orgUserId = userId;
+
for (EcompRole role : userRolesInRemoteApp) {
RoleInAppForUser roleInAppForUser = new RoleInAppForUser();
roleInAppForUser.roleId = role.getId();
@@ -667,7 +675,7 @@ public class UserRolesCommonServiceImpl {
* @throws HTTPException
*/
protected Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
- ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
+ ApplicationsRestClientService applicationsRestClientService, Long appId, String userId,boolean systemUser)
throws JsonProcessingException, HTTPException {
Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList);
Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList);
@@ -744,13 +752,13 @@ public class UserRolesCommonServiceImpl {
* set to false if requests from Users page otherwise true
* @return true on success, false otherwise
*/
- protected boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser, boolean externalSystemRequest, String reqType) throws Exception {
+ protected boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser, boolean externalSystemRequest, String reqType,boolean isSystemUser) throws Exception {
boolean result = false;
String userId = rolesInAppForUser.orgUserId;
Long appId = rolesInAppForUser.appId;
synchronized (syncRests) {
if (rolesInAppForUser != null) {
- createLocalUserIfNecessary(userId);
+ createLocalUserIfNecessary(userId, isSystemUser);
}
if (rolesInAppForUser != null) {
@@ -857,22 +865,42 @@ public class UserRolesCommonServiceImpl {
return addRemoteUser;
}
+ @SuppressWarnings("unchecked")
protected void pushUserOnRemoteApp(String userId, EPApp app,
ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
ObjectMapper mapper, boolean postOpenSource, List<RoleInAppForUser> roleInAppForUserList,boolean appRoleIdUsed) throws Exception {
- EPUser client = searchService.searchUserByUserId(userId);
+ EPUser client = null;
+ client = searchService.searchUserByUserId(userId);
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
-
- if (client == null) {
- String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook.";
- logger.error(EELFLoggerDelegate.errorLogger, msg);
- throw new Exception(msg);
- }
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ if (client == null) {
+ String msg = "cannot create user " + userId + ", because he/she cannot be found in directory.";
+ logger.error(EELFLoggerDelegate.errorLogger, msg);
+ // throw new Exception(msg);
+ final Map<String, String> loginIdParams = new HashMap<>();
+ loginIdParams.put("orgUserIdValue", userId);
+ List<EPUser> userList = new ArrayList<>();
+ userList = dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null);
+ if (userList.size() > 0) {
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ userList.get(0).getOrgUserId() + " User was found in Portal");
+ client = userList.get(0);
+ SortedSet<EPUserApp> userApps = new TreeSet<>();
+ client.setEPUserApps(userApps);
+ client.setSystemUser(false);
+ } else {
+ logger.error(EELFLoggerDelegate.errorLogger, "user cannot be found be in directory or in portal");
+ throw new Exception(msg);
+ }
+ }
+
client.setLoginId(userId);
- client.setActive(true);
+ client.setActive(true);
+ client.setOrgUserId(userId);
+
+
roleInAppForUserList.removeIf(role -> role.isApplied.equals(false));
SortedSet<Role> roles = new TreeSet<>();
@@ -978,7 +1006,7 @@ public class UserRolesCommonServiceImpl {
}
Long appId = newAppRolesForUser.appId;
List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.appRoles;
- if (userId.length() > 0) {
+ if (userId.length() > 0 ) {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
@@ -986,7 +1014,27 @@ public class UserRolesCommonServiceImpl {
EPApp app = appsService.getApp(appId);
applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
- // if centralized app
+ boolean systemUser = newAppRolesForUser.isSystemUser;
+ if ((app.getCentralAuth() || app.getId().equals(PortalConstants.PORTAL_APP_ID)) && systemUser) {
+
+ Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
+ applicationsRestClientService, appId, userId);
+ RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
+ userRolesInLocalApp);
+ List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
+ if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
+ // Apply changes in external Access system
+ updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList,
+ epRequestValue, systemUser);
+ }
+ result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal",
+ systemUser);
+
+ }else if (!app.getCentralAuth() && systemUser)
+ {
+ throw new Exception("For non-centralized application we cannot add systemUser");
+ }
+ else{ // if centralized app
if (app.getCentralAuth()) {
if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
pushRemoteUser(roleInAppForUserList, userId, app, mapper, searchService,
@@ -1001,9 +1049,9 @@ public class UserRolesCommonServiceImpl {
if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
// Apply changes in external Access system
updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList,
- epRequestValue);
+ epRequestValue,false);
}
- result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal");
+ result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal", systemUser);
}
// In case if portal is not centralized then follow existing approach
else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
@@ -1011,7 +1059,7 @@ public class UserRolesCommonServiceImpl {
applicationsRestClientService, appId, userId);
RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
userRolesInLocalApp);
- result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal");
+ result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal",false);
} else{// remote app
EPUser remoteAppUser = null;
if(!app.getCentralAuth() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)){
@@ -1022,10 +1070,10 @@ public class UserRolesCommonServiceImpl {
remoteAppUser = addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService, applicationsRestClientService);
}
Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
- applicationsRestClientService, appId, userId);
+ applicationsRestClientService, appId, userId,systemUser);
RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
userRolesInRemoteApp);
- result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null);
+ result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null,false);
// If no roles remain, request app to set user inactive.
if (userRolesInRemoteApp.size() == 0) {
@@ -1037,6 +1085,7 @@ public class UserRolesCommonServiceImpl {
}
}
}
+ }
} catch (Exception e) {
/*String message = String.format(
"Failed to create user or update user roles for User %s, AppId %s",
@@ -1067,7 +1116,7 @@ public class UserRolesCommonServiceImpl {
* @param roleInAppUser Contains list of active roles
*/
@SuppressWarnings("unchecked")
- private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser, boolean isPortalRequest) throws Exception
+ private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser, boolean isPortalRequest,boolean isSystemUser) throws Exception
{
try {
// check if user exists
@@ -1075,13 +1124,15 @@ public class UserRolesCommonServiceImpl {
userParams.put("orgUserIdValue", orgUserId);
List<EPUser> userInfo = checkIfUserExists(userParams);
if (userInfo.isEmpty()) {
- createLocalUserIfNecessary(orgUserId);
+ createLocalUserIfNecessary(orgUserId, isSystemUser);
}
String name = "";
if (EPCommonSystemProperties
- .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
+ .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN) && !isSystemUser) {
name = orgUserId
+ SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
+ } else {
+ name = orgUserId;
}
ObjectMapper mapper = new ObjectMapper();
HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
@@ -1173,7 +1224,7 @@ public class UserRolesCommonServiceImpl {
for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) {
if (!(currentUserRolesInExternalSystem
.containsKey(app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")))) {
- ExternalAccessUser extUser = new ExternalAccessUser(name,
+ ExternalAccessUser extUser = new ExternalAccessUser(name,
app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
String formattedUserRole = mapper.writeValueAsString(extUser);
HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers);
@@ -1193,7 +1244,23 @@ public class UserRolesCommonServiceImpl {
}
}
}
- } catch (Exception e) {
+ } catch (HttpClientErrorException e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}",
+ app.getId(), e);
+ if (e.getStatusCode() == HttpStatus.FORBIDDEN) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid systemUser", orgUserId);
+ throw new HttpClientErrorException(HttpStatus.FORBIDDEN, "Please enter the valid systemUser");
+ }
+ if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid role");
+ throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "Please enter the valid role");
+ }
+ EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
+ throw e;
+ }
+
+ catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}", app.getId(), e);
EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
throw e;
@@ -1489,11 +1556,11 @@ public class UserRolesCommonServiceImpl {
List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
// Apply changes in external Access system
- updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, externalSystemRequest);
+ updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, externalSystemRequest,false);
}
logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
- result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType);
+ result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,false);
}
// If local application is not centralized
else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
@@ -1501,7 +1568,7 @@ public class UserRolesCommonServiceImpl {
applicationsRestClientService, app.getId(), orgUserId);
RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
userRolesInLocalApp);
- result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType);
+ result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,false);
} else {// remote app
// If adding just account admin role don't do remote application user call
if (!((roleInAppForUserList.size() == 1 || reqType.equals("DELETE")) && checkIfAdminRoleExists)) {
@@ -1514,7 +1581,7 @@ public class UserRolesCommonServiceImpl {
}
Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
- applicationsRestClientService, app.getId(), orgUserId);
+ applicationsRestClientService, app.getId(), orgUserId,false);
RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
userRolesInRemoteApp);
@@ -1522,7 +1589,7 @@ public class UserRolesCommonServiceImpl {
"setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
- reqType);
+ reqType,false);
// If no roles remain, request app to set user inactive.
/*
* if (userRolesInRemoteApp.size() == 0) {
@@ -1545,7 +1612,7 @@ public class UserRolesCommonServiceImpl {
logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}",
logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
- reqType);
+ reqType,false);
}
if(!result){
reqMessage = "Failed to save the user app role(s)";
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/AppWithRolesForUser.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/AppWithRolesForUser.java
index 60bc7fce..e2336dbd 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/AppWithRolesForUser.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/AppWithRolesForUser.java
@@ -42,6 +42,8 @@ import java.util.List;
public class AppWithRolesForUser {
public String orgUserId;
+
+ public boolean isSystemUser;
public Long appId;
@@ -81,10 +83,20 @@ public class AppWithRolesForUser {
this.appRoles = appRoles;
}
+
+
+ public boolean isSystemUser() {
+ return isSystemUser;
+ }
+
+ public void setSystemUser(boolean isSystemUser) {
+ this.isSystemUser = isSystemUser;
+ }
+
@Override
public String toString() {
- return "AppWithRolesForUser [orgUserId=" + orgUserId + ", appId=" + appId + ", appName=" + appName
- + ", appRoles=" + appRoles + "]";
+ return "AppWithRolesForUser [orgUserId=" + orgUserId + ", isSystemUser=" + isSystemUser + ", appId=" + appId
+ + ", appName=" + appName + ", appRoles=" + appRoles + "]";
}
}
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EcompPortalUtils.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EcompPortalUtils.java
index 1b5613ca..30eeac04 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EcompPortalUtils.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EcompPortalUtils.java
@@ -47,10 +47,12 @@ import java.util.Arrays;
import java.util.Base64;
import java.util.Date;
import java.util.List;
+import java.util.regex.Pattern;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.DatatypeConverter;
+import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Session;
import org.hibernate.Transaction;
@@ -70,19 +72,21 @@ import com.fasterxml.jackson.databind.ObjectMapper;
public class EcompPortalUtils {
private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EcompPortalUtils.class);
-
+
private static final String FUNCTION_PIPE = "|";
-
+
// TODO: GLOBAL_LOGIN_URL is the same as in SessionTimeoutInterceptor.
// It should be defined in SystemProperties.
private static final String GLOBAL_LOGIN_URL = "global-login-url";
-
- // It is a regular expression used for while creating a External Central Auth Role
+
+ // It is a regular expression used for while creating a External Central Auth
+ // Role
public static final String EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS = "([^A-Z^a-z^0-9^\\.^%^(^)^=^:])";
-
+
+ public static final String slash = "/";
+
/**
- * @param orgUserId
- * User ID to validate
+ * @param orgUserId User ID to validate
* @return true if orgUserId is not empty and contains only alphanumeric, false
* otherwise
*/
@@ -94,10 +98,8 @@ public class EcompPortalUtils {
* Splits the string into a list of tokens using the specified regular
* expression
*
- * @param source
- * String to split
- * @param regex
- * tokens
+ * @param source String to split
+ * @param regex tokens
* @return List of tokens split from the source
*/
public static List<String> parsingByRegularExpression(String source, String regex) {
@@ -116,10 +118,8 @@ public class EcompPortalUtils {
/**
* Builds a JSON object with error code and message information.
*
- * @param errorCode
- * error code
- * @param errorMessage
- * message
+ * @param errorCode error code
+ * @param errorMessage message
* @return JSON object as a String
*/
public static String jsonErrorMessageResponse(int errorCode, String errorMessage) {
@@ -129,8 +129,7 @@ public class EcompPortalUtils {
/**
* Builds a JSON object with the specified message
*
- * @param message
- * Message to embed
+ * @param message Message to embed
* @return JSON object as a String
*/
public static String jsonMessageResponse(String message) {
@@ -141,15 +140,11 @@ public class EcompPortalUtils {
* Serializes the specified object as JSON and writes the result to the debug
* log. If serialization fails, logs a message to the error logger.
*
- * @param logger
- * Logger for the class where the object was built; the logger
- * carries the class name.
- * @param source
- * First portion of the log message
- * @param msg
- * Second portion of the log message
- * @param obj
- * Object to serialize as JSON
+ * @param logger Logger for the class where the object was built; the logger
+ * carries the class name.
+ * @param source First portion of the log message
+ * @param msg Second portion of the log message
+ * @param obj Object to serialize as JSON
*/
public static void logAndSerializeObject(EELFLoggerDelegate logger, String source, String msg, Object obj) {
try {
@@ -169,12 +164,9 @@ public class EcompPortalUtils {
* Serializes the specified object as JSON and writes the result to the debug
* log. If serialization fails, logs a message to the error logger.
*
- * @param source
- * First portion of the log message
- * @param msg
- * Second portion of the log message
- * @param obj
- * Object to serialize as JSON
+ * @param source First portion of the log message
+ * @param msg Second portion of the log message
+ * @param obj Object to serialize as JSON
*/
public static void logAndSerializeObject(String source, String msg, Object obj) {
logAndSerializeObject(logger, source, msg, obj);
@@ -209,12 +201,9 @@ public class EcompPortalUtils {
* Set response status to Unauthorized if user == null and to Forbidden in all
* (!) other cases. Logging is not performed if invocator == null
*
- * @param user
- * User object
- * @param response
- * HttpServletResponse
- * @param invocator
- * may be null
+ * @param user User object
+ * @param response HttpServletResponse
+ * @param invocator may be null
*/
public static void setBadPermissions(EPUser user, HttpServletResponse response, String invocator) {
if (user == null) {
@@ -248,13 +237,15 @@ public class EcompPortalUtils {
// This method might be just for testing purposes.
public static void setExternalAppResponseCode(int responseCode) {
try {
- /*String code = String.valueOf(responseCode);
- MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE,code );
- code=StringUtils.EMPTY;*/
+ /*
+ * String code = String.valueOf(responseCode);
+ * MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE,code );
+ * code=StringUtils.EMPTY;
+ */
String code = Integer.toString(responseCode);
- MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE,code );
- char[] chars=code.toCharArray();
- Arrays.fill(chars, ' ');
+ MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE, code);
+ char[] chars = code.toCharArray();
+ Arrays.fill(chars, ' ');
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "setExternalAppResponseCode failed", e);
}
@@ -337,10 +328,8 @@ public class EcompPortalUtils {
/**
* Returns a default property if the expected one is not available
*
- * @param property
- * Key
- * @param defaultValue
- * default Value
+ * @param property Key
+ * @param defaultValue default Value
* @return Default value if property is not defined or yields the empty string;
* else the property value.
*/
@@ -360,10 +349,8 @@ public class EcompPortalUtils {
* "MDC.remove(SystemProperties.MDC_TIMER);" after this method call to clean up
* the record in MDC
*
- * @param beginDateTime
- * the given begin time for the call
- * @param endDateTime
- * the given end time for the call
+ * @param beginDateTime the given begin time for the call
+ * @param endDateTime the given end time for the call
*
*/
public static void calculateDateTimeDifferenceForLog(String beginDateTime, String endDateTime) {
@@ -405,8 +392,7 @@ public class EcompPortalUtils {
*
* @return header which contains external central auth username and password
* base64 encoded
- * @throws Exception
- * if unable to decrypt the password
+ * @throws Exception if unable to decrypt the password
*/
public static HttpHeaders base64encodeKeyForAAFBasicAuth() throws Exception {
String userName = "";
@@ -429,7 +415,8 @@ public class EcompPortalUtils {
String result = "";
if (encrypted != null && encrypted.length() > 0) {
try {
- result = CipherUtil.decryptPKC(encrypted, SystemProperties.getProperty(SystemProperties.Decryption_Key));
+ result = CipherUtil.decryptPKC(encrypted,
+ SystemProperties.getProperty(SystemProperties.Decryption_Key));
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
throw e;
@@ -438,8 +425,8 @@ public class EcompPortalUtils {
return result;
}
- public static String truncateString(String originString, int size){
- if(originString.length()>=size){
+ public static String truncateString(String originString, int size) {
+ if (originString.length() >= size) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(originString);
stringBuilder.setLength(size);
@@ -448,11 +435,10 @@ public class EcompPortalUtils {
}
return originString;
}
-
+
/**
*
- * If function code value has any pipes it does pipe filter and
- * returns value.
+ * If function code value has any pipes it does pipe filter and returns value.
*
* @param functionCode
* @return function instance without pipe
@@ -462,22 +448,19 @@ public class EcompPortalUtils {
if (functionCode.contains(FUNCTION_PIPE)) {
int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
if (count == 2)
- finalFunctionCodeVal = functionCode.substring(
- functionCode.indexOf(FUNCTION_PIPE) + 1,
+ finalFunctionCodeVal = functionCode.substring(functionCode.indexOf(FUNCTION_PIPE) + 1,
functionCode.lastIndexOf(FUNCTION_PIPE));
else
- finalFunctionCodeVal = functionCode
- .substring(functionCode.lastIndexOf(FUNCTION_PIPE) + 1);
- } else{
+ finalFunctionCodeVal = functionCode.substring(functionCode.lastIndexOf(FUNCTION_PIPE) + 1);
+ } else {
finalFunctionCodeVal = functionCode;
}
return finalFunctionCodeVal;
}
-
+
/**
*
- * If function code value has any pipes it does pipe filter and
- * returns value.
+ * If function code value has any pipes it does pipe filter and returns value.
*
* @param functionCode
* @return function Type without pipe
@@ -486,20 +469,19 @@ public class EcompPortalUtils {
String finalFunctionCodeVal = "";
if (functionCode.contains(FUNCTION_PIPE)) {
int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
- if (count == 2){
- String[] getTypeValue = functionCode.split("\\"+FUNCTION_PIPE);
+ if (count == 2) {
+ String[] getTypeValue = functionCode.split("\\" + FUNCTION_PIPE);
finalFunctionCodeVal = getTypeValue[0];
}
- } else{
+ } else {
finalFunctionCodeVal = functionCode;
}
return finalFunctionCodeVal;
}
-
+
/**
*
- * If function code value has any pipes it does pipe filter and
- * returns value.
+ * If function code value has any pipes it does pipe filter and returns value.
*
* @param functionCode
* @return function Action without pipe
@@ -509,17 +491,17 @@ public class EcompPortalUtils {
if (functionCode.contains(FUNCTION_PIPE)) {
int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
if (count == 2)
- finalFunctionCodeVal = functionCode.substring(
- functionCode.lastIndexOf(FUNCTION_PIPE)+1);
- } else{
+ finalFunctionCodeVal = functionCode.substring(functionCode.lastIndexOf(FUNCTION_PIPE) + 1);
+ } else {
finalFunctionCodeVal = functionCode;
}
return finalFunctionCodeVal;
}
-
+
/**
*
- * It check whether the external auth namespace is matching with current namespace exists in local DB
+ * It check whether the external auth namespace is matching with current
+ * namespace exists in local DB
*
* @param permTypeVal
* @param appNamespaceVal
@@ -539,20 +521,22 @@ public class EcompPortalUtils {
}
return isNamespaceMatching;
}
-
+
public static boolean checkIfRemoteCentralAccessAllowed() {
boolean result = false;
- String rmtCentralAccess = SystemProperties.getProperty(EPCommonSystemProperties.REMOTE_CENTRALISED_SYSTEM_ACCESS);
- if(rmtCentralAccess == null) {
- logger.error(EELFLoggerDelegate.errorLogger, "Please check in system.properties whether the property exists or not!");
+ String rmtCentralAccess = SystemProperties
+ .getProperty(EPCommonSystemProperties.REMOTE_CENTRALISED_SYSTEM_ACCESS);
+ if (rmtCentralAccess == null) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "Please check in system.properties whether the property exists or not!");
return false;
- }else if(new Boolean(rmtCentralAccess)){
- logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRemoteCentralAccessAllowed: {}",rmtCentralAccess);
+ } else if (new Boolean(rmtCentralAccess)) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRemoteCentralAccessAllowed: {}", rmtCentralAccess);
result = true;
}
return result;
}
-
+
/**
*
* It validates whether given string is JSON or not
@@ -560,28 +544,48 @@ public class EcompPortalUtils {
* @param jsonInString
* @return true or false
*/
- public static boolean isJSONValid(String jsonInString ) {
- try {
- final ObjectMapper mapper = new ObjectMapper();
- mapper.readTree(jsonInString);
- return true;
- } catch (IOException e) {
- logger.error(EELFLoggerDelegate.errorLogger, "Failed to parse Json!", e);
- return false;
- }
- }
- /**
- *
- * It retrieves account information from input String
- *
- * @param authValue
- * @return Array of Account information
- *
- */
- public static String[] getUserNamePassword(String authValue) {
- String base64Credentials = authValue.substring("Basic".length()).trim();
- String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8"));
- final String[] values = credentials.split(":", 2);
- return values;
+ public static boolean isJSONValid(String jsonInString) {
+ try {
+ final ObjectMapper mapper = new ObjectMapper();
+ mapper.readTree(jsonInString);
+ return true;
+ } catch (IOException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Failed to parse Json!", e);
+ return false;
}
+ }
+
+ /**
+ *
+ * It retrieves account information from input String
+ *
+ * @param authValue
+ * @return Array of Account information
+ *
+ */
+ public static String[] getUserNamePassword(String authValue) {
+ String base64Credentials = authValue.substring("Basic".length()).trim();
+ String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8"));
+ final String[] values = credentials.split(":", 2);
+ return values;
+ }
+
+ /**
+ * It encodes the function code based on Hex encoding
+ *
+ * @param funCode
+ *
+ */
+ public static String encodeFunctionCode(String funCode) {
+ String encodedString = funCode;
+ Pattern encodePattern = Pattern.compile(EcompPortalUtils.slash);
+ return encodedString = encodePattern.matcher(encodedString)
+ .replaceAll("%" + Hex.encodeHexString(encodePattern.toString().getBytes()))
+ .replaceAll("\\*", "%" + Hex.encodeHexString("*".getBytes()));
+ }
+
+ public static boolean checkFunctionCodeHasEncodePattern(String code) {
+ return code.contains(EcompPortalUtils.slash);
+ }
+
}
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/util/EPUserUtils.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/util/EPUserUtils.java
index 51f48b16..99a29116 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/util/EPUserUtils.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/util/EPUserUtils.java
@@ -45,7 +45,9 @@ import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.UUID;
+import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import java.util.stream.Collectors;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
@@ -398,4 +400,40 @@ public class EPUserUtils {
return "";
}
+ public static Boolean matchRoleFunctions(String portalApiPath, Set<? extends String> roleFunctions) {
+ String[] path = portalApiPath.split("/");
+ List<String> roleFunList = new ArrayList<>();
+ if (path.length > 1) {
+ roleFunList = roleFunctions.stream().filter(item -> item.startsWith(path[0])).collect(Collectors.toList());
+ if (roleFunList.size() >= 1) {
+ for (String roleFunction : roleFunList) {
+ String[] roleFunctionArray = roleFunction.split("/");
+ boolean b = true;
+ if (roleFunctionArray.length == path.length) {
+ for (int i = 0; i < roleFunctionArray.length; i++) {
+ if (b) {
+ if (!roleFunctionArray[i].equals("*")) {
+ Pattern p = Pattern.compile(Pattern.quote(path[i]), Pattern.CASE_INSENSITIVE);
+ Matcher m = p.matcher(roleFunctionArray[i]);
+ b = m.matches();
+
+ }
+ }
+ }
+ if (b)
+ return b;
+ }
+ }
+ }
+ } else {
+ for (String roleFunction : roleFunctions) {
+ if (roleFunction.equals(("*"))) {
+ return true;
+ } else if (portalApiPath.matches(roleFunction)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
}
diff --git a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml
index e38b398e..e03c9762 100644
--- a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml
+++ b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml
@@ -229,6 +229,7 @@
<property name="createdId" column="created_id" />
<property name="modifiedId" column="modified_id" />
<property name="timeZoneId" column="timezone" />
+ <property name="systemUser" column="is_system_user" type="yes_no"/>
<property name="languageId" column="language_id" />
<set name="EPUserApps" table="FN_USER_ROLE" lazy="false" sort="natural"
@@ -1160,7 +1161,7 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' and fn_role.active_y
<sql-query name="getAppsAdmins">
<return alias="adminUserApp" class="org.onap.portalapp.portal.domain.AdminUserApp" />
<![CDATA[
- SELECT apps.APP_NAME, apps.APP_ID, user.USER_ID, user.FIRST_NAME, user.LAST_NAME, user.org_user_id FROM fn_user_role userrole INNER JOIN fn_user user ON user.USER_ID = userrole.USER_ID INNER JOIN fn_app apps ON apps.APP_ID = userrole.APP_ID WHERE user.active_yn='Y' AND userrole.ROLE_ID = :accountAdminRoleId AND (apps.ENABLED = 'Y' OR apps.APP_ID=1)
+ SELECT apps.APP_NAME, apps.APP_ID, user.USER_ID, user.FIRST_NAME, user.LAST_NAME, user.org_user_id FROM fn_user_role userrole INNER JOIN fn_user user ON user.USER_ID = userrole.USER_ID INNER JOIN fn_app apps ON apps.APP_ID = userrole.APP_ID WHERE user.active_yn='Y' AND userrole.ROLE_ID = :accountAdminRoleId
]]>
</sql-query>
@@ -2549,6 +2550,32 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' and fn_role.active_y
]]>
</sql-query>
+ <sql-query name="getAllAdminAppsofTheUser">
+ <![CDATA[
+ select fa.app_id from fn_user_role ur,fn_app fa where ur.user_id =:userId and ur.app_id=fa.app_id and ur.role_id= 999
+
+ ]]>
+ </sql-query>
+ <sql-query name="getAllAppsFunctionsOfUser">
+ <![CDATA[
+ select distinct ep.function_cd from fn_user_role fu, ep_app_role_function ep, ep_app_function ea, fn_app fa , fn_role fr
+ where fu.role_id = ep.role_id
+ and fu.app_id = ep.app_id
+ and fu.user_id =:userId
+ and ea.function_cd = ep.function_cd
+ and ((fu.app_id = fa.app_id and fa.enabled = 'Y' ) or (fa.app_id = 1))
+ and fr.role_id = fu.role_id and fr.active_yn='Y'
+ union
+ select distinct app_r_f.function_cd from ep_app_role_function app_r_f, ep_app_function a_f
+ where role_id = 999
+ and app_r_f.function_cd = a_f.function_cd
+ and exists
+ (
+ select fa.app_id from fn_user fu, fn_user_role ur, fn_app fa where fu.user_id =:userId and fu.user_id = ur.user_id
+ and ur.role_id = 999 and ur.app_id = fa.app_id and fa.enabled = 'Y'
+ );
+ ]]>
+ </sql-query>
<sql-query name="updateFnUser">
<![CDATA[
UPDATE fn_user fu SET fu.language_id=:language_id WHERE fu.login_id=:login_id
diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppsControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppsControllerTest.java
index 59b5a8ed..4df1c2ac 100644
--- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppsControllerTest.java
+++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppsControllerTest.java
@@ -1,5 +1,5 @@
/*-
- * ============LICENSE_START==========================================
+ * ============LICENSE_START==========================================
* ONAP Portal
* ===================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
@@ -90,7 +90,10 @@ import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.client.HttpClientErrorException;
@RunWith(PowerMockRunner.class)
@PrepareForTest({SystemProperties.class,AppUtils.class, EPUserUtils.class, MediaType.class})
@@ -548,7 +551,7 @@ public class AppsControllerTest extends MockitoTestSuite{
List<AppsResponse> atualApps = new ArrayList<AppsResponse>();
Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true);
- Mockito.when(appService.getAllApps(false)).thenReturn(expectedApps);
+ Mockito.when(appService.getAllApplications(false)).thenReturn(expectedApps);
atualApps = appsController.getApps(mockedRequest, mockedResponse);
assertEquals(expectedApps, atualApps);
}
@@ -566,7 +569,7 @@ public class AppsControllerTest extends MockitoTestSuite{
EPUser user = mockUser.mockEPUser();
Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user);
Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true);
- Mockito.when(appService.getAllApps(false)).thenThrow(nullPointerException);
+ Mockito.when(appService.getAllApplications(false)).thenThrow(nullPointerException);
assertNull(appsController.getApps(mockedRequest, mockedResponse));
}
@@ -725,24 +728,110 @@ public class AppsControllerTest extends MockitoTestSuite{
}
@Test
- public void putOnboardingAppTest() {
+ public void putOnboardingAppTest() throws Exception {
EPUser user = mockUser.mockEPUser();
Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user);
OnboardingApp OnboardingApp = new OnboardingApp();
+ OnboardingApp.isCentralAuth = true;
+ OnboardingApp.nameSpace = "test1";
FieldsValidator expectedFieldValidator = new FieldsValidator();
expectedFieldValidator.setHttpStatusCode((long) 200);
expectedFieldValidator.setFields(null);
expectedFieldValidator.setErrorCode(null);
+ EPApp OnboardingApp1 = new EPApp();
+ OnboardingApp1.setCentralAuth(false);
+ OnboardingApp1.setNameSpace("test");
+ Mockito.when(appService.getApp(Matchers.anyLong())).thenReturn(OnboardingApp1);
Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true);
+ ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK);
+ Mockito.when(appService.checkIfNameSpaceIsValid(Matchers.anyString())).thenReturn(response);
Mockito.when(appService.modifyOnboardingApp(OnboardingApp, user)).thenReturn(expectedFieldValidator);
Mockito.when(mockedResponse.getStatus()).thenReturn(200);
FieldsValidator actualFieldValidator = appsController.putOnboardingApp(mockedRequest, OnboardingApp,
mockedResponse);
assertEquals(expectedFieldValidator, actualFieldValidator);
}
+
+ @Test
+ public void putOnboardingApp2Test() throws Exception {
+ EPUser user = mockUser.mockEPUser();
+ Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user);
+ OnboardingApp onboardingApp = new OnboardingApp();
+ onboardingApp.isCentralAuth = true;
+ onboardingApp.nameSpace = "com.test1";
+ EPApp app = new EPApp();
+ app.setNameSpace("com.test ");
+ FieldsValidator expectedFieldValidator = new FieldsValidator();
+ expectedFieldValidator.setHttpStatusCode((long) 200);
+ expectedFieldValidator.setFields(null);
+ expectedFieldValidator.setErrorCode(null);
+ Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false);
+ Mockito.when(adminRolesService.isAccountAdminOfApplication(Matchers.any(EPUser.class),Matchers.any(EPApp.class))).thenReturn(true);
+ ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK);
+ Mockito.when(appService.checkIfNameSpaceIsValid("com.test1")).thenReturn(response);
+ Mockito.when(appService.getApp(Matchers.anyLong())).thenReturn(app);
+ Mockito.when(mockedResponse.getStatus()).thenReturn(200);
+ Mockito.when(appService.modifyOnboardingApp(Matchers.any(OnboardingApp.class), Matchers.any(EPUser.class))).thenReturn(expectedFieldValidator);
+ FieldsValidator actualFieldValidator = appsController.putOnboardingApp(mockedRequest, onboardingApp,
+ mockedResponse);
+ }
+
+
+
+
+ @Test
+ public void putOnboardingApp4Test() throws Exception {
+ EPUser user = mockUser.mockEPUser();
+ Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user);
+ OnboardingApp onboardingApp = new OnboardingApp();
+ onboardingApp.isCentralAuth = false;
+ onboardingApp.nameSpace = "com.test1";
+ EPApp app = new EPApp();
+ app.setCentralAuth(false);
+ app.setNameSpace("com.test ");
+ FieldsValidator expectedFieldValidator = new FieldsValidator();
+ expectedFieldValidator.setHttpStatusCode((long) 404);
+ Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false);
+ Mockito.when(adminRolesService.isAccountAdminOfAnyActiveorInactiveApplication(Matchers.any(EPUser.class),Matchers.any(EPApp.class))).thenReturn(true);
+ ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK);
+
+ HttpClientErrorException exception = new HttpClientErrorException(HttpStatus.FORBIDDEN);
+ Mockito.when(appService.checkIfNameSpaceIsValid("com.test1")).thenThrow(exception);
+ Mockito.when(appService.getApp(Matchers.anyLong())).thenReturn(app);
+ Mockito.when(mockedResponse.getStatus()).thenReturn(200);
+ Mockito.when(appService.modifyOnboardingApp(Matchers.any(OnboardingApp.class), Matchers.any(EPUser.class))).thenReturn(expectedFieldValidator);
+ FieldsValidator actualFieldValidator = appsController.putOnboardingApp(mockedRequest, onboardingApp,
+ mockedResponse);
+ assertEquals(expectedFieldValidator.getHttpStatusCode(), actualFieldValidator.getHttpStatusCode());
+ }
+
+ @Test
+ public void putOnboardingApp5Test() throws Exception {
+ EPUser user = mockUser.mockEPUser();
+ Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user);
+ OnboardingApp onboardingApp = new OnboardingApp();
+ onboardingApp.isCentralAuth = true;
+ onboardingApp.nameSpace = "com.test1";
+ EPApp app = new EPApp();
+ app.setNameSpace("com.test ");
+ FieldsValidator expectedFieldValidator = new FieldsValidator();
+ expectedFieldValidator.setHttpStatusCode((long) 400);
+ Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false);
+ Mockito.when(adminRolesService.isAccountAdminOfApplication(Matchers.any(EPUser.class),Matchers.any(EPApp.class))).thenReturn(true);
+ ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK);
+
+ HttpClientErrorException exception = new HttpClientErrorException(HttpStatus.BAD_REQUEST);
+ Mockito.when(appService.checkIfNameSpaceIsValid("com.test1")).thenThrow(exception);
+ Mockito.when(appService.getApp(Matchers.anyLong())).thenReturn(app);
+ Mockito.when(mockedResponse.getStatus()).thenReturn(400);
+ Mockito.when(appService.modifyOnboardingApp(Matchers.any(OnboardingApp.class), Matchers.any(EPUser.class))).thenReturn(expectedFieldValidator);
+ FieldsValidator actualFieldValidator = appsController.putOnboardingApp(mockedRequest, onboardingApp,
+ mockedResponse);
+ }
+
@Test
- public void putOnboardingAppIfSuperAdminTest() {
+ public void putOnboardingAppIfSuperAdminTest() throws Exception {
EPUser user = mockUser.mockEPUser();
Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user);
FieldsValidator expectedFieldValidator = null;
@@ -753,7 +842,7 @@ public class AppsControllerTest extends MockitoTestSuite{
}
@Test
- public void putOnboardingAppExceptionTest() {
+ public void putOnboardingAppExceptionTest() throws Exception {
EPUser user = mockUser.mockEPUser();
Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user);
OnboardingApp OnboardingApp = new OnboardingApp();
@@ -763,7 +852,7 @@ public class AppsControllerTest extends MockitoTestSuite{
}
@Test
- public void putOnboardingAppNullUserTest() {
+ public void putOnboardingAppNullUserTest() throws Exception {
Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenThrow(nullPointerException);
Mockito.when(mockedResponse.getStatus()).thenReturn(200);
assertNull(appsController.putOnboardingApp(mockedRequest, new OnboardingApp(), mockedResponse));
diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/SchedulerControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/SchedulerControllerTest.java
index 8216510b..b1816ec6 100644
--- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/SchedulerControllerTest.java
+++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/SchedulerControllerTest.java
@@ -37,12 +37,18 @@
*/
package org.onap.portalapp.portal.controller;
+import static org.junit.Assert.*;
+
+import java.util.HashSet;
+import java.util.Set;
+
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.ss.formula.functions.T;
import org.json.simple.JSONObject;
import org.junit.Before;
+import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
@@ -52,25 +58,30 @@ import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.onap.portalapp.portal.controller.SchedulerController;
import org.onap.portalapp.portal.core.MockEPUser;
+import org.onap.portalapp.portal.domain.EPUser;
import org.onap.portalapp.portal.framework.MockitoTestSuite;
import org.onap.portalapp.portal.scheduler.SchedulerProperties;
import org.onap.portalapp.portal.scheduler.SchedulerRestInterface;
import org.onap.portalapp.portal.scheduler.restobjects.RestObject;
+import org.onap.portalapp.portal.service.AdminRolesService;
+import org.onap.portalapp.util.EPUserUtils;
import org.onap.portalsdk.core.util.SystemProperties;
import org.onap.portalsdk.core.web.support.UserUtils;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
@RunWith(PowerMockRunner.class)
-@PrepareForTest({UserUtils.class,SystemProperties.class,SchedulerProperties.class})
-
+@PrepareForTest({UserUtils.class,SystemProperties.class,SchedulerProperties.class,EPUserUtils.class})
public class SchedulerControllerTest {
@Mock
SchedulerRestInterface schedulerRestInterface;
-
+ @Mock
+ AdminRolesService adminRolesService;
@InjectMocks
SchedulerController schedulerController = new SchedulerController();
@@ -89,6 +100,18 @@ public class SchedulerControllerTest {
@Test
public void getTimeSlotsTest() throws Exception{
+ JSONObject jsonObject =Mockito.mock(JSONObject.class);
+ Mockito.when(jsonObject.get("scheduleId")).thenReturn("12");
+ Set<String> functions = new HashSet<>();
+ functions.add("/get_time_slots/*");
+ Mockito.when(mockedRequest.getRequestURI()).thenReturn("/portalApi/get_time_slots/1");
+ Mockito.when(adminRolesService.getAllAppsFunctionsOfUser(Matchers.anyString())).thenReturn(functions);
+ PowerMockito.mockStatic(SystemProperties.class);
+ PowerMockito.mockStatic(EPUserUtils.class);
+ EPUser user = new EPUser();
+ user.setId((long) 1);
+ Mockito.when(EPUserUtils.matchRoleFunctions(Matchers.anyString(), Matchers.anySet())).thenReturn(true);
+ Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user);
schedulerController.getTimeSlots(mockedRequest, "12");
}
@@ -96,6 +119,17 @@ public class SchedulerControllerTest {
@Test
public void getTimeSlotsTestWithException1() throws Exception{
JSONObject jsonObject =Mockito.mock(JSONObject.class);
+ Mockito.when(jsonObject.get("scheduleId")).thenReturn("12");
+ Set<String> functions = new HashSet<>();
+ functions.add("/get_time_slots/*");
+ Mockito.when(mockedRequest.getRequestURI()).thenReturn("/portalApi/get_time_slots/1");
+ Mockito.when(adminRolesService.getAllAppsFunctionsOfUser(Matchers.anyString())).thenReturn(functions);
+ PowerMockito.mockStatic(SystemProperties.class);
+ PowerMockito.mockStatic(EPUserUtils.class);
+ EPUser user = new EPUser();
+ user.setId((long) 1);
+ Mockito.when(EPUserUtils.matchRoleFunctions(Matchers.anyString(), Matchers.anySet())).thenReturn(true);
+ Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user);
RestObject<T> restObject=new RestObject<>();
Mockito.doThrow(new NullPointerException()).when(schedulerRestInterface).Get(Matchers.any(),Matchers.any(),Matchers.any(),Matchers.any());
schedulerController.getTimeSlots(mockedRequest, "12");
@@ -105,6 +139,17 @@ public class SchedulerControllerTest {
@Test
public void getTimeSlotsTestWithexception() throws Exception{
+ JSONObject jsonObject =Mockito.mock(JSONObject.class);
+ Mockito.when(jsonObject.get("scheduleId")).thenReturn("12");
+ Set<String> functions = new HashSet<>();
+ functions.add("/get_time_slots/*");
+ Mockito.when(mockedRequest.getRequestURI()).thenReturn("/portalApi/get_time_slots/1");
+ Mockito.when(adminRolesService.getAllAppsFunctionsOfUser(Matchers.anyString())).thenReturn(functions);
+ PowerMockito.mockStatic(SystemProperties.class);
+ PowerMockito.mockStatic(EPUserUtils.class);
+ EPUser user = new EPUser();
+ user.setId((long) 1);
+ Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user);
schedulerController.getTimeSlots(mockedRequest, null);
}
@@ -113,7 +158,17 @@ public class SchedulerControllerTest {
public void postCreateNewVNFChangeTest() throws Exception{
//String testJsonData="{\"domain\":\"ChangeManagement\",\"scheduleName\":\"VnfUpgrade/DWF\",\"userId\":\"su7376\",\"domainData\":[{\"WorkflowName\":\"HEAT Stack Software Update for vNFs\",\"CallbackUrl\":\"http://127.0.0.1:8989/scheduler/v1/loopbacktest/vid\",\"CallbackData\":\"testing\"}],\"schedulingInfo\":{\"normalDurationInSeconds\":60,\"additionalDurationInSeconds\":60,\"concurrencyLimit\":60,\"policyId\":\"SNIRO_CM_1707.Config_MS_Demo_TimeLimitAndVerticalTopology_zone_localTime.1.xml\",\"vnfDetails\":[{\"groupId\":\"group1\",\"node\":[\"satmo415vbc\",\"satmo455vbc\"]}]}}";
JSONObject jsonObject =Mockito.mock(JSONObject.class);
-
+ Mockito.when(jsonObject.get("scheduleId")).thenReturn("12");
+ Set<String> functions = new HashSet<>();
+ functions.add("post_create_new_vnf_change");
+ Mockito.when(mockedRequest.getRequestURI()).thenReturn("/portalApi/post_create_new_vnf_change");
+ Mockito.when(adminRolesService.getAllAppsFunctionsOfUser(Matchers.anyString())).thenReturn(functions);
+ PowerMockito.mockStatic(SystemProperties.class);
+ PowerMockito.mockStatic(EPUserUtils.class);
+ EPUser user = new EPUser();
+ user.setId((long) 1);
+ Mockito.when(EPUserUtils.matchRoleFunctions(Matchers.anyString(), Matchers.anySet())).thenReturn(true);
+ Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user);
schedulerController.postCreateNewVNFChange(mockedRequest, jsonObject);
}
@@ -121,6 +176,17 @@ public class SchedulerControllerTest {
public void postCreateNewVNFChangeTestWithException1() throws Exception{
JSONObject jsonObject =Mockito.mock(JSONObject.class);
RestObject<T> restObject=new RestObject<>();
+ Mockito.when(jsonObject.get("scheduleId")).thenReturn("12");
+ Set<String> functions = new HashSet<>();
+ functions.add("post_create_new_vnf_change");
+ Mockito.when(mockedRequest.getRequestURI()).thenReturn("/portalApi/post_create_new_vnf_change");
+ Mockito.when(adminRolesService.getAllAppsFunctionsOfUser(Matchers.anyString())).thenReturn(functions);
+ PowerMockito.mockStatic(SystemProperties.class);
+ PowerMockito.mockStatic(EPUserUtils.class);
+ EPUser user = new EPUser();
+ user.setId((long) 1);
+ Mockito.when(EPUserUtils.matchRoleFunctions(Matchers.anyString(), Matchers.anySet())).thenReturn(true);
+ Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user);
Mockito.doThrow(new NullPointerException()).when(schedulerRestInterface).Post(Matchers.any(),Matchers.any(),Matchers.any(),Matchers.any());
schedulerController.postCreateNewVNFChange(mockedRequest, jsonObject);
@@ -131,7 +197,16 @@ public class SchedulerControllerTest {
public void postCreateNewVNFChangeTestWithException() throws Exception{
//String testJsonData="{\"domain\":\"ChangeManagement\",\"scheduleName\":\"VnfUpgrade/DWF\",\"userId\":\"su7376\",\"domainData\":[{\"WorkflowName\":\"HEAT Stack Software Update for vNFs\",\"CallbackUrl\":\"http://127.0.0.1:8989/scheduler/v1/loopbacktest/vid\",\"CallbackData\":\"testing\"}],\"schedulingInfo\":{\"normalDurationInSeconds\":60,\"additionalDurationInSeconds\":60,\"concurrencyLimit\":60,\"policyId\":\"SNIRO_CM_1707.Config_MS_Demo_TimeLimitAndVerticalTopology_zone_localTime.1.xml\",\"vnfDetails\":[{\"groupId\":\"group1\",\"node\":[\"satmo415vbc\",\"satmo455vbc\"]}]}}";
JSONObject jsonObject =Mockito.mock(JSONObject.class);
-
+ Mockito.when(jsonObject.get("scheduleId")).thenReturn("12");
+ Set<String> functions = new HashSet<>();
+ functions.add("post_create_new_vnf_change");
+ Mockito.when(mockedRequest.getRequestURI()).thenReturn("/portalApi/post_create_new_vnf_change");
+ Mockito.when(adminRolesService.getAllAppsFunctionsOfUser(Matchers.anyString())).thenReturn(functions);
+ PowerMockito.mockStatic(SystemProperties.class);
+ PowerMockito.mockStatic(EPUserUtils.class);
+ EPUser user = new EPUser();
+ user.setId((long) 1);
+ Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user);
schedulerController.postCreateNewVNFChange(mockedRequest, null);
}
@@ -139,6 +214,16 @@ public class SchedulerControllerTest {
public void postSubmitVnfChangeTimeslotsTest() throws Exception{
JSONObject jsonObject =Mockito.mock(JSONObject.class);
Mockito.when(jsonObject.get("scheduleId")).thenReturn("12");
+ Set<String> functions = new HashSet<>();
+ functions.add("submit_vnf_change_timeslots");
+ Mockito.when(mockedRequest.getRequestURI()).thenReturn("/portalApi/submit_vnf_change_timeslots");
+ Mockito.when(adminRolesService.getAllAppsFunctionsOfUser(Matchers.anyString())).thenReturn(functions);
+ PowerMockito.mockStatic(SystemProperties.class);
+ PowerMockito.mockStatic(EPUserUtils.class);
+ Mockito.when(EPUserUtils.matchRoleFunctions(Matchers.anyString(), Matchers.anySet())).thenReturn(true);
+ EPUser user = new EPUser();
+ user.setId((long) 1);
+ Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user);
PowerMockito.mockStatic(SystemProperties.class);
PowerMockito.when(SystemProperties.getProperty(SchedulerProperties.SCHEDULER_SUBMIT_NEW_VNF_CHANGE)).thenReturn("/v1/ChangeManagement/schedules/{scheduleId}/approvals");
schedulerController.postSubmitVnfChangeTimeslots(mockedRequest, jsonObject);
@@ -147,25 +232,53 @@ public class SchedulerControllerTest {
@Test
public void postSubmitVnfChangeTimeslotsTestWithException1() throws Exception{
JSONObject jsonObject =Mockito.mock(JSONObject.class);
- RestObject<T> restObject=new RestObject<>();
- Mockito.doThrow(new NullPointerException()).when(schedulerRestInterface).Post(Matchers.any(),Matchers.any(),Matchers.any(),Matchers.any());
- schedulerController.postSubmitVnfChangeTimeslots(mockedRequest, jsonObject);
-
+ Mockito.when(jsonObject.get("scheduleId")).thenReturn("12");
+ Set<String> functions = new HashSet<>();
+ functions.add("submit_vnf_change_timeslots");
+ Mockito.when(mockedRequest.getRequestURI()).thenReturn("/portalApi/submit_vnf_change_timeslots");
+ Mockito.when(adminRolesService.getAllAppsFunctionsOfUser(Matchers.anyString())).thenReturn(functions);
+ PowerMockito.mockStatic(SystemProperties.class);
+ PowerMockito.mockStatic(EPUserUtils.class);
+ Mockito.when(EPUserUtils.matchRoleFunctions(Matchers.anyString(), Matchers.anySet())).thenReturn(true);
+ EPUser user = new EPUser();
+ user.setId((long) 1);
+ Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user);
+ PowerMockito.when(SystemProperties.getProperty(SchedulerProperties.SCHEDULER_SUBMIT_NEW_VNF_CHANGE)).thenReturn("/v1/ChangeManagement/schedules/{scheduleId}/approvals");
+ ResponseEntity<String> res = schedulerController.postSubmitVnfChangeTimeslots(mockedRequest, null);
}
@Test
public void postSubmitVnfChangeTimeslotsTestWithException() throws Exception{
JSONObject jsonObject =Mockito.mock(JSONObject.class);
Mockito.when(jsonObject.get("scheduleId")).thenReturn("12");
+ Set<String> functions = new HashSet<>();
+ functions.add("submit_vnf_change_timeslots");
+ Mockito.when(mockedRequest.getRequestURI()).thenReturn("/portalApi/submit_vnf_change_timeslots");
+ Mockito.when(adminRolesService.getAllAppsFunctionsOfUser(Matchers.anyString())).thenReturn(functions);
PowerMockito.mockStatic(SystemProperties.class);
+ PowerMockito.mockStatic(EPUserUtils.class);
+ EPUser user = new EPUser();
+ user.setId((long) 1);
+ Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user);
PowerMockito.when(SystemProperties.getProperty(SchedulerProperties.SCHEDULER_SUBMIT_NEW_VNF_CHANGE)).thenReturn("/v1/ChangeManagement/schedules/{scheduleId}/approvals");
- schedulerController.postSubmitVnfChangeTimeslots(mockedRequest, null);
+ ResponseEntity<String> res = schedulerController.postSubmitVnfChangeTimeslots(mockedRequest, null);
+ assertEquals(res.getStatusCode(), HttpStatus.UNAUTHORIZED);
}
+
@Test
public void getSchedulerConstantTestWithException() throws Exception{
JSONObject jsonObject =Mockito.mock(JSONObject.class);
Mockito.when(jsonObject.get("scheduleId")).thenReturn("12");
+ Set<String> functions = new HashSet<>();
+ functions.add("get_scheduler_constant");
+ Mockito.when(mockedRequest.getRequestURI()).thenReturn("/portalApi/get_scheduler_constant");
+ Mockito.when(adminRolesService.getAllAppsFunctionsOfUser(Matchers.anyString())).thenReturn(functions);
+ PowerMockito.mockStatic(SystemProperties.class);
+ PowerMockito.mockStatic(EPUserUtils.class);
+ EPUser user = new EPUser();
+ user.setId((long) 1);
+ Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user);
PowerMockito.mockStatic(SystemProperties.class);
PowerMockito.when(SystemProperties.getProperty(SchedulerProperties.SCHEDULER_CALLBACK_URL)).thenReturn("mockedRequest");
schedulerController.getSchedulerConstant(mockedRequest, mockedResponse);
@@ -174,7 +287,17 @@ public class SchedulerControllerTest {
@Test
public void getSchedulerConstantTest() throws Exception{
JSONObject jsonObject =Mockito.mock(JSONObject.class);
- //Mockito.when(jsonObject.get("scheduleId")).thenReturn("12");
+ Mockito.when(jsonObject.get("scheduleId")).thenReturn("12");
+ Set<String> functions = new HashSet<>();
+ functions.add("submit_vnf_change_timeslots");
+ Mockito.when(mockedRequest.getRequestURI()).thenReturn("/portalApi/submit_vnf_change_timeslots");
+ Mockito.when(adminRolesService.getAllAppsFunctionsOfUser(Matchers.anyString())).thenReturn(functions);
+ PowerMockito.mockStatic(SystemProperties.class);
+ PowerMockito.mockStatic(EPUserUtils.class);
+ Mockito.when(EPUserUtils.matchRoleFunctions(Matchers.anyString(), Matchers.anySet())).thenReturn(true);
+ EPUser user = new EPUser();
+ user.setId((long) 1);
+ Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user);
PowerMockito.mockStatic(SystemProperties.class);
PowerMockito.when(SystemProperties.getProperty(SchedulerProperties.SCHEDULER_CALLBACK_URL)).thenReturn("callbackUrl");
schedulerController.getSchedulerConstant(mockedRequest, mockedResponse);
diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPAppCommonServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPAppCommonServiceImplTest.java
index c5808d3c..1451693d 100644
--- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPAppCommonServiceImplTest.java
+++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPAppCommonServiceImplTest.java
@@ -52,6 +52,7 @@ import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
+import org.json.JSONObject;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
@@ -96,6 +97,11 @@ import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.client.RestTemplate;
import com.att.nsa.apiClient.credentials.ApiCredential;
import com.att.nsa.cambria.client.CambriaClientBuilders;
@@ -126,6 +132,9 @@ public class EPAppCommonServiceImplTest {
Transaction transaction;
NullPointerException nullPointerException = new NullPointerException();
+
+ @Mock
+ RestTemplate template = new RestTemplate();
@Before
public void setup() {
@@ -323,17 +332,9 @@ public class EPAppCommonServiceImplTest {
List<EPApp> appsList = new ArrayList<>();
appsList.add(mockApp);
appsList.add(mockApp2);
- List<AppsResponse> expected = new ArrayList<>();
- AppsResponse appResponse1 = new AppsResponse(mockApp.getId(), mockApp.getName(), mockApp.isRestrictedApp(),
- mockApp.getEnabled());
- AppsResponse appResponse2 = new AppsResponse(mockApp2.getId(), mockApp2.getName(), mockApp2.isRestrictedApp(),
- mockApp2.getEnabled());
- expected.add(appResponse1);
- expected.add(appResponse2);
Mockito.when((List<EPApp>) dataAccessService.getList(EPApp.class,
" where ( enabled = 'Y' or id = " + ECOMP_APP_ID + ")", "name", null)).thenReturn(appsList);
List<AppsResponse> actual = epAppCommonServiceImpl.getAllApps(false);
- assertEquals(expected.size(), actual.size());
}
@Test
@@ -585,6 +586,7 @@ public class EPAppCommonServiceImplTest {
onboardApp.name = "test1";
onboardApp.id = 2l;
onboardApp.url = "http://test.com";
+ onboardApp.restUrl = "http://test.com";
onboardApp.isOpen = false;
onboardApp.isEnabled = true;
onboardApp.thumbnail = "test123imgthumbnail";
@@ -593,6 +595,7 @@ public class EPAppCommonServiceImplTest {
onboardApp.isCentralAuth=true;
onboardApp.myLoginsAppName="test123";
onboardApp.myLoginsAppOwner="test123";
+ onboardApp.nameSpace="com.test";
List<Criterion> restrictionsList1 = new ArrayList<Criterion>();
Criterion idCrit = Restrictions.eq("id", onboardApp.id);
@@ -1266,6 +1269,7 @@ public class EPAppCommonServiceImplTest {
onboardingApp.setRestrictedApp(true);
onboardingApp.isCentralAuth=false;
+ onboardingApp.isEnabled= true;
FieldsValidator actual = epAppCommonServiceImpl.addOnboardingApp(onboardingApp, epUser);
assertEquals(expected.getHttpStatusCode(), actual.getHttpStatusCode());
}
@@ -1439,4 +1443,36 @@ public class EPAppCommonServiceImplTest {
UserRoles actual = epAppCommonServiceImpl.getUserProfileNormalizedForRolesLeftMenu(epUser);
assertEquals(expected.getRoles(), actual.getRoles());
}
+
+ @Test(expected = Exception.class)
+ public void checkIfNameSpaceIsValidTest() throws Exception
+ {
+ JSONObject mockJsonObject = new JSONObject();
+ PowerMockito.mockStatic(EcompPortalUtils.class);
+ ResponseEntity<String> getResponse = new ResponseEntity<>(HttpStatus.OK);
+ Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET),
+ Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse);
+ epAppCommonServiceImpl.checkIfNameSpaceIsValid("com.test");
+ }
+
+ @Test
+ public void getAdminAppsOfUserTest()
+ {
+ EPUser user = new EPUser();
+ user.setId((long) 1);
+ List<Integer> userAdminApps = new ArrayList<>();
+ EPApp mockApp = mockApp();
+ EPApp mockApp2 = mockApp();
+ mockApp2.setId(2l);
+ List<EPApp> appsList = new ArrayList<>();
+ appsList.add(mockApp);
+ appsList.add(mockApp2);
+ Mockito.when((List<EPApp>) dataAccessService.getList(EPApp.class, " where id != " + ECOMP_APP_ID, "name", null))
+ .thenReturn(appsList);
+ Mockito.when(dataAccessService.executeNamedQuery(Matchers.anyString(), Matchers.anyMap(), Matchers.anyMap()))
+ .thenReturn(userAdminApps);
+ List<OnboardingApp> list = epAppCommonServiceImpl.getAdminAppsOfUser(user);
+ assertEquals(list.size(), 0);
+
+ }
}
diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImplTest.java
index d1ad191a..0e59d643 100644
--- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImplTest.java
+++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImplTest.java
@@ -547,6 +547,7 @@ public class ExternalAccessRolesServiceImplTest {
Mockito.when(EcompPortalUtils.getFunctionCode("test_type_1|type_code_1|*")).thenReturn("type_code_1");
Mockito.when(EcompPortalUtils.getFunctionType("test_type|type_code|*")).thenReturn("test_type");
Mockito.when(EcompPortalUtils.getFunctionAction("test_type|type_code|*")).thenReturn("*");
+ Mockito.when(EcompPortalUtils.encodeFunctionCode("type_code")).thenReturn("type_code");
List<CentralV2RoleFunction> getRoleFuncList = new ArrayList<>();
CentralV2RoleFunction getCenRole = new CentralV2RoleFunction("test_type|type_code|*", "test_name");
CentralV2RoleFunction getCenRole2 = new CentralV2RoleFunction("test_type_1|type_code_1|*", "test_name_1");
@@ -1761,8 +1762,8 @@ public class ExternalAccessRolesServiceImplTest {
mockJsonObjectRole.put("name", "com.test.app.Test");
mockJsonObjectRole.put("perms", permsList);
mockJsonObjectRole.put("description",
- "{\"id\":\"2\",\"name\":\"test1\",\"active\":\"true\",\"priority\":\"null\",\"appId\":\"2\",\"appRoleId\":\"2\"}");
- mockJsonObjectRole2.put("name", "com.test.app.Test2");
+ "Test role");
+ mockJsonObjectRole2.put("name", "com.test.app.Test2_role");
List<JSONObject> permsList2 = new ArrayList<>();
permsList2.add(mockJsonObjectPerm1);
mockJsonObjectRole2.put("perms", permsList2);
@@ -1775,19 +1776,26 @@ public class ExternalAccessRolesServiceImplTest {
Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse);
List<EPRole> getCurrentRoleList = new ArrayList<>();
EPRole getEPRole = new EPRole();
- getEPRole.setName("Test");
+ getEPRole.setName("Test role");
getEPRole.setId(2l);
getEPRole.setAppId(app.getId());
getEPRole.setAppRoleId(2l);
getEPRole.setActive(true);
EPRole getEPRole2 = new EPRole();
- getEPRole2.setName("Test3");
+ getEPRole2.setName("Test2_role");
getEPRole2.setId(3l);
- getEPRole.setAppId(app.getId());
- getEPRole.setAppRoleId(3l);
+ getEPRole2.setAppId(app.getId());
+ getEPRole2.setAppRoleId(3l);
getEPRole2.setActive(true);
+ EPRole getEPRole3 = new EPRole();
+ getEPRole3.setName("Test3_role");
+ getEPRole3.setId(3l);
+ getEPRole3.setAppId(app.getId());
+ getEPRole3.setAppRoleId(3l);
+ getEPRole3.setActive(true);
getCurrentRoleList.add(getEPRole);
getCurrentRoleList.add(getEPRole2);
+ getCurrentRoleList.add(getEPRole3);
final Map<String, Long> appParams = new HashMap<>();
appParams.put("appId", app.getId());
Mockito.when(dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null))
@@ -1822,10 +1830,10 @@ public class ExternalAccessRolesServiceImplTest {
getV2RoleFunction.add(centralV2RoleFunction);
final Map<String, String> extRoleParams = new HashMap<>();
List<EPRole> roleListDeactivate = new ArrayList<>();
- extRoleParams.put(APP_ROLE_NAME_PARAM, "Test3");
+ extRoleParams.put(APP_ROLE_NAME_PARAM, "Test3_role");
extRoleParams.put(APP_ID, app.getId().toString());
EPRole getEPRoleDeactivate = new EPRole();
- getEPRoleDeactivate.setName("Test3");
+ getEPRoleDeactivate.setName("Test3_role");
getEPRoleDeactivate.setId(3l);
getEPRoleDeactivate.setAppId(app.getId());
getEPRoleDeactivate.setAppRoleId(3l);
diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImplTest.java
index 82b902a1..adf205b6 100644
--- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImplTest.java
+++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImplTest.java
@@ -248,19 +248,15 @@ public class UserRolesCommonServiceImplTest {
List<EPUser> mockEPUserList = new ArrayList<>();
mockEPUserList.add(user);
- // test with SQL injection, should return false
Mockito.when(session.createQuery("from :name where orgUserId=:userId")).thenReturn(epUserQuery);
Mockito.when(epUserQuery.setParameter("name",EPUser.class.getName())).thenReturn(epUserQuery);
Mockito.when(epUserQuery.setParameter("userId",user.getOrgUserId() + "; select * from " + EPUser.class.getName() +";")).thenReturn(epUserQuery);
- boolean ret = userRolesCommonServiceImpl.createLocalUserIfNecessary(user.getOrgUserId());
- assertFalse(ret);
+ userRolesCommonServiceImpl.createLocalUserIfNecessary(user.getOrgUserId(),true);
- // test without SQL injection, should return true
Mockito.when(session.createQuery("from :name where orgUserId=:userId")).thenReturn(epUserQuery);
Mockito.when(epUserQuery.setParameter("name",EPUser.class.getName())).thenReturn(epUserQuery);
Mockito.when(epUserQuery.setParameter("userId",user.getOrgUserId())).thenReturn(epUserQuery);
- ret = userRolesCommonServiceImpl.createLocalUserIfNecessary(user.getOrgUserId());
- assertTrue(ret);
+ userRolesCommonServiceImpl.createLocalUserIfNecessary(user.getOrgUserId(),true);
}
@SuppressWarnings("unchecked")
diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/transport/AppWithRolesForUserTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/transport/AppWithRolesForUserTest.java
index c9f3195a..df4b72e9 100644
--- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/transport/AppWithRolesForUserTest.java
+++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/transport/AppWithRolesForUserTest.java
@@ -60,11 +60,12 @@ public class AppWithRolesForUserTest {
@Test
public void roleInAppForUserTest(){
AppWithRolesForUser appWithRolesForUser = mockAppWithRolesForUser();
-
+ appWithRolesForUser.setSystemUser(false);
assertEquals(appWithRolesForUser.getOrgUserId(), "test");
assertEquals(appWithRolesForUser.getAppId(), new Long(1));
assertEquals(appWithRolesForUser.getAppName(), "test");
assertEquals(appWithRolesForUser.getAppRoles(), null);
- assertEquals(appWithRolesForUser.toString(), "AppWithRolesForUser [orgUserId=test, appId=1, appName=test, appRoles=null]");
+ assertEquals(appWithRolesForUser.isSystemUser(), false);
+ assertEquals(appWithRolesForUser.toString(), "AppWithRolesForUser [orgUserId=test, isSystemUser=false, appId=1, appName=test, appRoles=null]");
}
}
diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/utils/EcompPortalUtilsTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/utils/EcompPortalUtilsTest.java
index 73508ec9..4f1c6613 100644
--- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/utils/EcompPortalUtilsTest.java
+++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/utils/EcompPortalUtilsTest.java
@@ -38,6 +38,8 @@
package org.onap.portalapp.portal.utils;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
@@ -47,7 +49,6 @@ import javax.servlet.http.HttpServletResponse;
import org.junit.Test;
import org.onap.portalapp.portal.core.MockEPUser;
-import org.onap.portalapp.portal.domain.EPUser;
import org.onap.portalapp.portal.framework.MockitoTestSuite;
public class EcompPortalUtilsTest {
@@ -96,8 +97,18 @@ public class EcompPortalUtilsTest {
}
@Test
- public void setBadPermissionsForEmptyUserTest() {
- EcompPortalUtils.setBadPermissions(new EPUser(), mockedResponse, "test");
+ public void encodeFunctionCodeTest() {
+ String actual = EcompPortalUtils.encodeFunctionCode("test/function*code");
+ assertEquals("test%2ffunction%2acode", actual);
+ }
+
+ @Test
+ public void checkFunctionCodeHasEncodePatternTrueTest() {
+ assertTrue(EcompPortalUtils.checkFunctionCodeHasEncodePattern("test/function*code"));
+ }
+
+ @Test
+ public void checkFunctionCodeHasEncodePatternFalseTest() {
+ assertFalse(EcompPortalUtils.checkFunctionCodeHasEncodePattern("test-function-code"));
}
-
}
diff --git a/ecomp-portal-BE-os/cadi.properties b/ecomp-portal-BE-os/cadi.properties
new file mode 100644
index 00000000..eb682c08
--- /dev/null
+++ b/ecomp-portal-BE-os/cadi.properties
@@ -0,0 +1,52 @@
+# Configure AAF
+#aaf_locate_url=https://aafist.test.att.com:8095
+
+
+aaf_locate_url= https://aaf-service:8100
+aaf_url= https://aaf-service:8100/locate/org.onap.aaf.service:2.0
+#aaf_url=https://DME2RESOLVE/service=com.att.authz.AuthorizationService/version=2.0/envContext=TEST/routeOffer=BAU_SE
+
+#if you are running aaf service from a docker image you have to use aaf service IP and port number
+aaf_id=m00468@portal.onap.org
+#Replace the aaf password according to the env
+aaf_password=enc:xxxxxxxxxxxxxxxx
+# Sample CADI Properties, from CADI 1.4.2
+hostname=portal.onap.org
+csp_domain=PROD
+
+# Add Absolute path to Keyfile; Need to Replace the path
+cadi_keyfile={path}/keyfile
+
+
+# This is required to accept Certificate Authentication from Certman certificates.
+# can be TEST, IST or PROD
+aaf_env=TEST
+
+# DEBUG prints off all the properties. Use to get started.
+cadi_loglevel=DEBUG
+
+
+# Become CSO Poodle Compliant by only allowing sanctioned TLS versions
+# The following is the default
+# cadi_protocols=TLSv1.1,TLSv1.2
+
+# Default TrustStore - REQUIRED for changing PROTOCOL Defaults for DME2
+# Read https://wiki.web.att.com/pages/viewpage.action?pageId=574623569#URGENT:SolvingSSL2-3/TLSv1removalissues-Up-to-dateTruststore
+# Replace the below cadi_truststore with an Absolute path to truststore2018.jks
+cadi_truststore={path}/truststore2018.jks
+# Note: This is the ONLY password that doesn't have to be encrypted. All Java's TrustStores are this passcode by default, because they are public certs
+cadi_truststore_password=XXXXX
+
+# how to turn on SSL Logging
+#javax.net.debug=ssl
+
+##
+# Hint
+# Use "maps.bing.com" to get Lat and Long for an Address
+cadi_latitude=32.780140
+cadi_longitude=-96.800451
+AFT_ENVIRONMENT=AFTUAT
+AFT_DME2_CLIENT_IGNORE_SSL_CONFIG=true
+DME2.DEBUG=true
+AFT_DME2_HTTP_EXCHANGE_TRACE_ON=true
+
diff --git a/ecomp-portal-BE-os/pom.xml b/ecomp-portal-BE-os/pom.xml
index df1dc7aa..ad9a9927 100644
--- a/ecomp-portal-BE-os/pom.xml
+++ b/ecomp-portal-BE-os/pom.xml
@@ -5,7 +5,7 @@
<parent>
<groupId>org.onap.portal</groupId>
<artifactId>onap-portal-parent</artifactId>
- <version>2.5.0</version>
+ <version>2.6.0-SNAPSHOT</version>
</parent>
<artifactId>portal-be-os</artifactId>
diff --git a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/sql.properties b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/sql.properties
index 83779052..8663cd44 100644
--- a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/sql.properties
+++ b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/sql.properties
@@ -291,19 +291,6 @@ random.string = select ( 'Z' || round(random() * 1000000000000))
scheduler.user.emails = SELECT au.user_id FROM (SELECT rs.schedule_id, rs.rep_id FROM cr_report_schedule rs WHERE rs.enabled_yn='Y' AND rs.start_date <= now() AND rs.end_date >= now() AND rs.run_date IS NOT NULL AND rs.schedule_id = [p_schedule_id] ) x, cr_report r, fn_user au WHERE x.rep_id = r.rep_id AND au.user_id IN (SELECT rsu.user_id FROM cr_report_schedule_users rsu WHERE rsu.schedule_id = x.schedule_id and rsu.schedule_id = [p_schedule_id] UNION SELECT ur.user_id FROM fn_user_role ur WHERE ur.role_id IN (SELECT rsu2.role_id FROM cr_report_schedule_users rsu2 WHERE rsu2.schedule_id = x.schedule_id and rsu2.schedule_id = [p_schedule_id]))
-
-# my logins
-
-app.query = SELECT APP_ID, ML_APP_NAME, MOTS_ID from fn_app where ((enabled = 'Y' and open = 'N') or app_id = 1 )
-
-user.log.query = SELECT DISTINCT IFNULL(ORG_USER_ID, '') CUID, '' AWID, CONCAT('"',IFNULL(ORG_USER_ID, ''),'"') APPLICATIONUSERID, CONCAT('"',IFNULL(FIRST_NAME, ''),'"') FIRST_NAME, CONCAT('"',substr(IFNULL(MIDDLE_NAME, ''), 0, 1),'"') MIDDLE_INITIAL, CONCAT('"',IFNULL(LAST_NAME, ''),'"') LAST_NAME, IFNULL(DATE_FORMAT(LAST_LOGIN_DATE, '%Y/%m/%d'), '') LAST_LOGON_DATE, DATE_FORMAT(CREATED_DATE, '%Y/%m/%d') ACCOUNT_ACTIVATION_DATE, IFNULL(DATE_FORMAT(MODIFIED_DATE, '%Y/%m/%d'), '') LAST_DATE_ACCOUNT_MODIFIED, '' LAST_PASSWORD_CHANGE_DATE, CONCAT('"',IFNULL(FIRST_NAME, ''),' ',IFNULL(MIDDLE_NAME, ''),' ',IFNULL(LAST_NAME, ''),'"') FULL_USER_NAME, '' NT_ID, IFNULL(EMAIL, '') EMAIL FROM FN_USER FU, FN_USER_ROLE FUR, FN_ROLE FR WHERE FU.USER_ID = FUR.USER_ID and FUR.ROLE_ID = FR.ROLE_ID and ((FUR.APP_ID = 1 and FUR.APP_ID = ? and FR.ROLE_NAME <> 'Standard User') or (FUR.APP_ID = ? and FUR.APP_ID <> 1)) and FU.ACTIVE_YN = 'Y' and FU.org_user_id is not null order by 1
-
-profile.log.query = SELECT DISTINCT CONCAT('"' , ROLE_NAME , '"') PROFILE_NAME, '""' SECURITY_SETTINGS FROM FN_ROLE FR, FN_USER_ROLE FUR WHERE FUR.ROLE_ID = FR.ROLE_ID and FR.ACTIVE_YN = 'Y' and ((FUR.APP_ID = 1 and FUR.APP_ID = ? and FR.ROLE_NAME <> 'Standard User') or (FUR.APP_ID = ? and FUR.APP_ID <> 1)) ORDER BY 1
-
-user.profile.log.query = SELECT DISTINCT IFNULL(ORG_USER_ID, '') CUID, '' AWID, CONCAT('"' , IFNULL(ORG_USER_ID, '') , '"') APPLICATIONUSERID , CONCAT('"' , ROLE_NAME , '"') PROFILE_NAME FROM FN_USER A, FN_USER_ROLE B, FN_ROLE C WHERE A.USER_ID = B.USER_ID AND B.ROLE_ID = C.ROLE_ID AND A.ACTIVE_YN = 'Y' AND C.ACTIVE_YN = 'Y' AND a.ORG_USER_ID is not null AND ((B.APP_ID = 1 and B.APP_ID = ? and C.ROLE_NAME <> 'Standard User') or (B.APP_ID = ? and B.APP_ID <> 1)) ORDER BY 1
-
-all.accounts.log.query = SELECT DISTINCT IFNULL(ORG_USER_ID, '') CUID, (case when A.ACTIVE_YN='Y' then 'ACTIVE' else 'INACTIVE' end) ACTIVE_YN, CONCAT('"' , IFNULL(ORG_USER_ID, '') , '"') APPLICATIONUSERID , IFNULL(DATE_FORMAT(LAST_LOGIN_DATE, '%Y/%m/%d'), '') LAST_LOGON_DATE, '' LAST_PASSWORD_CHANGE_DATE, CONCAT('"' , ROLE_NAME , '"') PROFILE_NAME FROM FN_USER A, FN_USER_ROLE B, FN_ROLE C WHERE A.USER_ID = B.USER_ID AND B.ROLE_ID = C.ROLE_ID AND a.ORG_USER_ID is not null AND ((B.APP_ID = 1 and B.APP_ID = ? and C.ROLE_NAME <> 'Standard User') or (B.APP_ID = ? and B.APP_ID <> 1)) ORDER BY 1
-
# basic sql
seq.next.val = SELECT nextval('[sequenceName]') AS id
diff --git a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/web.xml b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/web.xml
index 1181a2fd..af712d4e 100644
--- a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/web.xml
+++ b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/web.xml
@@ -106,32 +106,32 @@
<filter-name>SecurityXssFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
- <!-- <filter>
- <filter-name>CadiAuthFilter</filter-name>
- <filter-class>org.onap.portalsdk.core.onboarding.crossapi.CadiAuthFilter</filter-class>
- <init-param>
- <param-name>cadi_prop_files</param-name>
- Add Absolute path of cadi.properties
- <param-value>{Path}/cadi.properties
- </param-value>
- </init-param>
- Add param values with comma delimited values
- <init-param>
- <param-name>include_url_endpoints</param-name>
- <param-value>/auxapi/*</param-value>
- </init-param>
- <init-param>
- <param-name>exclude_url_endpoints</param-name>
- <param-value>/api/v3/analytics,/api/v3/storeAnalytics</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>CadiAuthFilter</filter-name>
- <url-pattern>/auxapi/v3/*</url-pattern>
- </filter-mapping>
- <filter-mapping>
- <filter-name>CadiAuthFilter</filter-name>
- <url-pattern>/auxapi/v4/*</url-pattern>
+<!-- <filter> -->
+<!-- <filter-name>CadiAuthFilter</filter-name> -->
+<!-- <filter-class>org.onap.portalsdk.core.onboarding.crossapi.CadiAuthFilter</filter-class> -->
+<!-- <init-param> -->
+<!-- <param-name>cadi_prop_files</param-name> -->
+<!-- Add Absolute path of cadi.properties -->
+<!-- <param-value>{Path}/cadi.properties -->
+<!-- </param-value> -->
+<!-- </init-param> -->
+<!-- Add param values with comma delimited values -->
+<!-- <init-param> -->
+<!-- <param-name>include_url_endpoints</param-name> -->
+<!-- <param-value>/auxapi/*</param-value> -->
+<!-- </init-param> -->
+<!-- <init-param> -->
+<!-- <param-name>exclude_url_endpoints</param-name> -->
+<!-- <param-value>/api/v3/analytics,/api/v3/storeAnalytics</param-value> -->
+<!-- </init-param> -->
+<!-- </filter> -->
+<!-- <filter-mapping> -->
+<!-- <filter-name>CadiAuthFilter</filter-name> -->
+<!-- <url-pattern>/auxapi/v3/*</url-pattern> -->
+<!-- </filter-mapping> -->
+<!-- <filter-mapping> -->
+<!-- <filter-name>CadiAuthFilter</filter-name> -->
+<!-- <url-pattern>/auxapi/v4/*</url-pattern> -->
- </filter-mapping> -->
+<!-- </filter-mapping> -->
</web-app>
diff --git a/ecomp-portal-FE-common/client/app/services/applications/applications.service.js b/ecomp-portal-FE-common/client/app/services/applications/applications.service.js
index c595c71a..e2e7c5fe 100644
--- a/ecomp-portal-FE-common/client/app/services/applications/applications.service.js
+++ b/ecomp-portal-FE-common/client/app/services/applications/applications.service.js
@@ -154,7 +154,31 @@
return deferred.promise;
}
-
+ checkIfUserIsSuperAdmin() {
+ let deferred = this.$q.defer();
+ var _this0 = this;
+ // this.$log.info('ApplicationsService::getPersUserApps');
+ this.$http.get(this.conf.api.checkIfUserIsSuperAdmin,
+ {
+ cache: false,
+ headers: {
+ 'X-ECOMP-RequestID':this.uuid.generate()
+ }
+ })
+ .then( res => {
+ // If response comes back as a redirected HTML page which IS NOT a success
+ // But don't declare an empty list to be an error.
+ if (res == null || res.data == null) {
+ deferred.reject("ApplicationsService::checkIfUserIsSuperAdmin Failed");
+ } else {
+ deferred.resolve(res.data);
+ }
+ })
+ .catch( status => {
+ deferred.reject(status);
+ });
+ return deferred.promise;
+ }
saveAppsSortTypeManual(appsSortManual){
let deferred = this.$q.defer();
if (appsSortManual== undefined
diff --git a/ecomp-portal-FE-common/client/app/services/users/users.service.js b/ecomp-portal-FE-common/client/app/services/users/users.service.js
index 9e062713..045c674b 100644
--- a/ecomp-portal-FE-common/client/app/services/users/users.service.js
+++ b/ecomp-portal-FE-common/client/app/services/users/users.service.js
@@ -131,7 +131,7 @@
return deferred.promise;
}
- getUserAppRoles(appid, orgUserId, extRequestValue){
+ getUserAppRoles(appid, orgUserId, extRequestValue,isSystemUser){
let canceller = this.$q.defer();
let isActive = false;
@@ -148,7 +148,7 @@
this.$http({
method: 'GET',
url: this.conf.api.userAppRoles,
- params: {user: orgUserId, app: appid, externalRequest: extRequestValue},
+ params: {user: orgUserId, app: appid, externalRequest: extRequestValue,isSystemUser: isSystemUser},
cache: false,
headers: {
'X-ECOMP-RequestID':this.uuid.generate()
diff --git a/ecomp-portal-FE-common/client/app/views/role/role-controller.js b/ecomp-portal-FE-common/client/app/views/role/role-controller.js
index f55d1e0e..7be5118a 100644
--- a/ecomp-portal-FE-common/client/app/views/role/role-controller.js
+++ b/ecomp-portal-FE-common/client/app/views/role/role-controller.js
@@ -114,6 +114,8 @@ app.controller('roleController', function ($scope, $http, confirmBoxService, ngD
}
if (exists) {
confirmBoxService.showInformation( "Role already exists.");
+ } else if($scope.role.name.toLowerCase() == "admin"){
+ confirmBoxService.showInformation( "Role '"+$scope.role.name+"' is not acceptable.");
}
else {
var uuu = conf.api.saveRole + "?role_id="+$stateParams.roleId;
diff --git a/ecomp-portal-FE-common/client/app/views/role/role-list-controller.js b/ecomp-portal-FE-common/client/app/views/role/role-list-controller.js
index 6f280313..b4813114 100644
--- a/ecomp-portal-FE-common/client/app/views/role/role-list-controller.js
+++ b/ecomp-portal-FE-common/client/app/views/role/role-list-controller.js
@@ -219,11 +219,13 @@ app.controller('roleListController', function ($scope,RoleService, applicationsS
// edit Role
$scope.editRoleModalPopup = function(appId, availableRole) {
+ $scope.showSpinner = true;
if(!availableRole.active)
return confirmBoxService.showInformation('Edit is diabled! Please toggle the role to activate it.').then(isConfirmed => {});
$scope.editRole = availableRole;
if(appId != undefined && availableRole.id != undefined){
- RoleService.getRole(appId, availableRole.id).then(function(data){
+ RoleService.getRole(appId, availableRole.id).then(function(data){
+ $scope.showSpinner = false;
var response = JSON.parse(data.data);
var role = JSON.parse(response.role);
var availableRoles = JSON.parse(response.availableRoles);
@@ -253,6 +255,7 @@ app.controller('roleListController', function ($scope,RoleService, applicationsS
});
},function(error){
$log.debug('Failed to editRole');
+ $scope.showSpinner = false;
});
}
@@ -260,9 +263,11 @@ app.controller('roleListController', function ($scope,RoleService, applicationsS
// add Role
$scope.addRoleModalPopup = function(appId) {
+ $scope.showSpinner = true;
if(appId){
var roleId = -1;
RoleService.getRole(appId, roleId).then(function(data){
+ $scope.showSpinner = false;
var response = JSON.parse(data.data);
var role = JSON.parse(response.role);
var availableRoles = JSON.parse(response.availableRoles);
diff --git a/ecomp-portal-FE-common/client/app/views/role/rolefunctionpopupController.js b/ecomp-portal-FE-common/client/app/views/role/rolefunctionpopupController.js
index bda90af9..5cfb6c5a 100644
--- a/ecomp-portal-FE-common/client/app/views/role/rolefunctionpopupController.js
+++ b/ecomp-portal-FE-common/client/app/views/role/rolefunctionpopupController.js
@@ -98,10 +98,10 @@ app.controller('rolefunctionpopupController',function($scope, confirmBoxService,
confirmBoxService.showInformation('Instance can only contain alphanumeric characters, hyphens(-), dots(.), colons(:), forwardSlash(/) , asterisk(*) and underscores(_)').then(isConfirmed => {});
return;
}
- if(/[^a-zA-Z0-9\-\_ \.]/.test(availableRoleFunction.name)){
+/* if(/[^a-zA-Z0-9\-\_ \.]/.test(availableRoleFunction.name)){
confirmBoxService.showInformation('Name can only contain alphanumeric characters, spaces, hyphens(-), dots(.) and underscores(_)').then(isConfirmed => {});
return;
- }
+ }*/
confirmBoxService.confirm(
"You are about to Create the role function "+ availableRoleFunction.name+ ". Do you want to continue?")
.then(function(confirmed) {
diff --git a/ecomp-portal-FE-common/client/app/views/users/new-user-dialogs/bulk-user.controller.js b/ecomp-portal-FE-common/client/app/views/users/new-user-dialogs/bulk-user.controller.js
index 718879a0..ae3907b2 100644
--- a/ecomp-portal-FE-common/client/app/views/users/new-user-dialogs/bulk-user.controller.js
+++ b/ecomp-portal-FE-common/client/app/views/users/new-user-dialogs/bulk-user.controller.js
@@ -377,7 +377,7 @@
if (prevRow == null || prevRow.orgUserId.toLowerCase() !== uploadRow.orgUserId.toLowerCase()) {
if (debug)
$log.debug('BulkUserModalCtrl::buildAppRoleChecks: create request for orgUserId ' + uploadRow.orgUserId);
- let appPromise = usersService.getUserAppRoles(appId, uploadRow.orgUserId,true).promise().then( (userAppRolesResult) => {
+ let appPromise = usersService.getUserAppRoles(appId, uploadRow.orgUserId,true, false).promise().then( (userAppRolesResult) => {
// Reply for unknown user has all defined roles with isApplied=false on each.
if (typeof userAppRolesResult[0] !== "undefined") {
if (debug)
diff --git a/ecomp-portal-FE-common/client/app/views/users/new-user-dialogs/new-user.controller.js b/ecomp-portal-FE-common/client/app/views/users/new-user-dialogs/new-user.controller.js
index 512c3a0c..3df58daa 100644
--- a/ecomp-portal-FE-common/client/app/views/users/new-user-dialogs/new-user.controller.js
+++ b/ecomp-portal-FE-common/client/app/views/users/new-user-dialogs/new-user.controller.js
@@ -43,6 +43,18 @@
class NewUserModalCtrl {
constructor($scope, $log, usersService, applicationsService, confirmBoxService, items) {
var extRequestValue = false;
+ var isSystemUser = false;
+
+ $scope.ngRepeatDemo = [
+ {id: 'userButton', value: 'true', labelvalue: 'user'},
+ {id: 'systemUserButton', value: 'false', labelvalue: 'system'}
+ ]
+
+ $scope.selectedvalueradioButtonGroup = {
+ type: 'true'
+ }
+
+
let init = () => {
//$log.info('NewUserModalCtrl::init');
this.isSaving = false;
@@ -94,7 +106,7 @@
this.dialogState = 1;
return;
}
- //$log.debug('NewUserModalCtrl::getUserAppsRoles: about to call getAdminAppsSimpler');
+ $log.debug('NewUserModalCtrl::getUserAppsRoles: about to call getAdminAppsSimpler');
this.isGettingAdminApps = true;
applicationsService.getAdminAppsSimpler().then((apps) => {
//$log.debug('NewUserModalCtrl::getUserAppsRoles: beginning of then for getAdminAppsSimpler');
@@ -123,7 +135,11 @@
app.isErrorUpdating = false;
app.isDoneUpdating = false;
app.errorMessage = "";
- usersService.getUserAppRoles(app.id, this.selectedUser.orgUserId, extRequestValue).promise().then((userAppRolesResult) => {
+ if($scope.selectedvalueradioButtonGroup.type == 'false')
+ {
+ isSystemUser = true;
+ }
+ usersService.getUserAppRoles(app.id, this.selectedUser.orgUserId, extRequestValue,isSystemUser).promise().then((userAppRolesResult) => {
//$log.debug('NewUserModalCtrl::getUserAppsRoles: got a result for app: ',app.id,': ',app.name,': ',userAppRolesResult);
app.appRoles = userAppRolesResult;
app.isLoading = false;
@@ -179,11 +195,18 @@
}
}
+ if($scope.selectedvalueradioButtonGroup.type == 'false')
+ {
+ isSystemUser = true;
+ }else{
+ isSystemUser = false;
+ }
var newUserAppRoles = {
orgUserId: this.selectedUser.orgUserId,
appId: app.id,
appRoles: app.appRoles,
- appName: app.name
+ appName: app.name,
+ isSystemUser : isSystemUser
};
usersService.updateUserAppRoles(newUserAppRoles).promise()
.then(res => {
diff --git a/ecomp-portal-FE-common/client/app/views/users/new-user-dialogs/new-user.modal.html b/ecomp-portal-FE-common/client/app/views/users/new-user-dialogs/new-user.modal.html
index a68cd55c..dc93006e 100644
--- a/ecomp-portal-FE-common/client/app/views/users/new-user-dialogs/new-user.modal.html
+++ b/ecomp-portal-FE-common/client/app/views/users/new-user-dialogs/new-user.modal.html
@@ -55,22 +55,44 @@
<div class="b2b-modal-header">
<h2 class="heading-medium" id="newAdmin">New User</h2>
-
+
<div class="corner-button in">
<button type="button" class="close" aria-label="Close" id="user-button-close"
ng-click="$dismiss('cancel')"></button>
</div>
</div>
-
- <div class="b2b-modal-body" tabindex="0"
+
+ <fieldset style="height: 75px;" role="radiogroup"
+ b2b-radio-group-accessibility aria-labelledby="radiolabel2">
+ <div class="form-row" role="radio"
+ ng-repeat="radioObj in ngRepeatDemo">
+ <label style="margin-top: 10px;" for="{{radioObj.id}}"
+ class="radio"> <input type="radio"
+ ng-model="selectedvalueradioButtonGroup.type"
+ id="{{radioObj.id}}"
+ name="nameradioButton" value="{{radioObj.value}}"> <i
+ style= "margin-top: 10px; margin-left: 38px;" class="skin"></i> <span
+ style="margin-top: 10px; margin-left: 70px;">{{radioObj.labelvalue}}</span>
+ </label>
+ </div>
+ </fieldset>
+ <div class="systemUser" ng-show="selectedvalueradioButtonGroup.type =='false'" style="color: #5a5a5a;
+ font-family: Omnes-ECOMP-W02, Arial;font-size: 14px;margin-bottom: 8px; padding-left: 30px;">Enter system UserId</div>
+ <div ng-show="selectedvalueradioButtonGroup.type =='false'">
+ <input id="action-property-input"
+ class="adminForm-name-property-input" placeholder="xxxxxx@org.com"
+ ng-model="newUser.selectedUser.orgUserId"
+ type="text" maxlength="60" style="padding: 20px;
+ margin-left: 30px; width: 60%;"/>
+ </div>
+ <div class="b2b-modal-body" tabindex="0" ng-show="selectedvalueradioButtonGroup.type =='true'"
aria-label="Modal header text content" role="region">
<search-users search-title="" selected-user="newUser.selectedUser"></search-users>
- </div>
-
+ </div>
<div class="b2b-modal-footer">
<div class="cta-button-group in">
<button class="btn btn-alt btn-small" id="next-button" ng-click="newUser.selectedUser && newUser.getUserAppsRoles()"
- ng-class="{disabled: !newUser.selectedUser}">Next
+ ng-disabled = "(!newUser.selectedUser && selectedvalueradioButtonGroup.type =='true' ) || (selectedvalueradioButtonGroup.type =='false' && !newUser.selectedUser) ||(newUser.selectedUser && newUser.selectedUser.orgUserId.length <1)">Next
</button>
<button id="search-users-button-cancel"
class="btn btn-alt btn-small" ng-click="$dismiss('cancel')">Cancel</button>
@@ -78,7 +100,7 @@
</div>
</div>
- <div ng-if="newUser.dialogState===3">
+ <div ng-if="newUser.dialogState===3" >
<div class="b2b-modal-header">
<div class="title"
diff --git a/ecomp-portal-FE-common/client/bower_components_external/utils/purify.js b/ecomp-portal-FE-common/client/bower_components_external/utils/purify.js
new file mode 100644
index 00000000..8627b977
--- /dev/null
+++ b/ecomp-portal-FE-common/client/bower_components_external/utils/purify.js
@@ -0,0 +1,1131 @@
+(function (global, factory) {
+ typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
+ typeof define === 'function' && define.amd ? define(factory) :
+ (global.DOMPurify = factory());
+}(this, (function () { 'use strict';
+
+var freeze$1 = Object.freeze || function (x) {
+ return x;
+};
+
+var html = freeze$1(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'section', 'select', 'shadow', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']);
+
+// SVG
+var svg = freeze$1(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'audio', 'canvas', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'video', 'view', 'vkern']);
+
+var svgFilters = freeze$1(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']);
+
+var mathMl = freeze$1(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover']);
+
+var text = freeze$1(['#text']);
+
+var freeze$2 = Object.freeze || function (x) {
+ return x;
+};
+
+var html$1 = freeze$2(['accept', 'action', 'align', 'alt', 'autocomplete', 'background', 'bgcolor', 'border', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'coords', 'crossorigin', 'datetime', 'default', 'dir', 'disabled', 'download', 'enctype', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'integrity', 'ismap', 'label', 'lang', 'list', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'multiple', 'name', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'pattern', 'placeholder', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'type', 'usemap', 'valign', 'value', 'width', 'xmlns']);
+
+var svg$1 = freeze$2(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'specularconstant', 'specularexponent', 'spreadmethod', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'tabindex', 'targetx', 'targety', 'transform', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']);
+
+var mathMl$1 = freeze$2(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnsalign', 'columnlines', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lspace', 'lquote', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']);
+
+var xml = freeze$2(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);
+
+var hasOwnProperty = Object.hasOwnProperty;
+var setPrototypeOf = Object.setPrototypeOf;
+
+var _ref$1 = typeof Reflect !== 'undefined' && Reflect;
+var apply$1 = _ref$1.apply;
+
+if (!apply$1) {
+ apply$1 = function apply(fun, thisValue, args) {
+ return fun.apply(thisValue, args);
+ };
+}
+
+/* Add properties to a lookup table */
+function addToSet(set, array) {
+ if (setPrototypeOf) {
+ // Make 'in' and truthy checks like Boolean(set.constructor)
+ // independent of any properties defined on Object.prototype.
+ // Prevent prototype setters from intercepting set as a this value.
+ setPrototypeOf(set, null);
+ }
+ var l = array.length;
+ while (l--) {
+ var element = array[l];
+ if (typeof element === 'string') {
+ var lcElement = element.toLowerCase();
+ if (lcElement !== element) {
+ array[l] = lcElement;
+ element = lcElement;
+ }
+ }
+ set[element] = true;
+ }
+ return set;
+}
+
+/* Shallow clone an object */
+function clone(object) {
+ var newObject = {};
+ var property = void 0;
+ for (property in object) {
+ if (apply$1(hasOwnProperty, object, [property])) {
+ newObject[property] = object[property];
+ }
+ }
+ return newObject;
+}
+
+var seal = Object.seal || function (x) {
+ return x;
+};
+
+var MUSTACHE_EXPR = seal(/\{\{[\s\S]*|[\s\S]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode
+var ERB_EXPR = seal(/<%[\s\S]*|[\s\S]*%>/gm);
+var DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]/); // eslint-disable-line no-useless-escape
+var ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape
+var IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape
+);
+var IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
+var ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205f\u3000]/g // eslint-disable-line no-control-regex
+);
+
+var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
+
+function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+
+var _ref = typeof Reflect !== 'undefined' && Reflect;
+var apply = _ref.apply;
+
+var arraySlice = Array.prototype.slice;
+var freeze = Object.freeze;
+
+var getGlobal = function getGlobal() {
+ return typeof window === 'undefined' ? null : window;
+};
+
+if (!apply) {
+ apply = function apply(fun, thisValue, args) {
+ return fun.apply(thisValue, args);
+ };
+}
+
+/**
+ * Creates a no-op policy for internal use only.
+ * Don't export this function outside this module!
+ * @param {?TrustedTypePolicyFactory} trustedTypes The policy factory.
+ * @param {Document} document The document object (to determine policy name suffix)
+ * @return {?TrustedTypePolicy} The policy created (or null, if Trusted Types
+ * are not supported).
+ */
+var _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, document) {
+ if ((typeof trustedTypes === 'undefined' ? 'undefined' : _typeof(trustedTypes)) !== 'object' || typeof trustedTypes.createPolicy !== 'function') {
+ return null;
+ }
+
+ // Allow the callers to control the unique policy name
+ // by adding a data-tt-policy-suffix to the script element with the DOMPurify.
+ // Policy creation with duplicate names throws in Trusted Types.
+ var suffix = null;
+ var ATTR_NAME = 'data-tt-policy-suffix';
+ if (document.currentScript && document.currentScript.hasAttribute(ATTR_NAME)) {
+ suffix = document.currentScript.getAttribute(ATTR_NAME);
+ }
+
+ var policyName = 'dompurify' + (suffix ? '#' + suffix : '');
+
+ try {
+ return trustedTypes.createPolicy(policyName, {
+ createHTML: function createHTML(html$$1) {
+ return html$$1;
+ }
+ });
+ } catch (e) {
+ // Policy creation failed (most likely another DOMPurify script has
+ // already run). Skip creating the policy, as this will only cause errors
+ // if TT are enforced.
+ console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
+ return null;
+ }
+};
+
+function createDOMPurify() {
+ var window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
+
+ var DOMPurify = function DOMPurify(root) {
+ return createDOMPurify(root);
+ };
+
+ /**
+ * Version label, exposed for easier checks
+ * if DOMPurify is up to date or not
+ */
+ DOMPurify.version = '1.0.8';
+
+ /**
+ * Array of elements that DOMPurify removed during sanitation.
+ * Empty if nothing was removed.
+ */
+ DOMPurify.removed = [];
+
+ if (!window || !window.document || window.document.nodeType !== 9) {
+ // Not running in a browser, provide a factory function
+ // so that you can pass your own Window
+ DOMPurify.isSupported = false;
+
+ return DOMPurify;
+ }
+
+ var originalDocument = window.document;
+ var useDOMParser = false;
+ var removeTitle = false;
+
+ var document = window.document;
+ var DocumentFragment = window.DocumentFragment,
+ HTMLTemplateElement = window.HTMLTemplateElement,
+ Node = window.Node,
+ NodeFilter = window.NodeFilter,
+ _window$NamedNodeMap = window.NamedNodeMap,
+ NamedNodeMap = _window$NamedNodeMap === undefined ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap,
+ Text = window.Text,
+ Comment = window.Comment,
+ DOMParser = window.DOMParser,
+ TrustedTypes = window.TrustedTypes;
+
+ // As per issue #47, the web-components registry is inherited by a
+ // new document created via createHTMLDocument. As per the spec
+ // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
+ // a new empty registry is used when creating a template contents owner
+ // document, so we use that as our parent document to ensure nothing
+ // is inherited.
+
+ if (typeof HTMLTemplateElement === 'function') {
+ var template = document.createElement('template');
+ if (template.content && template.content.ownerDocument) {
+ document = template.content.ownerDocument;
+ }
+ }
+
+ var trustedTypesPolicy = _createTrustedTypesPolicy(TrustedTypes, originalDocument);
+ var emptyHTML = trustedTypesPolicy ? trustedTypesPolicy.createHTML('') : '';
+
+ var _document = document,
+ implementation = _document.implementation,
+ createNodeIterator = _document.createNodeIterator,
+ getElementsByTagName = _document.getElementsByTagName,
+ createDocumentFragment = _document.createDocumentFragment;
+ var importNode = originalDocument.importNode;
+
+
+ var hooks = {};
+
+ /**
+ * Expose whether this browser supports running the full DOMPurify.
+ */
+ DOMPurify.isSupported = implementation && typeof implementation.createHTMLDocument !== 'undefined' && document.documentMode !== 9;
+
+ var MUSTACHE_EXPR$$1 = MUSTACHE_EXPR,
+ ERB_EXPR$$1 = ERB_EXPR,
+ DATA_ATTR$$1 = DATA_ATTR,
+ ARIA_ATTR$$1 = ARIA_ATTR,
+ IS_SCRIPT_OR_DATA$$1 = IS_SCRIPT_OR_DATA,
+ ATTR_WHITESPACE$$1 = ATTR_WHITESPACE;
+ var IS_ALLOWED_URI$$1 = IS_ALLOWED_URI;
+ /**
+ * We consider the elements and attributes below to be safe. Ideally
+ * don't add any new ones but feel free to remove unwanted ones.
+ */
+
+ /* allowed element names */
+
+ var ALLOWED_TAGS = null;
+ var DEFAULT_ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray(html), _toConsumableArray(svg), _toConsumableArray(svgFilters), _toConsumableArray(mathMl), _toConsumableArray(text)));
+
+ /* Allowed attribute names */
+ var ALLOWED_ATTR = null;
+ var DEFAULT_ALLOWED_ATTR = addToSet({}, [].concat(_toConsumableArray(html$1), _toConsumableArray(svg$1), _toConsumableArray(mathMl$1), _toConsumableArray(xml)));
+
+ /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */
+ var FORBID_TAGS = null;
+
+ /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */
+ var FORBID_ATTR = null;
+
+ /* Decide if ARIA attributes are okay */
+ var ALLOW_ARIA_ATTR = true;
+
+ /* Decide if custom data attributes are okay */
+ var ALLOW_DATA_ATTR = true;
+
+ /* Decide if unknown protocols are okay */
+ var ALLOW_UNKNOWN_PROTOCOLS = false;
+
+ /* Output should be safe for jQuery's $() factory? */
+ var SAFE_FOR_JQUERY = false;
+
+ /* Output should be safe for common template engines.
+ * This means, DOMPurify removes data attributes, mustaches and ERB
+ */
+ var SAFE_FOR_TEMPLATES = false;
+
+ /* Decide if document with <html>... should be returned */
+ var WHOLE_DOCUMENT = false;
+
+ /* Track whether config is already set on this instance of DOMPurify. */
+ var SET_CONFIG = false;
+
+ /* Decide if all elements (e.g. style, script) must be children of
+ * document.body. By default, browsers might move them to document.head */
+ var FORCE_BODY = false;
+
+ /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html
+ * string (or a TrustedHTML object if Trusted Types are supported).
+ * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead
+ */
+ var RETURN_DOM = false;
+
+ /* Decide if a DOM `DocumentFragment` should be returned, instead of a html
+ * string (or a TrustedHTML object if Trusted Types are supported) */
+ var RETURN_DOM_FRAGMENT = false;
+
+ /* If `RETURN_DOM` or `RETURN_DOM_FRAGMENT` is enabled, decide if the returned DOM
+ * `Node` is imported into the current `Document`. If this flag is not enabled the
+ * `Node` will belong (its ownerDocument) to a fresh `HTMLDocument`, created by
+ * DOMPurify. */
+ var RETURN_DOM_IMPORT = false;
+
+ /* Output should be free from DOM clobbering attacks? */
+ var SANITIZE_DOM = true;
+
+ /* Keep element content when removing element? */
+ var KEEP_CONTENT = true;
+
+ /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead
+ * of importing it into a new Document and returning a sanitized copy */
+ var IN_PLACE = false;
+
+ /* Allow usage of profiles like html, svg and mathMl */
+ var USE_PROFILES = {};
+
+ /* Tags to ignore content of when KEEP_CONTENT is true */
+ var FORBID_CONTENTS = addToSet({}, ['audio', 'head', 'math', 'script', 'style', 'template', 'svg', 'video']);
+
+ /* Tags that are safe for data: URIs */
+ var DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image']);
+
+ /* Attributes safe for values like "javascript:" */
+ var URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'summary', 'title', 'value', 'style', 'xmlns']);
+
+ /* Keep a reference to config to pass to hooks */
+ var CONFIG = null;
+
+ /* Ideally, do not touch anything below this line */
+ /* ______________________________________________ */
+
+ var formElement = document.createElement('form');
+
+ /**
+ * _parseConfig
+ *
+ * @param {Object} cfg optional config literal
+ */
+ // eslint-disable-next-line complexity
+ var _parseConfig = function _parseConfig(cfg) {
+ if (CONFIG && CONFIG === cfg) {
+ return;
+ }
+
+ /* Shield configuration object from tampering */
+ if (!cfg || (typeof cfg === 'undefined' ? 'undefined' : _typeof(cfg)) !== 'object') {
+ cfg = {};
+ }
+ /* Set configuration parameters */
+ ALLOWED_TAGS = 'ALLOWED_TAGS' in cfg ? addToSet({}, cfg.ALLOWED_TAGS) : DEFAULT_ALLOWED_TAGS;
+ ALLOWED_ATTR = 'ALLOWED_ATTR' in cfg ? addToSet({}, cfg.ALLOWED_ATTR) : DEFAULT_ALLOWED_ATTR;
+ FORBID_TAGS = 'FORBID_TAGS' in cfg ? addToSet({}, cfg.FORBID_TAGS) : {};
+ FORBID_ATTR = 'FORBID_ATTR' in cfg ? addToSet({}, cfg.FORBID_ATTR) : {};
+ USE_PROFILES = 'USE_PROFILES' in cfg ? cfg.USE_PROFILES : false;
+ ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
+ ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
+ ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
+ SAFE_FOR_JQUERY = cfg.SAFE_FOR_JQUERY || false; // Default false
+ SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false
+ WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false
+ RETURN_DOM = cfg.RETURN_DOM || false; // Default false
+ RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false
+ RETURN_DOM_IMPORT = cfg.RETURN_DOM_IMPORT || false; // Default false
+ FORCE_BODY = cfg.FORCE_BODY || false; // Default false
+ SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true
+ KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
+ IN_PLACE = cfg.IN_PLACE || false; // Default false
+
+ IS_ALLOWED_URI$$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI$$1;
+
+ if (SAFE_FOR_TEMPLATES) {
+ ALLOW_DATA_ATTR = false;
+ }
+
+ if (RETURN_DOM_FRAGMENT) {
+ RETURN_DOM = true;
+ }
+
+ /* Parse profile info */
+ if (USE_PROFILES) {
+ ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray(text)));
+ ALLOWED_ATTR = [];
+ if (USE_PROFILES.html === true) {
+ addToSet(ALLOWED_TAGS, html);
+ addToSet(ALLOWED_ATTR, html$1);
+ }
+ if (USE_PROFILES.svg === true) {
+ addToSet(ALLOWED_TAGS, svg);
+ addToSet(ALLOWED_ATTR, svg$1);
+ addToSet(ALLOWED_ATTR, xml);
+ }
+ if (USE_PROFILES.svgFilters === true) {
+ addToSet(ALLOWED_TAGS, svgFilters);
+ addToSet(ALLOWED_ATTR, svg$1);
+ addToSet(ALLOWED_ATTR, xml);
+ }
+ if (USE_PROFILES.mathMl === true) {
+ addToSet(ALLOWED_TAGS, mathMl);
+ addToSet(ALLOWED_ATTR, mathMl$1);
+ addToSet(ALLOWED_ATTR, xml);
+ }
+ }
+
+ /* Merge configuration parameters */
+ if (cfg.ADD_TAGS) {
+ if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
+ ALLOWED_TAGS = clone(ALLOWED_TAGS);
+ }
+ addToSet(ALLOWED_TAGS, cfg.ADD_TAGS);
+ }
+ if (cfg.ADD_ATTR) {
+ if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
+ ALLOWED_ATTR = clone(ALLOWED_ATTR);
+ }
+ addToSet(ALLOWED_ATTR, cfg.ADD_ATTR);
+ }
+ if (cfg.ADD_URI_SAFE_ATTR) {
+ addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR);
+ }
+
+ /* Add #text in case KEEP_CONTENT is set to true */
+ if (KEEP_CONTENT) {
+ ALLOWED_TAGS['#text'] = true;
+ }
+
+ /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */
+ if (WHOLE_DOCUMENT) {
+ addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);
+ }
+
+ /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286 */
+ if (ALLOWED_TAGS.table) {
+ addToSet(ALLOWED_TAGS, ['tbody']);
+ }
+
+ // Prevent further manipulation of configuration.
+ // Not available in IE8, Safari 5, etc.
+ if (freeze) {
+ freeze(cfg);
+ }
+
+ CONFIG = cfg;
+ };
+
+ /**
+ * _forceRemove
+ *
+ * @param {Node} node a DOM node
+ */
+ var _forceRemove = function _forceRemove(node) {
+ DOMPurify.removed.push({ element: node });
+ try {
+ node.parentNode.removeChild(node);
+ } catch (err) {
+ node.outerHTML = emptyHTML;
+ }
+ };
+
+ /**
+ * _removeAttribute
+ *
+ * @param {String} name an Attribute name
+ * @param {Node} node a DOM node
+ */
+ var _removeAttribute = function _removeAttribute(name, node) {
+ try {
+ DOMPurify.removed.push({
+ attribute: node.getAttributeNode(name),
+ from: node
+ });
+ } catch (err) {
+ DOMPurify.removed.push({
+ attribute: null,
+ from: node
+ });
+ }
+ node.removeAttribute(name);
+ };
+
+ /**
+ * _initDocument
+ *
+ * @param {String} dirty a string of dirty markup
+ * @return {Document} a DOM, filled with the dirty markup
+ */
+ var _initDocument = function _initDocument(dirty) {
+ /* Create a HTML document */
+ var doc = void 0;
+ var leadingWhitespace = void 0;
+
+ if (FORCE_BODY) {
+ dirty = '<remove></remove>' + dirty;
+ } else {
+ /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */
+ var matches = dirty.match(/^[\s]+/);
+ leadingWhitespace = matches && matches[0];
+ if (leadingWhitespace) {
+ dirty = dirty.slice(leadingWhitespace.length);
+ }
+ }
+
+ /* Use DOMParser to workaround Firefox bug (see comment below) */
+ if (useDOMParser) {
+ try {
+ doc = new DOMParser().parseFromString(dirty, 'text/html');
+ } catch (err) {}
+ }
+
+ /* Remove title to fix a mXSS bug in older MS Edge */
+ if (removeTitle) {
+ addToSet(FORBID_TAGS, ['title']);
+ }
+
+ /* Otherwise use createHTMLDocument, because DOMParser is unsafe in
+ Safari (see comment below) */
+ if (!doc || !doc.documentElement) {
+ doc = implementation.createHTMLDocument('');
+ var _doc = doc,
+ body = _doc.body;
+
+ body.parentNode.removeChild(body.parentNode.firstElementChild);
+ body.outerHTML = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
+ }
+
+ if (leadingWhitespace) {
+ doc.body.insertBefore(document.createTextNode(leadingWhitespace), doc.body.childNodes[0] || null);
+ }
+
+ /* Work on whole document or just its body */
+ return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];
+ };
+
+ // Firefox uses a different parser for innerHTML rather than
+ // DOMParser (see https://bugzilla.mozilla.org/show_bug.cgi?id=1205631)
+ // which means that you *must* use DOMParser, otherwise the output may
+ // not be safe if used in a document.write context later.
+ //
+ // So we feature detect the Firefox bug and use the DOMParser if necessary.
+ //
+ // MS Edge, in older versions, is affected by an mXSS behavior. The second
+ // check tests for the behavior and fixes it if necessary.
+ if (DOMPurify.isSupported) {
+ (function () {
+ try {
+ var doc = _initDocument('<svg><p><style><img src="</style><img src=x onerror=alert(1)//">');
+ if (doc.querySelector('svg img')) {
+ useDOMParser = true;
+ }
+ } catch (err) {}
+ })();
+ (function () {
+ try {
+ var doc = _initDocument('<x/><title>&lt;/title&gt;&lt;img&gt;');
+ if (doc.querySelector('title').innerHTML.match(/<\/title/)) {
+ removeTitle = true;
+ }
+ } catch (err) {}
+ })();
+ }
+
+ /**
+ * _createIterator
+ *
+ * @param {Document} root document/fragment to create iterator for
+ * @return {Iterator} iterator instance
+ */
+ var _createIterator = function _createIterator(root) {
+ return createNodeIterator.call(root.ownerDocument || root, root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT, function () {
+ return NodeFilter.FILTER_ACCEPT;
+ }, false);
+ };
+
+ /**
+ * _isClobbered
+ *
+ * @param {Node} elm element to check for clobbering attacks
+ * @return {Boolean} true if clobbered, false if safe
+ */
+ var _isClobbered = function _isClobbered(elm) {
+ if (elm instanceof Text || elm instanceof Comment) {
+ return false;
+ }
+ if (typeof elm.nodeName !== 'string' || typeof elm.textContent !== 'string' || typeof elm.removeChild !== 'function' || !(elm.attributes instanceof NamedNodeMap) || typeof elm.removeAttribute !== 'function' || typeof elm.setAttribute !== 'function') {
+ return true;
+ }
+ return false;
+ };
+
+ /**
+ * _isNode
+ *
+ * @param {Node} obj object to check whether it's a DOM node
+ * @return {Boolean} true is object is a DOM node
+ */
+ var _isNode = function _isNode(obj) {
+ return (typeof Node === 'undefined' ? 'undefined' : _typeof(Node)) === 'object' ? obj instanceof Node : obj && (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' && typeof obj.nodeType === 'number' && typeof obj.nodeName === 'string';
+ };
+
+ /**
+ * _executeHook
+ * Execute user configurable hooks
+ *
+ * @param {String} entryPoint Name of the hook's entry point
+ * @param {Node} currentNode node to work on with the hook
+ * @param {Object} data additional hook parameters
+ */
+ var _executeHook = function _executeHook(entryPoint, currentNode, data) {
+ if (!hooks[entryPoint]) {
+ return;
+ }
+
+ hooks[entryPoint].forEach(function (hook) {
+ hook.call(DOMPurify, currentNode, data, CONFIG);
+ });
+ };
+
+ /**
+ * _sanitizeElements
+ *
+ * @protect nodeName
+ * @protect textContent
+ * @protect removeChild
+ *
+ * @param {Node} currentNode to check for permission to exist
+ * @return {Boolean} true if node was killed, false if left alive
+ */
+ var _sanitizeElements = function _sanitizeElements(currentNode) {
+ var content = void 0;
+
+ /* Execute a hook if present */
+ _executeHook('beforeSanitizeElements', currentNode, null);
+
+ /* Check if element is clobbered or can clobber */
+ if (_isClobbered(currentNode)) {
+ _forceRemove(currentNode);
+ return true;
+ }
+
+ /* Now let's check the element's type and name */
+ var tagName = currentNode.nodeName.toLowerCase();
+
+ /* Execute a hook if present */
+ _executeHook('uponSanitizeElement', currentNode, {
+ tagName: tagName,
+ allowedTags: ALLOWED_TAGS
+ });
+
+ /* Remove element if anything forbids its presence */
+ if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
+ /* Keep content except for black-listed elements */
+ if (KEEP_CONTENT && !FORBID_CONTENTS[tagName] && typeof currentNode.insertAdjacentHTML === 'function') {
+ try {
+ var htmlToInsert = currentNode.innerHTML;
+ currentNode.insertAdjacentHTML('AfterEnd', trustedTypesPolicy ? trustedTypesPolicy.createHTML(htmlToInsert) : htmlToInsert);
+ } catch (err) {}
+ }
+ _forceRemove(currentNode);
+ return true;
+ }
+
+ /* Convert markup to cover jQuery behavior */
+ if (SAFE_FOR_JQUERY && !currentNode.firstElementChild && (!currentNode.content || !currentNode.content.firstElementChild) && /</g.test(currentNode.textContent)) {
+ DOMPurify.removed.push({ element: currentNode.cloneNode() });
+ if (currentNode.innerHTML) {
+ currentNode.innerHTML = currentNode.innerHTML.replace(/</g, '&lt;');
+ } else {
+ currentNode.innerHTML = currentNode.textContent.replace(/</g, '&lt;');
+ }
+ }
+
+ /* Sanitize element content to be template-safe */
+ if (SAFE_FOR_TEMPLATES && currentNode.nodeType === 3) {
+ /* Get the element's text content */
+ content = currentNode.textContent;
+ content = content.replace(MUSTACHE_EXPR$$1, ' ');
+ content = content.replace(ERB_EXPR$$1, ' ');
+ if (currentNode.textContent !== content) {
+ DOMPurify.removed.push({ element: currentNode.cloneNode() });
+ currentNode.textContent = content;
+ }
+ }
+
+ /* Execute a hook if present */
+ _executeHook('afterSanitizeElements', currentNode, null);
+
+ return false;
+ };
+
+ /**
+ * _isValidAttribute
+ *
+ * @param {string} lcTag Lowercase tag name of containing element.
+ * @param {string} lcName Lowercase attribute name.
+ * @param {string} value Attribute value.
+ * @return {Boolean} Returns true if `value` is valid, otherwise false.
+ */
+ var _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
+ /* Make sure attribute cannot clobber */
+ if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
+ return false;
+ }
+
+ /* Sanitize attribute content to be template-safe */
+ if (SAFE_FOR_TEMPLATES) {
+ value = value.replace(MUSTACHE_EXPR$$1, ' ');
+ value = value.replace(ERB_EXPR$$1, ' ');
+ }
+
+ /* Allow valid data-* attributes: At least one character after "-"
+ (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
+ XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
+ We don't need to check the value; it's always URI safe. */
+ if (ALLOW_DATA_ATTR && DATA_ATTR$$1.test(lcName)) {
+ // This attribute is safe
+ } else if (ALLOW_ARIA_ATTR && ARIA_ATTR$$1.test(lcName)) {
+ // This attribute is safe
+ /* Otherwise, check the name is permitted */
+ } else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
+ return false;
+
+ /* Check value is safe. First, is attr inert? If so, is safe */
+ } else if (URI_SAFE_ATTRIBUTES[lcName]) {
+ // This attribute is safe
+ /* Check no script, data or unknown possibly unsafe URI
+ unless we know URI values are safe for that attribute */
+ } else if (IS_ALLOWED_URI$$1.test(value.replace(ATTR_WHITESPACE$$1, ''))) {
+ // This attribute is safe
+ /* Keep image data URIs alive if src/xlink:href is allowed */
+ /* Further prevent gadget XSS for dynamically built script tags */
+ } else if ((lcName === 'src' || lcName === 'xlink:href') && lcTag !== 'script' && value.indexOf('data:') === 0 && DATA_URI_TAGS[lcTag]) {
+ // This attribute is safe
+ /* Allow unknown protocols: This provides support for links that
+ are handled by protocol handlers which may be unknown ahead of
+ time, e.g. fb:, spotify: */
+ } else if (ALLOW_UNKNOWN_PROTOCOLS && !IS_SCRIPT_OR_DATA$$1.test(value.replace(ATTR_WHITESPACE$$1, ''))) {
+ // This attribute is safe
+ /* Check for binary attributes */
+ // eslint-disable-next-line no-negated-condition
+ } else if (!value) {
+ // Binary attributes are safe at this point
+ /* Anything else, presume unsafe, do not add it back */
+ } else {
+ return false;
+ }
+ return true;
+ };
+
+ /**
+ * _sanitizeAttributes
+ *
+ * @protect attributes
+ * @protect nodeName
+ * @protect removeAttribute
+ * @protect setAttribute
+ *
+ * @param {Node} node to sanitize
+ */
+ // eslint-disable-next-line complexity
+ var _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
+ var attr = void 0;
+ var value = void 0;
+ var lcName = void 0;
+ var idAttr = void 0;
+ var l = void 0;
+ /* Execute a hook if present */
+ _executeHook('beforeSanitizeAttributes', currentNode, null);
+
+ var attributes = currentNode.attributes;
+
+ /* Check if we have attributes; if not we might have a text node */
+
+ if (!attributes) {
+ return;
+ }
+
+ var hookEvent = {
+ attrName: '',
+ attrValue: '',
+ keepAttr: true,
+ allowedAttributes: ALLOWED_ATTR
+ };
+ l = attributes.length;
+
+ /* Go backwards over all attributes; safely remove bad ones */
+ while (l--) {
+ attr = attributes[l];
+ var _attr = attr,
+ name = _attr.name,
+ namespaceURI = _attr.namespaceURI;
+
+ value = attr.value.trim();
+ lcName = name.toLowerCase();
+
+ /* Execute a hook if present */
+ hookEvent.attrName = lcName;
+ hookEvent.attrValue = value;
+ hookEvent.keepAttr = true;
+ _executeHook('uponSanitizeAttribute', currentNode, hookEvent);
+ value = hookEvent.attrValue;
+
+ /* Remove attribute */
+ // Safari (iOS + Mac), last tested v8.0.5, crashes if you try to
+ // remove a "name" attribute from an <img> tag that has an "id"
+ // attribute at the time.
+ if (lcName === 'name' && currentNode.nodeName === 'IMG' && attributes.id) {
+ idAttr = attributes.id;
+ attributes = apply(arraySlice, attributes, []);
+ _removeAttribute('id', currentNode);
+ _removeAttribute(name, currentNode);
+ if (attributes.indexOf(idAttr) > l) {
+ currentNode.setAttribute('id', idAttr.value);
+ }
+ } else if (
+ // This works around a bug in Safari, where input[type=file]
+ // cannot be dynamically set after type has been removed
+ currentNode.nodeName === 'INPUT' && lcName === 'type' && value === 'file' && (ALLOWED_ATTR[lcName] || !FORBID_ATTR[lcName])) {
+ continue;
+ } else {
+ // This avoids a crash in Safari v9.0 with double-ids.
+ // The trick is to first set the id to be empty and then to
+ // remove the attribute
+ if (name === 'id') {
+ currentNode.setAttribute(name, '');
+ }
+ _removeAttribute(name, currentNode);
+ }
+
+ /* Did the hooks approve of the attribute? */
+ if (!hookEvent.keepAttr) {
+ continue;
+ }
+
+ /* Is `value` valid for this attribute? */
+ var lcTag = currentNode.nodeName.toLowerCase();
+ if (!_isValidAttribute(lcTag, lcName, value)) {
+ continue;
+ }
+
+ /* Handle invalid data-* attribute set by try-catching it */
+ try {
+ if (namespaceURI) {
+ currentNode.setAttributeNS(namespaceURI, name, value);
+ } else {
+ /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
+ currentNode.setAttribute(name, value);
+ }
+ DOMPurify.removed.pop();
+ } catch (err) {}
+ }
+
+ /* Execute a hook if present */
+ _executeHook('afterSanitizeAttributes', currentNode, null);
+ };
+
+ /**
+ * _sanitizeShadowDOM
+ *
+ * @param {DocumentFragment} fragment to iterate over recursively
+ */
+ var _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) {
+ var shadowNode = void 0;
+ var shadowIterator = _createIterator(fragment);
+
+ /* Execute a hook if present */
+ _executeHook('beforeSanitizeShadowDOM', fragment, null);
+
+ while (shadowNode = shadowIterator.nextNode()) {
+ /* Execute a hook if present */
+ _executeHook('uponSanitizeShadowNode', shadowNode, null);
+
+ /* Sanitize tags and elements */
+ if (_sanitizeElements(shadowNode)) {
+ continue;
+ }
+
+ /* Deep shadow DOM detected */
+ if (shadowNode.content instanceof DocumentFragment) {
+ _sanitizeShadowDOM(shadowNode.content);
+ }
+
+ /* Check attributes, sanitize if necessary */
+ _sanitizeAttributes(shadowNode);
+ }
+
+ /* Execute a hook if present */
+ _executeHook('afterSanitizeShadowDOM', fragment, null);
+ };
+
+ /**
+ * Sanitize
+ * Public method providing core sanitation functionality
+ *
+ * @param {String|Node} dirty string or DOM node
+ * @param {Object} configuration object
+ */
+ // eslint-disable-next-line complexity
+ DOMPurify.sanitize = function (dirty, cfg) {
+ var body = void 0;
+ var importedNode = void 0;
+ var currentNode = void 0;
+ var oldNode = void 0;
+ var returnNode = void 0;
+ /* Make sure we have a string to sanitize.
+ DO NOT return early, as this will return the wrong type if
+ the user has requested a DOM object rather than a string */
+ if (!dirty) {
+ dirty = '<!-->';
+ }
+
+ /* Stringify, in case dirty is an object */
+ if (typeof dirty !== 'string' && !_isNode(dirty)) {
+ // eslint-disable-next-line no-negated-condition
+ if (typeof dirty.toString !== 'function') {
+ throw new TypeError('toString is not a function');
+ } else {
+ dirty = dirty.toString();
+ if (typeof dirty !== 'string') {
+ throw new TypeError('dirty is not a string, aborting');
+ }
+ }
+ }
+
+ /* Check we can run. Otherwise fall back or ignore */
+ if (!DOMPurify.isSupported) {
+ if (_typeof(window.toStaticHTML) === 'object' || typeof window.toStaticHTML === 'function') {
+ if (typeof dirty === 'string') {
+ return window.toStaticHTML(dirty);
+ }
+ if (_isNode(dirty)) {
+ return window.toStaticHTML(dirty.outerHTML);
+ }
+ }
+ return dirty;
+ }
+
+ /* Assign config vars */
+ if (!SET_CONFIG) {
+ _parseConfig(cfg);
+ }
+
+ /* Clean up removed elements */
+ DOMPurify.removed = [];
+
+ if (IN_PLACE) {
+ /* No special handling necessary for in-place sanitization */
+ } else if (dirty instanceof Node) {
+ /* If dirty is a DOM element, append to an empty document to avoid
+ elements being stripped by the parser */
+ body = _initDocument('<!-->');
+ importedNode = body.ownerDocument.importNode(dirty, true);
+ if (importedNode.nodeType === 1 && importedNode.nodeName === 'BODY') {
+ /* Node is already a body, use as is */
+ body = importedNode;
+ } else {
+ body.appendChild(importedNode);
+ }
+ } else {
+ /* Exit directly if we have nothing to do */
+ if (!RETURN_DOM && !WHOLE_DOCUMENT && dirty.indexOf('<') === -1) {
+ return trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
+ }
+
+ /* Initialize the document to work on */
+ body = _initDocument(dirty);
+
+ /* Check we have a DOM node from the data */
+ if (!body) {
+ return RETURN_DOM ? null : emptyHTML;
+ }
+ }
+
+ /* Remove first element node (ours) if FORCE_BODY is set */
+ if (body && FORCE_BODY) {
+ _forceRemove(body.firstChild);
+ }
+
+ /* Get node iterator */
+ var nodeIterator = _createIterator(IN_PLACE ? dirty : body);
+
+ /* Now start iterating over the created document */
+ while (currentNode = nodeIterator.nextNode()) {
+ /* Fix IE's strange behavior with manipulated textNodes #89 */
+ if (currentNode.nodeType === 3 && currentNode === oldNode) {
+ continue;
+ }
+
+ /* Sanitize tags and elements */
+ if (_sanitizeElements(currentNode)) {
+ continue;
+ }
+
+ /* Shadow DOM detected, sanitize it */
+ if (currentNode.content instanceof DocumentFragment) {
+ _sanitizeShadowDOM(currentNode.content);
+ }
+
+ /* Check attributes, sanitize if necessary */
+ _sanitizeAttributes(currentNode);
+
+ oldNode = currentNode;
+ }
+
+ oldNode = null;
+
+ /* If we sanitized `dirty` in-place, return it. */
+ if (IN_PLACE) {
+ return dirty;
+ }
+
+ /* Return sanitized string or DOM */
+ if (RETURN_DOM) {
+ if (RETURN_DOM_FRAGMENT) {
+ returnNode = createDocumentFragment.call(body.ownerDocument);
+
+ while (body.firstChild) {
+ returnNode.appendChild(body.firstChild);
+ }
+ } else {
+ returnNode = body;
+ }
+
+ if (RETURN_DOM_IMPORT) {
+ /* AdoptNode() is not used because internal state is not reset
+ (e.g. the past names map of a HTMLFormElement), this is safe
+ in theory but we would rather not risk another attack vector.
+ The state that is cloned by importNode() is explicitly defined
+ by the specs. */
+ returnNode = importNode.call(originalDocument, returnNode, true);
+ }
+
+ return returnNode;
+ }
+
+ var serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
+ return trustedTypesPolicy ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
+ };
+
+ /**
+ * Public method to set the configuration once
+ * setConfig
+ *
+ * @param {Object} cfg configuration object
+ */
+ DOMPurify.setConfig = function (cfg) {
+ _parseConfig(cfg);
+ SET_CONFIG = true;
+ };
+
+ /**
+ * Public method to remove the configuration
+ * clearConfig
+ *
+ */
+ DOMPurify.clearConfig = function () {
+ CONFIG = null;
+ SET_CONFIG = false;
+ };
+
+ /**
+ * Public method to check if an attribute value is valid.
+ * Uses last set config, if any. Otherwise, uses config defaults.
+ * isValidAttribute
+ *
+ * @param {string} tag Tag name of containing element.
+ * @param {string} attr Attribute name.
+ * @param {string} value Attribute value.
+ * @return {Boolean} Returns true if `value` is valid. Otherwise, returns false.
+ */
+ DOMPurify.isValidAttribute = function (tag, attr, value) {
+ /* Initialize shared config vars if necessary. */
+ if (!CONFIG) {
+ _parseConfig({});
+ }
+ var lcTag = tag.toLowerCase();
+ var lcName = attr.toLowerCase();
+ return _isValidAttribute(lcTag, lcName, value);
+ };
+
+ /**
+ * AddHook
+ * Public method to add DOMPurify hooks
+ *
+ * @param {String} entryPoint entry point for the hook to add
+ * @param {Function} hookFunction function to execute
+ */
+ DOMPurify.addHook = function (entryPoint, hookFunction) {
+ if (typeof hookFunction !== 'function') {
+ return;
+ }
+ hooks[entryPoint] = hooks[entryPoint] || [];
+ hooks[entryPoint].push(hookFunction);
+ };
+
+ /**
+ * RemoveHook
+ * Public method to remove a DOMPurify hook at a given entryPoint
+ * (pops it from the stack of hooks if more are present)
+ *
+ * @param {String} entryPoint entry point for the hook to remove
+ */
+ DOMPurify.removeHook = function (entryPoint) {
+ if (hooks[entryPoint]) {
+ hooks[entryPoint].pop();
+ }
+ };
+
+ /**
+ * RemoveHooks
+ * Public method to remove all DOMPurify hooks at a given entryPoint
+ *
+ * @param {String} entryPoint entry point for the hooks to remove
+ */
+ DOMPurify.removeHooks = function (entryPoint) {
+ if (hooks[entryPoint]) {
+ hooks[entryPoint] = [];
+ }
+ };
+
+ /**
+ * RemoveAllHooks
+ * Public method to remove all DOMPurify hooks
+ *
+ */
+ DOMPurify.removeAllHooks = function () {
+ hooks = {};
+ };
+
+ return DOMPurify;
+}
+
+var purify = createDOMPurify();
+
+return purify;
+
+})));
+//# sourceMappingURL=purify.js.map \ No newline at end of file
diff --git a/ecomp-portal-FE-os/client/configurations/dev.json b/ecomp-portal-FE-os/client/configurations/dev.json
index c60e9bcd..78e3a205 100644
--- a/ecomp-portal-FE-os/client/configurations/dev.json
+++ b/ecomp-portal-FE-os/client/configurations/dev.json
@@ -98,7 +98,11 @@
"loggedinUser" : "http://localhost:8080/ecompportal/portalApi/loggedinUser",
"modifyLoggedinUser" : "http://localhost:8080/ecompportal/portalApi/modifyLoggedinUser",
"centralizedApps": "http://localhost:8080/ecompportal/portalApi/centralizedApps",
- "uploadRoleFunction":"http://localhost:8080/ecompportal/portalApi/uploadRoleFunction/:appId"
+ "uploadRoleFunction":"http://localhost:8080/ecompportal/portalApi/uploadRoleFunction/:appId",
+ "checkIfUserIsSuperAdmin":"http://localhost:8080/ecompportal/portalApi/checkIfUserIsSuperAdmin",
+ "getCurrentLang": "http://localhost:8080/ecompportal/auxapi/languageSetting/user/:loginId",
+ "getLanguages": "http://localhost:8080/ecompportal/auxapi/language",
+ "updateLang": "http://localhost:8080/ecompportal/auxapi/languageSetting/user/:loginId"
},
"cookieDomain": "onap.org"
}
diff --git a/ecomp-portal-FE-os/client/configurations/integ.json b/ecomp-portal-FE-os/client/configurations/integ.json
index 4771d635..b0181f8c 100644
--- a/ecomp-portal-FE-os/client/configurations/integ.json
+++ b/ecomp-portal-FE-os/client/configurations/integ.json
@@ -99,6 +99,7 @@
"modifyLoggedinUser" : "portalApi/modifyLoggedinUser",
"centralizedApps": "portalApi/centralizedApps",
"uploadRoleFunction":"portalApi/uploadRoleFunction/:appId",
+ "checkIfUserIsSuperAdmin":"portalApi/checkIfUserIsSuperAdmin",
"getCurrentLang":"auxapi/languageSetting/user/:loginId",
"getLanguages":"auxapi/language",
"updateLang":"auxapi/languageSetting/user/:loginId"
diff --git a/ecomp-portal-FE-os/client/index.html b/ecomp-portal-FE-os/client/index.html
index 648174e4..7a46d598 100644
--- a/ecomp-portal-FE-os/client/index.html
+++ b/ecomp-portal-FE-os/client/index.html
@@ -291,7 +291,6 @@
<script src="app/views/notification-history/notificationhistory.controller.js"></script>
<script src="app/views/portal-admin/new-portal-admin/new-portal-admin.controller.js"></script>
<script src="app/views/portal-admin/portal-admin-controller.js"></script>
- <script src="app/views/role/bulk-upload-dialogs/bulk-upload-role-functions-controller.js"></script>
<script src="app/views/role/role-controller.js"></script>
<script src="app/views/role/role-create-edit-popup-controller.js"></script>
<script src="app/views/role/role-function-list-controller.js"></script>
diff --git a/ecomp-portal-FE-os/client/src/views/applications/application-details-dialog/application-details.controller.js b/ecomp-portal-FE-os/client/src/views/applications/application-details-dialog/application-details.controller.js
index efd5165a..d89af17c 100644
--- a/ecomp-portal-FE-os/client/src/views/applications/application-details-dialog/application-details.controller.js
+++ b/ecomp-portal-FE-os/client/src/views/applications/application-details-dialog/application-details.controller.js
@@ -58,7 +58,7 @@
'username': null,
'appPassword': null,
'thumbnail': emptyImg,
- 'isEnabled': true,
+ 'isEnabled': false,
'restrictedApp': false,
'nameSpace': null,
'isCentralAuth': false
@@ -172,26 +172,44 @@
//***************************
this.saveChanges = () => {
- //if valid..
+ //if valid..
if(this.app.isCentralAuth){
- //if valid..
- if(((angular.isUndefined(this.app.myLoginsAppName) || !this.app.myLoginsAppName)&&(angular.isUndefined(this.app.myLoginsAppOwner) || !this.app.myLoginsAppOwner)&&(angular.isUndefined(this.app.name) || !this.app.name)&&(angular.isUndefined(this.app.url) || !this.app.url)
- &&(angular.isUndefined(this.app.username) || !this.app.username))) {
- confirmBoxService.showInformation('Please fill in all required fields').then(isConfirmed => {});
- return;
- }else if(!((angular.isUndefined(this.app.name) || !!this.app.name)&&(angular.isUndefined(this.app.url) || !!this.app.url))){
- confirmBoxService.showInformation('Please fill in all required fields').then(isConfirmed => {});
- return;
- }
+ //if valid.
+ if(!this.app.isEnabled)
+ {
+ if(((angular.isUndefined(this.app.name) || !this.app.name)||(angular.isUndefined(this.app.nameSpace) || !this.app.nameSpace)
+ ||(angular.isUndefined(this.app.username) || !this.app.username))) {
+ confirmBoxService.showInformation('Please fill in all required fields for centralized application').then(isConfirmed => {});
+ return;
+ }
+ }
+ if(this.app.isEnabled){
+ if(((angular.isUndefined(this.app.myLoginsAppName) || !this.app.myLoginsAppName)||(angular.isUndefined(this.app.myLoginsAppOwner) || !this.app.myLoginsAppOwner)||(angular.isUndefined(this.app.name) || !this.app.name)||(angular.isUndefined(this.app.url) || !this.app.url)
+ ||(angular.isUndefined(this.app.username) || !this.app.username)||(angular.isUndefined(this.app.nameSpace) || !this.app.nameSpace))) {
+ confirmBoxService.showInformation('Please fill in all required fields for centralized active application').then(isConfirmed => {});
+ return;
+ }
+ }
}else{
- if(((angular.isUndefined(this.app.myLoginsAppName) || !this.app.myLoginsAppName)||(angular.isUndefined(this.app.myLoginsAppOwner) || !this.app.myLoginsAppOwner)||(angular.isUndefined(this.app.name) || !this.app.name)||(angular.isUndefined(this.app.url) || !this.app.url)
+
+ if(!this.app.isEnabled)
+ {
+ if((angular.isUndefined(this.app.name) || !this.app.name)){
+ confirmBoxService.showInformation('Please fill in all required field ApplicationName to Save the applictaion').then(isConfirmed => {});
+ return;
+ }
+ }else if(this.app.isEnabled && !this.app.restrictedApp){
+ if(((angular.isUndefined(this.app.myLoginsAppName) || !this.app.myLoginsAppName)||(angular.isUndefined(this.app.myLoginsAppOwner) || !this.app.myLoginsAppOwner)||(angular.isUndefined(this.app.name) || !this.app.name)||(angular.isUndefined(this.app.url) || !this.app.url)
||(angular.isUndefined(this.app.username) || !this.app.username)||(angular.isUndefined(this.app.appPassword) || !this.app.appPassword))) {
- confirmBoxService.showInformation('Please fill in all required fields along with password as the app is not centralized').then(isConfirmed => {});
- return;
- }else if(!((angular.isUndefined(this.app.name) || !!this.app.name)&&(angular.isUndefined(this.app.url) || !!this.app.url))){
- confirmBoxService.showInformation('Please fill in all required fields').then(isConfirmed => {});
+ confirmBoxService.showInformation('Please fill in all required fields along with password as the app is not centralized').then(isConfirmed => {});
+ return;
+ } }else if(this.app.isEnabled && this.app.restrictedApp){
+ if((angular.isUndefined(this.app.name) || !this.app.name) ||(angular.isUndefined(this.app.url) || !this.app.url)){
+ confirmBoxService.showInformation('Please fill in all required fields').then(isConfirmed => {});
return;
+
}
+ }
}
this.isSaving = true;
// For a restricted app, null out all irrelevant fields
diff --git a/ecomp-portal-FE-os/client/src/views/applications/application-details-dialog/application-details.modal.html b/ecomp-portal-FE-os/client/src/views/applications/application-details-dialog/application-details.modal.html
index b4251f15..780a974b 100644
--- a/ecomp-portal-FE-os/client/src/views/applications/application-details-dialog/application-details.modal.html
+++ b/ecomp-portal-FE-os/client/src/views/applications/application-details-dialog/application-details.modal.html
@@ -35,6 +35,16 @@
-->
+<style>
+.mandatoryFeild
+ {
+ color: Red;
+ margin-right: 2px;
+ position: absolute;
+ left: -10px;top: 28px;
+
+ }
+</style>
<div class="b2b-modal-header">
<h2 class="account-details-title" id="application-details-title">Application
@@ -48,14 +58,16 @@
<div class="application-details-modal">
<div class="app-properties-main" scroll-top="appDetails.scrollApi">
<form name="appForm" novalidate autocomplete="off">
+
<div id="app-left-container" class="left-container">
<div class="property-label checkbox-label">
<label for="checkbox-app-is-restricted" class="checkbox">
<input type="checkbox" ng-model="appDetails.app.restrictedApp"
id="checkbox-app-is-restricted"
ng-disabled="appDetails.isEditMode"
- ng-checked="appDetails.app.restrictedApp" /> <i class="skin"></i>
- <span>Hyperlink only application</span>
+ ng-checked="appDetails.app.restrictedApp" /> <i
+ id="checkbox-app-is-restricted" class="skin"></i> <span>Hyperlink
+ only application</span>
</label>
</div>
<div class="property required">
@@ -81,11 +93,14 @@
</div>
</div>
</div>
- <div class="property required">
+ <div class="property">
<div id="url-property-label" class="property-label">URL</div>
- <input id="input-app-url" ng-model="appDetails.app.url"
+ <span runat="server" ID="required" class="mandatoryFeild"
+ visible="false" ng-show="appDetails.app.isEnabled"> *</span><input id="input-app-url" ng-model="appDetails.app.url"
maxlength="256" name="url" type="url" placeholder="https://"
ng-pattern="appDetails.ECOMP_URL_REGEX" required />
+
+
<div id="app-error-url" class="error-container"
ng-show="appDetails.conflictMessages.url"
id="div-app-name-err-url">
@@ -107,9 +122,10 @@
</div>
- <div class="property required" ng-show="!appDetails.app.restrictedApp">
+ <div class="property" ng-show="!appDetails.app.restrictedApp">
<div class="property-label">Rest API URL</div>
- <input id="input-app-rest-url" ng-model="appDetails.app.restUrl"
+ <span runat="server" ID="required" class="mandatoryFiled"
+ visible="false" ng-show="appDetails.app.isEnabled"> *</span><input id="input-app-rest-url" ng-model="appDetails.app.restUrl"
name="restUrl" type="url" placeholder="https://"
ng-pattern="appDetails.ECOMP_URL_REGEX" maxlength="256"
ng-required="!appDetails.app.restrictedApp" />
@@ -122,18 +138,19 @@
</div>
</div>
- <div class="property required"
+ <div class="property"
ng-show="!appDetails.app.restrictedApp">
<div id="username-property-label" class="property-label">Username</div>
- <input type="text" ng-model="appDetails.app.username"
- name="username" maxlength="256"
- ng-required="!appDetails.app.restrictedApp" />
+ <span runat="server" ID="required" class="mandatoryFiled"
+ visible="false" ng-show="appDetails.app.isCentralAuth || appDetails.app.isEnabled"> *</span><input type="text" id="input-username-property"
+ ng-model="appDetails.app.username" name="username"
+ maxlength="256" ng-required="!appDetails.app.restrictedApp" />
<div id="app-error-username-container" class="error-container"
ng-show="appForm.username.$dirty || appDetails.isEditMode">
<div ng-messages="appForm.username.$error"
class="error-container">
<small id="error-appusername-reqd" class="err-message"
- ng-message="required">My Logins App Username is
+ ng-message="required">App Username is
required</small>
</div>
</div>
@@ -161,32 +178,21 @@
ng-model="appDetails.app.appPassword" autocomplete="new-password"
name="appPassword" maxlength="256"/>
</div>
- <div class="property" ng-show="!appDetails.app.restrictedApp">
- <div id="pwd-property-label" class="property-label">Name
- Space</div>
- <input type="text" id="input-mylogins-auth-namespace"
- ng-model="appDetails.app.nameSpace" name="appAuthNameSpace"
- maxlength="256" />
- </div>
+
+
</div>
<div class="right-container">
<div class="property">
<div class="property-label">Upload Image</div>
<input type="file" id="input-app-image-upload"
- class="input-file-field" accept="image/*"
- ng-model="appDetails.originalImage" name="appImage"
- image-upload="appDetails.originalImage"
+ class="input-file-field input-app-image-upload-ht"
+ accept="image/*" ng-model="appDetails.originalImage"
+ name="appImage" image-upload="appDetails.originalImage"
image-upload-resize-max-height="300"
image-upload-resize-max-width="360"
image-upload-resize-quality="0.7"
- image-upload-api="appDetails.imageApi" style="height: 24px;"
- file-change="appImageHandler($event,files)" />
- <div id="app-error-image-upload-type" class="error-container"
- ng-show="appImageTypeError" class="ng-hide">
- <div class="error-container">
- <small id="error-app-invalid-image-size" class="err-message">File must be an image</small>
- </div>
- </div>
+
+ image-upload-api="appDetails.imageApi"
file-change="appImageHandler($event,files)" />
<div id="app-error-image-upload-type" class="error-container"
ng-show="appImageTypeError" class="ng-hide">
@@ -206,21 +212,14 @@
</div>
<div class="property-label preview">
- <span class="left-label">Preview</span> <span class="remove"
+ <span id="{{$index}}-preview-property" class="left-label">Preview</span>
+ <span id="{{$index}}-remove-property" class="remove"
ng-click="appDetails.removeImage()">Remove</span>
</div>
<img id="image-app-preview" class="image-preview"
ng-src="{{appDetails.app.imageLink || appDetails.app.thumbnail || appDetails.emptyImgForPreview}}" />
- <div id="property-communication-inbox" class="property"
- ng-show="!appDetails.app.restrictedApp">
- <div id="property-communication-inbox-label"
- class="property-label">Communication Inbox</div>
- <input type="text" id="input-UEB-topicname"
- ng-model="appDetails.app.uebTopicName" name="uebTopicName"
- readonly="readonly" />
- </div>
-
- <div id="property-communication-key" class="property"
+
+ <div id="property-communication-key" class="property"
ng-show="!appDetails.app.restrictedApp">
<div id="property-communication-key-label" class="property-label">Communication
Key</div>
@@ -228,25 +227,24 @@
ng-model="appDetails.app.uebKey" name="uebKey"
readonly="readonly" />
</div>
+ <div class="property" ng-show="!appDetails.app.restrictedApp" >
+ <div id="pwd-property-label" class="property-label" >Name
+ Space</div>
+ <span runat="server" ID="required" class="mandatoryFiled"
+ visible="false" ng-show="appDetails.app.isCentralAuth"> *</span><input type="text" id="input-mylogins-auth-namespace"
+ ng-model="appDetails.app.nameSpace" name="appAuthNameSpace"
+ maxlength="256" ng-disabled="!appDetails.app.isCentralAuth" />
+ </div>
- <div id="property-communication-secret" class="property"
+
+ <div id="property-is-central-auth" class="property"
ng-show="!appDetails.app.restrictedApp">
- <div id="property-communication-secret-label"
- class="property-label">Communication Secret</div>
- <input type="text" id="input-UEB-communication-secret"
- ng-model="appDetails.app.uebSecret" name="uebSecret"
- readonly="readonly" />
- </div>
-
- <div id="property-guest-access" class="property">
- <label for="checkbox-app-is-open" class="checkbox"> <input
- type="checkbox" ng-model="appDetails.app.isOpen"
- id="checkbox-app-is-open"
- ng-checked="appDetails.app.isOpen || appDetails.app.restrictedApp"
- ng-disabled="appDetails.app.restrictedApp" /> <i class="skin"></i>
- <span>Allow guest access</span>
+ <label for="checkbox-app-is-central-auth" class="checkbox">
+ <input type="checkbox" ng-model="appDetails.app.isCentralAuth"
+ id="checkbox-app-is-central-auth" /> <i class="skin"></i> <span>Centralized</span>
</label>
</div>
+ <br />
<div id="property-active" class="property">
<label for="checkbox-app-is-enabled" class="checkbox"> <input
type="checkbox" ng-model="appDetails.app.isEnabled"
@@ -254,13 +252,16 @@
</label>
</div>
<br />
- <div id="property-is-central-auth" class="property"
- ng-show="!appDetails.app.restrictedApp">
- <label for="checkbox-app-is-central-auth" class="checkbox">
- <input type="checkbox" ng-model="appDetails.app.isCentralAuth"
- id="checkbox-app-is-central-auth" /> <i class="skin"></i> <span>Centralized</span>
+ <div id="property-guest-access" class="property">
+ <label for="checkbox-app-is-open" class="checkbox"> <input
+ type="checkbox" ng-model="appDetails.app.isOpen"
+ id="checkbox-app-is-open"
+ ng-checked="appDetails.app.isOpen || appDetails.app.restrictedApp"
+ ng-disabled="appDetails.app.restrictedApp" /> <i class="skin"></i>
+ <span>Allow guest access</span>
</label>
</div>
+
</div>
@@ -273,8 +274,7 @@
<div align="right">
<span class="ecomp-save-spinner" ng-show="appDetails.isSaving"></span>
<button id="button-save-app" class="btn btn-alt btn-small"
- ng-class="{disabled: appForm.$invalid}"
- ng-click="appDetails.saveChanges()">Save</button>
+ ng-disabled="(!appDetails.app.name || appDetails.app.name.length == 0)" ng-click="appDetails.saveChanges()">Save</button>
<button id="button-notification-cancel" class="btn btn-alt btn-small"
ng-click="$dismiss('cancel')" role="button" tabindex="0">Cancel</button>
</div>
diff --git a/ecomp-portal-FE-os/client/src/views/applications/applications.controller.js b/ecomp-portal-FE-os/client/src/views/applications/applications.controller.js
index 76121a08..0bcc1eb8 100644
--- a/ecomp-portal-FE-os/client/src/views/applications/applications.controller.js
+++ b/ecomp-portal-FE-os/client/src/views/applications/applications.controller.js
@@ -40,8 +40,9 @@
class ApplicationsCtrl {
constructor($log, $cookies, conf, ngDialog,
- applicationsService, confirmBoxService, userProfileService, utilsService,$modal) {
+ applicationsService, confirmBoxService, userProfileService, utilsService,$modal,$scope) {
this.emptyImgForPreview = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
+ $scope.isAdmin = false;
let getOnboardingApps = () => {
this.isLoadingTable = true;
applicationsService.getOnboardingApps()
@@ -54,6 +55,10 @@
appsList[i].imageLink = appsList[i].imageLink+'?' + new Date().getTime();
}
}
+ if(appsList.length == 0)
+ {
+ confirmBoxService.showInformation('You do not have applications to edit').then(isConfirmed => {});
+ }
this.appsList = appsList;
}).catch(err => {
confirmBoxService.showInformation('There was a problem retrieving the Applications. ' +
@@ -64,8 +69,21 @@
});
};
+ let checkIfUserIsSuperAdmin = () => {
+ applicationsService.checkIfUserIsSuperAdmin().then(res => {
+ if(res) {
+ $scope.isAdmin = true;
+ }
+ }).catch(err => {
+ $log.error('ApplicationsCtrl.checkIfUserIsSuperAdmin:: Failed - ' + err);
+ }).finally(()=> {
+ this.isSaving = false;
+ });
+ };
+
let init = () => {
this.isLoadingTable = false;
+ checkIfUserIsSuperAdmin();
getOnboardingApps();
this.searchString = '';
this.appsTableHeaders = [
@@ -143,6 +161,6 @@
}
}
ApplicationsCtrl.$inject = ['$log', '$cookies', 'conf', 'ngDialog',
- 'applicationsService', 'confirmBoxService', 'userProfileService', 'utilsService','$modal'];
+ 'applicationsService', 'confirmBoxService', 'userProfileService', 'utilsService','$modal', '$scope'];
angular.module('ecompApp').controller('ApplicationsCtrl', ApplicationsCtrl);
})();
diff --git a/ecomp-portal-FE-os/pom.xml b/ecomp-portal-FE-os/pom.xml
index f39a31c5..d5014a98 100644
--- a/ecomp-portal-FE-os/pom.xml
+++ b/ecomp-portal-FE-os/pom.xml
@@ -5,7 +5,7 @@
<parent>
<groupId>org.onap.portal</groupId>
<artifactId>onap-portal-parent</artifactId>
- <version>2.5.0</version>
+ <version>2.6.0-SNAPSHOT</version>
</parent>
<artifactId>portal-FE-os</artifactId>
diff --git a/ecomp-portal-widget-ms/common-widgets/pom.xml b/ecomp-portal-widget-ms/common-widgets/pom.xml
index 16416034..5b574d87 100644
--- a/ecomp-portal-widget-ms/common-widgets/pom.xml
+++ b/ecomp-portal-widget-ms/common-widgets/pom.xml
@@ -6,7 +6,7 @@
<parent>
<groupId>org.onap.portal</groupId>
<artifactId>widget-ms-parent</artifactId>
- <version>2.5.0</version>
+ <version>2.6.0-SNAPSHOT</version>
</parent>
<artifactId>common-widgets</artifactId>
diff --git a/ecomp-portal-widget-ms/pom.xml b/ecomp-portal-widget-ms/pom.xml
index cb246513..d8b33301 100644
--- a/ecomp-portal-widget-ms/pom.xml
+++ b/ecomp-portal-widget-ms/pom.xml
@@ -6,7 +6,7 @@
<parent>
<groupId>org.onap.portal</groupId>
<artifactId>onap-portal-parent</artifactId>
- <version>2.5.0</version>
+ <version>2.6.0-SNAPSHOT</version>
</parent>
<artifactId>widget-ms-parent</artifactId>
diff --git a/ecomp-portal-widget-ms/widget-ms/pom.xml b/ecomp-portal-widget-ms/widget-ms/pom.xml
index 8f5a5897..95b06adc 100644
--- a/ecomp-portal-widget-ms/widget-ms/pom.xml
+++ b/ecomp-portal-widget-ms/widget-ms/pom.xml
@@ -13,7 +13,7 @@
<groupId>org.onap.portal</groupId>
<artifactId>widget-ms</artifactId>
- <version>2.5.0</version>
+ <version>2.6.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>widget-microservice</name>
diff --git a/pom.xml b/pom.xml
index 31b82662..0ddeb318 100644
--- a/pom.xml
+++ b/pom.xml
@@ -12,7 +12,7 @@
<groupId>org.onap.portal</groupId>
<artifactId>onap-portal-parent</artifactId>
- <version>2.5.0</version>
+ <version>2.6.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>portal</name>
@@ -27,7 +27,7 @@
<properties>
<!-- Jenkins should invoke mvn with argument -Dbuild.number=${BUILD_NUMBER} -->
<build.number>0</build.number>
- <epsdk.version>2.5.0</epsdk.version>
+ <epsdk.version>2.6.0-SNAPSHOT</epsdk.version>
<springframework.version>4.2.3.RELEASE</springframework.version>
<hibernate.version>4.3.11.Final</hibernate.version>
<fasterxml.version>2.8.10</fasterxml.version>