From: Sunder Tattavarada Date: Mon, 17 Jun 2019 21:24:57 +0000 (+0000) Subject: Merge "MicroserviceParameter class DB constraints" X-Git-Tag: 3.2.0~279 X-Git-Url: https://gerrit.onap.org/r/gitweb?p=portal.git;a=commitdiff_plain;h=fd64af5e46b31e731e3e9e11b037361b0a73d965;hp=91346e516f078aff100c0df25621f09950118150 Merge "MicroserviceParameter class DB constraints" --- 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 Binary files /dev/null and b/deliveries/keystoreONAP.keystore differ diff --git a/deliveries/my.cnf b/deliveries/my.cnf index 97340675..e06a211c 100644 --- a/deliveries/my.cnf +++ b/deliveries/my.cnf @@ -180,6 +180,7 @@ quote-names max_allowed_packet = 16M [mysql] +default_character_set = utf8 #no-auto-rehash # faster start of mysql but no tab completion [isamchk] 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. --> + + org.glassfish.web + javax.el + 2.2.6 + + + + javax.el + el-api + 2.2.1-b04 + + + + org.jsoup + jsoup + 1.12.1 + org.glassfish.jersey.connectors jersey-jetty-connector 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 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 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 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(app.getThumbnail(), header); } + } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsControllerExternalRequest.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsControllerExternalRequest.java index cef5fa74..fe029e0e 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsControllerExternalRequest.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsControllerExternalRequest.java @@ -39,9 +39,15 @@ package org.onap.portalapp.portal.controller; import java.util.List; +import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import javax.validation.ConstraintViolation; +import javax.validation.Valid; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; import org.onap.portalapp.portal.domain.EPApp; import org.onap.portalapp.portal.domain.EPUser; import org.onap.portalapp.portal.ecomp.model.PortalRestResponse; @@ -88,16 +94,12 @@ import io.swagger.annotations.ApiOperation; @EnableAspectJAutoProxy @EPAuditLog public class AppsControllerExternalRequest implements BasicAuthenticationController { + private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory(); private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppsControllerExternalRequest.class); private static final String ONBOARD_APP = "/onboardApp"; - // Where is this used? - public boolean isAuxRESTfulCall() { - return true; - } - /** * For testing whether a user is a superadmin. */ @@ -145,10 +147,20 @@ public class AppsControllerExternalRequest implements BasicAuthenticationControl @RequestMapping(value = "/portalAdmin", method = RequestMethod.POST, produces = "application/json") @ResponseBody public PortalRestResponse postPortalAdmin(HttpServletRequest request, HttpServletResponse response, - @RequestBody EPUser epUser) { + @Valid @RequestBody EPUser epUser) { EcompPortalUtils.logAndSerializeObject(logger, "postPortalAdmin", "request", epUser); PortalRestResponse portalResponse = new PortalRestResponse<>(); + if (epUser!=null){ + Validator validator = VALIDATOR_FACTORY.getValidator(); + Set> constraintViolations = validator.validate(epUser); + if (!constraintViolations.isEmpty()){ + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage("Data is not valid"); + return portalResponse; + } + } + // Check mandatory fields. if (epUser.getEmail() == null || epUser.getEmail().trim().length() == 0 // || epUser.getLoginId() == null || epUser.getLoginId().trim().length() == 0 // @@ -248,10 +260,18 @@ public class AppsControllerExternalRequest implements BasicAuthenticationControl @RequestMapping(value = { ONBOARD_APP }, method = RequestMethod.POST, produces = "application/json") @ResponseBody public PortalRestResponse postOnboardAppExternal(HttpServletRequest request, HttpServletResponse response, - @RequestBody OnboardingApp newOnboardApp) { + @Valid @RequestBody OnboardingApp newOnboardApp) { EcompPortalUtils.logAndSerializeObject(logger, "postOnboardAppExternal", "request", newOnboardApp); PortalRestResponse portalResponse = new PortalRestResponse<>(); - + if (newOnboardApp != null){ + Validator validator = VALIDATOR_FACTORY.getValidator(); + Set> constraintViolations = validator.validate(newOnboardApp); + if (!constraintViolations.isEmpty()){ + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage("Data is not valid"); + return portalResponse; + } + } // Validate fields if (newOnboardApp.id != null) { portalResponse.setStatus(PortalRestStatusEnum.ERROR); @@ -335,9 +355,20 @@ public class AppsControllerExternalRequest implements BasicAuthenticationControl @RequestMapping(value = { ONBOARD_APP + "/{appId}" }, method = RequestMethod.PUT, produces = "application/json") @ResponseBody public PortalRestResponse putOnboardAppExternal(HttpServletRequest request, HttpServletResponse response, - @PathVariable("appId") Long appId, @RequestBody OnboardingApp oldOnboardApp) { + @PathVariable("appId") Long appId, @Valid @RequestBody OnboardingApp oldOnboardApp) { EcompPortalUtils.logAndSerializeObject(logger, "putOnboardAppExternal", "request", oldOnboardApp); PortalRestResponse portalResponse = new PortalRestResponse<>(); + + if (oldOnboardApp != null){ + Validator validator = VALIDATOR_FACTORY.getValidator(); + Set> constraintViolations = validator.validate(oldOnboardApp); + if (!constraintViolations.isEmpty()){ + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage("Data is not valid"); + return portalResponse; + } + } + // Validate fields. if (oldOnboardApp.id == null || !appId.equals(oldOnboardApp.id)) { portalResponse.setStatus(PortalRestStatusEnum.ERROR); diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/DashboardSearchResultController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/DashboardSearchResultController.java index 29f5b20f..04ee5e0b 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/DashboardSearchResultController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/DashboardSearchResultController.java @@ -45,8 +45,14 @@ import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; import javax.servlet.http.HttpServletRequest; +import javax.validation.ConstraintViolation; +import javax.validation.Valid; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; import org.onap.portalapp.controller.EPRestrictedBaseController; import org.onap.portalapp.portal.domain.EPUser; import org.onap.portalapp.portal.ecomp.model.PortalRestResponse; @@ -56,6 +62,7 @@ import org.onap.portalapp.portal.service.DashboardSearchService; import org.onap.portalapp.portal.transport.CommonWidget; import org.onap.portalapp.portal.transport.CommonWidgetMeta; import org.onap.portalapp.util.EPUserUtils; +import org.onap.portalapp.validation.SecureString; import org.onap.portalsdk.core.domain.support.CollaborateList; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.beans.factory.annotation.Autowired; @@ -68,6 +75,7 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/portalApi/search") public class DashboardSearchResultController extends EPRestrictedBaseController { + private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory(); private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardSearchResultController.class); @@ -85,8 +93,11 @@ public class DashboardSearchResultController extends EPRestrictedBaseController @RequestMapping(value = "/widgetData", method = RequestMethod.GET, produces = "application/json") public PortalRestResponse getWidgetData(HttpServletRequest request, @RequestParam String resourceType) { - return new PortalRestResponse(PortalRestStatusEnum.OK, "success", - searchService.getWidgetData(resourceType)); + if (stringIsNotSafeHtml(resourceType)) { + return new PortalRestResponse(PortalRestStatusEnum.ERROR, "resourceType: String string is not valid", ""); + } + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", + searchService.getWidgetData(resourceType)); } /** @@ -97,19 +108,26 @@ public class DashboardSearchResultController extends EPRestrictedBaseController * @return Rest response wrapped around a String; e.g., "success" or "ERROR" */ @RequestMapping(value = "/widgetDataBulk", method = RequestMethod.POST, produces = "application/json") - public PortalRestResponse saveWidgetDataBulk(@RequestBody CommonWidgetMeta commonWidgetMeta) { + public PortalRestResponse saveWidgetDataBulk(@Valid @RequestBody CommonWidgetMeta commonWidgetMeta) { logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetDataBulk: argument is {}", commonWidgetMeta); - if (commonWidgetMeta.getCategory() == null || commonWidgetMeta.getCategory().trim().equals("")) - return new PortalRestResponse(PortalRestStatusEnum.ERROR, "ERROR", - "Category cannot be null or empty"); + if (commonWidgetMeta.getCategory() == null || commonWidgetMeta.getCategory().trim().equals("")){ + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ERROR", + "Cateogry cannot be null or empty"); + }else { + Validator validator = VALIDATOR_FACTORY.getValidator(); + Set> constraintViolations = validator.validate(commonWidgetMeta); + if (!constraintViolations.isEmpty()) + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ERROR", + "Category is not valid"); + } // validate dates for (CommonWidget cw : commonWidgetMeta.getItems()) { String err = validateCommonWidget(cw); if (err != null) - return new PortalRestResponse(PortalRestStatusEnum.ERROR, err, null); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, err, null); } - return new PortalRestResponse(PortalRestStatusEnum.OK, "success", - searchService.saveWidgetDataBulk(commonWidgetMeta)); + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", + searchService.saveWidgetDataBulk(commonWidgetMeta)); } /** @@ -120,16 +138,23 @@ public class DashboardSearchResultController extends EPRestrictedBaseController * @return Rest response wrapped around a String; e.g., "success" or "ERROR" */ @RequestMapping(value = "/widgetData", method = RequestMethod.POST, produces = "application/json") - public PortalRestResponse saveWidgetData(@RequestBody CommonWidget commonWidget) { + public PortalRestResponse saveWidgetData(@Valid @RequestBody CommonWidget commonWidget) { logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetData: argument is {}", commonWidget); - if (commonWidget.getCategory() == null || commonWidget.getCategory().trim().equals("")) - return new PortalRestResponse(PortalRestStatusEnum.ERROR, "ERROR", - "Cateogry cannot be null or empty"); + if (commonWidget.getCategory() == null || commonWidget.getCategory().trim().equals("")){ + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ERROR", + "Category cannot be null or empty"); + }else { + Validator validator = VALIDATOR_FACTORY.getValidator(); + Set> constraintViolations = validator.validate(commonWidget); + if (!constraintViolations.isEmpty()) + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ERROR", + "Category is not valid"); + } String err = validateCommonWidget(commonWidget); if (err != null) - return new PortalRestResponse(PortalRestStatusEnum.ERROR, err, null); - return new PortalRestResponse(PortalRestStatusEnum.OK, "success", - searchService.saveWidgetData(commonWidget)); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, err, null); + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", + searchService.saveWidgetData(commonWidget)); } /** @@ -162,10 +187,17 @@ public class DashboardSearchResultController extends EPRestrictedBaseController * @return Rest response wrapped around a String; e.g., "success" or "ERROR" */ @RequestMapping(value = "/deleteData", method = RequestMethod.POST, produces = "application/json") - public PortalRestResponse deleteWidgetData(@RequestBody CommonWidget commonWidget) { + public PortalRestResponse deleteWidgetData(@Valid @RequestBody CommonWidget commonWidget) { + if (commonWidget!=null){ + Validator validator = VALIDATOR_FACTORY.getValidator(); + Set> constraintViolations = validator.validate(commonWidget); + if (!constraintViolations.isEmpty()) + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ERROR", + "CommonWidget is not valid"); + } logger.debug(EELFLoggerDelegate.debugLogger, "deleteWidgetData: argument is {}", commonWidget); - return new PortalRestResponse(PortalRestStatusEnum.OK, "success", - searchService.deleteWidgetData(commonWidget)); + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", + searchService.deleteWidgetData(commonWidget)); } /** @@ -185,11 +217,14 @@ public class DashboardSearchResultController extends EPRestrictedBaseController if (user == null) { return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: User object is null? - check logs", - new HashMap>()); + new HashMap<>()); } else if (searchString == null || searchString.trim().length() == 0) { return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is null", - new HashMap>()); - } else { + new HashMap<>()); + }else if (stringIsNotSafeHtml(searchString)){ + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is not valid", + new HashMap<>()); + }else { logger.debug(EELFLoggerDelegate.debugLogger, "searchPortal: user {}, search string '{}'", user.getLoginId(), searchString); Map> results = searchService.searchResults(user.getLoginId(), @@ -199,7 +234,7 @@ public class DashboardSearchResultController extends EPRestrictedBaseController } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "searchPortal failed", e); return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.", - new HashMap>()); + new HashMap<>()); } } @@ -258,4 +293,13 @@ public class DashboardSearchResultController extends EPRestrictedBaseController } } + private boolean stringIsNotSafeHtml(String string){ + SecureString secureString = new SecureString(string); + + Validator validator = VALIDATOR_FACTORY.getValidator(); + + Set> constraintViolations = validator.validate(secureString); + return !constraintViolations.isEmpty(); + } + } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/MicroserviceController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/MicroserviceController.java index 50eaa600..2f956cc3 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/MicroserviceController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/MicroserviceController.java @@ -39,9 +39,15 @@ package org.onap.portalapp.portal.controller; import java.util.List; +import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import javax.validation.ConstraintViolation; +import javax.validation.Valid; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; import org.onap.portalapp.controller.EPRestrictedBaseController; import org.onap.portalapp.portal.domain.MicroserviceData; import org.onap.portalapp.portal.domain.WidgetCatalog; @@ -72,6 +78,7 @@ import org.springframework.web.client.RestTemplate; @EnableAspectJAutoProxy @EPAuditLog public class MicroserviceController extends EPRestrictedBaseController { + public static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory(); String whatService = "widgets-service"; RestTemplate template = new RestTemplate(); @@ -84,53 +91,68 @@ public class MicroserviceController extends EPRestrictedBaseController { @RequestMapping(value = { "/portalApi/microservices" }, method = RequestMethod.POST) public PortalRestResponse createMicroservice(HttpServletRequest request, HttpServletResponse response, - @RequestBody MicroserviceData newServiceData) throws Exception { + @Valid @RequestBody MicroserviceData newServiceData) throws Exception { if (newServiceData == null) { - return new PortalRestResponse(PortalRestStatusEnum.ERROR, "FAILURE", - "MicroserviceData cannot be null or empty"); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "FAILURE", + "MicroserviceData cannot be null or empty"); + }else { + Validator validator = VALIDATOR_FACTORY.getValidator(); + + Set> constraintViolations = validator.validate(newServiceData); + if(!constraintViolations.isEmpty()){ + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, + "ERROR", "MicroserviceData is not valid"); + } } long serviceId = microserviceService.saveMicroservice(newServiceData); try { microserviceService.saveServiceParameters(serviceId, newServiceData.getParameterList()); } catch (Exception e) { - return new PortalRestResponse(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage()); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage()); } - return new PortalRestResponse(PortalRestStatusEnum.OK, "SUCCESS", ""); + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "SUCCESS", ""); } @RequestMapping(value = { "/portalApi/microservices" }, method = RequestMethod.GET) public List getMicroservice(HttpServletRequest request, HttpServletResponse response) throws Exception { - List list = microserviceService.getMicroserviceData(); - return list; + return microserviceService.getMicroserviceData(); } @RequestMapping(value = { "/portalApi/microservices/{serviceId}" }, method = RequestMethod.PUT) public PortalRestResponse updateMicroservice(HttpServletRequest request, HttpServletResponse response, - @PathVariable("serviceId") long serviceId, @RequestBody MicroserviceData newServiceData) throws Exception { + @PathVariable("serviceId") long serviceId, @Valid @RequestBody MicroserviceData newServiceData) { if (newServiceData == null) { - return new PortalRestResponse(PortalRestStatusEnum.ERROR, "FAILURE", - "MicroserviceData cannot be null or empty"); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "FAILURE", + "MicroserviceData cannot be null or empty"); + }else { + Validator validator = VALIDATOR_FACTORY.getValidator(); + + Set> constraintViolations = validator.validate(newServiceData); + if(!constraintViolations.isEmpty()){ + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, + "ERROR", "MicroserviceData is not valid"); + } } try { microserviceService.updateMicroservice(serviceId, newServiceData); } catch (Exception e) { - return new PortalRestResponse(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage()); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage()); } - return new PortalRestResponse(PortalRestStatusEnum.OK, "SUCCESS", ""); + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "SUCCESS", ""); } @RequestMapping(value = { "/portalApi/microservices/{serviceId}" }, method = RequestMethod.DELETE) public PortalRestResponse deleteMicroservice(HttpServletRequest request, HttpServletResponse response, - @PathVariable("serviceId") long serviceId) throws Exception { + @PathVariable("serviceId") long serviceId) { try { ParameterizedTypeReference> typeRef = new ParameterizedTypeReference>() { }; // If this service is assoicated with widgets, cannnot be deleted - ResponseEntity> ans = (ResponseEntity>) template.exchange( + ResponseEntity> ans = template.exchange( EcompPortalUtils.widgetMsProtocol() + "://" + consulHealthService.getServiceLocation(whatService, SystemProperties.getProperty("microservices.widget.local.port")) + "/widget/microservices/widgetCatalog/service/" + serviceId, HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), typeRef); @@ -140,17 +162,18 @@ public class MicroserviceController extends EPRestrictedBaseController { else{ StringBuilder sb = new StringBuilder(); for(int i = 0; i < widgets.size(); i++){ - sb.append("'" + widgets.get(i).getName() + "' "); + sb.append("'").append(widgets.get(i).getName()).append("' "); if(i < (widgets.size()-1)){ sb.append(","); } } - return new PortalRestResponse(PortalRestStatusEnum.WARN, "SOME WIDGETS ASSOICATE WITH THIS SERVICE", sb.toString()); + return new PortalRestResponse<>(PortalRestStatusEnum.WARN, "SOME WIDGETS ASSOICATE WITH THIS SERVICE", + sb.toString()); } } catch (Exception e) { - return new PortalRestResponse(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage()); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage()); } - return new PortalRestResponse(PortalRestStatusEnum.OK, "SUCCESS", ""); + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "SUCCESS", ""); } } 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 c8e22d39..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 @@ -50,6 +50,11 @@ import java.util.TreeSet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import javax.validation.ConstraintViolation; +import javax.validation.Valid; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; import org.apache.commons.lang.StringUtils; import org.json.JSONObject; import org.onap.portalapp.controller.EPRestrictedBaseController; @@ -79,6 +84,7 @@ 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; +import org.onap.portalapp.validation.SecureString; import org.onap.portalsdk.core.domain.AuditLog; import org.onap.portalsdk.core.domain.Role; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; @@ -111,6 +117,8 @@ import com.fasterxml.jackson.databind.type.TypeFactory; @EnableAspectJAutoProxy @EPAuditLog public class RoleManageController extends EPRestrictedBaseController { + private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory(); + private static final String PIPE = "|"; private static final String ROLE_INVALID_CHARS = "%=():,\"\""; @@ -122,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); @@ -178,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 toggleRole(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId, - @PathVariable("roleId") Long roleId) throws Exception { + public Map toggleRole(HttpServletRequest request, HttpServletResponse response, + @PathVariable("appId") Long appId, @PathVariable("roleId") Long roleId) throws Exception { EPApp requestedApp = null; String restcallStatus = null; HashMap responseMap = new HashMap<>(); @@ -224,10 +229,10 @@ public class RoleManageController extends EPRestrictedBaseController { } return responseMap; } - + @RequestMapping(value = { "/portalApi/role_list/removeRole/{appId}/{roleId}" }, method = RequestMethod.POST) - public Map removeRole(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId, - @PathVariable("roleId") Long roleId) throws Exception { + public Map removeRole(HttpServletRequest request, HttpServletResponse response, + @PathVariable("appId") Long appId, @PathVariable("roleId") Long roleId) throws Exception { EPUser user = EPUserUtils.getUserSession(request); EPApp requestedApp = null; @@ -290,7 +295,7 @@ public class RoleManageController extends EPRestrictedBaseController { } return responseMap; } - + @RequestMapping(value = { "/portalApi/role/saveRole/{appId}" }, method = RequestMethod.POST) public Map saveRole(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId) throws Exception { @@ -345,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 { @@ -436,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 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 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; @@ -470,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 answer = null; - Map 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 answer = null; + Map 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; @@ -497,8 +506,17 @@ public class RoleManageController extends EPRestrictedBaseController { } @RequestMapping(value = { "/portalApi/role_function_list/saveRoleFunction/{appId}" }, method = RequestMethod.POST) - public PortalRestResponse saveRoleFunction(HttpServletRequest request, HttpServletResponse response, @RequestBody CentralV2RoleFunction roleFunc, + public PortalRestResponse saveRoleFunction(HttpServletRequest request, HttpServletResponse response, @Valid @RequestBody CentralV2RoleFunction roleFunc, @PathVariable("appId") Long appId) throws Exception { + if (roleFunc!=null) { + Validator validator = VALIDATOR_FACTORY.getValidator(); + Set> constraintViolations = validator.validate(roleFunc); + + if(!constraintViolations.isEmpty()){ + logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction: Failed"); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Data is not valid", "ERROR"); + } + } EPUser user = EPUserUtils.getUserSession(request); boolean saveOrUpdateResponse = false; try { @@ -506,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())) { @@ -528,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"); } @@ -547,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()); @@ -594,6 +605,19 @@ public class RoleManageController extends EPRestrictedBaseController { public PortalRestResponse removeRoleFunction(HttpServletRequest request, HttpServletResponse response, @RequestBody String roleFunc, @PathVariable("appId") Long appId) throws Exception { EPUser user = EPUserUtils.getUserSession(request); + + if (roleFunc!=null) { + SecureString secureString = new SecureString(roleFunc); + + Validator validator = VALIDATOR_FACTORY.getValidator(); + Set> constraintViolations = validator.validate(secureString); + + if(!constraintViolations.isEmpty()){ + logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction: Failed"); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Data is not valid", "ERROR"); + } + } + try { EPApp requestedApp = appService.getApp(appId); if (isAuthorizedUser(user, requestedApp)) { @@ -656,18 +680,30 @@ public class RoleManageController extends EPRestrictedBaseController { @RequestMapping(value = { "/portalApi/centralizedApps" }, method = RequestMethod.GET) public List getCentralizedAppRoles(HttpServletRequest request, HttpServletResponse response, String userId) throws IOException { + if(userId!=null) { + SecureString secureString = new SecureString(userId); + + Validator validator = VALIDATOR_FACTORY.getValidator(); + Set> constraintViolations = validator.validate(secureString); + + if(!constraintViolations.isEmpty()){ + logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction: Failed"); + return null; + } + } EPUser user = EPUserUtils.getUserSession(request); List 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; } @@ -684,7 +720,6 @@ public class RoleManageController extends EPRestrictedBaseController { this.roleController = roleController; } - @RequestMapping(value = { "/portalApi/syncRoles" }, method = RequestMethod.POST, produces = "application/json") public PortalRestResponse syncRoles(HttpServletRequest request, HttpServletResponse response, @RequestBody Long appId) { @@ -706,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 syncFunctions(HttpServletRequest request, HttpServletResponse response, @RequestBody Long appId) { @@ -756,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 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 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))) @@ -791,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 bulkUploadRoleFunc(HttpServletRequest request, HttpServletResponse response, @RequestBody UploadRoleFunctionExtSystem data, @PathVariable("appId") Long appId) { EPUser user = EPUserUtils.getUserSession(request); @@ -801,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 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(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(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(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(schedulerResWrapper.getResponse(), + HttpStatus.INTERNAL_SERVER_ERROR)); + } + }else{ + return (new ResponseEntity("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 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(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(responseWrapper.getResponse(), HttpStatus.INTERNAL_SERVER_ERROR)); + return new ResponseEntity(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(responseWrapper.getResponse(), HttpStatus.INTERNAL_SERVER_ERROR)); + } + }else{ + return (new ResponseEntity("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 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(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(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(responseWrapper.getResponse(), HttpStatus.INTERNAL_SERVER_ERROR)); + } + }else{ + return (new ResponseEntity("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> getSchedulerConstant(HttpServletRequest request, - HttpServletResponse response) { + HttpServletResponse response) throws Exception { logger.debug(EELFLoggerDelegate.debugLogger, "get scheduler constant"); PortalRestResponse> 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 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 map = new HashMap<>(); - for (Map.Entry 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 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 map = new HashMap<>(); + for (Map.Entry 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>(PortalRestStatusEnum.OK, "success", + map); + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getSchedulerConstant failed", e); + portalRestResponse = new PortalRestResponse>(PortalRestStatusEnum.ERROR, + e.getMessage(), null); } - logger.debug(EELFLoggerDelegate.debugLogger, " portalRestResponse - getSchedulerConstant= {}", - map); - portalRestResponse = new PortalRestResponse>(PortalRestStatusEnum.OK, "success", map); - - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "getSchedulerConstant failed", e); - portalRestResponse = new PortalRestResponse>(PortalRestStatusEnum.ERROR, e.getMessage(), - null); + } - return portalRestResponse; + else{ + logger.error(EELFLoggerDelegate.errorLogger, "getSchedulerConstant failed: User unauthorized to make this call"); + portalRestResponse = new PortalRestResponse>(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 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/TicketEventController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/TicketEventController.java index b9f6f76d..71f7f81a 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/TicketEventController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/TicketEventController.java @@ -47,6 +47,10 @@ import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; import org.onap.portalapp.portal.domain.EPUser; import org.onap.portalapp.portal.ecomp.model.PortalRestResponse; import org.onap.portalapp.portal.ecomp.model.PortalRestStatusEnum; @@ -56,6 +60,7 @@ import org.onap.portalapp.portal.service.UserNotificationService; import org.onap.portalapp.portal.transport.EpNotificationItem; import org.onap.portalapp.portal.transport.EpRoleNotificationItem; import org.onap.portalapp.portal.utils.PortalConstants; +import org.onap.portalapp.validation.SecureString; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; @@ -80,7 +85,7 @@ import io.swagger.annotations.ApiOperation; @EnableAspectJAutoProxy @EPAuditLog public class TicketEventController implements BasicAuthenticationController { - + private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory(); @Autowired private UserNotificationService userNotificationService; @@ -105,6 +110,19 @@ public class TicketEventController implements BasicAuthenticationController { logger.debug(EELFLoggerDelegate.debugLogger, "Ticket Event notification" + ticketEventJson); PortalRestResponse portalResponse = new PortalRestResponse<>(); + + if (ticketEventJson!=null){ + SecureString secureString = new SecureString(ticketEventJson); + Validator validator = VALIDATOR_FACTORY.getValidator(); + + Set> constraintViolations = validator.validate(secureString); + if (!constraintViolations.isEmpty()){ + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage("Data is not valid"); + return portalResponse; + } + } + try { JsonNode ticketEventNotif = mapper.readTree(ticketEventJson); 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 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 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/AppContactUs.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/AppContactUs.java index 6cf2ea79..0fe8a351 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/AppContactUs.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/AppContactUs.java @@ -37,6 +37,7 @@ */ package org.onap.portalapp.portal.domain; +import org.hibernate.validator.constraints.SafeHtml; import org.onap.portalsdk.core.domain.support.DomainVo; import com.fasterxml.jackson.annotation.JsonBackReference; @@ -46,10 +47,15 @@ public class AppContactUs extends DomainVo { private static final long serialVersionUID = -2742197830465055134L; @JsonBackReference private EPApp app; + @SafeHtml private String description; + @SafeHtml private String contactEmail; + @SafeHtml private String contactName; + @SafeHtml private String url; + @SafeHtml private String activeYN; public EPApp getApp() { diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/CentralV2RoleFunction.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/CentralV2RoleFunction.java index d2ded5ad..a761103f 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/CentralV2RoleFunction.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/CentralV2RoleFunction.java @@ -39,6 +39,7 @@ package org.onap.portalapp.portal.domain; import java.io.Serializable; +import org.hibernate.validator.constraints.SafeHtml; import org.onap.portalsdk.core.domain.support.DomainVo; import com.fasterxml.jackson.annotation.JsonIgnore; @@ -50,14 +51,18 @@ public class CentralV2RoleFunction extends DomainVo implements Serializable, Com * */ private static final long serialVersionUID = -4018975640065252688L; + @SafeHtml private String code; + @SafeHtml private String name; @JsonIgnore private Long appId; @JsonIgnore private Long roleId; private String type; + @SafeHtml private String action; + @SafeHtml private String editUrl; diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPApp.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPApp.java index 6e77e747..8227d9ab 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPApp.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPApp.java @@ -41,7 +41,9 @@ import java.util.Arrays; import javax.persistence.Lob; +import javax.validation.Valid; import org.apache.commons.lang.StringUtils; +import org.hibernate.validator.constraints.SafeHtml; import org.onap.portalsdk.core.domain.support.DomainVo; /** @@ -50,29 +52,44 @@ import org.onap.portalsdk.core.domain.support.DomainVo; public class EPApp extends DomainVo { private static final long serialVersionUID = 1L; - + @SafeHtml private String name; + @SafeHtml private String imageUrl; + @SafeHtml private String description; + @SafeHtml private String notes; + @SafeHtml private String url; + @SafeHtml private String alternateUrl; + @SafeHtml private String appRestEndpoint; + @SafeHtml private String mlAppName; + @SafeHtml private String mlAppAdminId; private Long motsId; + @SafeHtml private String username; + @SafeHtml private String appPassword; @Lob private byte[] thumbnail; private Boolean open; private Boolean enabled; + @SafeHtml private String uebTopicName; + @SafeHtml private String uebKey; + @SafeHtml private String uebSecret; private Integer appType; + @Valid private AppContactUs contactUs; private Boolean centralAuth; + @SafeHtml private String nameSpace; public EPApp() { diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPRole.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPRole.java index f9ff97d1..55f7e0cc 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPRole.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPRole.java @@ -41,6 +41,8 @@ import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; +import javax.validation.Valid; +import org.hibernate.validator.constraints.SafeHtml; import org.onap.portalsdk.core.domain.RoleFunction; import org.onap.portalsdk.core.domain.support.DomainVo; import com.fasterxml.jackson.annotation.JsonIgnore; @@ -48,6 +50,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore; public class EPRole extends DomainVo { private static final long serialVersionUID = 1L; + @SafeHtml private String name; private boolean active; private Integer priority; @@ -57,7 +60,7 @@ public class EPRole extends DomainVo { private Long appRoleId; // used by ONAP only private SortedSet roleFunctions = new TreeSet(); - + @Valid private SortedSet childRoles = new TreeSet(); @JsonIgnore 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 ce7495f7..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 @@ -42,6 +42,8 @@ import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; +import javax.validation.Valid; +import org.hibernate.validator.constraints.SafeHtml; import org.onap.portalapp.portal.utils.PortalConstants; import org.onap.portalsdk.core.domain.User; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; @@ -52,44 +54,78 @@ public class EPUser extends User { private Long orgId; private Long managerId; + @SafeHtml private String firstName; + @SafeHtml private String middleInitial; + @SafeHtml private String lastName; + @SafeHtml private String phone; + @SafeHtml private String fax; + @SafeHtml private String cellular; + @SafeHtml private String email; private Long addressId; + @SafeHtml private String alertMethodCd; + @SafeHtml private String hrid; + @SafeHtml private String orgUserId; + @SafeHtml private String orgCode; + @SafeHtml private String address1; + @SafeHtml private String address2; + @SafeHtml private String city; + @SafeHtml private String state; + @SafeHtml private String zipCode; + @SafeHtml private String country; + @SafeHtml private String orgManagerUserId; + @SafeHtml private String locationClli; + @SafeHtml private String businessCountryCode; + @SafeHtml private String businessCountryName; + @SafeHtml private String businessUnit; + @SafeHtml private String businessUnitName; + @SafeHtml private String department; + @SafeHtml private String departmentName; + @SafeHtml private String companyCode; + @SafeHtml private String company; + @SafeHtml private String zipCodeSuffix; + @SafeHtml private String jobTitle; + @SafeHtml private String commandChain; + @SafeHtml private String siloStatus; + @SafeHtml private String costCenter; + @SafeHtml private String financialLocCode; - + @SafeHtml private String loginId; + @SafeHtml private String loginPwd; private Date lastLoginDate; private boolean active; @@ -97,15 +133,19 @@ public class EPUser extends User { private Long selectedProfileId; private Long timeZoneId; 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; - + @Valid private SortedSet userApps = new TreeSet(); + @Valid private SortedSet pseudoRoles = new TreeSet(); public EPUser() {} @@ -653,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/domain/EPUserApp.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPUserApp.java index 3470a9e3..d644c998 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPUserApp.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPUserApp.java @@ -37,6 +37,7 @@ */ package org.onap.portalapp.portal.domain; +import javax.validation.Valid; import org.onap.portalsdk.core.domain.support.DomainVo; @SuppressWarnings("rawtypes") @@ -45,7 +46,9 @@ public class EPUserApp extends DomainVo implements java.io.Serializable, Compara private static final long serialVersionUID = 1L; private Long userId; + @Valid private EPApp app; + @Valid private EPRole role; private Integer priority; @@ -61,13 +64,12 @@ public class EPUserApp extends DomainVo implements java.io.Serializable, Compara } public Long getAppRoleId() { - return (role.getAppRoleId() == null) ? null : role.getAppRoleId(); + return this.role.getAppRoleId(); } @Override public String toString() { - String str = "[u: "+getUserId()+"; a: "+getAppId()+", r: "+getRoleId()+"; appRoleId: "+getAppRoleId()+"]"; - return str; + return "[u: "+getUserId()+"; a: "+getAppId()+", r: "+getRoleId()+"; appRoleId: "+getAppRoleId()+"]"; } public Long getUserId() { @@ -102,6 +104,7 @@ public class EPUserApp extends DomainVo implements java.io.Serializable, Compara this.priority = priority; } + @Override public boolean equals(Object other) { if ((this == other)) return true; @@ -111,10 +114,10 @@ public class EPUserApp extends DomainVo implements java.io.Serializable, Compara return false; EPUserApp castOther = (EPUserApp) other; - return (this.getUserId().equals(castOther.getUserId())) - && (this.getApp().getId().equals(castOther.getApp().getId())) - && (this.getRole().getId().equals(castOther.getRole().getId())) - && ((this.priority==null && castOther.getPriority()==null) || this.getPriority().equals(castOther.getPriority())); + return (otherUserIdIsSameAsThisUserId(castOther)) + && (otherAppIdIsSameAsThis(castOther)) + && (otherRoleIsSameAsThis(castOther)) + && (otherPriorityIsSameAsThis(castOther)); } public int hashCode() { @@ -135,4 +138,19 @@ public class EPUserApp extends DomainVo implements java.io.Serializable, Compara return c1.compareTo(c2); } + private boolean otherPriorityIsSameAsThis(EPUserApp other){ + return (this.priority==null && other.getPriority()==null) || this.getPriority().equals(other.getPriority()); + } + + private boolean otherRoleIsSameAsThis(EPUserApp other){ + return this.getRole().getId().equals(other.getRole().getId()); + } + + private boolean otherAppIdIsSameAsThis(EPUserApp other){ + return this.getApp().getId().equals(other.getApp().getId()); + } + + private boolean otherUserIdIsSameAsThisUserId(EPUserApp other){ + return this.getUserId().equals(other.getUserId()); + } } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/MicroserviceData.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/MicroserviceData.java index f62b8928..b8f79d06 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/MicroserviceData.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/MicroserviceData.java @@ -44,6 +44,8 @@ import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; +import javax.validation.Valid; +import org.hibernate.validator.constraints.SafeHtml; import org.onap.portalsdk.core.domain.support.DomainVo; public class MicroserviceData extends DomainVo { @@ -55,23 +57,23 @@ public class MicroserviceData extends DomainVo { } private Long id; - + @SafeHtml private String name; - + @SafeHtml private String active; - + @SafeHtml private String desc; private long appId; - + @SafeHtml private String url; - + @SafeHtml private String securityType; - + @SafeHtml private String username; - + @SafeHtml private String password; - + @Valid private List parameterList; public Long getId() { diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/MicroserviceParameter.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/MicroserviceParameter.java index 0c645716..848c6a2a 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/MicroserviceParameter.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/MicroserviceParameter.java @@ -37,6 +37,7 @@ */ package org.onap.portalapp.portal.domain; +import org.hibernate.validator.constraints.SafeHtml; import org.onap.portalsdk.core.domain.support.DomainVo; public class MicroserviceParameter extends DomainVo { @@ -50,9 +51,9 @@ public class MicroserviceParameter extends DomainVo { private Long id; private long serviceId; - + @SafeHtml private String para_key; - + @SafeHtml private String para_value; public Long getId() { 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 roleFunctions) { - String[] path = portalApiPath.split("/"); - List 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/scheduler/SchedulerRestInt.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInt.java index cc371719..098846f0 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInt.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInt.java @@ -4,6 +4,8 @@ * =================================================================== * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== * * Unless otherwise specified, all software contained herein is licensed * under the Apache License, Version 2.0 (the "License"); @@ -38,23 +40,15 @@ package org.onap.portalapp.portal.scheduler; -import java.text.DateFormat; -import java.text.SimpleDateFormat; - +import org.onap.portalapp.util.DateUtil; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; public class SchedulerRestInt { /** The logger. */ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerRestInterface.class); - - /** The Constant dateFormat. */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - - /** The request date format. */ - public DateFormat requestDateFormat = new SimpleDateFormat("EEE, dd MMM YYYY HH:mm:ss z"); - + public SchedulerRestInt() { - requestDateFormat.setTimeZone(java.util.TimeZone.getTimeZone("GMT")); + DateUtil.getRequestDateFormat().setTimeZone(java.util.TimeZone.getTimeZone("GMT")); } } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerUtil.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerUtil.java index ce2048b2..c1ca8735 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerUtil.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerUtil.java @@ -4,6 +4,8 @@ * =================================================================== * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== * * Unless otherwise specified, all software contained herein is licensed * under the Apache License, Version 2.0 (the "License"); @@ -37,25 +39,21 @@ */ package org.onap.portalapp.portal.scheduler; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; - +import com.fasterxml.jackson.databind.ObjectMapper; import org.onap.portalapp.portal.scheduler.restobjects.GetTimeSlotsRestObject; import org.onap.portalapp.portal.scheduler.restobjects.PostCreateNewVnfRestObject; import org.onap.portalapp.portal.scheduler.restobjects.PostSubmitVnfChangeRestObject; 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.util.DateUtil; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.Date; public class SchedulerUtil { private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerUtil.class); - - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); public static GetTimeSlotsWrapper getTimeSlotsWrapResponse (GetTimeSlotsRestObject rs) { @@ -127,8 +125,10 @@ public class SchedulerUtil { r_json_str = mapper.writeValueAsString(t); } catch ( com.fasterxml.jackson.core.JsonProcessingException j ) { - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " Unable to parse object as json"); - } + logger.debug(EELFLoggerDelegate.debugLogger, + DateUtil.getDateFormat().format(new Date()) + "<== " + methodName + " Unable " + "to " + + "parse object as json"); + } } return (r_json_str); } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/client/HttpBasicClient.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/client/HttpBasicClient.java index 14b03478..17dc3f1e 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/client/HttpBasicClient.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/client/HttpBasicClient.java @@ -4,6 +4,8 @@ * =================================================================== * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== * * Unless otherwise specified, all software contained herein is licensed * under the Apache License, Version 2.0 (the "License"); @@ -39,9 +41,6 @@ package org.onap.portalapp.portal.scheduler.client; -import java.text.DateFormat; -import java.text.SimpleDateFormat; - import javax.servlet.ServletContext; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; @@ -64,10 +63,6 @@ public class HttpBasicClient{ /** The logger. */ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HttpBasicClient.class); - - /** The Constant dateFormat. */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - /** * Obtain a basic HTTP client . * diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/client/HttpsBasicClient.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/client/HttpsBasicClient.java index 857bec31..d618a6ee 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/client/HttpsBasicClient.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/client/HttpsBasicClient.java @@ -4,6 +4,8 @@ * =================================================================== * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== * * Unless otherwise specified, all software contained herein is licensed * under the Apache License, Version 2.0 (the "License"); @@ -39,7 +41,6 @@ package org.onap.portalapp.portal.scheduler.client; import java.io.File; -import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; @@ -55,8 +56,8 @@ import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.ClientProperties; import org.onap.portalapp.portal.scheduler.SchedulerProperties; import org.onap.portalapp.portal.scheduler.util.CustomJacksonJaxBJsonProvider; +import org.onap.portalapp.util.DateUtil; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.util.SystemProperties; /** * General SSL client using the VID tomcat keystore. It doesn't use client certificates. @@ -66,10 +67,7 @@ public class HttpsBasicClient{ /** The logger. */ static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HttpsBasicClient.class); - - /** The Constant dateFormat. */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - + /** * Retrieve an SSL client. * @@ -85,11 +83,14 @@ public class HttpsBasicClient{ SSLContext ctx = null; try { - + + SimpleDateFormat dateFormat = DateUtil.getDateFormat(); config.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true); String truststore_path = SchedulerProperties.getProperty(SchedulerProperties.VID_TRUSTSTORE_FILENAME); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + " " + methodName + " truststore_path=" + truststore_path); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + " " + methodName + " " + + "truststore_path=" + + truststore_path); String truststore_password = SchedulerProperties.getProperty(SchedulerProperties.VID_TRUSTSTORE_PASSWD_X); @@ -97,7 +98,8 @@ public class HttpsBasicClient{ //logger.debug(dateFormat.format(new Date()) + " " + methodName + " decrypted_truststore_password=" + decrypted_truststore_password); File tr = new File (truststore_path); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + " " + methodName + " absolute truststore path=" + tr.getAbsolutePath()); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + " " + methodName + " absolute " + + "truststore path=" + tr.getAbsolutePath()); //String keystore_path = certFilePath + AAIProperties.FILESEPARTOR + SystemProperties.getProperty(AAIProperties.AAI_KEYSTORE_FILENAME); //String keystore_password = SystemProperties.getProperty(AAIProperties.AAI_KEYSTORE_PASSWD_X); diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduleraux/SchedulerAuxRestInt.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduleraux/SchedulerAuxRestInt.java index 1785bd13..75919eee 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduleraux/SchedulerAuxRestInt.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduleraux/SchedulerAuxRestInt.java @@ -4,6 +4,8 @@ * =================================================================== * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== * * Unless otherwise specified, all software contained herein is licensed * under the Apache License, Version 2.0 (the "License"); @@ -38,11 +40,11 @@ package org.onap.portalapp.portal.scheduleraux; -import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import org.onap.portalapp.portal.scheduler.policy.rest.RequestDetails; +import org.onap.portalapp.util.DateUtil; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import com.fasterxml.jackson.databind.ObjectMapper; @@ -51,15 +53,9 @@ public class SchedulerAuxRestInt { /** The logger. */ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerAuxRestInterface.class); - - /** The Constant dateFormat. */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - - /** The request date format. */ - public DateFormat requestDateFormat = new SimpleDateFormat("EEE, dd MMM YYYY HH:mm:ss z"); - + public SchedulerAuxRestInt() { - requestDateFormat.setTimeZone(java.util.TimeZone.getTimeZone("GMT")); + DateUtil.getRequestDateFormat().setTimeZone(java.util.TimeZone.getTimeZone("GMT")); } /** @@ -68,6 +64,7 @@ public class SchedulerAuxRestInt { * @param r the r */ public void logRequest ( RequestDetails r ) { + SimpleDateFormat dateFormat = DateUtil.getDateFormat(); String methodName = "logRequest"; ObjectMapper mapper = new ObjectMapper(); String r_json_str = ""; @@ -77,9 +74,13 @@ public class SchedulerAuxRestInt { r_json_str = mapper.writeValueAsString(r); } catch ( com.fasterxml.jackson.core.JsonProcessingException j ) { - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " Unable to parse request as json"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " " + + "Unable to " + + "parse request as json"); } } - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " Request=(" + r_json_str + ")"); + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " Request=" + + "(" + + r_json_str + ")"); } -} \ No newline at end of file +} diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduleraux/SchedulerAuxRestInterface.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduleraux/SchedulerAuxRestInterface.java index e0a2fe5f..01a52cc8 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduleraux/SchedulerAuxRestInterface.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduleraux/SchedulerAuxRestInterface.java @@ -4,6 +4,8 @@ * =================================================================== * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== * * Unless otherwise specified, all software contained herein is licensed * under the Apache License, Version 2.0 (the "License"); @@ -37,19 +39,13 @@ */ package org.onap.portalapp.portal.scheduleraux; -import java.lang.reflect.Type; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Collections; -import java.util.Date; - -import javax.annotation.PostConstruct; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.Entity; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.Response; - +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; import org.apache.commons.codec.binary.Base64; import org.apache.cxf.jaxrs.impl.ResponseImpl; import org.eclipse.jetty.util.security.Password; @@ -59,26 +55,26 @@ import org.onap.portalapp.portal.logging.logic.EPLogUtil; import org.onap.portalapp.portal.scheduler.SchedulerProperties; import org.onap.portalapp.portal.scheduler.client.HttpBasicClient; import org.onap.portalapp.portal.scheduler.policy.rest.RequestDetails; +import org.onap.portalapp.util.DateUtil; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.http.HttpStatus; import org.springframework.web.client.HttpClientErrorException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonParseException; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.Response; +import java.lang.reflect.Type; +import java.text.SimpleDateFormat; +import java.util.Collections; +import java.util.Date; public class SchedulerAuxRestInterface extends SchedulerAuxRestInt implements SchedulerAuxRestInterfaceIfc { /** The logger. */ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerAuxRestInterface.class); - /** The Constant dateFormat. */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - /** The client. */ private static Client client = null; @@ -147,6 +143,7 @@ public class SchedulerAuxRestInterface extends SchedulerAuxRestInt implements Sc String methodName = "Get"; logger.debug(EELFLoggerDelegate.debugLogger, " start", methodName); + SimpleDateFormat dateFormat = DateUtil.getDateFormat(); String url = ""; restObject.set(t); @@ -165,8 +162,8 @@ public class SchedulerAuxRestInterface extends SchedulerAuxRestInt implements Sc if (status == 200) { t = (T) cres.readEntity(t.getClass()); restObject.set(t); - logger.debug(EELFLoggerDelegate.debugLogger, " REST api was successfull!", dateFormat.format(new Date()), - methodName); + logger.debug(EELFLoggerDelegate.debugLogger, " REST api was successfull!", + dateFormat.format(new Date()), methodName); } else { throw new Exception(methodName + " with status=" + status + ", url= " + url); @@ -183,6 +180,7 @@ public class SchedulerAuxRestInterface extends SchedulerAuxRestInt implements Sc String methodName = "Delete"; String url = ""; Response cres = null; + SimpleDateFormat dateFormat = DateUtil.getDateFormat(); logRequest(r); @@ -191,7 +189,7 @@ public class SchedulerAuxRestInterface extends SchedulerAuxRestInt implements Sc url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_SERVER_URL_VAL) + path; logger.debug(EELFLoggerDelegate.debugLogger, " methodName sending request to: ", - dateFormat.format(new Date()), url, methodName); + dateFormat.format(new Date()), url, methodName); cres = client.target(url).request().accept("application/json").headers(commonHeaders) // .entity(r) @@ -235,8 +233,8 @@ public class SchedulerAuxRestInterface extends SchedulerAuxRestInt implements Sc url, e); EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value()); } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "Exception with the URL ", dateFormat.format(new Date()), - methodName, url, e); + logger.error(EELFLoggerDelegate.errorLogger, "Exception with the URL ", + dateFormat.format(new Date()), methodName, url, e); EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value()); throw e; @@ -324,4 +322,4 @@ public class SchedulerAuxRestInterface extends SchedulerAuxRestInt implements Sc public void logRequest(RequestDetails r) { // TODO Auto-generated method stub } -} \ No newline at end of file +} diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduleraux/SchedulerAuxUtil.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduleraux/SchedulerAuxUtil.java index 4a4c9283..f0f0af5a 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduleraux/SchedulerAuxUtil.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduleraux/SchedulerAuxUtil.java @@ -4,6 +4,8 @@ * =================================================================== * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== * * Unless otherwise specified, all software contained herein is licensed * under the Apache License, Version 2.0 (the "License"); @@ -37,18 +39,13 @@ */ package org.onap.portalapp.portal.scheduleraux; -import java.text.DateFormat; -import java.text.SimpleDateFormat; - import org.glassfish.jersey.client.ClientResponse; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; public class SchedulerAuxUtil { private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerAuxUtil.class); - - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - + public static SchedulerAuxResponseWrapper wrapResponse ( String body, int statusCode ) { SchedulerAuxResponseWrapper w = new SchedulerAuxResponseWrapper(); 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 getRolesByApp(EPUser user, Long appId); public boolean isAccountAdminOfApplication(EPUser user, EPApp app); + public Set 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 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 apps = appsService.getAppsFullList(); HashMap enabledApps = new HashMap(); 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 newAppsWhereUserIsAdmin = new ArrayList(); 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 getAllAppsFunctionsOfUser(String OrgUserId) throws RoleFunctionException { + final Map params = new HashMap<>(); + params.put("userId", OrgUserId); + List getRoleFuncListOfPortal = dataAccessService.executeNamedQuery("getAllAppsFunctionsOfUser", params, null); + Set getRoleFuncListOfPortalSet = new HashSet<>(getRoleFuncListOfPortal); + Set 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 finalRoleFunctionSet = new HashSet<>(); + for (String roleFn : getRoleFuncListOfPortalSet) { + finalRoleFunctionSet.add(EPUserUtils.decodeFunctionCode(roleFn)); + } + +// List functionsOfUser = new ArrayList<>(getRoleFuncListOfPortal); + return finalRoleFunctionSet; + } + + + @Override + public boolean isAccountAdminOfAnyActiveorInactiveApplication(EPUser user, EPApp app) { + Boolean isApplicationAccountAdmin=false; + try { + final Map userParams = new HashMap<>(); + userParams.put("userId", user.getId()); + logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for user {}", user.getId()); + List 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 5c3c51bf..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 @@ -4,6 +4,8 @@ * =================================================================== * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== * * Unless otherwise specified, all software contained herein is licensed * under the Apache License, Version 2.0 (the "License"); @@ -48,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; @@ -58,12 +61,13 @@ 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; import org.onap.portalapp.portal.domain.AppsResponse; 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.domain.EPUserAppRolesRequest; import org.onap.portalapp.portal.domain.EPUserAppRolesRequestDetail; @@ -95,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; @@ -109,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); @@ -120,6 +133,8 @@ public class EPAppCommonServiceImpl implements EPAppService { protected SessionFactory sessionFactory; @Autowired private DataAccessService dataAccessService; + + RestTemplate template = new RestTemplate(); @PostConstruct private void init() { @@ -128,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 getUserAsAdminApps(EPUser user) { @@ -405,6 +479,23 @@ public class EPAppCommonServiceImpl implements EPAppService { return appsModified; } + + @Override + public List 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 apps = all + ? (List) dataAccessService.getList(EPApp.class, " where id != " + ECOMP_APP_ID, "name", null) + :dataAccessService.getList(EPApp.class, null); + + List appsModified = new ArrayList(); + 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 params = new HashMap<>(); @@ -487,13 +578,13 @@ 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 || onboardingApp.url.length() == 0 || onboardingApp.restrictedApp == null || onboardingApp.isOpen == null || onboardingApp.isEnabled == null - || (onboardingApp.id != null && onboardingApp.id.equals(ECOMP_APP_ID)) + || (onboardingApp.id != null && ECOMP_APP_ID.equals(onboardingApp.id.toString())) // For a normal app (appType == PortalConstants.PortalAppId), // these fields must be filled // in. @@ -509,7 +600,7 @@ public class EPAppCommonServiceImpl implements EPAppService { if (onboardingApp.name == null || onboardingApp.name.length() == 0 || onboardingApp.url == null || onboardingApp.url.length() == 0 || onboardingApp.restrictedApp == null || onboardingApp.isOpen == null || onboardingApp.isEnabled == null - || (onboardingApp.id != null && onboardingApp.id.equals(ECOMP_APP_ID)) + || (onboardingApp.id != null && ECOMP_APP_ID.equals(onboardingApp.id.toString())) // For a normal app (appType == PortalConstants.PortalAppId), // these fields must be filled // in. @@ -525,7 +616,7 @@ public class EPAppCommonServiceImpl implements EPAppService { } return fieldsValidator; - } + }*/ @Override public List getUserApps(EPUser user) { @@ -738,6 +829,27 @@ public class EPAppCommonServiceImpl implements EPAppService { } return onboardingAppsList; } + + @SuppressWarnings("unchecked") + @Override + public List getAdminAppsOfUser(EPUser user) { + + List onboardingAppsList = new ArrayList(); + List userAdminApps = new ArrayList<>(); + final Map 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 userAdminApps1 = userAdminApps; + List userApplicationAdmins = onboardingAppsList.stream().filter(x -> userAdminApps1.contains((int) (long)x.id)).collect(Collectors.toList()); + + return userApplicationAdmins; + } @Override public List getEnabledNonOpenOnboardingApps() { @@ -756,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 apps; if (onboardingApp.id == null) { List restrictionsList = new ArrayList(); - 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) dataAccessService.getList(EPApp.class, null, restrictionsList, null); - - } else { List restrictionsList = new ArrayList(); 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) dataAccessService.getList(EPApp.class, null, restrictionsList, null); @@ -784,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); @@ -1494,7 +1615,7 @@ public class EPAppCommonServiceImpl implements EPAppService { // Don't encrypt or decrypt the password if it is null or the empty string private String decryptedPassword(String encryptedAppPwd, EPApp app) { String result = ""; - if (encryptedAppPwd != null & encryptedAppPwd.length() > 0) { + if (encryptedAppPwd != null && !encryptedAppPwd.isEmpty()) { try { result = CipherUtil.decryptPKC(encryptedAppPwd, SystemProperties.getProperty(SystemProperties.Decryption_Key)); @@ -1507,7 +1628,7 @@ public class EPAppCommonServiceImpl implements EPAppService { protected String encryptedPassword(String decryptedAppPwd, EPApp app) { String result = ""; - if (decryptedAppPwd != null & decryptedAppPwd.length() > 0) { + if (decryptedAppPwd != null && !decryptedAppPwd.isEmpty()) { try { result = CipherUtil.encryptPKC(decryptedAppPwd, SystemProperties.getProperty(SystemProperties.Decryption_Key)); @@ -1800,4 +1921,57 @@ public class EPAppCommonServiceImpl implements EPAppService { return userAndRoles; } -} \ No newline at end of file + + @SuppressWarnings("unused") + @Override + public ResponseEntity checkIfNameSpaceIsValid(String namespace) throws Exception { + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity entity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Connecting to External Auth system for : "+namespace); + ResponseEntity 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 list = new ArrayList(); + 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 getAdminAppsOfUser(EPUser user); + + public ResponseEntity checkIfNameSpaceIsValid(String namespace) throws Exception ; + + List 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 @@ -415,13 +415,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 getAppRoles(Long appId) throws Exception { - List applicationRoles = null; - final Map 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 getApp(String uebkey) throws Exception { - List app = null; - try { - final Map 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 entity = new HttpEntity<>(headers); - ResponseEntity 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 addResponse = null; - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - EPApp app = getApp(uebkey).get(0); - String newRole = updateExistingRoleInExternalSystem(addRole, app); - HttpEntity 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 deleteRoleInExternalSystem(String delRole) throws Exception { - ResponseEntity delResponse = null; - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - HttpEntity 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 deleteResponse = null; - List 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 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 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 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 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 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 deleteResponse; - Map 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 roleFunctionListNew, String name, List list) throws Exception { - boolean response; - Map updateRoleFunc = new HashMap<>(); - for (RoleFunction addPerm : roleFunctionListNew) { - updateRoleFunc.put(addPerm.getCode(), addPerm); - } - final Map extRolePermMap = new HashMap<>(); - final Map 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 entity = new HttpEntity<>(updateRolePerms, headers); - logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: {} for POST: {}", - CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms); - ResponseEntity 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 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 entity = new HttpEntity<>(addPerms, headers); - logger.debug(EELFLoggerDelegate.debugLogger, "addPartnerHasRoleFunctionsToGlobalRole: {} ", - CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); - try { - ResponseEntity 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 epRoleList, Role updateExtRole, - List 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 permsDetailList = getExtAuthPerrmissonList(app, extPerms); - final Map existingPermsWithRoles = new HashMap<>(); - final Map existingPermsWithRolesWithPipes = new HashMap<>(); - final Map userRquestedFunctionsMap = new HashMap<>(); - final Map 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 epAppRoleFuncParams = new HashMap<>(); - epAppRoleFuncParams.put("requestedAppId", app.getId()); - epAppRoleFuncParams.put("roleId", updateExtRole.getId()); - List 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 entity = new HttpEntity<>(updateRolePerms, headers); - logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} ", - CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); - ResponseEntity 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 entity = new HttpEntity<>(updateRolePerms, headers); - logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} for POST: {} ", - CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms); - ResponseEntity 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 convertSetToListOfRoleFunctions(Role updateExtRole) { - Set roleFunctionSetList = updateExtRole.getRoleFunctions(); - List roleFunctionList = new ArrayList<>(); - ObjectMapper roleFuncMapper = new ObjectMapper(); - Iterator 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 deleteEntity = new HttpEntity<>(permDetails, headers); - logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: {} for DELETE: {} ", - CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, permDetails); - ResponseEntity 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 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 postEntity = new HttpEntity<>(addNewRole, headers); - logger.debug(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: {} for POST: {} ", - CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addNewRole); - ResponseEntity 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 roleFunctionList = addRoleInDB.getRoleFunctions(); - List roleFunctionListNew = new ArrayList<>(); - ObjectMapper mapper = new ObjectMapper(); - Iterator itetaror = roleFunctionList.iterator(); - while (itetaror.hasNext()) { - Object nextValue = itetaror.next(); - RoleFunction roleFunction = mapper.convertValue(nextValue, RoleFunction.class); - roleFunctionListNew.add(roleFunction); - } - List 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 getRoleCreated = null; - final Map epAppRoleParams = new HashMap<>(); - final Map 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 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 applicationRoles; - List 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 checkRoleEntity = new HttpEntity<>(headers); - logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRoleExitsInExternalSystem: {} ", - CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); - ResponseEntity 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 roleFunctionListNew, EPApp app, List applicationRoles, - Long roleAppId) throws Exception { - final Map 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 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 roleFunction) { - final Map appFunctionsFilter = new HashMap<>(); - final Map 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 role) { - final Map appRoleFuncsParams = new HashMap<>(); - appRoleFuncsParams.put("appId", app.getId()); - appRoleFuncsParams.put("roleId", role.get(0).getId()); - List appRoleFunctionList = - dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null); - if (!appRoleFunctionList.isEmpty()) { - for (EPAppRoleFunction approleFunction : appRoleFunctionList) { - dataAccessService.deleteDomainObject(approleFunction, null); - } - } - } - - @Override - @SuppressWarnings("unchecked") - public List getUser(String loginId) throws InvalidUserException { - final Map userParams = new HashMap<>(); - userParams.put("org_user_id", loginId); - List 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 params = new HashMap<>(); - List userList = null; - CentralV2User cenV2User = null; - String result = null; - try { - params.put("orgUserIdValue", loginId); - List 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 getRolesForApp(String uebkey) throws Exception { - logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Entering into getRolesForApp"); - List roleList = new ArrayList<>(); - final Map params = new HashMap<>(); - try { - List app = getApp(uebkey); - List appRolesList = getAppRoles(app.get(0).getId()); - roleList = createCentralRoleObject(app, appRolesList, roleList, params); - if (app.get(0).getId() != PortalConstants.PORTAL_APP_ID) { - List globalRoleList = getGlobalRolesOfApplication(app.get(0).getId()); - List globalRolesList = getGlobalRolesOfPortal(); - List 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 getRoleFuncList(String uebkey) throws Exception { - EPApp app = getApp(uebkey).get(0); - List finalRoleList = new ArrayList<>(); - final Map params = new HashMap<>(); - params.put(APP_ID, app.getId()); - List 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 userAppSet, EPApp app) throws Exception { - final Map params = new HashMap<>(); - CentralV2User userAppList = new CentralV2User(); - CentralV2User user1 = null; - final Map params1 = new HashMap<>(); - List 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()); - 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 appRoleFunctionList = - dataAccessService.executeNamedQuery("getAppRoleFunctionList", params, null); - SortedSet 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 params = new HashMap<>(); - List roleList = new ArrayList<>(); - CentralV2Role cenRole = new CentralV2Role(); - List roleInfo = null; - List 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 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 getPartnerAppRoleInfo(Long roleId, EPApp app) { - List roleInfo; - final Map 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 getPortalAppRoleInfo(Long roleId) { - List roleInfo; - final Map 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 createCentralRoleObject(List app, List roleInfo, - List roleList, Map params) throws RoleFunctionException { - for (EPRole role : roleInfo) { - params.put("roleId", role.getId()); - params.put(APP_ID, app.get(0).getId()); - List cenRoleFuncList = - dataAccessService.executeNamedQuery("getAppRoleFunctionList", params, null); - SortedSet 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 childRoles = new TreeSet<>(); - SortedSet 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 getRoleFuncList = null; - final Map 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 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 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 entity = new HttpEntity<>(addFunction, headers); - logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for POST: {}", - CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction); - ResponseEntity 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 entity = new HttpEntity<>(updateRoleFunction, headers); - logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for PUT: {}", - CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRoleFunction); - ResponseEntity 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 params = new HashMap<>(); - params.put(FUNCTION_CODE_PARAMS, code); - params.put(APP_ID, String.valueOf(app.getId())); - List 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 entity = new HttpEntity<>(deleteRoleFunction, headers); - logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleFunctionInExternalSystem: {} for DELETE: {} ", - CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, deleteRoleFunction); - ResponseEntity 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 epRoleList = null; - EPApp app = getApp(uebkey).get(0); - final Map 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 epRoleList, EPApp app) throws Exception { - ResponseEntity deleteResponse; - ResponseEntity 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 entity = new HttpEntity<>(headers); - getNameSpaceIfExists(app); - logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} ", - CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); - ResponseEntity 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 userRoleentity = new HttpEntity<>(headers); - logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} ", - CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); - ResponseEntity 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 getActiveRoles(String uebkey) throws Exception { - List roleList = new ArrayList<>(); - try { - List app = getApp(uebkey); - final Map 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 restrictionsList = new ArrayList(); - 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 = (List) dataAccessService.getList(EPRole.class, null, restrictionsList, null); - roleList = createCentralRoleObject(app, epRole, roleList, params); - List 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 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 permsDetailList = getExtAuthPerrmissonList(app, extPerms); - // get functions in DB - final Map params = new HashMap<>(); - final Map roleFuncMap = new HashMap<>(); - params.put(APP_ID, app.getId()); - List 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 portalRoleList = getGlobalRolesOfPortal(); - final Map 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 currentRolesInDB = getAppRoleNamesWithUnderscoreMap(app); - // store External Permissions with Pipe and without Pipe (just - // instance) - final Map extAccessPermsContainsPipeMap = new HashMap<>(); - final Map 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 roleFunctionList = - addGetLocalFunction(app, roleFuncMap, permsDetail, code, getFunctionCodeKey); - List 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 currentRolesInDB, - List roleFunctionList, List roles, - Map existingPortalRolesMap) throws Exception { - if (!roleFunctionList.isEmpty()) { - final Map appRoleFuncParams = new HashMap<>(); - final Map currentAppRoleFunctionsMap = new HashMap<>(); - final Map currentRolesInExtSystem = new HashMap<>(); - appRoleFuncParams.put("functionCd", roleFunctionList.get(0).getCode()); - appRoleFuncParams.put("appId", String.valueOf(app.getId())); - List 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 params = new HashMap<>(); - EPRole role = existingPortalRolesMap.get(extAuthAppRoleName); - EPAppRoleFunction addGlobalRoleFunctions = new EPAppRoleFunction(); - params.put("appId", app.getId()); - params.put("roleId", role.getId()); - List 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 currentRolesInDB, - List 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 addGetLocalFunction(EPApp app, - final Map roleFuncMap, ExternalAccessPermsDetail permsDetail, String code, - CentralV2RoleFunction getFunctionCodeKey) { - String finalFunctionCodeVal = - addToLocalIfFunctionNotExists(app, roleFuncMap, permsDetail, code, getFunctionCodeKey); - final Map appSyncFuncsParams = new HashMap<>(); - appSyncFuncsParams.put("appId", String.valueOf(app.getId())); - appSyncFuncsParams.put("functionCd", finalFunctionCodeVal); - List 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 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 getAppRoleNamesWithUnderscoreMap(EPApp app) { - final Map currentRolesInDB = new HashMap<>(); - List getCurrentRoleList = null; - final Map 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 getAppRoleNamesMap(EPApp app) { - final Map currentRolesInDB = new HashMap<>(); - List getCurrentRoleList = null; - final Map 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 getExtAuthPerrmissonList(EPApp app, JSONArray extPerms) throws IOException { - ExternalAccessPermsDetail permDetails = null; - List 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 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 response = null; - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - HttpEntity 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 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 getRoleByNameParams = new HashMap<>(); - List 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 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 roleParams = new HashMap<>(); - roleParams.put(APP_ROLE_NAME_PARAM, role); - List 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 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 app = getApp(uebkey); - List roles = getAppRoles(app.get(0).getId()); - List cenRoleList = new ArrayList<>(); - final Map 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 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 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 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 roles = getAppRoles(app.getId()); - final Map params = new HashMap<>(); - Integer roleFunctions = 0; - try { - for (EPRole role : roles) { - params.put("roleId", role.getId()); - List 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 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 params = new HashMap<>(); - params.put("appId", app.getId()); - List 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 entity = new HttpEntity<>(addFunction, headers); - logger.debug(EELFLoggerDelegate.debugLogger, "addFunctionInExternalSystem: {} for POST: {}", - CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction); - ResponseEntity 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 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 roles = getAppRoles(app.getId()); - final Map params = new HashMap<>(); - Integer roleFunctions = 0; - try { - for (EPRole role : roles) { - params.put("roleId", role.getId()); - List 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 params = new HashMap<>(); - params.put("appId", app.getId()); - List 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 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 externalRoleDetailsList = getExternalRoleDetailsList(app, mapper, extRole); - List finalRoleList = new ArrayList<>(); - for (ExternalRoleDetails externalRole : externalRoleDetailsList) { - EPRole ecompRole = convertExternalRoleDetailstoEpRole(externalRole); - finalRoleList.add(ecompRole); - } - List applicationRolesList; - applicationRolesList = getAppRoles(app.getId()); - List applicationRoleIdList = new ArrayList<>(); - for (EPRole applicationRole : applicationRolesList) { - applicationRoleIdList.add(applicationRole.getName()); - } - List 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 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 getRoleCreatedInSync = null; - if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) { - final Map 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 roleList = new ArrayList<>(); - final Map 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 finalRoleList) { - for (EPRole roleItem : finalRoleList) { - final Map roleParams = new HashMap<>(); - List 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 finalRoleList, - List applicationRolesList) { - final Map checkRolesInactive = new HashMap<>(); - for (EPRole extrole : finalRoleList) { - checkRolesInactive.put(extrole.getName(), extrole); - } - for (EPRole role : applicationRolesList) { - try { - final Map extRoleParams = new HashMap<>(); - List 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 getExternalRoleDetailsList(EPApp app, ObjectMapper mapper, JSONArray extRole) - throws IOException { - List externalRoleDetailsList = new ArrayList<>(); - ExternalAccessPerms externalAccessPerms = new ExternalAccessPerms(); - List functionCodelist = new ArrayList<>(); - Map curRolesMap = getAppRoleNamesMap(app); - Map 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 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 roleFunctionsMap = new HashMap<>(); - final Map appRoleFuncsParams = new HashMap<>(); - if (roleId != null) { - appRoleFuncsParams.put("appId", app.getId()); - appRoleFuncsParams.put("roleId", roleId); - // get role functions from DB - List 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 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 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 response = null; - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - HttpEntity 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 response = null; - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - HttpEntity 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 params = new HashMap<>(); - params.put("uebKey", app.getUebKey()); - List 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 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 getMenuFunctionsList(String uebkey) throws Exception { - List appMenuFunctionsList = null; - List appMenuFunctionsFinalList = new ArrayList<>(); - try { - EPApp app = getApp(uebkey).get(0); - final Map 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 getAllAppUsers(String uebkey) throws Exception { - List usersList = new ArrayList<>(); - List usersfinalList = new ArrayList<>(); - try { - EPApp app = getApp(uebkey).get(0); - final Map appParams = new HashMap<>(); - appParams.put("appId", app.getId()); - List userList = - (List) dataAccessService.executeNamedQuery("ApplicationUserRoles", appParams, null); - for (EcompUserRoles ecompUserRole : userList) { - boolean found = false; - Set 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 roleFunctionSet = new TreeSet<>(); - if (role != null) { - roleFunctionSet = (SortedSet) 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 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 roleFunctionList = newRole.getRoleFunctions(); - Set roleFunctionListNew = new HashSet<>(); - Iterator 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 getCentralizedAppsOfUser(String userId) { - Map params = new HashMap<>(); - params.put("userId", userId); - List 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 getGlobalRolesOfApplication(Long appId) { - Map params = new HashMap<>(); - params.put("appId", appId); - List globalRoles = new ArrayList<>(); - try { - globalRoles = - dataAccessService.executeNamedQuery("getGlobalRoleWithApplicationRoleFunctions", params, null); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e); - } - List 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 roleWithApplicationRoleFucntions = new ArrayList<>(); - Map 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 rolesfinalList = finalListOfCentralRoles(roleWithApplicationRoleFucntions); - finalGlobalrole = rolesfinalList.get(0); - } else { - List roleList = getPortalAppRoleInfo(roleId); - finalGlobalrole = convertRoleToCentralV2Role(roleList.get(0)); - } - return finalGlobalrole; - } - - private List finalListOfCentralRoles(List globalRoles) { - List rolesfinalList = new ArrayList<>(); - for (GlobalRoleWithApplicationRoleFunction role : globalRoles) { - boolean found = false; - for (CentralV2Role cenRole : rolesfinalList) { - if (role.getRoleId().equals(cenRole.getId())) { - SortedSet 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 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 getGlobalRolesOfPortal() { - List 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 convertCentralRoleFunctionToRoleFunctionObject( - List answer) { - List 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 epUserList; - List appList = getApp(uebkey); - app = appList.get(0); - epUserList = getUser(loginId); - EPUser user = epUserList.get(0); - Set userAppSet = user.getEPUserApps(); - return createEPUser(user, userAppSet, app); - } - - private List getUserAppRoles(EPApp app, EPUser user) { - final Map userParams = new HashMap<>(); - userParams.put("appId", app.getId()); - userParams.put("userId", user.getId()); - @SuppressWarnings("unchecked") - List userAppsRolesList = - dataAccessService.executeNamedQuery("getUserAppCurrentRoles", userParams, null); - List 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 missingUserApplicationRoles(String uebkey, String loginId, Set CurrentUserRoles) - throws Exception { - List appList = getApp(uebkey); - EPApp app = appList.get(0); - List epUserList; - epUserList = getUser(loginId); - List missingUserAppRoles = new ArrayList<>(); - List roleNamesList = CurrentUserRoles.stream().map(EcompRole::getName).collect(Collectors.toList()); - logger.debug(EELFLoggerDelegate.debugLogger, "Roles of User from hibernate :" + roleNamesList); - List userApplicationsRolesfromDB = getUserAppRoles(app, epUserList.get(0)); - if (userApplicationsRolesfromDB.size() > 0) { - missingUserAppRoles = userApplicationsRolesfromDB.stream().filter(x -> !roleNamesList.contains(x.getName())) - .collect(Collectors.toList()); - } - List MissingroleNamesList = - missingUserAppRoles.stream().map(EcompRole::getName).collect(Collectors.toList()); - logger.debug(EELFLoggerDelegate.debugLogger, "MissingUserAppRoles():" + MissingroleNamesList); - - List finalMissingRoleList = new ArrayList<>(); - if (missingUserAppRoles.size() > 0) { - final Map 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 appRoleFunctionList = - dataAccessService.executeNamedQuery("getAppRoleFunctionList", params, null); - SortedSet 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 userV2Apps = cenV2User.getUserApps(); - Set userApps = new TreeSet<>(); - for (CentralV2UserApp userApp : userV2Apps) { - CentralApp app = userApp.getApp(); - CentralUserApp cua = new CentralUserApp(); - cua.setUserId(null); - cua.setApp(app); - SortedSet 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 convertV2CentralRoleListToOldVerisonCentralRoleList(List v2CenRoleList) { - List cenRoleList = new ArrayList<>(); - for (CentralV2Role v2CenRole : v2CenRoleList) { - SortedSet 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 getNameSpaceIfExists(EPApp app) throws Exception { - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - HttpEntity entity = new HttpEntity<>(headers); - logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Connecting to External Auth system"); - ResponseEntity 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 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 params = new HashMap<>(); - params.put("uebKey", app.getUebKey()); - params.put("roleId", String.valueOf(roleId)); - List 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 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 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 entity) { - logger.debug(EELFLoggerDelegate.debugLogger, "bulkUploadRoleFunc: {} for POST: {}", - CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms); - ResponseEntity 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 getUserRolesEntity = new HttpEntity<>(headers); - ResponseEntity getResponse = getUserRolesFromExtAuthSystem(name, getUserRolesEntity); - List 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 userRoleDetailList, JSONArray extRoles, - String loginId) throws InvalidUserException { - HashMap userParams = new HashMap<>(); - userParams.put("orgUserId", loginId); - // Get all centralized applications existing user roles from local - List currentUserAppRoles = - dataAccessService.executeNamedQuery("getUserCentralizedAppRoles", userParams, null); - EPUser user = getUser(loginId).get(0); - // Get all centralized applications roles from local - HashMap cenAppRolesMap = getCentralizedAppRoleList(); - HashMap currentCentralizedUserAppRolesMap = - getCurrentUserCentralizedAppRoles(currentUserAppRoles); - // Get all centralized applications + admin role from local - HashMap 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 userRoleDetailList, EPUser user, - HashMap cenAppRolesMap, - HashMap currentCentralizedUserAppRolesMap, - HashMap 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 getCentralizedAdminAppsInfo() { - List centralizedApps = dataAccessService.executeNamedQuery("getCentralizedApps", null, null); - HashMap 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 getCurrentUserCentralizedAppRoles( - List currentUserAppRoles) { - HashMap 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 getCentralizedAppRoleList() { - List centralizedAppRoles = - dataAccessService.executeNamedQuery("getAllCentralizedAppsRoles", null, null); - HashMap 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 getUserRolesFromExtAuthSystem(String name, HttpEntity getUserRolesEntity) { - logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles"); - ResponseEntity 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 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 getAppRoles(Long appId) throws Exception { + List applicationRoles = null; + final Map 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 getApp(String uebkey) throws Exception { + List app = null; + try { + final Map 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 entity = new HttpEntity<>(headers); + ResponseEntity 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 addResponse = null; + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + EPApp app = getApp(uebkey).get(0); + String newRole = updateExistingRoleInExternalSystem(addRole, app); + HttpEntity 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 deleteRoleInExternalSystem(String delRole) throws Exception { + ResponseEntity delResponse = null; + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity 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 deleteResponse = null; + List 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 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 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 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 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 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 deleteResponse; + Map 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 roleFunctionListNew, String name, List list) throws Exception { + boolean response; + Map updateRoleFunc = new HashMap<>(); + for (RoleFunction addPerm : roleFunctionListNew) { + updateRoleFunc.put(addPerm.getCode(), addPerm); + } + final Map extRolePermMap = new HashMap<>(); + final Map 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 entity = new HttpEntity<>(updateRolePerms, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: {} for POST: {}", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms); + ResponseEntity 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 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 entity = new HttpEntity<>(addPerms, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "addPartnerHasRoleFunctionsToGlobalRole: {} ", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); + try { + ResponseEntity 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 epRoleList, Role updateExtRole, + List 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 permsDetailList = getExtAuthPerrmissonList(app, extPerms); + final Map existingPermsWithRoles = new HashMap<>(); + final Map existingPermsWithRolesWithPipes = new HashMap<>(); + final Map userRquestedFunctionsMap = new HashMap<>(); + final Map 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 epAppRoleFuncParams = new HashMap<>(); + epAppRoleFuncParams.put("requestedAppId", app.getId()); + epAppRoleFuncParams.put("roleId", updateExtRole.getId()); + List 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 entity = new HttpEntity<>(updateRolePerms, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} ", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); + ResponseEntity 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 entity = new HttpEntity<>(updateRolePerms, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} for POST: {} ", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms); + ResponseEntity 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 convertSetToListOfRoleFunctions(Role updateExtRole) { + Set roleFunctionSetList = updateExtRole.getRoleFunctions(); + List roleFunctionList = new ArrayList<>(); + ObjectMapper roleFuncMapper = new ObjectMapper(); + Iterator 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 deleteEntity = new HttpEntity<>(permDetails, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: {} for DELETE: {} ", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, permDetails); + ResponseEntity 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 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 postEntity = new HttpEntity<>(addNewRole, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: {} for POST: {} ", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addNewRole); + ResponseEntity 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 roleFunctionList = addRoleInDB.getRoleFunctions(); + List roleFunctionListNew = new ArrayList<>(); + ObjectMapper mapper = new ObjectMapper(); + Iterator itetaror = roleFunctionList.iterator(); + while (itetaror.hasNext()) { + Object nextValue = itetaror.next(); + RoleFunction roleFunction = mapper.convertValue(nextValue, RoleFunction.class); + roleFunctionListNew.add(roleFunction); + } + List 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 getRoleCreated = null; + final Map epAppRoleParams = new HashMap<>(); + final Map 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 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 applicationRoles; + List 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 checkRoleEntity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRoleExitsInExternalSystem: {} ", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); + ResponseEntity 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 roleFunctionListNew, EPApp app, List applicationRoles, + Long roleAppId) throws Exception { + final Map 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 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 roleFunction) { + final Map appFunctionsFilter = new HashMap<>(); + final Map 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 role) { + final Map appRoleFuncsParams = new HashMap<>(); + appRoleFuncsParams.put("appId", app.getId()); + appRoleFuncsParams.put("roleId", role.get(0).getId()); + List appRoleFunctionList = dataAccessService + .executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null); + if (!appRoleFunctionList.isEmpty()) { + for (EPAppRoleFunction approleFunction : appRoleFunctionList) { + dataAccessService.deleteDomainObject(approleFunction, null); + } + } + } + + @Override + @SuppressWarnings("unchecked") + public List getUser(String loginId) throws InvalidUserException { + final Map userParams = new HashMap<>(); + userParams.put("org_user_id", loginId); + List 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 params = new HashMap<>(); + List userList = null; + CentralV2User cenV2User = null; + String result = null; + try { + params.put("orgUserIdValue", loginId); + List 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 getRolesForApp(String uebkey) throws Exception { + logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Entering into getRolesForApp"); + List roleList = new ArrayList<>(); + final Map params = new HashMap<>(); + try { + List app = getApp(uebkey); + List appRolesList = getAppRoles(app.get(0).getId()); + roleList = createCentralRoleObject(app, appRolesList, roleList, params); + if (app.get(0).getId() != PortalConstants.PORTAL_APP_ID) { + List globalRoleList = getGlobalRolesOfApplication(app.get(0).getId()); + List globalRolesList = getGlobalRolesOfPortal(); + List 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 getRoleFuncList(String uebkey) throws Exception { + EPApp app = getApp(uebkey).get(0); + List finalRoleList = new ArrayList<>(); + final Map params = new HashMap<>(); + params.put(APP_ID, app.getId()); + List 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 userAppSet, EPApp app) throws Exception { + final Map params = new HashMap<>(); + CentralV2User userAppList = new CentralV2User(); + CentralV2User user1 = null; + final Map params1 = new HashMap<>(); + List 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()); + 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 appRoleFunctionList = dataAccessService + .executeNamedQuery("getAppRoleFunctionList", params, null); + SortedSet 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 params = new HashMap<>(); + List roleList = new ArrayList<>(); + CentralV2Role cenRole = new CentralV2Role(); + List roleInfo = null; + List 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 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 getPartnerAppRoleInfo(Long roleId, EPApp app) { + List roleInfo; + final Map 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 getPortalAppRoleInfo(Long roleId) { + List roleInfo; + final Map 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 createCentralRoleObject(List app, List roleInfo, + List roleList, Map params) throws RoleFunctionException { + for (EPRole role : roleInfo) { + params.put("roleId", role.getId()); + params.put(APP_ID, app.get(0).getId()); + List cenRoleFuncList = dataAccessService.executeNamedQuery("getAppRoleFunctionList", + params, null); + SortedSet 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 childRoles = new TreeSet<>(); + SortedSet 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 getRoleFuncList = null; + final Map 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 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 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 entity = new HttpEntity<>(addFunction, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for POST: {}", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction); + ResponseEntity 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 entity = new HttpEntity<>(updateRoleFunction, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for PUT: {}", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRoleFunction); + ResponseEntity 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 params = new HashMap<>(); + params.put(FUNCTION_CODE_PARAMS, code); + params.put(APP_ID, String.valueOf(app.getId())); + List 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 entity = new HttpEntity<>(deleteRoleFunction, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleFunctionInExternalSystem: {} for DELETE: {} ", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, deleteRoleFunction); + ResponseEntity 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 epRoleList = null; + EPApp app = getApp(uebkey).get(0); + final Map 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 epRoleList, EPApp app) throws Exception { + ResponseEntity deleteResponse; + ResponseEntity 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 entity = new HttpEntity<>(headers); + getNameSpaceIfExists(app); + logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} ", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); + ResponseEntity 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 userRoleentity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} ", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); + ResponseEntity 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 getActiveRoles(String uebkey) throws Exception { + List roleList = new ArrayList<>(); + try { + List app = getApp(uebkey); + final Map 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 restrictionsList = new ArrayList(); + 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 = (List) dataAccessService.getList(EPRole.class, null, restrictionsList, null); + roleList = createCentralRoleObject(app, epRole, roleList, params); + List 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 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 permsDetailList = getExtAuthPerrmissonList(app, extPerms); + // get functions in DB + final Map params = new HashMap<>(); + final Map roleFuncMap = new HashMap<>(); + params.put(APP_ID, app.getId()); + List 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 portalRoleList = getGlobalRolesOfPortal(); + final Map 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 currentRolesInDB = getAppRoleNamesWithUnderscoreMap(app); + // store External Permissions with Pipe and without Pipe (just + // instance) + final Map extAccessPermsContainsPipeMap = new HashMap<>(); + final Map 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 roleFunctionList = addGetLocalFunction(app, roleFuncMap, permsDetail, code, + getFunctionCodeKey); + List 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 currentRolesInDB, + List roleFunctionList, List roles, + Map existingPortalRolesMap) throws Exception { + if (!roleFunctionList.isEmpty()) { + final Map appRoleFuncParams = new HashMap<>(); + final Map currentAppRoleFunctionsMap = new HashMap<>(); + final Map currentRolesInExtSystem = new HashMap<>(); + appRoleFuncParams.put("functionCd", roleFunctionList.get(0).getCode()); + appRoleFuncParams.put("appId", String.valueOf(app.getId())); + List 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 params = new HashMap<>(); + EPRole role = existingPortalRolesMap.get(extAuthAppRoleName); + EPAppRoleFunction addGlobalRoleFunctions = new EPAppRoleFunction(); + params.put("appId", app.getId()); + params.put("roleId", role.getId()); + List 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 currentRolesInDB, + List 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 addGetLocalFunction(EPApp app, + final Map roleFuncMap, ExternalAccessPermsDetail permsDetail, String code, + CentralV2RoleFunction getFunctionCodeKey) { + String finalFunctionCodeVal = addToLocalIfFunctionNotExists(app, roleFuncMap, permsDetail, code, + getFunctionCodeKey); + final Map appSyncFuncsParams = new HashMap<>(); + appSyncFuncsParams.put("appId", String.valueOf(app.getId())); + appSyncFuncsParams.put("functionCd", finalFunctionCodeVal); + List 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 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 getAppRoleNamesWithUnderscoreMap(EPApp app) { + final Map currentRolesInDB = new HashMap<>(); + List getCurrentRoleList = null; + final Map 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 getAppRoleNamesMap(EPApp app) { + final Map currentRolesInDB = new HashMap<>(); + List getCurrentRoleList = null; + final Map 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 getExtAuthPerrmissonList(EPApp app, JSONArray extPerms) throws IOException { + ExternalAccessPermsDetail permDetails = null; + List 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 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 response = null; + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity 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 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 getRoleByNameParams = new HashMap<>(); + List 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 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 roleParams = new HashMap<>(); + roleParams.put(APP_ROLE_NAME_PARAM, role); + List 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 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 app = getApp(uebkey); + List roles = getAppRoles(app.get(0).getId()); + List cenRoleList = new ArrayList<>(); + final Map 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 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 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 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 roles = getAppRoles(app.getId()); + final Map params = new HashMap<>(); + Integer roleFunctions = 0; + try { + for (EPRole role : roles) { + params.put("roleId", role.getId()); + List 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 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 params = new HashMap<>(); + params.put("appId", app.getId()); + List 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 entity = new HttpEntity<>(addFunction, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "addFunctionInExternalSystem: {} for POST: {}", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction); + ResponseEntity 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 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 roles = getAppRoles(app.getId()); + final Map params = new HashMap<>(); + Integer roleFunctions = 0; + try { + for (EPRole role : roles) { + params.put("roleId", role.getId()); + List 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 params = new HashMap<>(); + params.put("appId", app.getId()); + List 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 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 externalRoleDetailsList = getExternalRoleDetailsList(app, mapper, extRole); + List finalRoleList = new ArrayList<>(); + for (ExternalRoleDetails externalRole : externalRoleDetailsList) { + EPRole ecompRole = convertExternalRoleDetailstoEpRole(externalRole); + finalRoleList.add(ecompRole); + } + List applicationRolesList; + applicationRolesList = getAppRoles(app.getId()); + List applicationRoleIdList = new ArrayList<>(); + for (EPRole applicationRole : applicationRolesList) { + applicationRoleIdList.add(applicationRole.getName()); + } + List 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 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 getRoleCreatedInSync = null; + if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + final Map 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 roleList = new ArrayList<>(); + final Map 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 finalRoleList, + List applicationRolesList) { + final Map checkRolesInactive = new HashMap<>(); + for (EPRole extrole : finalRoleList) { + checkRolesInactive.put(extrole.getName(), extrole); + } + for (EPRole role : applicationRolesList) { + try { + final Map extRoleParams = new HashMap<>(); + List 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 getExternalRoleDetailsList(EPApp app, ObjectMapper mapper, JSONArray extRole) + throws IOException { + List externalRoleDetailsList = new ArrayList<>(); + ExternalAccessPerms externalAccessPerms = new ExternalAccessPerms(); + List functionCodelist = new ArrayList<>(); + Map curRolesMap = getAppRoleNamesMap(app); + Map 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 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 roleFunctionsMap = new HashMap<>(); + final Map appRoleFuncsParams = new HashMap<>(); + if (roleId != null) { + appRoleFuncsParams.put("appId", app.getId()); + appRoleFuncsParams.put("roleId", roleId); + // get role functions from DB + List 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 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 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 response = null; + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity 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 response = null; + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity 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 params = new HashMap<>(); + params.put("uebKey", app.getUebKey()); + List 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 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 getMenuFunctionsList(String uebkey) throws Exception { + List appMenuFunctionsList = null; + List appMenuFunctionsFinalList = new ArrayList<>(); + try { + EPApp app = getApp(uebkey).get(0); + final Map 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 getAllAppUsers(String uebkey) throws Exception { + List usersList = new ArrayList<>(); + List usersfinalList = new ArrayList<>(); + try { + EPApp app = getApp(uebkey).get(0); + final Map appParams = new HashMap<>(); + appParams.put("appId", app.getId()); + List userList = (List) dataAccessService + .executeNamedQuery("ApplicationUserRoles", appParams, null); + for (EcompUserRoles ecompUserRole : userList) { + boolean found = false; + Set 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 roleFunctionSet = new TreeSet<>(); + if (role != null) { + roleFunctionSet = (SortedSet) 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 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 roleFunctionList = newRole.getRoleFunctions(); + Set roleFunctionListNew = new HashSet<>(); + Iterator 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 getCentralizedAppsOfUser(String userId) { + Map params = new HashMap<>(); + params.put("userId", userId); + List 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 getGlobalRolesOfApplication(Long appId) { + Map params = new HashMap<>(); + params.put("appId", appId); + List globalRoles = new ArrayList<>(); + try { + globalRoles = dataAccessService.executeNamedQuery("getGlobalRoleWithApplicationRoleFunctions", params, + null); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e); + } + List 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 roleWithApplicationRoleFucntions = new ArrayList<>(); + Map 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 rolesfinalList = finalListOfCentralRoles(roleWithApplicationRoleFucntions); + finalGlobalrole = rolesfinalList.get(0); + } else { + List roleList = getPortalAppRoleInfo(roleId); + finalGlobalrole = convertRoleToCentralV2Role(roleList.get(0)); + } + return finalGlobalrole; + } + + private List finalListOfCentralRoles(List globalRoles) { + List rolesfinalList = new ArrayList<>(); + for (GlobalRoleWithApplicationRoleFunction role : globalRoles) { + boolean found = false; + for (CentralV2Role cenRole : rolesfinalList) { + if (role.getRoleId().equals(cenRole.getId())) { + SortedSet 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 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 getGlobalRolesOfPortal() { + List 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 convertCentralRoleFunctionToRoleFunctionObject( + List answer) { + List 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 epUserList; + List appList = getApp(uebkey); + app = appList.get(0); + epUserList = getUser(loginId); + EPUser user = epUserList.get(0); + Set userAppSet = user.getEPUserApps(); + return createEPUser(user, userAppSet, app); + } + + private List getUserAppRoles(EPApp app, EPUser user) { + final Map userParams = new HashMap<>(); + userParams.put("appId", app.getId()); + userParams.put("userId", user.getId()); + @SuppressWarnings("unchecked") + List userAppsRolesList = dataAccessService.executeNamedQuery("getUserAppCurrentRoles", + userParams, null); + List 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 missingUserApplicationRoles(String uebkey, String loginId, Set CurrentUserRoles) + throws Exception { + List appList = getApp(uebkey); + EPApp app = appList.get(0); + List epUserList; + epUserList = getUser(loginId); + List missingUserAppRoles = new ArrayList<>(); + List roleNamesList = CurrentUserRoles.stream().map(EcompRole::getName).collect(Collectors.toList()); + logger.debug(EELFLoggerDelegate.debugLogger, "Roles of User from hibernate :" + roleNamesList); + List userApplicationsRolesfromDB = getUserAppRoles(app, epUserList.get(0)); + if (userApplicationsRolesfromDB.size() > 0) { + missingUserAppRoles = userApplicationsRolesfromDB.stream().filter(x -> !roleNamesList.contains(x.getName())) + .collect(Collectors.toList()); + } + List MissingroleNamesList = missingUserAppRoles.stream().map(EcompRole::getName) + .collect(Collectors.toList()); + logger.debug(EELFLoggerDelegate.debugLogger, "MissingUserAppRoles():" + MissingroleNamesList); + + List finalMissingRoleList = new ArrayList<>(); + if (missingUserAppRoles.size() > 0) { + final Map 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 appRoleFunctionList = dataAccessService + .executeNamedQuery("getAppRoleFunctionList", params, null); + SortedSet 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 userV2Apps = cenV2User.getUserApps(); + Set userApps = new TreeSet<>(); + for (CentralV2UserApp userApp : userV2Apps) { + CentralApp app = userApp.getApp(); + CentralUserApp cua = new CentralUserApp(); + cua.setUserId(null); + cua.setApp(app); + SortedSet 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 convertV2CentralRoleListToOldVerisonCentralRoleList(List v2CenRoleList) { + List cenRoleList = new ArrayList<>(); + for (CentralV2Role v2CenRole : v2CenRoleList) { + SortedSet 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 getNameSpaceIfExists(EPApp app) throws Exception { + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity entity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Connecting to External Auth system"); + ResponseEntity 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 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 params = new HashMap<>(); + params.put("uebKey", app.getUebKey()); + params.put("roleId", String.valueOf(roleId)); + List 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 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 entity) { + logger.debug(EELFLoggerDelegate.debugLogger, "bulkUploadRoleFunc: {} for POST: {}", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms); + ResponseEntity 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 getUserRolesEntity = new HttpEntity<>(headers); + ResponseEntity getResponse = getUserRolesFromExtAuthSystem(name, getUserRolesEntity); + List 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 userRoleDetailList, JSONArray extRoles, + String loginId) throws InvalidUserException { + HashMap userParams = new HashMap<>(); + userParams.put("orgUserId", loginId); + // Get all centralized applications existing user roles from local + List currentUserAppRoles = dataAccessService + .executeNamedQuery("getUserCentralizedAppRoles", userParams, null); + EPUser user = getUser(loginId).get(0); + // Get all centralized applications roles from local + HashMap cenAppRolesMap = getCentralizedAppRoleList(); + HashMap currentCentralizedUserAppRolesMap = getCurrentUserCentralizedAppRoles( + currentUserAppRoles); + // Get all centralized applications + admin role from local + HashMap 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 userRoleDetailList, EPUser user, + HashMap cenAppRolesMap, + HashMap currentCentralizedUserAppRolesMap, + HashMap 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 getCentralizedAdminAppsInfo() { + List centralizedApps = dataAccessService.executeNamedQuery("getCentralizedApps", null, null); + HashMap 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 getCurrentUserCentralizedAppRoles( + List currentUserAppRoles) { + HashMap 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 getCentralizedAppRoleList() { + List centralizedAppRoles = dataAccessService + .executeNamedQuery("getAllCentralizedAppsRoles", null, null); + HashMap 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 getUserRolesFromExtAuthSystem(String name, HttpEntity getUserRolesEntity) { + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles"); + ResponseEntity 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 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/MicroserviceServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/MicroserviceServiceImpl.java index e90aeb74..b41d898a 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/MicroserviceServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/MicroserviceServiceImpl.java @@ -4,6 +4,8 @@ * =================================================================== * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== * * Unless otherwise specified, all software contained herein is licensed * under the Apache License, Version 2.0 (the "License"); @@ -42,8 +44,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import javax.crypto.BadPaddingException; - import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Restrictions; import org.onap.portalapp.portal.domain.MicroserviceData; @@ -75,9 +75,8 @@ public class MicroserviceServiceImpl implements MicroserviceService { return newService.getId(); } - public void saveServiceParameters(long serviceId, List list) throws Exception { - for (int i = 0; i < list.size(); i++) { - MicroserviceParameter para = list.get(i); + public void saveServiceParameters(long serviceId, List list) { + for (MicroserviceParameter para : list) { para.setServiceId(serviceId); getDataAccessService().saveDomainObject(para, null); } @@ -85,9 +84,9 @@ public class MicroserviceServiceImpl implements MicroserviceService { @Override public MicroserviceData getMicroserviceDataById(long id) { - MicroserviceData data = null; + MicroserviceData data; try { - List restrictionsList = new ArrayList(); + List restrictionsList = new ArrayList<>(); Criterion idCriterion = Restrictions.eq("id", id); restrictionsList.add(idCriterion); data = (MicroserviceData) dataAccessService.getList(MicroserviceData.class, null, restrictionsList, null).get(0); @@ -102,34 +101,35 @@ public class MicroserviceServiceImpl implements MicroserviceService { @SuppressWarnings("unchecked") @Override - public List getMicroserviceData() throws Exception { + public List getMicroserviceData() { List list = (List) dataAccessService.getList(MicroserviceData.class, null); - for (int i = 0; i < list.size(); i++) { - if (list.get(i).getPassword() != null) - list.get(i).setPassword(EPCommonSystemProperties.APP_DISPLAY_PASSWORD); //to hide password from get request - list.get(i).setParameterList(getServiceParameters(list.get(i).getId())); + for (MicroserviceData microserviceData : list) { + if (microserviceData.getPassword() != null) { + microserviceData + .setPassword(EPCommonSystemProperties.APP_DISPLAY_PASSWORD); //to hide password from get request + } + microserviceData.setParameterList(getServiceParameters(microserviceData.getId())); } return list; } private List getServiceParameters(long serviceId) { - List list = getMicroServiceParametersList(serviceId); - return list; + return getMicroServiceParametersList(serviceId); } @SuppressWarnings("unchecked") private List getMicroServiceParametersList(long serviceId) { - List restrictionsList = new ArrayList(); + List restrictionsList = new ArrayList<>(); Criterion serviceIdCriterion = Restrictions.eq("serviceId", serviceId); restrictionsList.add(serviceIdCriterion); return (List) dataAccessService.getList(MicroserviceParameter.class, null, restrictionsList, null); } @Override - public void deleteMicroservice(long serviceId) throws Exception { + public void deleteMicroservice(long serviceId) { try { - Map params = new HashMap(); + Map params = new HashMap<>(); params.put("serviceId", Long.toString(serviceId)); dataAccessService.executeNamedQuery("deleteMicroserviceParameter", params, null); @@ -156,17 +156,16 @@ public class MicroserviceServiceImpl implements MicroserviceService { getDataAccessService().saveDomainObject(newService, null); List oldService = getServiceParameters(serviceId); boolean foundParam; - for (int i = 0; i < oldService.size(); i++) { + for (MicroserviceParameter microserviceParameter : oldService) { foundParam = false; for (int n = 0; n < newService.getParameterList().size(); n++) { - if (newService.getParameterList().get(n).getId().equals(oldService.get(i).getId())) { + if (newService.getParameterList().get(n).getId().equals(microserviceParameter.getId())) { foundParam = true; break; } } - if (foundParam == false) { - MicroserviceParameter pd = oldService.get(i); - getDataAccessService().deleteDomainObject(pd, null); + if (!foundParam) { + getDataAccessService().deleteDomainObject(microserviceParameter, null); } } for (int i = 0; i < newService.getParameterList().size(); i++) { @@ -184,7 +183,7 @@ public class MicroserviceServiceImpl implements MicroserviceService { @Override @SuppressWarnings("unchecked") public List getParametersById(long serviceId) { - List restrictionsList = new ArrayList(); + List restrictionsList = new ArrayList<>(); Criterion contextIdCrit = Restrictions.eq("serviceId", serviceId); restrictionsList.add(contextIdCrit); List list = (List) dataAccessService @@ -196,7 +195,7 @@ public class MicroserviceServiceImpl implements MicroserviceService { private String decryptedPassword(String encryptedPwd) throws Exception { String result = ""; - if (encryptedPwd != null & encryptedPwd.length() > 0) { + if (encryptedPwd != null && !encryptedPwd.isEmpty()) { try { result = CipherUtil.decryptPKC(encryptedPwd, SystemProperties.getProperty(SystemProperties.Decryption_Key)); @@ -210,7 +209,7 @@ public class MicroserviceServiceImpl implements MicroserviceService { private String encryptedPassword(String decryptedPwd) throws Exception { String result = ""; - if (decryptedPwd != null & decryptedPwd.length() > 0) { + if (decryptedPwd != null && !decryptedPwd.isEmpty()) { try { result = CipherUtil.encryptPKC(decryptedPwd, SystemProperties.getProperty(SystemProperties.Decryption_Key)); 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 5d9761ce..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,7 +177,7 @@ public class UserRolesCommonServiceImpl { * * @param userId */ - protected void createLocalUserIfNecessary(String userId) { + protected void createLocalUserIfNecessary(String userId,boolean isSystemUser) { if (StringUtils.isEmpty(userId)) { logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty userId!"); return; @@ -188,9 +189,20 @@ public class UserRolesCommonServiceImpl { transaction = localSession.beginTransaction(); @SuppressWarnings("unchecked") List userList = localSession - .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + userId + "'").list(); + .createQuery("from :name where orgUserId=:userId") + .setParameter("name",EPUser.class.getName()) + .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"; @@ -625,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(); @@ -662,7 +675,7 @@ public class UserRolesCommonServiceImpl { * @throws HTTPException */ protected Set postUsersRolesToRemoteApp(List roleInAppForUserList, ObjectMapper mapper, - ApplicationsRestClientService applicationsRestClientService, Long appId, String userId) + ApplicationsRestClientService applicationsRestClientService, Long appId, String userId,boolean systemUser) throws JsonProcessingException, HTTPException { Set updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList); Set updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList); @@ -739,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) { @@ -852,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 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 loginIdParams = new HashMap<>(); + loginIdParams.put("orgUserIdValue", userId); + List 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 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 roles = new TreeSet<>(); @@ -973,7 +1006,7 @@ public class UserRolesCommonServiceImpl { } Long appId = newAppRolesForUser.appId; List roleInAppForUserList = newAppRolesForUser.appRoles; - if (userId.length() > 0) { + if (userId.length() > 0 ) { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); @@ -981,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 userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper, + applicationsRestClientService, appId, userId); + RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId, + userRolesInLocalApp); + List 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, @@ -996,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)){ @@ -1006,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)){ @@ -1017,10 +1070,10 @@ public class UserRolesCommonServiceImpl { remoteAppUser = addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService, applicationsRestClientService); } Set 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) { @@ -1032,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", @@ -1062,7 +1116,7 @@ public class UserRolesCommonServiceImpl { * @param roleInAppUser Contains list of active roles */ @SuppressWarnings("unchecked") - private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List roleInAppUser, boolean isPortalRequest) throws Exception + private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List roleInAppUser, boolean isPortalRequest,boolean isSystemUser) throws Exception { try { // check if user exists @@ -1070,13 +1124,15 @@ public class UserRolesCommonServiceImpl { userParams.put("orgUserIdValue", orgUserId); List 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(); @@ -1168,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 entity = new HttpEntity<>(formattedUserRole, headers); @@ -1188,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; @@ -1484,11 +1556,11 @@ public class UserRolesCommonServiceImpl { List 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)){ @@ -1496,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)) { @@ -1509,7 +1581,7 @@ public class UserRolesCommonServiceImpl { } Set userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper, - applicationsRestClientService, app.getId(), orgUserId); + applicationsRestClientService, app.getId(), orgUserId,false); RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(), userRolesInRemoteApp); @@ -1517,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) { @@ -1540,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/transport/CentralV2UserApp.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CentralV2UserApp.java index 2ada8ed1..17007a5f 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CentralV2UserApp.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CentralV2UserApp.java @@ -38,6 +38,7 @@ package org.onap.portalapp.portal.transport; import java.io.Serializable; +import java.util.Objects; @SuppressWarnings("rawtypes") public class CentralV2UserApp implements Serializable, Comparable{ @@ -99,7 +100,20 @@ public class CentralV2UserApp implements Serializable, Comparable{ this.priority = priority; } - + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof CentralV2UserApp)) { + return false; + } + CentralV2UserApp castOther = (CentralV2UserApp) other; + return Objects.equals(this.userId, castOther.userId) && + Objects.equals(this.app, castOther.app) && + Objects.equals(this.role, castOther.role) && + Objects.equals(this.priority, castOther.priority); + } public int compareTo(Object other){ CentralV2UserApp castOther = (CentralV2UserApp) other; diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CommonWidget.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CommonWidget.java index ec27d987..3fbdc3e8 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CommonWidget.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CommonWidget.java @@ -44,6 +44,7 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; +import org.hibernate.validator.constraints.SafeHtml; import org.onap.portalsdk.core.domain.support.DomainVo; import com.fasterxml.jackson.annotation.JsonInclude; @@ -63,28 +64,33 @@ public class CommonWidget extends DomainVo{ private Long id; @Column(name = "category") + @SafeHtml public String category; @Column(name = "href") + @SafeHtml public String href; @Column(name = "title") + @SafeHtml public String title; @Column(name = "content") + @SafeHtml public String content; @Column(name = "event_date") + @SafeHtml public String eventDate; @Column(name = "sort_order") public Integer sortOrder; - + public CommonWidget(){ - + } - + public CommonWidget(String category, String href, String title, String content, String eventDate, Integer sortOrder){ this.category = category; this.href = href; diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CommonWidgetMeta.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CommonWidgetMeta.java index 55dfc91a..51a02652 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CommonWidgetMeta.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CommonWidgetMeta.java @@ -38,14 +38,17 @@ package org.onap.portalapp.portal.transport; import java.util.List; +import javax.validation.Valid; +import org.hibernate.validator.constraints.SafeHtml; public class CommonWidgetMeta { - + @SafeHtml private String category; + @Valid private List items; - - public CommonWidgetMeta(){ - + + public CommonWidgetMeta(){ + } public CommonWidgetMeta(String category, List items){ diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/OnboardingApp.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/OnboardingApp.java index f2503b42..37ad5add 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/OnboardingApp.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/OnboardingApp.java @@ -37,6 +37,8 @@ */ package org.onap.portalapp.portal.transport; +import org.hibernate.validator.constraints.SafeHtml; + /** * Model of rows in the fn_app table; serialized as a message add or update an * on-boarded application. @@ -44,21 +46,21 @@ package org.onap.portalapp.portal.transport; public class OnboardingApp { public Long id; - + @SafeHtml public String name; - + @SafeHtml public String imageUrl; - + @SafeHtml public String imageLink; - + @SafeHtml public String description; - + @SafeHtml public String notes; - + @SafeHtml public String url; - + @SafeHtml public String alternateUrl; - + @SafeHtml public String restUrl; public Boolean isOpen; @@ -66,27 +68,27 @@ public class OnboardingApp { public Boolean isEnabled; public Long motsId; - + @SafeHtml public String myLoginsAppName; - + @SafeHtml public String myLoginsAppOwner; - + @SafeHtml public String username; - + @SafeHtml public String appPassword; - + @SafeHtml public String thumbnail; - + @SafeHtml public String uebTopicName; - + @SafeHtml public String uebKey; - + @SafeHtml public String uebSecret; public Boolean restrictedApp; public Boolean isCentralAuth; - + @SafeHtml public String nameSpace; /** 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 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/DateUtil.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/util/DateUtil.java new file mode 100644 index 00000000..211f8ab9 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/util/DateUtil.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (c) 2019 Samsung. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + * + * ============LICENSE_END============================================ + * + * + */ + +package org.onap.portalapp.util; + +import java.text.SimpleDateFormat; + +public class DateUtil { + + private DateUtil() { + throw new IllegalStateException("Utility class"); + } + + public static SimpleDateFormat getDateFormat() { + return new SimpleDateFormat("HH:mm:ss:SSSS"); + } + + public static SimpleDateFormat getRequestDateFormat(){ + return new SimpleDateFormat("EEE, dd MMM YYYY HH:mm:ss z"); + } +} 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 roleFunctions) { + String[] path = portalApiPath.split("/"); + List 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/java/org/onap/portalapp/validation/DataValidator.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/validation/DataValidator.java new file mode 100644 index 00000000..46a60c81 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/validation/DataValidator.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + * + * ============LICENSE_END============================================ + * + * + */ + +package org.onap.portalapp.validation; + +import java.util.Set; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; +import org.springframework.stereotype.Component; + +@Component +public class DataValidator { + private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory(); + + public Set> getConstraintViolations(E classToValid){ + Validator validator = VALIDATOR_FACTORY.getValidator(); + Set> constraintViolations = validator.validate(classToValid); + return constraintViolations; + } + + public boolean isValid(E classToValid){ + Set> constraintViolations = getConstraintViolations(classToValid); + return constraintViolations.isEmpty(); + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/validation/SecureString.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/validation/SecureString.java new file mode 100644 index 00000000..2afbddac --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/validation/SecureString.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + * + * ============LICENSE_END============================================ + * + * + */ + +package org.onap.portalapp.validation; + +import org.hibernate.validator.constraints.SafeHtml; + +public class SecureString { + + @SafeHtml + private String data; + + public SecureString(String string) { + this.data = string; + } + + public String getString() { + return data; + } +} 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 @@ + @@ -2549,6 +2550,32 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' and fn_role.active_y ]]> + + + + + + expectedportalRestResponse = new PortalRestResponse(); + expectedportalRestResponse.setMessage("Data is not valid"); + expectedportalRestResponse.setResponse(null); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + EPUser user = mockUser.mockEPUser(); + user.setEmail("“>"); + user.setLoginPwd("pwd"); + user.setLoginId("Test"); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(userService.getUserByUserId(user.getOrgUserId())).thenThrow(nullPointerException); + PortalRestResponse actualPortalRestResponse = appsControllerExternalRequest + .postPortalAdmin(mockedRequest, mockedResponse, user); + assertEquals(expectedportalRestResponse, actualPortalRestResponse); + } + @Test public void postPortalAdminCreateUserIfNotFoundTest() throws Exception { PortalRestResponse expectedportalRestResponse = new PortalRestResponse(); @@ -276,6 +294,36 @@ public class AppsControllerExternalRequestTest extends MockitoTestSuite { } + @Test + public void postOnboardAppExternalXSSTest() { + PortalRestResponse expectedportalRestResponse = new PortalRestResponse(); + expectedportalRestResponse.setMessage( + "Data is not valid"); + expectedportalRestResponse.setResponse(null); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + + OnboardingApp expectedOnboardingApp = new OnboardingApp();; + expectedOnboardingApp.name = "test"; + expectedOnboardingApp.url="test.com"; + expectedOnboardingApp.restUrl=""; + expectedOnboardingApp.myLoginsAppOwner="testUser"; + expectedOnboardingApp.restrictedApp=false; + expectedOnboardingApp.isOpen=true; + expectedOnboardingApp.isEnabled=true; + EPUser user = mockUser.mockEPUser(); + user.setEmail("guestT@test.portal.onap.org"); + user.setLoginPwd("pwd"); + user.setLoginId("Test"); + List expectedList = new ArrayList(); + expectedList.add(user); + + PortalRestResponse actualPortalRestResponse = appsControllerExternalRequest + .postOnboardAppExternal(mockedRequest, mockedResponse, expectedOnboardingApp); + assertEquals(expectedportalRestResponse, actualPortalRestResponse); + + } + @Test public void putOnboardAppExternalifAppNullTest() { PortalRestResponse expectedportalRestResponse = new PortalRestResponse(); @@ -292,6 +340,38 @@ public class AppsControllerExternalRequestTest extends MockitoTestSuite { assertEquals(actualPortalRestResponse, expectedportalRestResponse); } + @Test + public void putOnboardAppExternalXSSTest() { + PortalRestResponse expectedportalRestResponse = new PortalRestResponse(); + expectedportalRestResponse.setMessage( + "Data is not valid"); + expectedportalRestResponse.setResponse(null); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + + OnboardingApp expectedOnboardingApp = new OnboardingApp();; + expectedOnboardingApp.name = "test"; + expectedOnboardingApp.url="test.com"; + expectedOnboardingApp.restUrl=""; + expectedOnboardingApp.myLoginsAppOwner="testUser"; + expectedOnboardingApp.restrictedApp=false; + expectedOnboardingApp.isOpen=true; + expectedOnboardingApp.isEnabled=true; + EPUser user = mockUser.mockEPUser(); + user.setEmail("guestT@test.portal.onap.org"); + user.setLoginPwd("pwd"); + user.setLoginId("Test"); + List expectedList = new ArrayList(); + expectedList.add(user); + + Long appId = (long) 1; + + PortalRestResponse actualPortalRestResponse = appsControllerExternalRequest + .putOnboardAppExternal(mockedRequest, mockedResponse, appId, expectedOnboardingApp); + assertEquals(expectedportalRestResponse, actualPortalRestResponse); + + } + @Test public void putOnboardAppExternalIfOnboardingAppDetailsNullTest() { PortalRestResponse expectedportalRestResponse = new PortalRestResponse(); 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 atualApps = new ArrayList(); 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 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 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 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 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/DashboardSearchResultControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/DashboardSearchResultControllerTest.java index 839b9fd5..34667853 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/DashboardSearchResultControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/DashboardSearchResultControllerTest.java @@ -93,7 +93,7 @@ public class DashboardSearchResultControllerTest { @Test public void getWidgetDataTest() { String resourceType = "test"; - PortalRestResponse ecpectedPortalRestResponse = new PortalRestResponse(); + PortalRestResponse ecpectedPortalRestResponse = new PortalRestResponse<>(); ecpectedPortalRestResponse.setMessage("success"); ecpectedPortalRestResponse.setResponse(null); ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.OK); @@ -104,9 +104,22 @@ public class DashboardSearchResultControllerTest { } + @Test + public void getWidgetDataXSSTest() { + String resourceType = "\"\""; + PortalRestResponse expectedPortalRestResponse = new PortalRestResponse<>(); + expectedPortalRestResponse.setMessage("resourceType: String string is not valid"); + expectedPortalRestResponse.setResponse(""); + expectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + Mockito.when(searchService.getWidgetData(resourceType)).thenReturn(null); + PortalRestResponse acutualPoratlRestResponse = dashboardSearchResultController + .getWidgetData(mockedRequest, resourceType); + assertEquals(expectedPortalRestResponse,acutualPoratlRestResponse); + } + @Test public void saveWidgetDataBulkTest() { - PortalRestResponse ecpectedPortalRestResponse = new PortalRestResponse(); + PortalRestResponse ecpectedPortalRestResponse = new PortalRestResponse<>(); ecpectedPortalRestResponse.setMessage("success"); ecpectedPortalRestResponse.setResponse(null); ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.OK); @@ -114,7 +127,7 @@ public class DashboardSearchResultControllerTest { CommonWidgetMeta commonWidgetMeta = new CommonWidgetMeta(); commonWidgetMeta.setCategory("test"); - List commonWidgetList = new ArrayList(); + List commonWidgetList = new ArrayList<>(); CommonWidget commonWidget = new CommonWidget(); commonWidget.setId((long) 1); commonWidget.setCategory("test"); @@ -135,9 +148,40 @@ public class DashboardSearchResultControllerTest { assertEquals(actualPortalRestResponse, ecpectedPortalRestResponse); } + @Test + public void saveWidgetDataBulkXSSTest() { + PortalRestResponse ecpectedPortalRestResponse = new PortalRestResponse<>(); + ecpectedPortalRestResponse.setMessage("ERROR"); + ecpectedPortalRestResponse.setResponse("Category is not valid"); + ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + + CommonWidgetMeta commonWidgetMeta = new CommonWidgetMeta(); + commonWidgetMeta.setCategory("test"); + + List commonWidgetList = new ArrayList<>(); + CommonWidget commonWidget = new CommonWidget(); + commonWidget.setId((long) 1); + commonWidget.setCategory("test"); + commonWidget.setHref("\"\""); + commonWidget.setTitle("test_title"); + commonWidget.setContent("test_content"); + commonWidget.setEventDate(null); + commonWidget.setSortOrder(1); + + commonWidgetList.add(commonWidget); + + commonWidgetMeta.setItems(commonWidgetList); + + Mockito.when(searchService.saveWidgetDataBulk(commonWidgetMeta)).thenReturn(null); + + PortalRestResponse actualPortalRestResponse = dashboardSearchResultController + .saveWidgetDataBulk(commonWidgetMeta); + assertEquals(ecpectedPortalRestResponse, actualPortalRestResponse); + } + @Test public void saveWidgetDataBulkIfCategoryNullTest() { - PortalRestResponse ecpectedPortalRestResponse = new PortalRestResponse(); + PortalRestResponse ecpectedPortalRestResponse = new PortalRestResponse<>(); ecpectedPortalRestResponse.setMessage("java.text.ParseException: Unparseable date: \"1\""); ecpectedPortalRestResponse.setResponse(null); ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); @@ -145,7 +189,7 @@ public class DashboardSearchResultControllerTest { CommonWidgetMeta commonWidgetMeta = new CommonWidgetMeta(); commonWidgetMeta.setCategory("test"); - List commonWidgetList = new ArrayList(); + List commonWidgetList = new ArrayList<>(); CommonWidget commonWidget = new CommonWidget(); commonWidget.setId(null); commonWidget.setCategory(null); @@ -166,7 +210,7 @@ public class DashboardSearchResultControllerTest { @Test public void saveWidgetDataTest() { - PortalRestResponse ecpectedPortalRestResponse = new PortalRestResponse(); + PortalRestResponse ecpectedPortalRestResponse = new PortalRestResponse<>(); ecpectedPortalRestResponse.setMessage("success"); ecpectedPortalRestResponse.setResponse(null); ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.OK); @@ -187,11 +231,34 @@ public class DashboardSearchResultControllerTest { } + @Test + public void saveWidgetDataXSSTest() { + PortalRestResponse expectedPortalRestResponse = new PortalRestResponse<>(); + expectedPortalRestResponse.setMessage("ERROR"); + expectedPortalRestResponse.setResponse("Category is not valid"); + expectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + CommonWidget commonWidget = new CommonWidget(); + commonWidget.setId((long) 1); + commonWidget.setCategory("test"); + commonWidget.setHref("\"\""); + commonWidget.setTitle("test_title"); + commonWidget.setContent("test_content"); + commonWidget.setEventDate(null); + commonWidget.setSortOrder(1); + + Mockito.when(searchService.saveWidgetData(commonWidget)).thenReturn(null); + + PortalRestResponse actualPortalRestResponse = dashboardSearchResultController + .saveWidgetData(commonWidget); + assertEquals(expectedPortalRestResponse, actualPortalRestResponse); + + } + @Test public void saveWidgetDataExceptionTest() { - PortalRestResponse ecpectedPortalRestResponse = new PortalRestResponse(); + PortalRestResponse ecpectedPortalRestResponse = new PortalRestResponse<>(); ecpectedPortalRestResponse.setMessage("ERROR"); - ecpectedPortalRestResponse.setResponse("Cateogry cannot be null or empty"); + ecpectedPortalRestResponse.setResponse("Category cannot be null or empty"); ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); CommonWidget commonWidget = new CommonWidget(); commonWidget.setId((long) 1); @@ -212,7 +279,7 @@ public class DashboardSearchResultControllerTest { @Test public void saveWidgetDataDateErrorTest() { - PortalRestResponse ecpectedPortalRestResponse = new PortalRestResponse(); + PortalRestResponse ecpectedPortalRestResponse = new PortalRestResponse<>(); ecpectedPortalRestResponse.setMessage("java.text.ParseException: Unparseable date: \"1\""); ecpectedPortalRestResponse.setResponse(null); ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); @@ -233,8 +300,9 @@ public class DashboardSearchResultControllerTest { } + @Test public void deleteWidgetDataTest() { - PortalRestResponse ecpectedPortalRestResponse = new PortalRestResponse(); + PortalRestResponse ecpectedPortalRestResponse = new PortalRestResponse<>(); ecpectedPortalRestResponse.setMessage("success"); ecpectedPortalRestResponse.setResponse(null); ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.OK); @@ -254,15 +322,37 @@ public class DashboardSearchResultControllerTest { assertEquals(actualPortalRestResponse, ecpectedPortalRestResponse); } + @Test + public void deleteWidgetDataXSSTest() { + PortalRestResponse expectedPortalRestResponse = new PortalRestResponse<>(); + expectedPortalRestResponse.setMessage("ERROR"); + expectedPortalRestResponse.setResponse("CommonWidget is not valid"); + expectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + CommonWidget commonWidget = new CommonWidget(); + commonWidget.setId((long) 1); + commonWidget.setCategory("test"); + commonWidget.setHref("test_href"); + commonWidget.setTitle("\"\""); + commonWidget.setContent("test_content"); + commonWidget.setEventDate(null); + commonWidget.setSortOrder(1); + Mockito.when(searchService.deleteWidgetData(commonWidget)).thenReturn(null); + + PortalRestResponse actualPortalRestResponse = dashboardSearchResultController + .deleteWidgetData(commonWidget); + + assertEquals(expectedPortalRestResponse, actualPortalRestResponse); + } + @Test public void searchPortalIfUserIsNull() { EPUser user = null; Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); String searchString = "test"; - PortalRestResponse>> expectedResult = new PortalRestResponse>>(); + PortalRestResponse>> expectedResult = new PortalRestResponse<>(); expectedResult.setMessage("searchPortal: User object is null? - check logs"); - expectedResult.setResponse(new HashMap>()); + expectedResult.setResponse(new HashMap<>()); expectedResult.setStatus(PortalRestStatusEnum.ERROR); PortalRestResponse>> actualResult = dashboardSearchResultController .searchPortal(mockedRequest, searchString); @@ -272,13 +362,12 @@ public class DashboardSearchResultControllerTest { @Test public void searchPortalIfSearchStringNullTest() { EPUser user = mockUser.mockEPUser(); - ; Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); String searchString = null; - PortalRestResponse>> expectedResult = new PortalRestResponse>>(); + PortalRestResponse>> expectedResult = new PortalRestResponse<>(); expectedResult.setMessage("searchPortal: String string is null"); - expectedResult.setResponse(new HashMap>()); + expectedResult.setResponse(new HashMap<>()); expectedResult.setStatus(PortalRestStatusEnum.ERROR); PortalRestResponse>> actualResult = dashboardSearchResultController @@ -289,10 +378,9 @@ public class DashboardSearchResultControllerTest { @Test public void searchPortalIfSearchTest() { EPUser user = mockUser.mockEPUser(); - ; Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); String searchString = "test"; - List searchResultItemList = new ArrayList(); + List searchResultItemList = new ArrayList<>(); SearchResultItem searchResultItem = new SearchResultItem(); searchResultItem.setId((long) 1); @@ -301,10 +389,10 @@ public class DashboardSearchResultControllerTest { searchResultItem.setTarget("test_target"); searchResultItem.setUuid("test_UUId"); searchResultItemList.add(searchResultItem); - Map> expectedResultMap = new HashMap>(); + Map> expectedResultMap = new HashMap<>(); expectedResultMap.put(searchString, searchResultItemList); - PortalRestResponse>> expectedResult = new PortalRestResponse>>(); + PortalRestResponse>> expectedResult = new PortalRestResponse<>(); expectedResult.setMessage("success"); expectedResult.setResponse(expectedResultMap); expectedResult.setStatus(PortalRestStatusEnum.OK); @@ -319,13 +407,12 @@ public class DashboardSearchResultControllerTest { @Test public void searchPortalIfSearchExcptionTest() { EPUser user = mockUser.mockEPUser(); - ; Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); String searchString = "test"; - PortalRestResponse>> expectedResult = new PortalRestResponse>>(); + PortalRestResponse>> expectedResult = new PortalRestResponse<>(); expectedResult.setMessage("null - check logs."); - expectedResult.setResponse(new HashMap>()); + expectedResult.setResponse(new HashMap<>()); expectedResult.setStatus(PortalRestStatusEnum.ERROR); Mockito.when(searchService.searchResults(user.getLoginId(), searchString)).thenThrow(nullPointerException); @@ -336,9 +423,8 @@ public class DashboardSearchResultControllerTest { @Test public void getActiveUsersTest() { - List expectedActiveUsers = new ArrayList(); + List expectedActiveUsers = new ArrayList<>(); EPUser user = mockUser.mockEPUser(); - ; Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); String userId = user.getOrgUserId(); Mockito.when(searchService.getRelatedUsers(userId)).thenReturn(expectedActiveUsers); @@ -349,7 +435,7 @@ public class DashboardSearchResultControllerTest { @Test public void getActiveUsersExceptionTest() { - List expectedActiveUsers = new ArrayList(); + List expectedActiveUsers = new ArrayList<>(); EPUser user = mockUser.mockEPUser(); Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); String userId = user.getOrgUserId(); @@ -363,7 +449,7 @@ public class DashboardSearchResultControllerTest { public void activeUsersTest() { EPUser user = mockUser.mockEPUser(); Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); - PortalRestResponse> expectedResult = new PortalRestResponse>(); + PortalRestResponse> expectedResult = new PortalRestResponse<>(); expectedResult.setMessage("success"); expectedResult.setResponse(new ArrayList<>()); expectedResult.setStatus(PortalRestStatusEnum.OK); @@ -377,7 +463,7 @@ public class DashboardSearchResultControllerTest { public void activeUsersIfUserNullTest() { EPUser user = null; Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); - PortalRestResponse> expectedResult = new PortalRestResponse>(); + PortalRestResponse> expectedResult = new PortalRestResponse<>(); expectedResult.setMessage("User object is null? - check logs"); expectedResult.setResponse(new ArrayList<>()); expectedResult.setStatus(PortalRestStatusEnum.ERROR); @@ -390,7 +476,7 @@ public class DashboardSearchResultControllerTest { public void activeUsersExceptionTest() { EPUser user = mockUser.mockEPUser(); Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); - PortalRestResponse> expectedResult = new PortalRestResponse>(); + PortalRestResponse> expectedResult = new PortalRestResponse<>(); expectedResult.setMessage("null - check logs."); expectedResult.setResponse(new ArrayList<>()); expectedResult.setStatus(PortalRestStatusEnum.ERROR); diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/MicroserviceControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/MicroserviceControllerTest.java index 21d0cf70..81e1f8b2 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/MicroserviceControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/MicroserviceControllerTest.java @@ -96,7 +96,7 @@ public class MicroserviceControllerTest extends MockitoTestSuite{ @SuppressWarnings("rawtypes") @Mock - ResponseEntity> ans = new ResponseEntity>(HttpStatus.OK); + ResponseEntity> ans = new ResponseEntity<>(HttpStatus.OK); @Before public void setup() { @@ -114,11 +114,10 @@ public class MicroserviceControllerTest extends MockitoTestSuite{ @Test public void createMicroserviceIfServiceDataNullTest() throws Exception { - PortalRestResponse expectedportalRestResponse = new PortalRestResponse(); + PortalRestResponse expectedportalRestResponse = new PortalRestResponse<>(); expectedportalRestResponse.setMessage("FAILURE"); expectedportalRestResponse.setResponse("MicroserviceData cannot be null or empty"); - PortalRestStatusEnum portalRestStatusEnum = null; - expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR); MicroserviceData microserviceData = null; PortalRestResponse actualportalRestResponse = microserviceController.createMicroservice(mockedRequest, mockedResponse, microserviceData); @@ -127,23 +126,35 @@ public class MicroserviceControllerTest extends MockitoTestSuite{ @Test public void createMicroserviceTest() throws Exception { - PortalRestResponse expectedportalRestResponse = new PortalRestResponse(); + PortalRestResponse expectedportalRestResponse = new PortalRestResponse<>(); expectedportalRestResponse.setMessage("SUCCESS"); expectedportalRestResponse.setResponse(""); - PortalRestStatusEnum portalRestStatusEnum = null; - expectedportalRestResponse.setStatus(portalRestStatusEnum.OK); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.OK); PortalRestResponse actualportalRestResponse = microserviceController.createMicroservice(mockedRequest, mockedResponse, microserviceData); assertEquals(actualportalRestResponse, expectedportalRestResponse); } + @Test + public void createMicroserviceXSSTest() throws Exception { + PortalRestResponse expectedportalRestResponse = new PortalRestResponse<>(); + expectedportalRestResponse.setMessage("ERROR"); + expectedportalRestResponse.setResponse("MicroserviceData is not valid"); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + MicroserviceData XSSMicroserviceData = new MicroserviceData(); + XSSMicroserviceData.setActive(""); + XSSMicroserviceData.setName(""); + PortalRestResponse actualportalRestResponse = microserviceController.createMicroservice(mockedRequest, + mockedResponse, XSSMicroserviceData); + assertEquals(expectedportalRestResponse, actualportalRestResponse); + } + @Test public void createMicroserviceExceptionTest() throws Exception { - PortalRestResponse expectedportalRestResponse = new PortalRestResponse(); + PortalRestResponse expectedportalRestResponse = new PortalRestResponse<>(); expectedportalRestResponse.setMessage("FAILURE"); expectedportalRestResponse.setResponse(null); - PortalRestStatusEnum portalRestStatusEnum = null; - expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR); Mockito.when(microserviceService.saveMicroservice(microserviceData)).thenReturn((long) 1); Mockito.when(microserviceData.getParameterList()).thenThrow(nullPointerException); PortalRestResponse actualportalRestResponse = microserviceController.createMicroservice(mockedRequest, @@ -159,12 +170,11 @@ public class MicroserviceControllerTest extends MockitoTestSuite{ } @Test - public void updateMicroserviceIfServiceISNullTest() throws Exception { - PortalRestResponse expectedportalRestResponse = new PortalRestResponse(); + public void updateMicroserviceIfServiceISNullTest() { + PortalRestResponse expectedportalRestResponse = new PortalRestResponse<>(); expectedportalRestResponse.setMessage("FAILURE"); expectedportalRestResponse.setResponse("MicroserviceData cannot be null or empty"); - PortalRestStatusEnum portalRestStatusEnum = null; - expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR); MicroserviceData microserviceData = null; PortalRestResponse actualportalRestResponse = microserviceController.updateMicroservice(mockedRequest, mockedResponse, 1, microserviceData); @@ -172,24 +182,36 @@ public class MicroserviceControllerTest extends MockitoTestSuite{ } @Test - public void updateMicroserviceTest() throws Exception { - PortalRestResponse expectedportalRestResponse = new PortalRestResponse(); + public void updateMicroserviceTest() { + PortalRestResponse expectedportalRestResponse = new PortalRestResponse<>(); expectedportalRestResponse.setMessage("SUCCESS"); expectedportalRestResponse.setResponse(""); - PortalRestStatusEnum portalRestStatusEnum = null; - expectedportalRestResponse.setStatus(portalRestStatusEnum.OK); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.OK); PortalRestResponse actualportalRestResponse = microserviceController.updateMicroservice(mockedRequest, - mockedResponse, 1, microserviceData); + mockedResponse, 1, microserviceData); assertEquals(actualportalRestResponse, expectedportalRestResponse); } @Test - public void updateMicroserviceExceptionTest() throws Exception { - PortalRestResponse expectedportalRestResponse = new PortalRestResponse(); + public void updateMicroserviceXSSTest() { + PortalRestResponse expectedportalRestResponse = new PortalRestResponse<>(); + expectedportalRestResponse.setMessage("ERROR"); + expectedportalRestResponse.setResponse("MicroserviceData is not valid"); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + MicroserviceData XSSMicroserviceData = new MicroserviceData(); + XSSMicroserviceData.setActive(""); + XSSMicroserviceData.setName(""); + PortalRestResponse actualportalRestResponse = microserviceController.updateMicroservice(mockedRequest, + mockedResponse, 1, XSSMicroserviceData); + assertEquals(expectedportalRestResponse, actualportalRestResponse); + } + + @Test + public void updateMicroserviceExceptionTest() { + PortalRestResponse expectedportalRestResponse = new PortalRestResponse<>(); expectedportalRestResponse.setMessage("FAILURE"); expectedportalRestResponse.setResponse(null); - PortalRestStatusEnum portalRestStatusEnum = null; - expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR); Mockito.when(microserviceController.updateMicroservice(mockedRequest, mockedResponse, 1, microserviceData)) .thenThrow(nullPointerException); PortalRestResponse actualportalRestResponse = microserviceController.updateMicroservice(mockedRequest, @@ -198,14 +220,14 @@ public class MicroserviceControllerTest extends MockitoTestSuite{ } @Test - public void deleteMicroserviceExceptionTest() throws Exception { - PortalRestResponse expectedportalRestResponse = new PortalRestResponse(); + public void deleteMicroserviceExceptionTest() { + PortalRestResponse expectedportalRestResponse = new PortalRestResponse<>(); expectedportalRestResponse.setMessage("FAILURE"); PowerMockito.mockStatic(EcompPortalUtils.class); expectedportalRestResponse.setResponse( - "I/O error on GET request for \"" + EcompPortalUtils.widgetMsProtocol() + "://null/widget/microservices/widgetCatalog/service/1\":null; nested exception is java.net.UnknownHostException: null"); - PortalRestStatusEnum portalRestStatusEnum = null; - expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + "I/O error on GET request for \"" + org.onap.portalapp.portal.utils.EcompPortalUtils.widgetMsProtocol() + + "://null/widget/microservices/widgetCatalog/service/1\":null; nested exception is java.net.UnknownHostException: null"); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR); PowerMockito.mockStatic(WidgetServiceHeaders.class); PortalRestResponse actuaPportalRestResponse = microserviceController.deleteMicroservice(mockedRequest, mockedResponse, 1); @@ -215,13 +237,11 @@ public class MicroserviceControllerTest extends MockitoTestSuite{ @SuppressWarnings("unchecked") @Test public void deleteMicroserviceTest() throws Exception { - String HTTPS = "https://"; - PortalRestResponse expectedportalRestResponse = new PortalRestResponse(); + PortalRestResponse expectedportalRestResponse = new PortalRestResponse<>(); expectedportalRestResponse.setMessage("SOME WIDGETS ASSOICATE WITH THIS SERVICE"); expectedportalRestResponse.setResponse("'null' ,'null' "); - PortalRestStatusEnum portalRestStatusEnum = null; - expectedportalRestResponse.setStatus(portalRestStatusEnum.WARN); - List List = new ArrayList(); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.WARN); + List List = new ArrayList<>(); WidgetCatalog widgetCatalog = new WidgetCatalog(); widgetCatalog.setId(1); WidgetCatalog widgetCatalog1 = new WidgetCatalog(); @@ -236,7 +256,7 @@ public class MicroserviceControllerTest extends MockitoTestSuite{ ParameterizedTypeReference> typeRef = new ParameterizedTypeReference>() { }; Mockito.when(template.exchange( - EcompPortalUtils.widgetMsProtocol() + "://" + consulHealthService.getServiceLocation(whatService, SystemProperties.getProperty("microservices.widget.local.port")) + org.onap.portalapp.portal.utils.EcompPortalUtils.widgetMsProtocol() + "://" + consulHealthService.getServiceLocation(whatService, SystemProperties.getProperty("microservices.widget.local.port")) + "/widget/microservices/widgetCatalog/service/" + 1, HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), typeRef)).thenReturn(ans); @@ -248,12 +268,11 @@ public class MicroserviceControllerTest extends MockitoTestSuite{ @SuppressWarnings("unchecked") @Test public void deleteMicroserviceWhenNoWidgetsAssociatedTest() throws Exception { - PortalRestResponse expectedportalRestResponse = new PortalRestResponse(); + PortalRestResponse expectedportalRestResponse = new PortalRestResponse<>(); expectedportalRestResponse.setMessage("SUCCESS"); expectedportalRestResponse.setResponse(""); - PortalRestStatusEnum portalRestStatusEnum = null; - expectedportalRestResponse.setStatus(portalRestStatusEnum.OK); - List List = new ArrayList(); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.OK); + List List = new ArrayList<>(); PowerMockito.mockStatic(WidgetServiceHeaders.class); PowerMockito.mockStatic(EcompPortalUtils.class); String whatService = "widgets-service"; @@ -262,7 +281,7 @@ public class MicroserviceControllerTest extends MockitoTestSuite{ ParameterizedTypeReference> typeRef = new ParameterizedTypeReference>() { }; Mockito.when(template.exchange( - EcompPortalUtils.widgetMsProtocol() + "://" + consulHealthService.getServiceLocation(whatService, SystemProperties.getProperty("microservices.widget.local.port")) + org.onap.portalapp.portal.utils.EcompPortalUtils.widgetMsProtocol() + "://" + consulHealthService.getServiceLocation(whatService, SystemProperties.getProperty("microservices.widget.local.port")) + "/widget/microservices/widgetCatalog/service/" + 1, HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), typeRef)).thenReturn(ans); PortalRestResponse actuaPportalRestResponse = microserviceController.deleteMicroservice(mockedRequest, diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/RoleManageControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/RoleManageControllerTest.java index 8bfa39c3..9673cb2c 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/RoleManageControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/RoleManageControllerTest.java @@ -370,6 +370,48 @@ public class RoleManageControllerTest { assertEquals(expected, actual); } + @Test + public void saveRoleFunctionXSSTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + Mockito.when(adminRolesService.isAccountAdminOfApplication(user, CentralApp())).thenReturn(true); + Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); + Mockito.doNothing().when(roleFunctionListController).saveRoleFunction(mockedRequest, mockedResponse, "test"); + CentralV2RoleFunction addNewFunc = new CentralV2RoleFunction(); + addNewFunc.setCode("“>"); + addNewFunc.setType("Test"); + addNewFunc.setAction("Test"); + addNewFunc.setName("Test"); + CentralV2RoleFunction roleFunction = mockCentralRoleFunction(); + roleFunction.setCode("Test|Test|Test"); + Mockito.when(externalAccessRolesService.getRoleFunction("Test|Test|Test", "test")).thenReturn(roleFunction); + Mockito.when(externalAccessRolesService.saveCentralRoleFunction(Matchers.anyObject(), Matchers.anyObject())) + .thenReturn(true); + Mockito.when(EcompPortalUtils.getFunctionCode(roleFunction.getCode())).thenReturn("Test"); + Mockito.when(EcompPortalUtils.getFunctionType(roleFunction.getCode())).thenReturn("Test"); + Mockito.when(EcompPortalUtils.getFunctionAction(roleFunction.getCode())).thenReturn("Test"); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + List userList = new ArrayList<>(); + userList.add(user); + List appList = new ArrayList<>(); + appList.add(CentralApp()); + Mockito.when(externalAccessRolesService.getUser("guestT")).thenReturn(userList); + StringWriter sw = new StringWriter(); + PrintWriter writer = new PrintWriter(sw); + Mockito.when(mockedResponse.getWriter()).thenReturn(writer); + ResponseEntity response = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); + PortalRestResponse actual = roleManageController.saveRoleFunction(mockedRequest, mockedResponse, + addNewFunc, (long) 1); + PortalRestResponse expected = new PortalRestResponse(PortalRestStatusEnum.ERROR, + "Data is not valid", "ERROR"); + assertEquals(expected, actual); + } + @Test public void saveRoleFunctionExceptionTest() throws Exception { Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); @@ -420,6 +462,36 @@ public class RoleManageControllerTest { assertEquals(expected, actual); } + @Test + public void removeRoleFunctionXSSTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + Mockito.when(adminRolesService.isAccountAdminOfApplication(user, CentralApp())).thenReturn(true); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); + String roleFun = ""; + CentralV2RoleFunction roleFunction = mockCentralRoleFunction(); + Mockito.when(externalAccessRolesService.getRoleFunction("Test|Test|Test", "test")).thenReturn(roleFunction); + StringWriter sw = new StringWriter(); + PrintWriter writer = new PrintWriter(sw); + Mockito.when(mockedResponse.getWriter()).thenReturn(writer); + Mockito.when(externalAccessRolesService.deleteCentralRoleFunction(Matchers.anyString(), Matchers.anyObject())) + .thenReturn(true); + List appList = new ArrayList<>(); + appList.add(CentralApp()); + ResponseEntity response = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); + PortalRestResponse actual = roleManageController.removeRoleFunction(mockedRequest, mockedResponse, + roleFun, (long) 1); + PortalRestResponse expected = new PortalRestResponse(PortalRestStatusEnum.ERROR, + "Data is not valid", "ERROR"); + assertEquals(expected, actual); + } + @Test public void removeRoleFunctionExceptionTest() throws Exception { EPUser user = mockUser.mockEPUser(); @@ -908,6 +980,13 @@ public class RoleManageControllerTest { List actual = roleManageController.getCentralizedAppRoles(mockedRequest, mockedResponse, user.getOrgUserId()); assertEquals(cenApps.size(), actual.size()); } + + @Test + public void getCentralizedAppRolesXSSTest() throws IOException { + String id = (""); + List actual = roleManageController.getCentralizedAppRoles(mockedRequest, mockedResponse, id); + assertNull(actual); + } @Test public void getCentralizedAppRolesExceptionTest() throws IOException { 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 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 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 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 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 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 restObject=new RestObject<>(); + Mockito.when(jsonObject.get("scheduleId")).thenReturn("12"); + Set 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 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 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 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 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 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 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 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 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 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/controller/TicketEventControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/TicketEventControllerTest.java index aca7c1b3..211462d1 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/TicketEventControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/TicketEventControllerTest.java @@ -150,6 +150,18 @@ public class TicketEventControllerTest { assertTrue(actualPortalRestResponse.getStatus().compareTo(PortalRestStatusEnum.OK) == 0); } + @Test + public void saveXSSTest() throws Exception { + String ticketEventJson = "