2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
8 * Unless otherwise specified, all software contained herein is licensed
9 * under the Apache License, Version 2.0 (the "License");
10 * you may not use this software except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * Unless otherwise specified, all documentation contained herein is licensed
22 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23 * you may not use this documentation except in compliance with the License.
24 * You may obtain a copy of the License at
26 * https://creativecommons.org/licenses/by/4.0/
28 * Unless required by applicable law or agreed to in writing, documentation
29 * distributed under the License is distributed on an "AS IS" BASIS,
30 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31 * See the License for the specific language governing permissions and
32 * limitations under the License.
34 * ============LICENSE_END============================================
38 package org.onap.portalapp.portal.service;
40 import java.io.IOException;
41 import java.util.ArrayList;
42 import java.util.HashMap;
43 import java.util.HashSet;
44 import java.util.Iterator;
45 import java.util.List;
48 import java.util.SortedSet;
49 import java.util.TreeSet;
50 import java.util.regex.Pattern;
51 import java.util.stream.Collectors;
53 import org.apache.commons.codec.DecoderException;
54 import org.apache.commons.codec.binary.Hex;
55 import org.hibernate.Query;
56 import org.hibernate.Session;
57 import org.hibernate.SessionFactory;
58 import org.hibernate.Transaction;
59 import org.hibernate.criterion.Criterion;
60 import org.hibernate.criterion.Restrictions;
61 import org.json.JSONArray;
62 import org.json.JSONObject;
63 import org.onap.portalapp.portal.domain.CentralV2RoleFunction;
64 import org.onap.portalapp.portal.domain.CentralizedApp;
65 import org.onap.portalapp.portal.domain.EPApp;
66 import org.onap.portalapp.portal.domain.EPAppRoleFunction;
67 import org.onap.portalapp.portal.domain.EPRole;
68 import org.onap.portalapp.portal.domain.EPUser;
69 import org.onap.portalapp.portal.domain.EPUserApp;
70 import org.onap.portalapp.portal.domain.ExternalRoleDetails;
71 import org.onap.portalapp.portal.ecomp.model.UploadRoleFunctionExtSystem;
72 import org.onap.portalapp.portal.exceptions.DeleteDomainObjectFailedException;
73 import org.onap.portalapp.portal.exceptions.ExternalAuthSystemException;
74 import org.onap.portalapp.portal.exceptions.InactiveApplicationException;
75 import org.onap.portalapp.portal.exceptions.InvalidApplicationException;
76 import org.onap.portalapp.portal.exceptions.InvalidUserException;
77 import org.onap.portalapp.portal.exceptions.RoleFunctionException;
78 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
79 import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
80 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
81 import org.onap.portalapp.portal.transport.BulkUploadRoleFunction;
82 import org.onap.portalapp.portal.transport.BulkUploadUserRoles;
83 import org.onap.portalapp.portal.transport.CentralApp;
84 import org.onap.portalapp.portal.transport.CentralRole;
85 import org.onap.portalapp.portal.transport.CentralRoleFunction;
86 import org.onap.portalapp.portal.transport.CentralUser;
87 import org.onap.portalapp.portal.transport.CentralUserApp;
88 import org.onap.portalapp.portal.transport.CentralV2Role;
89 import org.onap.portalapp.portal.transport.CentralV2User;
90 import org.onap.portalapp.portal.transport.CentralV2UserApp;
91 import org.onap.portalapp.portal.transport.CentralizedAppRoles;
92 import org.onap.portalapp.portal.transport.EPUserAppCurrentRoles;
93 import org.onap.portalapp.portal.transport.EcompUserRoles;
94 import org.onap.portalapp.portal.transport.ExternalAccessPerms;
95 import org.onap.portalapp.portal.transport.ExternalAccessPermsDetail;
96 import org.onap.portalapp.portal.transport.ExternalAccessRole;
97 import org.onap.portalapp.portal.transport.ExternalAccessRolePerms;
98 import org.onap.portalapp.portal.transport.ExternalAccessUser;
99 import org.onap.portalapp.portal.transport.ExternalAccessUserRoleDetail;
100 import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator;
101 import org.onap.portalapp.portal.transport.GlobalRoleWithApplicationRoleFunction;
102 import org.onap.portalapp.portal.transport.LocalRole;
103 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
104 import org.onap.portalapp.portal.utils.EcompPortalUtils;
105 import org.onap.portalapp.portal.utils.PortalConstants;
106 import org.onap.portalapp.util.EPUserUtils;
107 import org.onap.portalsdk.core.domain.Role;
108 import org.onap.portalsdk.core.domain.RoleFunction;
109 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
110 import org.onap.portalsdk.core.restful.domain.EcompRole;
111 import org.onap.portalsdk.core.restful.domain.EcompRoleFunction;
112 import org.onap.portalsdk.core.restful.domain.EcompUser;
113 import org.onap.portalsdk.core.service.DataAccessService;
114 import org.onap.portalsdk.core.util.SystemProperties;
115 import org.springframework.beans.factory.annotation.Autowired;
116 import org.springframework.context.annotation.EnableAspectJAutoProxy;
117 import org.springframework.http.HttpEntity;
118 import org.springframework.http.HttpHeaders;
119 import org.springframework.http.HttpMethod;
120 import org.springframework.http.HttpStatus;
121 import org.springframework.http.ResponseEntity;
122 import org.springframework.stereotype.Service;
123 import org.springframework.transaction.annotation.Transactional;
124 import org.springframework.web.client.HttpClientErrorException;
125 import org.springframework.web.client.RestTemplate;
127 import com.fasterxml.jackson.core.JsonProcessingException;
128 import com.fasterxml.jackson.databind.DeserializationFeature;
129 import com.fasterxml.jackson.databind.ObjectMapper;
130 import com.fasterxml.jackson.databind.type.TypeFactory;
132 @Service("externalAccessRolesService")
133 @EnableAspectJAutoProxy
136 public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesService {
137 private static final String APP_ROLE_NAME_PARAM = "appRoleName";
138 private static final String GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM = "getRoletoUpdateInExternalAuthSystem";
139 private static final String GET_PORTAL_APP_ROLES_QUERY = "getPortalAppRoles";
140 private static final String GET_ROLE_FUNCTION_QUERY = "getRoleFunction";
141 private static final String FUNCTION_CODE_PARAMS = "functionCode";
142 private static final String AND_FUNCTION_CD_EQUALS = " and function_cd = '";
143 private static final String OWNER = ".owner";
144 private static final String ADMIN = ".admin";
145 private static final String ACCOUNT_ADMINISTRATOR = ".Account_Administrator";
146 private static final String FUNCTION_PIPE = "|";
147 private static final String EXTERNAL_AUTH_PERMS = "perms";
148 private static final String EXTERNAL_AUTH_ROLE_DESCRIPTION = "description";
149 private static final String IS_EMPTY_JSON_STRING = "{}";
150 private static final String CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE = "Connecting to External Auth system";
151 private static final String APP_ID = "appId";
152 private static final String ROLE_NAME = "name";
153 private static final String APP_ID_EQUALS = " app_id = ";
154 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesServiceImpl.class);
156 private DataAccessService dataAccessService;
158 private EPAppService epAppService;
160 private SessionFactory sessionFactory;
162 EPRoleService ePRoleService;
163 RestTemplate template = new RestTemplate();
164 // These decode values are based on HexDecoder
165 static final String decodeValueOfForwardSlash = "2f";
166 static final String decodeValueOfHiphen = "2d";
167 static final String decodeValueOfStar = "2a";
169 @SuppressWarnings("unchecked")
171 public List<EPRole> getAppRoles(Long appId) throws Exception {
172 List<EPRole> applicationRoles = null;
173 final Map<String, Long> appParams = new HashMap<>();
176 applicationRoles = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
178 appParams.put("appId", appId);
179 applicationRoles = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
181 } catch (Exception e) {
182 logger.error(EELFLoggerDelegate.errorLogger, "getAppRoles: failed", e);
185 return applicationRoles;
188 @SuppressWarnings("unchecked")
190 public List<EPApp> getApp(String uebkey) throws Exception {
191 List<EPApp> app = null;
193 final Map<String, String> appUebkeyParams = new HashMap<>();
194 appUebkeyParams.put("appKey", uebkey);
195 app = dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null);
196 if (!app.isEmpty() && !app.get(0).getEnabled()
197 && !app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
198 throw new InactiveApplicationException("Application:" + app.get(0).getName() + " is Unavailable");
200 } catch (Exception e) {
201 logger.error(EELFLoggerDelegate.errorLogger, "getApp: failed", e);
208 * It returns single application role from external auth system
212 * @return JSON string which contains application role details
215 private String getSingleAppRole(String addRole, EPApp app) throws Exception {
216 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
217 HttpEntity<String> entity = new HttpEntity<>(headers);
218 ResponseEntity<String> response = null;
219 logger.debug(EELFLoggerDelegate.debugLogger, "getSingleAppRole: Connecting to External Auth system");
220 response = template.exchange(
221 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
224 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
225 HttpMethod.GET, entity, String.class);
226 logger.debug(EELFLoggerDelegate.debugLogger,
227 "getSingleAppRole: Finished GET app role from External Auth system and status code: {} ",
228 response.getStatusCode().value());
229 return response.getBody();
233 public boolean addRole(Role addRole, String uebkey) throws Exception {
234 boolean response = false;
235 ResponseEntity<String> addResponse = null;
236 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
237 EPApp app = getApp(uebkey).get(0);
238 String newRole = updateExistingRoleInExternalSystem(addRole, app);
239 HttpEntity<String> entity = new HttpEntity<>(newRole, headers);
240 logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Connecting to External Auth system");
241 addResponse = template.exchange(
242 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
243 HttpMethod.POST, entity, String.class);
244 if (addResponse.getStatusCode().value() == 201) {
246 logger.debug(EELFLoggerDelegate.debugLogger,
247 "addRole: Finished adding role in the External Auth system and response code: {} ",
248 addResponse.getStatusCode().value());
250 if (addResponse.getStatusCode().value() == 406) {
251 logger.error(EELFLoggerDelegate.errorLogger,
252 "addRole: Failed to add in the External Auth system due to {} and status code: {}",
253 addResponse.getBody(), addResponse.getStatusCode().value());
260 * It deletes record in external auth system
263 * @return JSON String which has status code and response body
266 private ResponseEntity<String> deleteRoleInExternalSystem(String delRole) throws Exception {
267 ResponseEntity<String> delResponse = null;
268 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
269 HttpEntity<String> entity = new HttpEntity<>(delRole, headers);
270 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: {} for DELETE: {}",
271 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, delRole);
272 delResponse = template.exchange(
273 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role?force=true",
274 HttpMethod.DELETE, entity, String.class);
275 logger.debug(EELFLoggerDelegate.debugLogger,
276 "deleteRoleInExternalSystem: Finished DELETE operation in the External Auth system {} and status code: {} ",
277 delRole, delResponse.getStatusCode().value());
282 * It updates role in external auth system
284 * @param updateExtRole
286 * @return true if success else false
288 * If updateRoleInExternalSystem fails we catch it in logger for
291 private boolean updateRoleInExternalSystem(Role updateExtRole, EPApp app, boolean isGlobalRole) throws Exception {
292 boolean response = false;
293 ObjectMapper mapper = new ObjectMapper();
294 ResponseEntity<String> deleteResponse = null;
295 List<EPRole> epRoleList = null;
296 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)
297 || (isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
298 epRoleList = getPortalAppRoleInfo(updateExtRole.getId());
300 epRoleList = getPartnerAppRoleInfo(updateExtRole.getId(), app);
302 // Assigning functions to global role
303 if ((isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
304 List<RoleFunction> globalRoleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole);
305 EPApp portalAppInfo = epAppService.getApp(PortalConstants.PORTAL_APP_ID);
306 addFunctionsTOGlobalRole(epRoleList, updateExtRole, globalRoleFunctionListNew, mapper, app, portalAppInfo);
309 String appRole = getSingleAppRole(epRoleList.get(0).getName(), app);
310 List<RoleFunction> roleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole);
311 if (!appRole.equals(IS_EMPTY_JSON_STRING)) {
312 JSONObject jsonObj = new JSONObject(appRole);
313 JSONArray extRole = jsonObj.getJSONArray("role");
314 if (!extRole.getJSONObject(0).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
315 String roleName = extRole.getJSONObject(0).getString(ROLE_NAME);
316 Map<String, String> delRoleKeyMapper = new HashMap<>();
317 delRoleKeyMapper.put(ROLE_NAME, roleName);
318 String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
319 deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
320 if (deleteResponse.getStatusCode().value() != 200) {
321 throw new ExternalAuthSystemException(deleteResponse.getBody());
323 addRole(updateExtRole, app.getUebKey());
325 String desc = extRole.getJSONObject(0).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
326 String name = extRole.getJSONObject(0).getString(ROLE_NAME);
327 List<ExternalAccessPerms> list = new ArrayList<>();
328 if (extRole.getJSONObject(0).has(EXTERNAL_AUTH_PERMS)) {
329 JSONArray perms = extRole.getJSONObject(0).getJSONArray(EXTERNAL_AUTH_PERMS);
330 list = mapper.readValue(perms.toString(), TypeFactory.defaultInstance()
331 .constructCollectionType(List.class, ExternalAccessPerms.class));
333 // If role name or role functions are updated then delete
334 // record in External System and add new record to avoid
336 boolean isRoleNameChanged = false;
337 if (!desc.equals(updateExtRole.getName())) {
338 isRoleNameChanged = true;
339 deleteRoleInExtSystem(mapper, name);
340 addRole(updateExtRole, app.getUebKey());
341 // add partner functions to the global role in External
343 if (!list.isEmpty() && isGlobalRole) {
344 addPartnerHasRoleFunctionsToGlobalRole(list, mapper, app, updateExtRole);
347 perm -> EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace()));
348 // if role name is changes please ignore the previous
349 // functions in External Auth
350 // and update with user requested functions
351 addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name, list);
353 // Delete role in External System if role is inactive
354 if (!updateExtRole.getActive()) {
355 deleteRoleInExtSystem(mapper, name);
357 if (!isRoleNameChanged) {
358 response = addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name,
363 // It seems like role exists in local DB but not in External
365 if (updateExtRole.getActive()) {
366 addRole(updateExtRole, app.getUebKey());
367 ExternalAccessRolePerms extAddRolePerms = null;
368 ExternalAccessPerms extAddPerms = null;
369 List<RoleFunction> roleFunctionListAdd = convertSetToListOfRoleFunctions(updateExtRole);
370 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
371 for (RoleFunction roleFunc : roleFunctionListAdd) {
372 extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + roleFunc.getType(),
373 roleFunc.getCode(), roleFunc.getAction());
374 extAddRolePerms = new ExternalAccessRolePerms(extAddPerms,
375 app.getNameSpace() + "." + updateExtRole.getName().replaceAll(
376 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
377 response = addRoleFuncExtSysRestAPI(mapper, extAddRolePerms, headers);
385 private void deleteRoleInExtSystem(ObjectMapper mapper, String name)
386 throws JsonProcessingException, Exception, ExternalAuthSystemException {
387 ResponseEntity<String> deleteResponse;
388 Map<String, String> delRoleKeyMapper = new HashMap<>();
389 delRoleKeyMapper.put(ROLE_NAME, name);
390 String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
391 deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
392 if (deleteResponse.getStatusCode().value() != 200) {
393 logger.error(EELFLoggerDelegate.errorLogger,
394 "updateRoleInExternalSystem: Failed to delete role in external system due to {} ",
395 deleteResponse.getBody());
396 throw new ExternalAuthSystemException(deleteResponse.getBody());
400 private boolean addRemoveFunctionsToRole(Role updateExtRole, EPApp app, ObjectMapper mapper,
401 List<RoleFunction> roleFunctionListNew, String name, List<ExternalAccessPerms> list) throws Exception {
403 Map<String, RoleFunction> updateRoleFunc = new HashMap<>();
404 for (RoleFunction addPerm : roleFunctionListNew) {
405 updateRoleFunc.put(addPerm.getCode(), addPerm);
407 final Map<String, ExternalAccessPerms> extRolePermMap = new HashMap<>();
408 final Map<String, ExternalAccessPerms> extRolePermMapPipes = new HashMap<>();
409 list.removeIf(perm -> !EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace()));
410 // Update permissions in the ExternalAccess System
411 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
412 if (!list.isEmpty()) {
413 for (ExternalAccessPerms perm : list) {
414 RoleFunction roleFunc = updateRoleFunc.get(perm.getType().substring(app.getNameSpace().length() + 1)
415 + FUNCTION_PIPE + perm.getInstance() + FUNCTION_PIPE + perm.getAction());
416 if (roleFunc == null) {
417 RoleFunction roleFuncPipeFilter = updateRoleFunc.get(perm.getInstance());
418 if (roleFuncPipeFilter == null)
419 removePermForRole(perm, mapper, name, headers);
421 extRolePermMap.put(perm.getInstance(), perm);
422 extRolePermMapPipes.put(perm.getType().substring(app.getNameSpace().length() + 1) + FUNCTION_PIPE
423 + perm.getInstance() + FUNCTION_PIPE + perm.getAction(), perm);
427 if (!roleFunctionListNew.isEmpty()) {
428 for (RoleFunction roleFunc : roleFunctionListNew) {
429 if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
430 ExternalAccessPerms perm = extRolePermMapPipes.get(roleFunc.getCode());
432 response = addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers,
436 if (!extRolePermMap.containsKey(EcompPortalUtils.getFunctionCode(roleFunc.getCode()))) {
437 response = addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers,
447 * Adds function to the role in the external auth system while editing a
448 * role or updating new functions to a role
451 private boolean addFunctionsToRoleInExternalAuthSystem(Role updateExtRole, EPApp app, ObjectMapper mapper,
452 HttpHeaders headers, RoleFunction roleFunc) throws JsonProcessingException {
454 ExternalAccessRolePerms extRolePerms;
455 ExternalAccessPerms extPerms;
459 if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
460 code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
461 type = EcompPortalUtils.getFunctionType(roleFunc.getCode());
462 action = getFunctionCodeAction(roleFunc.getCode());
464 code = roleFunc.getCode();
465 type = roleFunc.getCode().contains("menu") ? "menu" : "url";
468 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, code, action);
469 extRolePerms = new ExternalAccessRolePerms(extPerms, app.getNameSpace() + "." + updateExtRole.getName()
470 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
471 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
472 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
473 logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: {} for POST: {}",
474 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
475 ResponseEntity<String> addResponse = template.exchange(
476 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
477 HttpMethod.POST, entity, String.class);
478 if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 409) {
480 logger.debug(EELFLoggerDelegate.debugLogger,
481 "updateRoleInExternalSystem: Connected to External Auth system but something went wrong! due to {} and statuscode: {}",
482 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
485 logger.debug(EELFLoggerDelegate.debugLogger,
486 "updateRoleInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ",
487 updateRolePerms, addResponse.getStatusCode().value());
492 private void addPartnerHasRoleFunctionsToGlobalRole(List<ExternalAccessPerms> permslist, ObjectMapper mapper,
493 EPApp app, Role updateExtRole) throws Exception {
494 for (ExternalAccessPerms perm : permslist) {
495 if (!EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace())) {
496 ExternalAccessRolePerms extAddGlobalRolePerms = null;
497 ExternalAccessPerms extAddPerms = null;
498 extAddPerms = new ExternalAccessPerms(perm.getType(), perm.getInstance(), perm.getAction());
499 extAddGlobalRolePerms = new ExternalAccessRolePerms(extAddPerms,
500 app.getNameSpace() + "." + updateExtRole.getName().replaceAll(
501 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
502 String addPerms = mapper.writeValueAsString(extAddGlobalRolePerms);
503 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
504 HttpEntity<String> entity = new HttpEntity<>(addPerms, headers);
505 logger.debug(EELFLoggerDelegate.debugLogger, "addPartnerHasRoleFunctionsToGlobalRole: {} ",
506 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
508 ResponseEntity<String> addResponse = template
509 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
510 + "role/perm", HttpMethod.POST, entity, String.class);
511 if (addResponse.getStatusCode().value() != 201) {
512 logger.debug(EELFLoggerDelegate.debugLogger,
513 "addPartnerHasRoleFunctionsToGlobalRole: While adding permission to the role in External Auth system something went wrong! due to {} and statuscode: {}",
514 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
516 logger.debug(EELFLoggerDelegate.debugLogger,
517 "addPartnerHasRoleFunctionsToGlobalRole: Finished adding permissions to roles in External Auth system and status code: {} ",
518 addResponse.getStatusCode().value());
520 } catch (Exception e) {
521 logger.error(EELFLoggerDelegate.errorLogger,
522 "addPartnerHasRoleFunctionsToGlobalRole: Failed for POST request: {} due to ", addPerms, e);
528 @SuppressWarnings("unchecked")
529 private void addFunctionsTOGlobalRole(List<EPRole> epRoleList, Role updateExtRole,
530 List<RoleFunction> roleFunctionListNew, ObjectMapper mapper, EPApp app, EPApp portalAppInfo)
533 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addFunctionsTOGlobalRole");
534 // GET Permissions from External Auth System
535 JSONArray extPerms = getExtAuthPermissions(app);
536 List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);
537 final Map<String, ExternalAccessPermsDetail> existingPermsWithRoles = new HashMap<>();
538 final Map<String, ExternalAccessPermsDetail> existingPermsWithRolesWithPipes = new HashMap<>();
539 final Map<String, RoleFunction> userRquestedFunctionsMap = new HashMap<>();
540 final Map<String, RoleFunction> userRquestedFunctionsMapPipesFilter = new HashMap<>();
541 for (ExternalAccessPermsDetail permDetail : permsDetailList) {
542 existingPermsWithRoles.put(EcompPortalUtils.getFunctionCode(permDetail.getInstance()), permDetail);
543 existingPermsWithRolesWithPipes.put(permDetail.getInstance(), permDetail);
545 // Add If function does not exists for role in External Auth System
546 for (RoleFunction roleFunc : roleFunctionListNew) {
547 String roleFuncCode = "";
548 ExternalAccessPermsDetail permsDetail;
549 if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
550 roleFuncCode = roleFunc.getCode();
551 permsDetail = existingPermsWithRolesWithPipes.get(roleFunc.getCode());
553 roleFuncCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
554 permsDetail = existingPermsWithRoles.get(roleFuncCode);
556 if (null == permsDetail.getRoles()
557 || !permsDetail.getRoles()
558 .contains(portalAppInfo.getNameSpace() + FUNCTION_PIPE
559 + epRoleList.get(0).getName().replaceAll(
560 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
562 addRoleFunctionsToGlobalRoleInExternalSystem(roleFunc, updateExtRole, mapper, app, portalAppInfo);
564 userRquestedFunctionsMap.put(roleFuncCode, roleFunc);
565 userRquestedFunctionsMapPipesFilter.put(EcompPortalUtils.getFunctionCode(roleFuncCode), roleFunc);
567 // Delete functions if exists in External Auth System but not in
570 final Map<String, Long> epAppRoleFuncParams = new HashMap<>();
571 epAppRoleFuncParams.put("requestedAppId", app.getId());
572 epAppRoleFuncParams.put("roleId", updateExtRole.getId());
573 List<GlobalRoleWithApplicationRoleFunction> globalRoleFunctionList = dataAccessService
574 .executeNamedQuery("getGlobalRoleForRequestedApp", epAppRoleFuncParams, null);
575 for (GlobalRoleWithApplicationRoleFunction globalRoleFunc : globalRoleFunctionList) {
576 String globalRoleFuncWithoutPipes = "";
577 RoleFunction roleFunc = null;
578 if (globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
579 globalRoleFuncWithoutPipes = globalRoleFunc.getFunctionCd();
580 roleFunc = userRquestedFunctionsMap.get(globalRoleFuncWithoutPipes);
582 globalRoleFuncWithoutPipes = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd());
583 roleFunc = userRquestedFunctionsMapPipesFilter.get(globalRoleFuncWithoutPipes);
585 if (roleFunc == null) {
586 ExternalAccessPermsDetail permDetailFromMap = globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)
587 ? existingPermsWithRolesWithPipes.get(globalRoleFuncWithoutPipes)
588 : existingPermsWithRoles.get(globalRoleFuncWithoutPipes);
589 ExternalAccessPerms perm = new ExternalAccessPerms(permDetailFromMap.getType(),
590 EcompPortalUtils.getFunctionCode(permDetailFromMap.getInstance()),
591 permDetailFromMap.getAction());
592 String roleName = portalAppInfo.getNameSpace() + "." + globalRoleFunc.getRoleName()
593 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_");
594 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
595 removePermForRole(perm, mapper, roleName, headers);
598 logger.debug(EELFLoggerDelegate.debugLogger, "Finished addFunctionsTOGlobalRole");
599 } catch (Exception e) {
600 logger.error(EELFLoggerDelegate.errorLogger, "addFunctionsTOGlobalRole: Failed", e);
605 private void addRoleFunctionsToGlobalRoleInExternalSystem(RoleFunction addFunction, Role globalRole,
606 ObjectMapper mapper, EPApp app, EPApp portalAppInfo) throws Exception {
608 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addRoleFunctionsToGlobalRoleInExternalSystem");
609 ExternalAccessRolePerms extAddRolePerms = null;
610 ExternalAccessPerms extAddPerms = null;
611 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
615 if (addFunction.getCode().contains(FUNCTION_PIPE)) {
616 code = EcompPortalUtils.getFunctionCode(addFunction.getCode());
617 type = getFunctionCodeType(addFunction.getCode());
618 action = getFunctionCodeAction(addFunction.getCode());
620 code = addFunction.getCode();
621 type = addFunction.getCode().contains("menu") ? "menu" : "url";
624 extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, code, action);
625 extAddRolePerms = new ExternalAccessRolePerms(extAddPerms, portalAppInfo.getNameSpace() + "." + globalRole
626 .getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
627 String updateRolePerms = mapper.writeValueAsString(extAddRolePerms);
628 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
629 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} ",
630 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
631 ResponseEntity<String> addResponse = template.exchange(
632 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
633 HttpMethod.POST, entity, String.class);
634 if (addResponse.getStatusCode().value() != 201) {
635 logger.debug(EELFLoggerDelegate.debugLogger,
636 "addRoleFunctionsInExternalSystem: While adding permission to the role in External Auth system something went wrong! due to {} and statuscode: {}",
637 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
639 logger.debug(EELFLoggerDelegate.debugLogger,
640 "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system and status code: {} ",
641 addResponse.getStatusCode().value());
643 logger.debug(EELFLoggerDelegate.debugLogger, "Finished addRoleFunctionsToGlobalRoleInExternalSystem");
644 } catch (Exception e) {
645 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionsToGlobalRoleInExternalSystem: Failed", e);
650 private boolean addRoleFuncExtSysRestAPI(ObjectMapper addPermsMapper, ExternalAccessRolePerms extAddRolePerms,
651 HttpHeaders headers) throws JsonProcessingException {
653 String updateRolePerms = addPermsMapper.writeValueAsString(extAddRolePerms);
654 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
655 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} for POST: {} ",
656 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
657 ResponseEntity<String> addResponse = template.exchange(
658 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
659 HttpMethod.POST, entity, String.class);
660 if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 409) {
662 logger.debug(EELFLoggerDelegate.debugLogger,
663 "addRoleFunctionsInExternalSystem: While adding permission to the role in External Auth system something went wrong! due to {} and statuscode: {}",
664 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
667 logger.debug(EELFLoggerDelegate.debugLogger,
668 "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ",
669 updateRolePerms, addResponse.getStatusCode().value());
676 * It converts list of functions in updateExtRole parameter to the
677 * RoleFunction object
679 * @param updateExtRole
680 * @return list of functions
682 @SuppressWarnings("unchecked")
683 private List<RoleFunction> convertSetToListOfRoleFunctions(Role updateExtRole) {
684 Set<RoleFunction> roleFunctionSetList = updateExtRole.getRoleFunctions();
685 List<RoleFunction> roleFunctionList = new ArrayList<>();
686 ObjectMapper roleFuncMapper = new ObjectMapper();
687 Iterator<RoleFunction> itetaror = roleFunctionSetList.iterator();
688 while (itetaror.hasNext()) {
689 Object nextValue = itetaror.next();
690 RoleFunction roleFunction = roleFuncMapper.convertValue(nextValue, RoleFunction.class);
691 roleFunctionList.add(roleFunction);
693 return roleFunctionList.stream().distinct().collect(Collectors.toList());
697 * It delete permissions/functions in the external auth system
703 * @throws JsonProcessingException
706 private void removePermForRole(ExternalAccessPerms perm, ObjectMapper permMapper, String name, HttpHeaders headers)
707 throws ExternalAuthSystemException, JsonProcessingException {
708 ExternalAccessRolePerms extAccessRolePerms = new ExternalAccessRolePerms(perm, name);
709 String permDetails = permMapper.writeValueAsString(extAccessRolePerms);
711 HttpEntity<String> deleteEntity = new HttpEntity<>(permDetails, headers);
712 logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: {} for DELETE: {} ",
713 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, permDetails);
714 ResponseEntity<String> deletePermResponse = template
715 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
716 + "role/" + name + "/perm", HttpMethod.DELETE, deleteEntity, String.class);
717 if (deletePermResponse.getStatusCode().value() != 200) {
718 throw new ExternalAuthSystemException(deletePermResponse.getBody());
720 logger.debug(EELFLoggerDelegate.debugLogger,
721 "removePermForRole: Finished deleting permission to role in External Auth system: {} and status code: {}",
722 permDetails, deletePermResponse.getStatusCode().value());
723 } catch (Exception e) {
724 if (e.getMessage().contains("404")) {
725 logger.error(EELFLoggerDelegate.errorLogger, "Failed to add role for DELETE request: {} due to {}",
726 permDetails, e.getMessage());
734 * It will create new role in the External Auth System
738 * @return true if successfully added in the system else false
740 * If fails to add role in the system
742 private void addNewRoleInExternalSystem(List<EPRole> newRole, EPApp app)
743 throws Exception, HttpClientErrorException {
745 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
746 ObjectMapper mapper = new ObjectMapper();
747 String addNewRole = "";
748 ExternalAccessRole extRole = new ExternalAccessRole();
749 extRole.setName(app.getNameSpace() + "." + newRole.get(0).getName()
750 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
751 extRole.setDescription(String.valueOf(newRole.get(0).getName()));
752 addNewRole = mapper.writeValueAsString(extRole);
753 HttpEntity<String> postEntity = new HttpEntity<>(addNewRole, headers);
754 logger.debug(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: {} for POST: {} ",
755 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addNewRole);
756 ResponseEntity<String> addNewRoleInExternalSystem = template.exchange(
757 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
758 HttpMethod.POST, postEntity, String.class);
759 if (addNewRoleInExternalSystem.getStatusCode().value() == 201) {
760 logger.debug(EELFLoggerDelegate.debugLogger,
761 "addNewRoleInExternalSystem: Finished adding into External Auth system for POST: {} and status code: {}",
762 addNewRole, addNewRoleInExternalSystem.getStatusCode().value());
764 } catch (HttpClientErrorException ht) {
765 dataAccessService.deleteDomainObjects(EPRole.class, " role_id = " + newRole.get(0).getId(), null);
766 logger.error(EELFLoggerDelegate.debugLogger,
767 "addNewRoleInExternalSystem: Failed to add in External Auth system and status code: {}", ht);
768 throw new HttpClientErrorException(ht.getStatusCode());
774 * It updates existing role in the External Auth System
777 * It Contains role information
779 * @return string which is formatted to match with the external auth system
780 * @throws JsonProcessingException
782 private String updateExistingRoleInExternalSystem(Role addRole, EPApp app) throws JsonProcessingException {
783 ObjectMapper mapper = new ObjectMapper();
784 String addNewRole = "";
785 ExternalAccessRole extRole = new ExternalAccessRole();
786 extRole.setName(app.getNameSpace() + "." + addRole.getName()
787 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
788 extRole.setDescription(String.valueOf(addRole.getName()));
789 addNewRole = mapper.writeValueAsString(extRole);
794 * It create a role in the external auth system and then in our local
798 * @return true else false
801 @SuppressWarnings("unchecked")
802 @Transactional(rollbackFor = Exception.class)
803 public boolean addRoleInEcompDB(Role addRoleInDB, EPApp app) throws Exception {
804 boolean result = false;
805 EPRole epRole = null;
806 Set<RoleFunction> roleFunctionList = addRoleInDB.getRoleFunctions();
807 List<RoleFunction> roleFunctionListNew = new ArrayList<>();
808 ObjectMapper mapper = new ObjectMapper();
809 Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
810 while (itetaror.hasNext()) {
811 Object nextValue = itetaror.next();
812 RoleFunction roleFunction = mapper.convertValue(nextValue, RoleFunction.class);
813 roleFunctionListNew.add(roleFunction);
815 List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct().collect(Collectors.toList());
817 if (addRoleInDB.getId() == null) { // check if it is new role
818 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
819 checkIfRoleExitsInExternalSystem(addRoleInDB, app);
821 EPRole epRoleNew = new EPRole();
822 epRoleNew.setActive(addRoleInDB.getActive());
823 epRoleNew.setName(addRoleInDB.getName());
824 epRoleNew.setPriority(addRoleInDB.getPriority());
825 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
826 epRoleNew.setAppId(null);
828 epRoleNew.setAppId(app.getId());
830 dataAccessService.saveDomainObject(epRoleNew, null);
831 List<EPRole> getRoleCreated = null;
832 final Map<String, String> epAppRoleParams = new HashMap<>();
833 final Map<String, String> epAppPortalRoleParams = new HashMap<>();
834 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
835 epAppRoleParams.put("appId", String.valueOf(app.getId()));
836 epAppRoleParams.put(APP_ROLE_NAME_PARAM, addRoleInDB.getName());
837 List<EPRole> roleCreated = dataAccessService
838 .executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, epAppRoleParams, null);
839 EPRole epUpdateRole = roleCreated.get(0);
840 epUpdateRole.setAppRoleId(epUpdateRole.getId());
841 dataAccessService.saveDomainObject(epUpdateRole, null);
842 getRoleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
843 epAppRoleParams, null);
845 epAppPortalRoleParams.put(APP_ROLE_NAME_PARAM, addRoleInDB.getName());
846 getRoleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY,
847 epAppPortalRoleParams, null);
849 // Add role in External Auth system
850 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
851 addNewRoleInExternalSystem(getRoleCreated, app);
854 } else { // if role already exists then update it
855 EPRole globalRole = null;
856 List<EPRole> applicationRoles;
857 List<EPRole> globalRoleList = getGlobalRolesOfPortal();
858 boolean isGlobalRole = false;
859 if (!globalRoleList.isEmpty()) {
860 EPRole role = globalRoleList.stream().filter(x -> addRoleInDB.getId().equals(x.getId())).findAny()
867 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)
868 || (globalRole != null && app.getId() != globalRole.getAppId())) {
869 applicationRoles = getPortalAppRoleInfo(addRoleInDB.getId());
871 applicationRoles = getPartnerAppRoleInfo(addRoleInDB.getId(), app);
873 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
874 updateRoleInExternalSystem(addRoleInDB, app, isGlobalRole);
875 // Add all user to the re-named role in external auth system
876 if (!applicationRoles.isEmpty()
877 && !addRoleInDB.getName().equals(applicationRoles.get(0).getName())) {
878 bulkUploadUsersSingleRole(app.getUebKey(), applicationRoles.get(0).getId(),
879 addRoleInDB.getName());
882 deleteRoleFunction(app, applicationRoles);
883 if (!applicationRoles.isEmpty()) {
884 epRole = applicationRoles.get(0);
885 epRole.setName(addRoleInDB.getName());
886 epRole.setPriority(addRoleInDB.getPriority());
887 epRole.setActive(addRoleInDB.getActive());
888 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
889 epRole.setAppId(null);
890 epRole.setAppRoleId(null);
891 } else if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)
892 && applicationRoles.get(0).getAppRoleId() == null) {
893 epRole.setAppRoleId(epRole.getId());
895 dataAccessService.saveDomainObject(epRole, null);
897 Long roleAppId = null;
898 if (globalRole != null && !app.getId().equals(globalRole.getAppId()))
899 roleAppId = PortalConstants.PORTAL_APP_ID;
900 saveRoleFunction(listWithoutDuplicates, app, applicationRoles, roleAppId);
903 } catch (Exception e) {
904 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInEcompDB is failed", e);
912 * It validates whether role exists in external auth system
919 private void checkIfRoleExitsInExternalSystem(Role checkRole, EPApp app) throws Exception {
920 getNameSpaceIfExists(app);
921 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
922 String roleName = app.getNameSpace() + "." + checkRole.getName()
923 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_");
924 HttpEntity<String> checkRoleEntity = new HttpEntity<>(headers);
925 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRoleExitsInExternalSystem: {} ",
926 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
927 ResponseEntity<String> checkRoleInExternalSystem = template
928 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
929 + roleName, HttpMethod.GET, checkRoleEntity, String.class);
930 if (!checkRoleInExternalSystem.getBody().equals(IS_EMPTY_JSON_STRING)) {
932 "checkIfRoleExitsInExternalSystem: Role already exists in external system {} and status code: {} ",
933 checkRoleInExternalSystem.getBody(), checkRoleInExternalSystem.getStatusCode().value());
934 throw new ExternalAuthSystemException(" Role already exists in external system");
939 * It saves list of functions to the role in portal
941 * @param roleFunctionListNew
943 * @param applicationRoles
946 @SuppressWarnings("unchecked")
947 private void saveRoleFunction(List<RoleFunction> roleFunctionListNew, EPApp app, List<EPRole> applicationRoles,
948 Long roleAppId) throws Exception {
949 final Map<String, String> getAppFunctionParams = new HashMap<>();
950 for (RoleFunction roleFunc : roleFunctionListNew) {
951 String code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
952 EPAppRoleFunction appRoleFunc = new EPAppRoleFunction();
953 appRoleFunc.setAppId(app.getId());
954 appRoleFunc.setRoleId(applicationRoles.get(0).getId());
955 appRoleFunc.setRoleAppId(String.valueOf(roleAppId));
956 getAppFunctionParams.put("appId", String.valueOf(app.getId()));
957 getAppFunctionParams.put(FUNCTION_CODE_PARAMS, roleFunc.getCode());
958 // query to check if function code has pipes
959 List<CentralV2RoleFunction> roleFunction = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY,
960 getAppFunctionParams, null);
961 if (roleFunction.isEmpty()) {
962 getAppFunctionParams.put(FUNCTION_CODE_PARAMS, code);
963 roleFunction = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null);
965 if (roleFunction.size() > 1) {
966 CentralV2RoleFunction getExactFunctionCode = appFunctionListFilter(code, roleFunction);
967 appRoleFunc.setCode(getExactFunctionCode.getCode());
969 appRoleFunc.setCode(roleFunction.get(0).getCode());
971 dataAccessService.saveDomainObject(appRoleFunc, null);
977 * It filters the app functions which starts with similar name in the result
981 * @param roleFunction
982 * @return CentralRoleFunction
984 private CentralV2RoleFunction appFunctionListFilter(String roleFuncCode, List<CentralV2RoleFunction> roleFunction) {
985 final Map<String, CentralV2RoleFunction> appFunctionsFilter = new HashMap<>();
986 final Map<String, CentralV2RoleFunction> appFunctionsFilterPipes = new HashMap<>();
987 CentralV2RoleFunction getExactFunctionCode = null;
988 for (CentralV2RoleFunction cenRoleFunction : roleFunction) {
989 appFunctionsFilter.put(cenRoleFunction.getCode(), cenRoleFunction);
990 appFunctionsFilterPipes.put(EcompPortalUtils.getFunctionCode(cenRoleFunction.getCode()), cenRoleFunction);
992 getExactFunctionCode = appFunctionsFilter.get(roleFuncCode);
993 if (getExactFunctionCode == null) {
994 getExactFunctionCode = appFunctionsFilterPipes.get(roleFuncCode);
996 return getExactFunctionCode;
1000 * It deletes all EPAppRoleFunction records in the portal
1005 @SuppressWarnings("unchecked")
1006 private void deleteRoleFunction(EPApp app, List<EPRole> role) {
1007 final Map<String, Long> appRoleFuncsParams = new HashMap<>();
1008 appRoleFuncsParams.put("appId", app.getId());
1009 appRoleFuncsParams.put("roleId", role.get(0).getId());
1010 List<EPAppRoleFunction> appRoleFunctionList = dataAccessService
1011 .executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null);
1012 if (!appRoleFunctionList.isEmpty()) {
1013 for (EPAppRoleFunction approleFunction : appRoleFunctionList) {
1014 dataAccessService.deleteDomainObject(approleFunction, null);
1020 @SuppressWarnings("unchecked")
1021 public List<EPUser> getUser(String loginId) throws InvalidUserException {
1022 final Map<String, String> userParams = new HashMap<>();
1023 userParams.put("org_user_id", loginId);
1024 List<EPUser> userList = dataAccessService.executeNamedQuery("getEPUserByOrgUserId", userParams, null);
1025 if (userList.isEmpty()) {
1026 throw new InvalidUserException("User not found");
1032 public String getV2UserWithRoles(String loginId, String uebkey) throws Exception {
1033 final Map<String, String> params = new HashMap<>();
1034 List<EPUser> userList = null;
1035 CentralV2User cenV2User = null;
1036 String result = null;
1038 params.put("orgUserIdValue", loginId);
1039 List<EPApp> appList = getApp(uebkey);
1040 if (!appList.isEmpty()) {
1041 userList = getUser(loginId);
1042 if (!userList.isEmpty()) {
1043 ObjectMapper mapper = new ObjectMapper();
1044 cenV2User = getV2UserAppRoles(loginId, uebkey);
1045 result = mapper.writeValueAsString(cenV2User);
1046 } else if (userList.isEmpty()) {
1047 throw new InvalidUserException("User not found");
1050 throw new InactiveApplicationException("Application not found");
1052 } catch (Exception e) {
1053 logger.error(EELFLoggerDelegate.errorLogger, "getUser: failed", e);
1060 public List<CentralV2Role> getRolesForApp(String uebkey) throws Exception {
1061 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Entering into getRolesForApp");
1062 List<CentralV2Role> roleList = new ArrayList<>();
1063 final Map<String, Long> params = new HashMap<>();
1065 List<EPApp> app = getApp(uebkey);
1066 List<EPRole> appRolesList = getAppRoles(app.get(0).getId());
1067 roleList = createCentralRoleObject(app, appRolesList, roleList, params);
1068 if (app.get(0).getId() != PortalConstants.PORTAL_APP_ID) {
1069 List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
1070 List<EPRole> globalRolesList = getGlobalRolesOfPortal();
1071 List<CentralV2Role> portalsGlobalRolesFinlaList = new ArrayList<>();
1072 if (!globalRolesList.isEmpty()) {
1073 for (EPRole eprole : globalRolesList) {
1074 CentralV2Role cenRole = convertRoleToCentralV2Role(eprole);
1075 portalsGlobalRolesFinlaList.add(cenRole);
1077 roleList.addAll(globalRoleList);
1078 for (CentralV2Role role : portalsGlobalRolesFinlaList) {
1079 CentralV2Role result = roleList.stream().filter(x -> role.getId().equals(x.getId())).findAny()
1085 for (EPRole role : globalRolesList) {
1086 CentralV2Role cenRole = convertRoleToCentralV2Role(role);
1087 roleList.add(cenRole);
1091 } catch (Exception e) {
1092 logger.error(EELFLoggerDelegate.errorLogger, "getRolesForApp: Failed!", e);
1095 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Finished!");
1096 return roleList.stream().distinct().collect(Collectors.toList());
1099 @SuppressWarnings("unchecked")
1101 public List<CentralV2RoleFunction> getRoleFuncList(String uebkey) throws Exception {
1102 EPApp app = getApp(uebkey).get(0);
1103 List<CentralV2RoleFunction> finalRoleList = new ArrayList<>();
1104 final Map<String, Long> params = new HashMap<>();
1105 params.put(APP_ID, app.getId());
1106 List<CentralV2RoleFunction> getRoleFuncList = dataAccessService.executeNamedQuery("getAllRoleFunctions", params,
1108 for (CentralV2RoleFunction roleFuncItem : getRoleFuncList) {
1109 String code = EcompPortalUtils.getFunctionCode(roleFuncItem.getCode());
1111 if (roleFuncItem.getCode().contains("|"))
1112 type = EcompPortalUtils.getFunctionType(roleFuncItem.getCode());
1114 type = getFunctionCodeType(roleFuncItem.getCode());
1115 String action = getFunctionCodeAction(roleFuncItem.getCode());
1116 roleFuncItem.setCode(EPUserUtils.decodeFunctionCode(code));
1117 roleFuncItem.setType(type);
1118 roleFuncItem.setAction(action);
1119 finalRoleList.add(roleFuncItem);
1121 return finalRoleList;
1125 public String getFunctionCodeAction(String roleFuncItem) {
1126 return (!roleFuncItem.contains(FUNCTION_PIPE)) ? "*" : EcompPortalUtils.getFunctionAction(roleFuncItem);
1130 public String getFunctionCodeType(String roleFuncItem) {
1132 if ((roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))
1133 || (!roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))) {
1135 } else if (checkIfCodeHasNoPipesAndHasTypeUrl(roleFuncItem) || checkIfCodeHasPipesAndHasTypeUrl(roleFuncItem)
1136 || checkIfCodeHasNoPipesAndHasNoTypeUrl(roleFuncItem)) {
1138 } else if (roleFuncItem.contains(FUNCTION_PIPE)
1139 && (!roleFuncItem.contains("menu") || roleFuncItem.contains("url"))) {
1140 type = EcompPortalUtils.getFunctionType(roleFuncItem);
1147 * It check whether function code has no pipes and no url string in it
1149 * @param roleFuncItem
1150 * @return true or false
1152 private boolean checkIfCodeHasNoPipesAndHasNoTypeUrl(String roleFuncItem) {
1153 return !roleFuncItem.contains(FUNCTION_PIPE) && !roleFuncItem.contains("url");
1158 * It check whether function code has pipes and url string in it
1160 * @param roleFuncItem
1161 * @return true or false
1163 private boolean checkIfCodeHasPipesAndHasTypeUrl(String roleFuncItem) {
1164 return roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
1169 * It check whether function code has no pipes and has url string in it
1171 * @param roleFuncItem
1172 * @return true or false
1174 private boolean checkIfCodeHasNoPipesAndHasTypeUrl(String roleFuncItem) {
1175 return !roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
1179 * It returns user detail information which is deep copy of EPUser.class
1188 @SuppressWarnings("unchecked")
1189 private CentralV2User createEPUser(EPUser userInfo, Set<EPUserApp> userAppSet, EPApp app) throws Exception {
1190 final Map<String, Long> params = new HashMap<>();
1191 CentralV2User userAppList = new CentralV2User();
1192 CentralV2User user1 = null;
1193 final Map<String, Long> params1 = new HashMap<>();
1194 List<EPRole> globalRoleList = new ArrayList<>();
1196 if (app.getId() != PortalConstants.PORTAL_APP_ID) {
1197 params1.put("userId", userInfo.getId());
1198 params1.put("appId", app.getId());
1199 globalRoleList = dataAccessService.executeNamedQuery("userAppGlobalRoles", params1, null);
1201 userAppList.setUserApps(new TreeSet<CentralV2UserApp>());
1202 for (EPUserApp userApp : userAppSet) {
1203 if (userApp.getRole().getActive()) {
1204 EPApp epApp = userApp.getApp();
1205 String globalRole = userApp.getRole().getName().toLowerCase();
1206 if (((epApp.getId().equals(app.getId()))
1207 && (!userApp.getRole().getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)))
1208 || ((epApp.getId().equals(PortalConstants.PORTAL_APP_ID))
1209 && (globalRole.toLowerCase().startsWith("global_")))) {
1210 CentralV2UserApp cua = new CentralV2UserApp();
1211 cua.setUserId(null);
1212 CentralApp cenApp = new CentralApp(1L, epApp.getCreated(), epApp.getModified(),
1213 epApp.getCreatedId(), epApp.getModifiedId(), epApp.getRowNum(), epApp.getName(),
1214 epApp.getImageUrl(), epApp.getDescription(), epApp.getNotes(), epApp.getUrl(),
1215 epApp.getAlternateUrl(), epApp.getAppRestEndpoint(), epApp.getMlAppName(),
1216 epApp.getMlAppAdminId(), String.valueOf(epApp.getMotsId()), epApp.getAppPassword(),
1217 String.valueOf(epApp.getOpen()), String.valueOf(epApp.getEnabled()),
1218 epApp.getThumbnail(), epApp.getUsername(), epApp.getUebKey(), epApp.getUebSecret(),
1219 epApp.getUebTopicName());
1220 cenApp.setAppPassword(EPCommonSystemProperties.APP_DISPLAY_PASSWORD);
1223 if (globalRole.toLowerCase().startsWith("global_")
1224 && epApp.getId().equals(PortalConstants.PORTAL_APP_ID)
1225 && !epApp.getId().equals(app.getId())) {
1226 appId = app.getId();
1227 EPRole result = null;
1228 if (globalRoleList.size() > 0)
1229 result = globalRoleList.stream()
1230 .filter(x -> userApp.getRole().getId().equals(x.getId())).findAny()
1235 appId = userApp.getApp().getId();
1237 params.put("roleId", userApp.getRole().getId());
1238 params.put(APP_ID, appId);
1239 List<CentralV2RoleFunction> appRoleFunctionList = dataAccessService
1240 .executeNamedQuery("getAppRoleFunctionList", params, null);
1241 SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>();
1242 for (CentralV2RoleFunction roleFunc : appRoleFunctionList) {
1243 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1244 String type = getFunctionCodeType(roleFunc.getCode());
1245 String action = getFunctionCodeAction(roleFunc.getCode());
1246 CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(roleFunc.getId(),
1247 functionCode, roleFunc.getName(), null, type, action, null);
1248 roleFunctionSet.add(cenRoleFunc);
1250 Long userRoleId = null;
1251 if (globalRole.toLowerCase().startsWith("global_")
1252 || epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1253 userRoleId = userApp.getRole().getId();
1255 userRoleId = userApp.getRole().getAppRoleId();
1257 CentralV2Role cenRole = new CentralV2Role(userRoleId, userApp.getRole().getCreated(),
1258 userApp.getRole().getModified(), userApp.getRole().getCreatedId(),
1259 userApp.getRole().getModifiedId(), userApp.getRole().getRowNum(),
1260 userApp.getRole().getName(), userApp.getRole().getActive(),
1261 userApp.getRole().getPriority(), roleFunctionSet, null, null);
1262 cua.setRole(cenRole);
1263 userAppList.getUserApps().add(cua);
1267 user1 = new CentralV2User(null, userInfo.getCreated(), userInfo.getModified(), userInfo.getCreatedId(),
1268 userInfo.getModifiedId(), userInfo.getRowNum(), userInfo.getOrgId(), userInfo.getManagerId(),
1269 userInfo.getFirstName(), userInfo.getMiddleInitial(), userInfo.getLastName(), userInfo.getPhone(),
1270 userInfo.getFax(), userInfo.getCellular(), userInfo.getEmail(), userInfo.getAddressId(),
1271 userInfo.getAlertMethodCd(), userInfo.getHrid(), userInfo.getOrgUserId(), userInfo.getOrgCode(),
1272 userInfo.getAddress1(), userInfo.getAddress2(), userInfo.getCity(), userInfo.getState(),
1273 userInfo.getZipCode(), userInfo.getCountry(), userInfo.getOrgManagerUserId(),
1274 userInfo.getLocationClli(), userInfo.getBusinessCountryCode(), userInfo.getBusinessCountryName(),
1275 userInfo.getBusinessUnit(), userInfo.getBusinessUnitName(), userInfo.getDepartment(),
1276 userInfo.getDepartmentName(), userInfo.getCompanyCode(), userInfo.getCompany(),
1277 userInfo.getZipCodeSuffix(), userInfo.getJobTitle(), userInfo.getCommandChain(),
1278 userInfo.getSiloStatus(), userInfo.getCostCenter(), userInfo.getFinancialLocCode(),
1279 userInfo.getLoginId(), userInfo.getLoginPwd(), userInfo.getLastLoginDate(), userInfo.getActive(),
1280 userInfo.getInternal(), userInfo.getSelectedProfileId(), userInfo.getTimeZoneId(),
1281 userInfo.isOnline(), userInfo.getChatId(), userAppList.getUserApps(), null);
1282 } catch (Exception e) {
1283 logger.error(EELFLoggerDelegate.errorLogger, "createEPUser: createEPUser failed", e);
1290 public CentralV2Role getRoleInfo(Long roleId, String uebkey) throws Exception {
1291 final Map<String, Long> params = new HashMap<>();
1292 List<CentralV2Role> roleList = new ArrayList<>();
1293 CentralV2Role cenRole = new CentralV2Role();
1294 List<EPRole> roleInfo = null;
1295 List<EPApp> app = null;
1297 app = getApp(uebkey);
1298 if (app.isEmpty()) {
1299 throw new InactiveApplicationException("Application not found");
1301 if (app.get(0).getId() != PortalConstants.PORTAL_APP_ID) {
1302 List<EPRole> globalRoleList = new ArrayList<>();
1303 globalRoleList = getGlobalRolesOfPortal();
1304 if (globalRoleList.size() > 0) {
1305 EPRole result = globalRoleList.stream().filter(x -> roleId.equals(x.getId())).findAny()
1308 return getGlobalRoleForRequestedApp(app.get(0).getId(), roleId);
1311 if (app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
1312 roleInfo = getPortalAppRoleInfo(roleId);
1314 roleInfo = getPartnerAppRoleInfo(roleId, app.get(0));
1316 roleList = createCentralRoleObject(app, roleInfo, roleList, params);
1317 if (roleList.isEmpty()) {
1320 } catch (Exception e) {
1321 logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo: failed", e);
1324 return roleList.get(0);
1327 @SuppressWarnings("unchecked")
1328 private List<EPRole> getPartnerAppRoleInfo(Long roleId, EPApp app) {
1329 List<EPRole> roleInfo;
1330 final Map<String, Long> getPartnerAppRoleParams = new HashMap<>();
1331 getPartnerAppRoleParams.put("appRoleId", roleId);
1332 getPartnerAppRoleParams.put("appId", app.getId());
1333 roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams, null);
1334 if (roleInfo.isEmpty()) {
1335 getPartnerAppRoleParams.put("appRoleId", roleId);
1336 roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleById", getPartnerAppRoleParams, null);
1341 @SuppressWarnings("unchecked")
1342 private List<EPRole> getPortalAppRoleInfo(Long roleId) {
1343 List<EPRole> roleInfo;
1344 final Map<String, Long> getPortalAppRoleParams = new HashMap<>();
1345 getPortalAppRoleParams.put("roleId", roleId);
1346 roleInfo = dataAccessService.executeNamedQuery("getPortalAppRoleByRoleId", getPortalAppRoleParams, null);
1352 * It returns list of app roles along with role functions and which went
1360 * @throws DecoderException
1362 @SuppressWarnings("unchecked")
1364 public List<CentralV2Role> createCentralRoleObject(List<EPApp> app, List<EPRole> roleInfo,
1365 List<CentralV2Role> roleList, Map<String, Long> params) throws RoleFunctionException {
1366 for (EPRole role : roleInfo) {
1367 params.put("roleId", role.getId());
1368 params.put(APP_ID, app.get(0).getId());
1369 List<CentralV2RoleFunction> cenRoleFuncList = dataAccessService.executeNamedQuery("getAppRoleFunctionList",
1371 SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>();
1372 for (CentralV2RoleFunction roleFunc : cenRoleFuncList) {
1373 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1374 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
1375 String type = getFunctionCodeType(roleFunc.getCode());
1376 String action = getFunctionCodeAction(roleFunc.getCode());
1377 CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(role.getId(), functionCode,
1378 roleFunc.getName(), null, type, action, null);
1379 roleFunctionSet.add(cenRoleFunc);
1381 SortedSet<CentralV2Role> childRoles = new TreeSet<>();
1382 SortedSet<CentralV2Role> parentRoles = new TreeSet<>();
1383 CentralV2Role cenRole = null;
1384 if (role.getAppRoleId() == null) {
1385 cenRole = new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
1386 role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
1387 roleFunctionSet, childRoles, parentRoles);
1389 cenRole = new CentralV2Role(role.getAppRoleId(), role.getCreated(), role.getModified(),
1390 role.getCreatedId(), role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(),
1391 role.getPriority(), roleFunctionSet, childRoles, parentRoles);
1393 roleList.add(cenRole);
1398 @SuppressWarnings("unchecked")
1400 public CentralV2RoleFunction getRoleFunction(String functionCode, String uebkey) throws Exception {
1401 String code = EcompPortalUtils.getFunctionCode(functionCode);
1402 String encodedCode = encodeFunctionCode(code);
1403 CentralV2RoleFunction roleFunc = null;
1404 EPApp app = getApp(uebkey).get(0);
1405 List<CentralV2RoleFunction> getRoleFuncList = null;
1406 final Map<String, String> params = new HashMap<>();
1408 params.put(FUNCTION_CODE_PARAMS, functionCode);
1409 params.put(APP_ID, String.valueOf(app.getId()));
1410 getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
1411 if (getRoleFuncList.isEmpty()) {
1412 params.put(FUNCTION_CODE_PARAMS, encodedCode);
1413 getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
1414 if (getRoleFuncList.isEmpty()) {
1418 if (getRoleFuncList.size() > 1) {
1419 CentralV2RoleFunction cenV2RoleFunction = appFunctionListFilter(encodedCode, getRoleFuncList);
1420 if (cenV2RoleFunction == null)
1422 roleFunc = checkIfPipesExitsInFunctionCode(cenV2RoleFunction);
1424 // Check even if single record have pipes
1425 if (!getRoleFuncList.isEmpty() && getRoleFuncList.get(0).getCode().contains(FUNCTION_PIPE)) {
1426 roleFunc = checkIfPipesExitsInFunctionCode(getRoleFuncList.get(0));
1428 roleFunc = getRoleFuncList.get(0);
1431 } catch (Exception e) {
1432 logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction: failed", e);
1438 private CentralV2RoleFunction checkIfPipesExitsInFunctionCode(CentralV2RoleFunction getRoleFuncList) {
1439 CentralV2RoleFunction roleFunc;
1440 String functionCodeFormat = getRoleFuncList.getCode();
1441 if (functionCodeFormat.contains(FUNCTION_PIPE)) {
1442 String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(functionCodeFormat);
1443 String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(functionCodeFormat);
1444 String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(functionCodeFormat);
1445 roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), newfunctionCodeFormat,
1446 getRoleFuncList.getName(), getRoleFuncList.getAppId(), newfunctionTypeFormat,
1447 newfunctionActionFormat, getRoleFuncList.getEditUrl());
1449 roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), functionCodeFormat, getRoleFuncList.getName(),
1450 getRoleFuncList.getAppId(), getRoleFuncList.getEditUrl());
1456 public boolean saveCentralRoleFunction(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
1458 boolean saveOrUpdateFunction = false;
1460 domainCentralRoleFunction.setCode(encodeFunctionCode(domainCentralRoleFunction.getCode()));
1461 final Map<String, String> functionParams = new HashMap<>();
1462 functionParams.put("appId", String.valueOf(app.getId()));
1463 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1464 addRoleFunctionInExternalSystem(domainCentralRoleFunction, app);
1466 if (domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null) {
1467 domainCentralRoleFunction.setCode(domainCentralRoleFunction.getType() + FUNCTION_PIPE
1468 + domainCentralRoleFunction.getCode() + FUNCTION_PIPE + domainCentralRoleFunction.getAction());
1470 domainCentralRoleFunction.setAppId(app.getId());
1471 dataAccessService.saveDomainObject(domainCentralRoleFunction, null);
1472 saveOrUpdateFunction = true;
1473 } catch (Exception e) {
1474 logger.error(EELFLoggerDelegate.errorLogger, "saveCentralRoleFunction: failed", e);
1477 return saveOrUpdateFunction;
1481 * It creates application permission in external auth system
1483 * @param domainCentralRoleFunction
1487 private void addRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
1489 ObjectMapper mapper = new ObjectMapper();
1490 ExternalAccessPerms extPerms = new ExternalAccessPerms();
1491 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1493 String instance = "";
1495 if ((domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null)
1496 || domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)) {
1497 type = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)
1498 ? EcompPortalUtils.getFunctionType(domainCentralRoleFunction.getCode())
1499 : domainCentralRoleFunction.getType();
1500 instance = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)
1501 ? EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode())
1502 : domainCentralRoleFunction.getCode();
1503 action = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)
1504 ? EcompPortalUtils.getFunctionAction(domainCentralRoleFunction.getCode())
1505 : domainCentralRoleFunction.getAction();
1507 type = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url";
1508 instance = domainCentralRoleFunction.getCode();
1511 // get Permissions from External Auth System
1512 JSONArray extPermsList = getExtAuthPermissions(app);
1513 List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPermsList);
1514 String requestedPerm = type + FUNCTION_PIPE + instance + FUNCTION_PIPE + action;
1515 boolean checkIfFunctionsExits = permsDetailList.stream()
1516 .anyMatch(permsDetail -> permsDetail.getInstance().equals(requestedPerm));
1517 if (!checkIfFunctionsExits) {
1519 extPerms.setAction(action);
1520 extPerms.setInstance(instance);
1521 extPerms.setType(app.getNameSpace() + "." + type);
1522 extPerms.setDescription(domainCentralRoleFunction.getName());
1523 String addFunction = mapper.writeValueAsString(extPerms);
1524 HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
1525 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for POST: {}",
1526 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
1527 ResponseEntity<String> addPermResponse = template.exchange(
1528 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
1529 HttpMethod.POST, entity, String.class);
1530 logger.debug(EELFLoggerDelegate.debugLogger,
1531 "addRoleFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ",
1532 addPermResponse.getStatusCode().value(), addFunction);
1533 } catch (HttpClientErrorException e) {
1534 logger.error(EELFLoggerDelegate.errorLogger,
1535 "HttpClientErrorException - Failed to add function in external central auth system", e);
1536 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1538 } catch (Exception e) {
1539 logger.error(EELFLoggerDelegate.errorLogger,
1540 "addRoleFunctionInExternalSystem: Failed to add fucntion in external central auth system", e);
1545 extPerms.setAction(action);
1546 extPerms.setInstance(instance);
1547 extPerms.setType(app.getNameSpace() + "." + type);
1548 extPerms.setDescription(domainCentralRoleFunction.getName());
1549 String updateRoleFunction = mapper.writeValueAsString(extPerms);
1550 HttpEntity<String> entity = new HttpEntity<>(updateRoleFunction, headers);
1551 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for PUT: {}",
1552 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRoleFunction);
1553 ResponseEntity<String> updatePermResponse = template.exchange(
1554 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
1555 HttpMethod.PUT, entity, String.class);
1556 logger.debug(EELFLoggerDelegate.debugLogger,
1557 "addRoleFunctionInExternalSystem: Finished updating permission in External Auth system {} and response: {} ",
1558 updateRoleFunction, updatePermResponse.getStatusCode().value());
1559 } catch (HttpClientErrorException e) {
1560 logger.error(EELFLoggerDelegate.errorLogger,
1561 "HttpClientErrorException - Failed to add function in external central auth system", e);
1562 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1564 } catch (Exception e) {
1565 logger.error(EELFLoggerDelegate.errorLogger,
1566 "addRoleFunctionInExternalSystem: Failed to update function in external central auth system",
1573 @SuppressWarnings("unchecked")
1575 @Transactional(rollbackFor = Exception.class)
1576 public boolean deleteCentralRoleFunction(String code, EPApp app) {
1577 boolean deleteFunctionResponse = false;
1579 final Map<String, String> params = new HashMap<>();
1580 params.put(FUNCTION_CODE_PARAMS, code);
1581 params.put(APP_ID, String.valueOf(app.getId()));
1582 List<CentralV2RoleFunction> domainCentralRoleFunction = dataAccessService
1583 .executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
1584 CentralV2RoleFunction appFunctionCode = appFunctionListFilter(code, domainCentralRoleFunction);
1585 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1586 deleteRoleFunctionInExternalSystem(appFunctionCode, app);
1587 // Delete role function dependency records
1588 deleteAppRoleFunctions(appFunctionCode.getCode(), app);
1590 dataAccessService.deleteDomainObject(appFunctionCode, null);
1591 deleteFunctionResponse = true;
1592 } catch (Exception e) {
1593 logger.error(EELFLoggerDelegate.errorLogger, "deleteCentralRoleFunction: failed", e);
1595 return deleteFunctionResponse;
1599 * It deletes app function record in portal
1604 private void deleteAppRoleFunctions(String code, EPApp app) {
1605 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
1606 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + code + "'", null);
1611 * It deletes permission in the external auth system
1613 * @param domainCentralRoleFunction
1617 private void deleteRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
1620 ObjectMapper mapper = new ObjectMapper();
1621 ExternalAccessPerms extPerms = new ExternalAccessPerms();
1622 String instanceValue = EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode());
1623 String checkType = getFunctionCodeType(domainCentralRoleFunction.getCode());
1624 String actionValue = getFunctionCodeAction(domainCentralRoleFunction.getCode());
1625 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1626 extPerms.setAction(actionValue);
1627 extPerms.setInstance(instanceValue);
1628 extPerms.setType(app.getNameSpace() + "." + checkType);
1629 extPerms.setDescription(domainCentralRoleFunction.getName());
1630 String deleteRoleFunction = mapper.writeValueAsString(extPerms);
1631 HttpEntity<String> entity = new HttpEntity<>(deleteRoleFunction, headers);
1632 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleFunctionInExternalSystem: {} for DELETE: {} ",
1633 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, deleteRoleFunction);
1634 ResponseEntity<String> delPermResponse = template
1635 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1636 + "perm?force=true", HttpMethod.DELETE, entity, String.class);
1637 logger.debug(EELFLoggerDelegate.debugLogger,
1638 "deleteRoleFunctionInExternalSystem: Finished deleting permission in External Auth system {} and status code: {} ",
1639 deleteRoleFunction, delPermResponse.getStatusCode().value());
1640 } catch (HttpClientErrorException e) {
1641 logger.error(EELFLoggerDelegate.errorLogger,
1642 "HttpClientErrorException - Failed to delete functions in External System", e);
1643 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1644 } catch (Exception e) {
1645 if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
1646 logger.debug(EELFLoggerDelegate.debugLogger,
1647 " deleteRoleFunctionInExternalSystem: It seems like function is already deleted in external central auth system but exists in local DB",
1650 logger.error(EELFLoggerDelegate.errorLogger,
1651 "deleteRoleFunctionInExternalSystem: Failed to delete functions in External System", e);
1657 public ExternalRequestFieldsValidator saveRoleForApplication(Role saveRole, String uebkey) throws Exception {
1658 boolean response = false;
1659 String message = "";
1661 EPApp app = getApp(uebkey).get(0);
1662 addRoleInEcompDB(saveRole, app);
1664 } catch (Exception e) {
1665 message = e.getMessage();
1666 logger.error(EELFLoggerDelegate.errorLogger, "saveRoleForApplication failed", e);
1668 return new ExternalRequestFieldsValidator(response, message);
1671 @SuppressWarnings("unchecked")
1673 public boolean deleteRoleForApplication(String deleteRole, String uebkey) throws Exception {
1674 Session localSession = sessionFactory.openSession();
1675 Transaction transaction = null;
1676 boolean result = false;
1678 List<EPRole> epRoleList = null;
1679 EPApp app = getApp(uebkey).get(0);
1680 final Map<String, String> deleteRoleParams = new HashMap<>();
1681 deleteRoleParams.put(APP_ROLE_NAME_PARAM, deleteRole);
1682 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1683 epRoleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, deleteRoleParams, null);
1685 deleteRoleParams.put(APP_ID, String.valueOf(app.getId()));
1686 epRoleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
1687 deleteRoleParams, null);
1689 if (!epRoleList.isEmpty()) {
1690 transaction = localSession.beginTransaction();
1691 // Delete app role functions before deleting role
1692 deleteRoleFunction(app, epRoleList);
1693 if (app.getId() == 1) {
1694 // Delete fn_user_ role
1695 dataAccessService.deleteDomainObjects(EPUserApp.class,
1696 APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
1697 boolean isPortalRequest = false;
1698 deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest);
1700 deleteRoleInExternalAuthSystem(epRoleList, app);
1701 transaction.commit();
1702 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: committed the transaction");
1703 dataAccessService.deleteDomainObject(epRoleList.get(0), null);
1706 } catch (Exception e) {
1707 logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleForApplication: failed", e);
1710 localSession.close();
1717 * It deletes role for application in external auth system
1719 * @param epRoleList contains role information
1720 * @param app contains application information
1723 private void deleteRoleInExternalAuthSystem(List<EPRole> epRoleList, EPApp app) throws Exception {
1724 ResponseEntity<String> deleteResponse;
1725 ResponseEntity<String> res = getNameSpaceIfExists(app);
1726 if (res.getStatusCode() == HttpStatus.OK) {
1727 // Delete Role in External System
1728 String deleteRoleKey = "{\"name\":\"" + app.getNameSpace() + "." + epRoleList.get(0).getName()
1729 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_") + "\"}";
1730 deleteResponse = deleteRoleInExternalSystem(deleteRoleKey);
1731 if (deleteResponse.getStatusCode().value() != 200 && deleteResponse.getStatusCode().value() != 404) {
1732 EPLogUtil.logExternalAuthAccessAlarm(logger, deleteResponse.getStatusCode());
1733 logger.error(EELFLoggerDelegate.errorLogger,
1734 "deleteRoleForApplication: Failed to delete role in external auth system! due to {} ",
1735 deleteResponse.getBody());
1737 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: about to commit the transaction");
1743 * It deletes application user role in external auth system
1750 private void deleteUserRoleInExternalSystem(EPRole role, EPApp app, String LoginId) throws Exception {
1751 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1752 HttpEntity<String> entity = new HttpEntity<>(headers);
1753 getNameSpaceIfExists(app);
1754 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} ",
1755 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1756 ResponseEntity<String> getResponse = template.exchange(
1757 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
1759 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
1760 + "/" + app.getNameSpace() + "."
1762 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
1763 HttpMethod.GET, entity, String.class);
1764 logger.debug(EELFLoggerDelegate.debugLogger,
1765 "deleteUserRoleInExternalSystem: Finished GET user roles from External Auth system and response: {} ",
1766 getResponse.getBody());
1767 if (getResponse.getStatusCode().value() != 200) {
1768 throw new ExternalAuthSystemException(getResponse.getBody());
1770 String res = getResponse.getBody();
1771 if (!res.equals(IS_EMPTY_JSON_STRING)) {
1772 HttpEntity<String> userRoleentity = new HttpEntity<>(headers);
1773 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} ",
1774 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1775 ResponseEntity<String> deleteResponse = template.exchange(
1776 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
1778 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
1779 + "/" + app.getNameSpace() + "."
1780 + role.getName().replaceAll(
1781 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
1782 HttpMethod.DELETE, userRoleentity, String.class);
1783 if (deleteResponse.getStatusCode().value() != 200) {
1784 throw new ExternalAuthSystemException("Failed to delete user role");
1786 logger.debug(EELFLoggerDelegate.debugLogger,
1787 "deleteUserRoleInExternalSystem: Finished deleting user role in External Auth system and status code: {} ",
1788 deleteResponse.getStatusCode().value());
1792 @SuppressWarnings("unchecked")
1794 public List<CentralV2Role> getActiveRoles(String uebkey) throws Exception {
1795 List<CentralV2Role> roleList = new ArrayList<>();
1797 List<EPApp> app = getApp(uebkey);
1798 final Map<String, Long> params = new HashMap<>();
1801 if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
1802 appId = app.get(0).getId();
1804 List<Criterion> restrictionsList = new ArrayList<Criterion>();
1805 Criterion active_ynCrt = Restrictions.eq("active", Boolean.TRUE);
1808 appIdCrt = Restrictions.isNull("appId");
1810 appIdCrt = Restrictions.eq("appId", appId);
1811 Criterion andCrit = Restrictions.and(active_ynCrt, appIdCrt);
1812 restrictionsList.add(andCrit);
1813 List<EPRole> epRole = (List<EPRole>) dataAccessService.getList(EPRole.class, null, restrictionsList, null);
1814 roleList = createCentralRoleObject(app, epRole, roleList, params);
1815 List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
1816 if (globalRoleList.size() > 0)
1817 roleList.addAll(globalRoleList);
1818 } catch (Exception e) {
1819 logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles: failed", e);
1826 @Transactional(rollbackFor = Exception.class)
1827 public ExternalRequestFieldsValidator deleteDependencyRoleRecord(Long roleId, String uebkey, String LoginId)
1829 Session localSession = sessionFactory.openSession();
1830 String message = "";
1831 Transaction transaction = null;
1832 boolean response = false;
1835 transaction = localSession.beginTransaction();
1836 List<EPRole> epRoleList = null;
1837 app = getApp(uebkey).get(0);
1838 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1839 epRoleList = getPortalAppRoleInfo(roleId);
1841 epRoleList = getPartnerAppRoleInfo(roleId, app);
1843 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1844 // Delete User Role in External System before deleting role
1845 deleteUserRoleInExternalSystem(epRoleList.get(0), app, LoginId);
1847 // Delete user app roles
1848 dataAccessService.deleteDomainObjects(EPUserApp.class,
1849 APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
1850 boolean isPortalRequest = false;
1851 deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest);
1852 transaction.commit();
1853 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1854 // Final call to delete role once all dependencies has been
1856 deleteRoleInExternalAuthSystem(epRoleList, app);
1858 dataAccessService.deleteDomainObjects(EPRole.class, " role_id = " + epRoleList.get(0).getId(), null);
1859 logger.debug(EELFLoggerDelegate.debugLogger, "deleteDependencyRoleRecord: committed the transaction");
1861 } catch (HttpClientErrorException e) {
1862 logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord: HttpClientErrorException", e);
1863 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1864 message = e.getMessage();
1865 } catch (Exception e) {
1866 logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord failed", e);
1867 EcompPortalUtils.rollbackTransaction(transaction,
1868 "deleteDependencyRoleRecord rollback, exception = " + e.toString());
1869 message = e.getMessage();
1871 localSession.close();
1873 return new ExternalRequestFieldsValidator(response, message);
1877 @SuppressWarnings("unchecked")
1879 public void syncRoleFunctionFromExternalAccessSystem(EPApp app) {
1881 // get Permissions from External Auth System
1882 JSONArray extPerms = getExtAuthPermissions(app);
1883 List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);
1884 // get functions in DB
1885 final Map<String, Long> params = new HashMap<>();
1886 final Map<String, CentralV2RoleFunction> roleFuncMap = new HashMap<>();
1887 params.put(APP_ID, app.getId());
1888 List<CentralV2RoleFunction> appFunctions = dataAccessService.executeNamedQuery("getAllRoleFunctions",
1890 if (!appFunctions.isEmpty()) {
1891 for (CentralV2RoleFunction roleFunc : appFunctions) {
1892 roleFuncMap.put(roleFunc.getCode(), roleFunc);
1895 // get Roles for portal in DB
1896 List<EPRole> portalRoleList = getGlobalRolesOfPortal();
1897 final Map<String, EPRole> existingPortalRolesMap = new HashMap<>();
1898 for (EPRole epRole : portalRoleList) {
1899 existingPortalRolesMap.put(epRole.getName().replaceAll(
1900 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), epRole);
1903 final Map<String, EPRole> currentRolesInDB = getAppRoleNamesWithUnderscoreMap(app);
1904 // store External Permissions with Pipe and without Pipe (just
1906 final Map<String, ExternalAccessPermsDetail> extAccessPermsContainsPipeMap = new HashMap<>();
1907 final Map<String, ExternalAccessPermsDetail> extAccessPermsMap = new HashMap<>();
1908 for (ExternalAccessPermsDetail permsDetailInfoWithPipe : permsDetailList) {
1909 extAccessPermsContainsPipeMap.put(permsDetailInfoWithPipe.getInstance(), permsDetailInfoWithPipe);
1910 String finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetailInfoWithPipe.getInstance());
1911 extAccessPermsMap.put(finalFunctionCodeVal, permsDetailInfoWithPipe);
1913 // Add if new functions and app role functions were added in
1914 // external auth system
1915 for (ExternalAccessPermsDetail permsDetail : permsDetailList) {
1916 String code = permsDetail.getInstance();
1917 CentralV2RoleFunction getFunctionCodeKey = roleFuncMap.get(permsDetail.getInstance());
1918 List<CentralV2RoleFunction> roleFunctionList = addGetLocalFunction(app, roleFuncMap, permsDetail, code,
1919 getFunctionCodeKey);
1920 List<String> roles = permsDetail.getRoles();
1921 if (roles != null) {
1922 // Check if function has any roles and which does not exist
1923 // in External Auth System. If exists delete in local
1924 addRemoveIfFunctionsRolesIsSyncWithExternalAuth(app, currentRolesInDB, roleFunctionList, roles,
1925 existingPortalRolesMap);
1928 // Check if function does exits in External Auth System but exits in
1929 // local then delete function and its dependencies
1930 for (CentralV2RoleFunction roleFunc : appFunctions) {
1932 ExternalAccessPermsDetail getFunctionCodeContainsPipeKey = extAccessPermsContainsPipeMap
1933 .get(roleFunc.getCode());
1934 if (null == getFunctionCodeContainsPipeKey) {
1935 ExternalAccessPermsDetail getFunctionCodeKey = extAccessPermsMap.get(roleFunc.getCode());
1936 if (null == getFunctionCodeKey) {
1937 deleteAppRoleFuncDoesNotExitsInExtSystem(app, roleFunc);
1940 } catch (Exception e) {
1941 logger.error(EELFLoggerDelegate.errorLogger,
1942 "syncRoleFunctionFromExternalAccessSystem: Failed to delete function", e);
1945 logger.debug(EELFLoggerDelegate.debugLogger,
1946 "syncRoleFunctionFromExternalAccessSystem: Finished syncRoleFunctionFromExternalAccessSystem");
1947 } catch (Exception e) {
1948 logger.error(EELFLoggerDelegate.errorLogger,
1949 "syncRoleFunctionFromExternalAccessSystem: Failed syncRoleFunctionFromExternalAccessSystem", e);
1953 @SuppressWarnings("unchecked")
1954 private void addRemoveIfFunctionsRolesIsSyncWithExternalAuth(EPApp app, final Map<String, EPRole> currentRolesInDB,
1955 List<CentralV2RoleFunction> roleFunctionList, List<String> roles,
1956 Map<String, EPRole> existingPortalRolesMap) throws Exception {
1957 if (!roleFunctionList.isEmpty()) {
1958 final Map<String, String> appRoleFuncParams = new HashMap<>();
1959 final Map<String, LocalRole> currentAppRoleFunctionsMap = new HashMap<>();
1960 final Map<String, String> currentRolesInExtSystem = new HashMap<>();
1961 appRoleFuncParams.put("functionCd", roleFunctionList.get(0).getCode());
1962 appRoleFuncParams.put("appId", String.valueOf(app.getId()));
1963 List<LocalRole> localRoleList = dataAccessService.executeNamedQuery("getCurrentAppRoleFunctions",
1964 appRoleFuncParams, null);
1965 for (LocalRole localRole : localRoleList) {
1966 currentAppRoleFunctionsMap.put(localRole.getRolename().replaceAll(
1967 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), localRole);
1969 for (String addRole : roles) {
1970 currentRolesInExtSystem.put(addRole.substring(addRole.indexOf(FUNCTION_PIPE) + 1), addRole);
1972 for (String extAuthrole : roles) {
1973 String roleNameSpace = extAuthrole.substring(0, extAuthrole.indexOf(FUNCTION_PIPE));
1974 boolean isNameSpaceMatching = EcompPortalUtils.checkNameSpaceMatching(roleNameSpace,
1975 app.getNameSpace());
1976 if (isNameSpaceMatching) {
1977 if (!currentAppRoleFunctionsMap
1978 .containsKey(extAuthrole.substring(app.getNameSpace().length() + 1))) {
1979 EPRole localAddFuntionRole = currentRolesInDB
1980 .get(extAuthrole.substring(app.getNameSpace().length() + 1));
1981 if (localAddFuntionRole == null) {
1982 checkAndAddRoleInDB(app, currentRolesInDB, roleFunctionList, extAuthrole);
1984 EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
1985 addAppRoleFunc.setAppId(app.getId());
1986 addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
1987 addAppRoleFunc.setRoleId(localAddFuntionRole.getId());
1988 dataAccessService.saveDomainObject(addAppRoleFunc, null);
1991 // This block is to save global role function if exists
1993 String extAuthAppRoleName = extAuthrole.substring(extAuthrole.indexOf(FUNCTION_PIPE) + 1);
1994 boolean checkIfGlobalRoleExists = existingPortalRolesMap.containsKey(extAuthAppRoleName);
1995 if (checkIfGlobalRoleExists) {
1996 final Map<String, Long> params = new HashMap<>();
1997 EPRole role = existingPortalRolesMap.get(extAuthAppRoleName);
1998 EPAppRoleFunction addGlobalRoleFunctions = new EPAppRoleFunction();
1999 params.put("appId", app.getId());
2000 params.put("roleId", role.getId());
2001 List<EPAppRoleFunction> currentGlobalRoleFunctionsList = dataAccessService
2002 .executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", params, null);
2003 boolean checkIfRoleFunctionExists = currentGlobalRoleFunctionsList.stream()
2004 .anyMatch(currentGlobalRoleFunction -> currentGlobalRoleFunction.getCode()
2005 .equals(roleFunctionList.get(0).getCode()));
2006 if (role != null && !checkIfRoleFunctionExists) {
2007 addGlobalRoleFunctions.setAppId(app.getId());
2008 addGlobalRoleFunctions.setRoleId(role.getId());
2009 if (!app.getId().equals(role.getAppRoleId())) {
2010 addGlobalRoleFunctions.setRoleAppId((PortalConstants.PORTAL_APP_ID).toString());
2012 addGlobalRoleFunctions.setRoleAppId(null);
2014 addGlobalRoleFunctions.setCode(roleFunctionList.get(0).getCode());
2015 dataAccessService.saveDomainObject(addGlobalRoleFunctions, null);
2020 for (LocalRole localRoleDelete : localRoleList) {
2021 if (!currentRolesInExtSystem.containsKey(localRoleDelete.getRolename()
2022 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
2023 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
2024 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunctionList.get(0).getCode()
2025 + "'" + " and role_id = " + localRoleDelete.getRoleId().longValue(),
2032 private void deleteAppRoleFuncDoesNotExitsInExtSystem(EPApp app, CentralV2RoleFunction roleFunc) {
2033 logger.debug(EELFLoggerDelegate.debugLogger,
2034 "syncRoleFunctionFromExternalAccessSystem: Deleting app role function {}", roleFunc.getCode());
2035 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
2036 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() + "'", null);
2037 logger.debug(EELFLoggerDelegate.debugLogger,
2038 "syncRoleFunctionFromExternalAccessSystem: Deleted app role function {}", roleFunc.getCode());
2039 logger.debug(EELFLoggerDelegate.debugLogger,
2040 "syncRoleFunctionFromExternalAccessSystem: Deleting app function {}", roleFunc.getCode());
2041 dataAccessService.deleteDomainObjects(CentralV2RoleFunction.class,
2042 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() + "'", null);
2043 logger.debug(EELFLoggerDelegate.debugLogger,
2044 "syncRoleFunctionFromExternalAccessSystem: Deleted app function {}", roleFunc.getCode());
2047 private void checkAndAddRoleInDB(EPApp app, final Map<String, EPRole> currentRolesInDB,
2048 List<CentralV2RoleFunction> roleFunctionList, String roleList) throws Exception {
2049 if (!currentRolesInDB.containsKey(roleList.substring(app.getNameSpace().length() + 1))) {
2050 Role role = addRoleInDBIfDoesNotExists(app, roleList.substring(app.getNameSpace().length() + 1));
2051 addRoleDescriptionInExtSystem(role, app);
2052 if (!roleFunctionList.isEmpty()) {
2054 if (!roleFunctionList.isEmpty()) {
2055 EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
2056 addAppRoleFunc.setAppId(app.getId());
2057 addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
2058 addAppRoleFunc.setRoleId(role.getId());
2059 dataAccessService.saveDomainObject(addAppRoleFunc, null);
2061 } catch (Exception e) {
2062 logger.error(EELFLoggerDelegate.errorLogger,
2063 "syncRoleFunctionFromExternalAccessSystem: Failed to save app role function ", e);
2069 @SuppressWarnings("unchecked")
2070 private List<CentralV2RoleFunction> addGetLocalFunction(EPApp app,
2071 final Map<String, CentralV2RoleFunction> roleFuncMap, ExternalAccessPermsDetail permsDetail, String code,
2072 CentralV2RoleFunction getFunctionCodeKey) {
2073 String finalFunctionCodeVal = addToLocalIfFunctionNotExists(app, roleFuncMap, permsDetail, code,
2074 getFunctionCodeKey);
2075 final Map<String, String> appSyncFuncsParams = new HashMap<>();
2076 appSyncFuncsParams.put("appId", String.valueOf(app.getId()));
2077 appSyncFuncsParams.put("functionCd", finalFunctionCodeVal);
2078 List<CentralV2RoleFunction> roleFunctionList = null;
2079 roleFunctionList = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams,
2081 if (roleFunctionList.isEmpty()) {
2082 appSyncFuncsParams.put("functionCd", code);
2083 roleFunctionList = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams,
2086 return roleFunctionList;
2089 private String addToLocalIfFunctionNotExists(EPApp app, final Map<String, CentralV2RoleFunction> roleFuncMap,
2090 ExternalAccessPermsDetail permsDetail, String code, CentralV2RoleFunction getFunctionCodeKey) {
2091 String finalFunctionCodeVal = "";
2092 if (null == getFunctionCodeKey) {
2093 finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetail.getInstance());
2094 CentralV2RoleFunction checkIfCodeStillExits = roleFuncMap.get(finalFunctionCodeVal);
2095 // If function does not exist in local then add!
2096 if (null == checkIfCodeStillExits) {
2097 logger.debug(EELFLoggerDelegate.debugLogger,
2098 "syncRoleFunctionFromExternalAccessSystem: Adding function: {} ", code);
2099 addFunctionInEcompDB(app, permsDetail, code);
2100 logger.debug(EELFLoggerDelegate.debugLogger,
2101 "syncRoleFunctionFromExternalAccessSystem: Finished adding function: {} ", code);
2104 return finalFunctionCodeVal;
2107 @SuppressWarnings("unchecked")
2109 public Map<String, EPRole> getAppRoleNamesWithUnderscoreMap(EPApp app) {
2110 final Map<String, EPRole> currentRolesInDB = new HashMap<>();
2111 List<EPRole> getCurrentRoleList = null;
2112 final Map<String, Long> appParams = new HashMap<>();
2113 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2114 getCurrentRoleList = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
2116 appParams.put("appId", app.getId());
2117 getCurrentRoleList = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
2119 for (EPRole role : getCurrentRoleList) {
2120 currentRolesInDB.put(role.getName()
2121 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), role);
2123 return currentRolesInDB;
2126 @SuppressWarnings("unchecked")
2127 private Map<String, EPRole> getAppRoleNamesMap(EPApp app) {
2128 final Map<String, EPRole> currentRolesInDB = new HashMap<>();
2129 List<EPRole> getCurrentRoleList = null;
2130 final Map<String, Long> appParams = new HashMap<>();
2131 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2132 getCurrentRoleList = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
2134 appParams.put("appId", app.getId());
2135 getCurrentRoleList = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
2137 for (EPRole role : getCurrentRoleList) {
2138 currentRolesInDB.put(role.getName(), role);
2140 return currentRolesInDB;
2143 private List<ExternalAccessPermsDetail> getExtAuthPerrmissonList(EPApp app, JSONArray extPerms) throws IOException {
2144 ExternalAccessPermsDetail permDetails = null;
2145 List<ExternalAccessPermsDetail> permsDetailList = new ArrayList<>();
2146 for (int i = 0; i < extPerms.length(); i++) {
2147 String description = null;
2148 if (extPerms.getJSONObject(i).has("description")) {
2149 description = extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
2151 description = extPerms.getJSONObject(i).getString("type") + "|"
2152 + extPerms.getJSONObject(i).getString("instance") + "|"
2153 + extPerms.getJSONObject(i).getString("action");
2155 if (extPerms.getJSONObject(i).has("roles")) {
2156 ObjectMapper rolesListMapper = new ObjectMapper();
2157 JSONArray resRoles = extPerms.getJSONObject(i).getJSONArray("roles");
2158 List<String> list = rolesListMapper.readValue(resRoles.toString(),
2159 TypeFactory.defaultInstance().constructCollectionType(List.class, String.class));
2160 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
2161 extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
2162 + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
2163 + extPerms.getJSONObject(i).getString("action"),
2164 extPerms.getJSONObject(i).getString("action"), list, description);
2165 permsDetailList.add(permDetails);
2167 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
2168 extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
2169 + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
2170 + extPerms.getJSONObject(i).getString("action"),
2171 extPerms.getJSONObject(i).getString("action"), description);
2172 permsDetailList.add(permDetails);
2175 return permsDetailList;
2178 private JSONArray getExtAuthPermissions(EPApp app) throws Exception {
2179 ResponseEntity<String> response = null;
2180 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2181 HttpEntity<String> entity = new HttpEntity<>(headers);
2182 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: {} ",
2183 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2184 response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
2185 + "perms/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
2186 String res = response.getBody();
2187 logger.debug(EELFLoggerDelegate.debugLogger,
2188 "syncRoleFunctionFromExternalAccessSystem: Finished GET permissions from External Auth system and response: {} ",
2189 response.getBody());
2190 JSONObject jsonObj = new JSONObject(res);
2191 JSONArray extPerms = jsonObj.getJSONArray("perm");
2192 for (int i = 0; i < extPerms.length(); i++) {
2193 if (extPerms.getJSONObject(i).getString("type").equals(app.getNameSpace() + ".access")) {
2203 * Add function into local DB
2206 * @param permsDetail
2209 private void addFunctionInEcompDB(EPApp app, ExternalAccessPermsDetail permsDetail, String code) {
2211 CentralV2RoleFunction addFunction = new CentralV2RoleFunction();
2212 addFunction.setAppId(app.getId());
2213 addFunction.setCode(code);
2214 addFunction.setName(permsDetail.getDescription());
2215 dataAccessService.saveDomainObject(addFunction, null);
2216 } catch (Exception e) {
2217 logger.error(EELFLoggerDelegate.errorLogger, "addFunctionInEcompDB: Failed to add function", e);
2223 * It updates description of a role in external auth system
2229 private boolean addRoleDescriptionInExtSystem(Role role, EPApp app) throws Exception {
2230 boolean status = false;
2232 String addRoleNew = updateExistingRoleInExternalSystem(role, app);
2233 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2234 HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
2236 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
2237 HttpMethod.PUT, entity, String.class);
2239 } catch (HttpClientErrorException e) {
2240 logger.error(EELFLoggerDelegate.errorLogger,
2241 "HttpClientErrorException - Failed to addRoleDescriptionInExtSystem", e);
2242 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2243 } catch (Exception e) {
2244 logger.error(EELFLoggerDelegate.errorLogger, "addRoleDescriptionInExtSystem: Failed", e);
2251 * While sync functions form external auth system if new role found we
2252 * should add in local and return Role.class object
2258 @SuppressWarnings("unchecked")
2259 private Role addRoleInDBIfDoesNotExists(EPApp app, String role) {
2260 Role setNewRole = new Role();
2262 // functions can have new role created in External Auth System
2265 boolean isCreated = checkIfRoleExitsElseCreateInSyncFunctions(role, app);
2266 final Map<String, String> getRoleByNameParams = new HashMap<>();
2267 List<EPRole> getRoleCreated = null;
2268 getRoleByNameParams.put(APP_ROLE_NAME_PARAM, role);
2269 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2270 getRoleByNameParams.put("appId", String.valueOf(app.getId()));
2271 List<EPRole> roleCreated = dataAccessService
2272 .executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, getRoleByNameParams, null);
2274 EPRole epUpdateRole = roleCreated.get(0);
2275 epUpdateRole.setAppRoleId(epUpdateRole.getId());
2276 dataAccessService.saveDomainObject(epUpdateRole, null);
2277 getRoleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
2278 getRoleByNameParams, null);
2280 getRoleCreated = roleCreated;
2283 getRoleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, getRoleByNameParams,
2286 if (getRoleCreated != null && !getRoleCreated.isEmpty()) {
2287 EPRole roleObject = getRoleCreated.get(0);
2288 setNewRole.setId(roleObject.getId());
2289 setNewRole.setName(roleObject.getName());
2290 setNewRole.setActive(roleObject.getActive());
2291 setNewRole.setPriority(roleObject.getPriority());
2293 } catch (Exception e) {
2294 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInDBIfDoesNotExists: Failed", e);
2299 @SuppressWarnings("unchecked")
2300 private boolean checkIfRoleExitsElseCreateInSyncFunctions(String role, EPApp app) {
2301 boolean isCreated = false;
2302 final Map<String, String> roleParams = new HashMap<>();
2303 roleParams.put(APP_ROLE_NAME_PARAM, role);
2304 List<EPRole> roleCreated = null;
2305 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2306 roleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, roleParams, null);
2308 roleParams.put("appId", String.valueOf(app.getId()));
2309 roleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams,
2312 if (roleCreated == null || roleCreated.isEmpty()) {
2313 roleParams.put("appId", String.valueOf(app.getId()));
2314 EPRole epRoleNew = new EPRole();
2315 epRoleNew.setActive(true);
2316 epRoleNew.setName(role);
2317 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2318 epRoleNew.setAppId(null);
2320 epRoleNew.setAppId(app.getId());
2322 dataAccessService.saveDomainObject(epRoleNew, null);
2331 @SuppressWarnings("unchecked")
2332 public Integer bulkUploadFunctions(String uebkey) throws Exception {
2333 EPApp app = getApp(uebkey).get(0);
2334 List<RoleFunction> roleFuncList = dataAccessService.executeNamedQuery("getAllFunctions", null, null);
2335 CentralV2RoleFunction cenRoleFunc = null;
2336 Integer functionsAdded = 0;
2338 for (RoleFunction roleFunc : roleFuncList) {
2339 cenRoleFunc = new CentralV2RoleFunction(roleFunc.getCode(), roleFunc.getName());
2340 addRoleFunctionInExternalSystem(cenRoleFunc, app);
2343 } catch (HttpClientErrorException e) {
2344 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadFunctions failed", e);
2345 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2346 } catch (Exception e) {
2347 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions: failed", e.getMessage(), e);
2349 return functionsAdded;
2353 public Integer bulkUploadRoles(String uebkey) throws Exception {
2354 List<EPApp> app = getApp(uebkey);
2355 List<EPRole> roles = getAppRoles(app.get(0).getId());
2356 List<CentralV2Role> cenRoleList = new ArrayList<>();
2357 final Map<String, Long> params = new HashMap<>();
2358 Integer rolesListAdded = 0;
2360 cenRoleList = createCentralRoleObject(app, roles, cenRoleList, params);
2361 ObjectMapper mapper = new ObjectMapper();
2362 mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
2363 String roleList = mapper.writeValueAsString(cenRoleList);
2364 List<Role> roleObjectList = mapper.readValue(roleList,
2365 TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
2366 for (Role role : roleObjectList) {
2367 addRoleInExternalSystem(role, app.get(0));
2370 if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
2371 // Add Account Admin role in External AUTH System
2373 String addAccountAdminRole = "";
2374 ExternalAccessRole extRole = new ExternalAccessRole();
2375 extRole.setName(app.get(0).getNameSpace() + "." + PortalConstants.ADMIN_ROLE
2376 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2377 addAccountAdminRole = mapper.writeValueAsString(extRole);
2378 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2379 HttpEntity<String> entity = new HttpEntity<>(addAccountAdminRole, headers);
2381 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
2382 HttpMethod.POST, entity, String.class);
2384 } catch (HttpClientErrorException e) {
2385 logger.error(EELFLoggerDelegate.errorLogger,
2386 "HttpClientErrorException - Failed to create Account Admin role", e);
2387 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2388 } catch (Exception e) {
2389 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2390 logger.error(EELFLoggerDelegate.errorLogger,
2391 "bulkUploadRoles: Account Admin Role already exits but does not break functionality",
2394 logger.error(EELFLoggerDelegate.errorLogger,
2395 "bulkUploadRoles: Failed to create Account Admin role", e.getMessage());
2399 } catch (Exception e) {
2400 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles: failed", e);
2403 return rolesListAdded;
2407 * It creating new role in external auth system while doing bulk upload
2413 private void addRoleInExternalSystem(Role role, EPApp app) throws Exception {
2414 String addRoleNew = updateExistingRoleInExternalSystem(role, app);
2415 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2417 HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
2419 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
2420 HttpMethod.POST, entity, String.class);
2421 } catch (HttpClientErrorException e) {
2422 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addRoleInExternalSystem",
2424 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2425 } catch (Exception e) {
2426 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2427 logger.error(EELFLoggerDelegate.errorLogger,
2428 "addRoleInExternalSystem: Role already exits but does not break functionality", e);
2430 logger.error(EELFLoggerDelegate.errorLogger,
2431 "addRoleInExternalSystem: Failed to addRoleInExternalSystem", e.getMessage());
2437 @SuppressWarnings("unchecked")
2438 public Integer bulkUploadRolesFunctions(String uebkey) throws Exception {
2439 EPApp app = getApp(uebkey).get(0);
2440 List<EPRole> roles = getAppRoles(app.getId());
2441 final Map<String, Long> params = new HashMap<>();
2442 Integer roleFunctions = 0;
2444 for (EPRole role : roles) {
2445 params.put("roleId", role.getId());
2446 List<BulkUploadRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("uploadAllRoleFunctions",
2448 if (!appRoleFunc.isEmpty()) {
2449 for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
2450 addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
2455 } catch (HttpClientErrorException e) {
2456 logger.error(EELFLoggerDelegate.errorLogger,
2457 "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
2458 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2459 } catch (Exception e) {
2460 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
2462 return roleFunctions;
2466 * Its adding a role function while doing bulk upload
2468 * @param addRoleFunc
2472 private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, EPRole role, EPApp app) {
2474 String instance = "";
2476 if (addRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
2477 type = EcompPortalUtils.getFunctionType(addRoleFunc.getFunctionCd());
2478 instance = EcompPortalUtils.getFunctionCode(addRoleFunc.getFunctionCd());
2479 action = EcompPortalUtils.getFunctionAction(addRoleFunc.getFunctionCd());
2481 type = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
2482 instance = addRoleFunc.getFunctionCd();
2485 ExternalAccessRolePerms extRolePerms = null;
2486 ExternalAccessPerms extPerms = null;
2487 ObjectMapper mapper = new ObjectMapper();
2489 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2490 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, instance, action,
2491 addRoleFunc.getFunctionName());
2492 extRolePerms = new ExternalAccessRolePerms(extPerms, app.getNameSpace() + "." + role.getName()
2493 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2494 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
2495 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
2497 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
2498 HttpMethod.POST, entity, String.class);
2499 } catch (Exception e) {
2500 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2501 logger.error(EELFLoggerDelegate.errorLogger,
2502 "addRoleFunctionsInExternalSystem: RoleFunction already exits but does not break functionality",
2505 logger.error(EELFLoggerDelegate.errorLogger,
2506 "addRoleFunctionsInExternalSystem: Failed to addRoleFunctionsInExternalSystem", e.getMessage());
2511 @SuppressWarnings("unchecked")
2513 public Integer bulkUploadPartnerFunctions(String uebkey) throws Exception {
2514 EPApp app = getApp(uebkey).get(0);
2515 final Map<String, Long> params = new HashMap<>();
2516 params.put("appId", app.getId());
2517 List<CentralV2RoleFunction> roleFuncList = dataAccessService.executeNamedQuery("getPartnerAppFunctions", params,
2519 Integer functionsAdded = 0;
2521 for (CentralV2RoleFunction roleFunc : roleFuncList) {
2522 addFunctionInExternalSystem(roleFunc, app);
2525 } catch (HttpClientErrorException e) {
2526 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadPartnerFunctions failed",
2528 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2529 } catch (Exception e) {
2530 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerFunctions: failed", e.getMessage(), e);
2532 return functionsAdded;
2535 private void addFunctionInExternalSystem(CentralV2RoleFunction roleFunc, EPApp app) throws Exception {
2536 ObjectMapper mapper = new ObjectMapper();
2537 ExternalAccessPerms extPerms = new ExternalAccessPerms();
2538 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2540 String instance = "";
2542 if ((roleFunc.getCode().contains(FUNCTION_PIPE))
2543 || (roleFunc.getType() != null && roleFunc.getAction() != null)) {
2544 type = EcompPortalUtils.getFunctionType(roleFunc.getCode());
2545 instance = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
2546 action = EcompPortalUtils.getFunctionAction(roleFunc.getCode());
2548 type = roleFunc.getCode().contains("menu") ? "menu" : "url";
2549 instance = roleFunc.getCode();
2553 extPerms.setAction(action);
2554 extPerms.setInstance(instance);
2555 extPerms.setType(app.getNameSpace() + "." + type);
2556 extPerms.setDescription(roleFunc.getName());
2557 String addFunction = mapper.writeValueAsString(extPerms);
2558 HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
2559 logger.debug(EELFLoggerDelegate.debugLogger, "addFunctionInExternalSystem: {} for POST: {}",
2560 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
2561 ResponseEntity<String> addPermResponse = template.exchange(
2562 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
2563 HttpMethod.POST, entity, String.class);
2564 logger.debug(EELFLoggerDelegate.debugLogger,
2565 "addFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ",
2566 addPermResponse.getStatusCode().value(), addFunction);
2567 } catch (HttpClientErrorException e) {
2568 logger.error(EELFLoggerDelegate.errorLogger,
2569 "HttpClientErrorException - Failed to add function in external central auth system", e);
2570 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2572 } catch (Exception e) {
2573 logger.error(EELFLoggerDelegate.errorLogger,
2574 "addFunctionInExternalSystem: Failed to add fucntion in external central auth system", e);
2580 public void bulkUploadPartnerRoles(String uebkey, List<Role> roleList) throws Exception {
2581 EPApp app = getApp(uebkey).get(0);
2582 for (Role role : roleList) {
2583 addRoleInExternalSystem(role, app);
2587 @SuppressWarnings("unchecked")
2589 public Integer bulkUploadPartnerRoleFunctions(String uebkey) throws Exception {
2590 EPApp app = getApp(uebkey).get(0);
2591 List<EPRole> roles = getAppRoles(app.getId());
2592 final Map<String, Long> params = new HashMap<>();
2593 Integer roleFunctions = 0;
2595 for (EPRole role : roles) {
2596 params.put("roleId", role.getId());
2597 List<BulkUploadRoleFunction> appRoleFunc = dataAccessService
2598 .executeNamedQuery("uploadPartnerRoleFunctions", params, null);
2599 if (!appRoleFunc.isEmpty()) {
2600 for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
2601 addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
2606 // upload global role functions to ext auth system
2607 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2608 roleFunctions = bulkUploadGlobalRoleFunctions(app, roleFunctions);
2610 } catch (HttpClientErrorException e) {
2611 logger.error(EELFLoggerDelegate.errorLogger,
2612 "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
2613 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2614 } catch (Exception e) {
2615 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
2617 return roleFunctions;
2620 @SuppressWarnings("unchecked")
2621 private Integer bulkUploadGlobalRoleFunctions(EPApp app, Integer roleFunctions) throws Exception {
2623 EPApp portalApp = epAppService.getApp(1l);
2624 final Map<String, Long> params = new HashMap<>();
2625 params.put("appId", app.getId());
2626 List<GlobalRoleWithApplicationRoleFunction> globalRoleFuncs = dataAccessService
2627 .executeNamedQuery("getBulkUploadPartnerGlobalRoleFunctions", params, null);
2628 ObjectMapper mapper = new ObjectMapper();
2629 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2630 for (GlobalRoleWithApplicationRoleFunction globalRoleFunc : globalRoleFuncs) {
2631 ExternalAccessRolePerms extRolePerms;
2632 ExternalAccessPerms extPerms;
2634 String instance = "";
2636 if (globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
2637 type = EcompPortalUtils.getFunctionType(globalRoleFunc.getFunctionCd());
2638 instance = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd());
2639 action = EcompPortalUtils.getFunctionAction(globalRoleFunc.getFunctionCd());
2641 type = globalRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
2642 instance = globalRoleFunc.getFunctionCd();
2645 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, instance, action);
2646 extRolePerms = new ExternalAccessRolePerms(extPerms,
2647 portalApp.getNameSpace() + "." + globalRoleFunc.getRoleName().replaceAll(
2648 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2649 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
2650 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
2651 updateRoleFunctionInExternalSystem(updateRolePerms, entity);
2654 } catch (HttpClientErrorException e) {
2655 logger.error(EELFLoggerDelegate.errorLogger,
2656 "HttpClientErrorException - Failed to add role function in external central auth system", e);
2657 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2659 } catch (Exception e) {
2660 logger.error(EELFLoggerDelegate.errorLogger,
2661 "bulkUploadGlobalRoleFunctions: Failed to add role fucntion in external central auth system", e);
2664 return roleFunctions;
2669 public void syncApplicationRolesWithEcompDB(EPApp app) {
2671 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Started");
2672 // Sync functions and roles assigned to it which also creates new roles if does
2673 // not exits in portal
2674 syncRoleFunctionFromExternalAccessSystem(app);
2675 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Finished");
2676 ObjectMapper mapper = new ObjectMapper();
2677 logger.debug(EELFLoggerDelegate.debugLogger, "Entering to getAppRolesJSONFromExtAuthSystem");
2678 // Get Permissions from External Auth System
2679 JSONArray extRole = getAppRolesJSONFromExtAuthSystem(app);
2680 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into getExternalRoleDetailsList");
2682 List<ExternalRoleDetails> externalRoleDetailsList = getExternalRoleDetailsList(app, mapper, extRole);
2683 List<EPRole> finalRoleList = new ArrayList<>();
2684 for (ExternalRoleDetails externalRole : externalRoleDetailsList) {
2685 EPRole ecompRole = convertExternalRoleDetailstoEpRole(externalRole);
2686 finalRoleList.add(ecompRole);
2688 List<EPRole> applicationRolesList;
2689 applicationRolesList = getAppRoles(app.getId());
2690 List<String> applicationRoleIdList = new ArrayList<>();
2691 for (EPRole applicationRole : applicationRolesList) {
2692 applicationRoleIdList.add(applicationRole.getName());
2694 List<EPRole> roleListToBeAddInEcompDB = new ArrayList<>();
2695 for (EPRole aafRole : finalRoleList) {
2696 if (!applicationRoleIdList.contains(aafRole.getName())) {
2697 roleListToBeAddInEcompDB.add(aafRole);
2700 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into inactiveRolesNotInExternalAuthSystem");
2701 // Check if roles exits in external Access system and if not make inactive in DB
2702 inactiveRolesNotInExternalAuthSystem(app, finalRoleList, applicationRolesList);
2703 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addNewRoleInEcompDBUpdateDescInExtAuthSystem");
2704 // Add new roles in DB and updates role description in External Auth System
2705 addNewRoleInEcompDBUpdateDescInExtAuthSystem(app, roleListToBeAddInEcompDB);
2706 logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: Finished");
2707 } catch (HttpClientErrorException e) {
2708 logger.error(EELFLoggerDelegate.errorLogger,
2709 "syncApplicationRolesWithEcompDB: Failed due to the External Auth System", e);
2710 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2711 } catch (Exception e) {
2712 logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed ", e);
2718 * It adds new roles in DB and updates description in External Auth System
2721 * @param roleListToBeAddInEcompDB
2723 @SuppressWarnings("unchecked")
2724 private void addNewRoleInEcompDBUpdateDescInExtAuthSystem(EPApp app, List<EPRole> roleListToBeAddInEcompDB) {
2725 EPRole roleToBeAddedInEcompDB;
2726 for (int i = 0; i < roleListToBeAddInEcompDB.size(); i++) {
2728 roleToBeAddedInEcompDB = roleListToBeAddInEcompDB.get(i);
2729 if (app.getId() == 1) {
2730 roleToBeAddedInEcompDB.setAppRoleId(null);
2732 dataAccessService.saveDomainObject(roleToBeAddedInEcompDB, null);
2733 List<EPRole> getRoleCreatedInSync = null;
2734 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2735 final Map<String, String> globalRoleParams = new HashMap<>();
2736 globalRoleParams.put("appId", String.valueOf(app.getId()));
2737 globalRoleParams.put("appRoleName", roleToBeAddedInEcompDB.getName());
2738 getRoleCreatedInSync = dataAccessService
2739 .executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, globalRoleParams, null);
2740 EPRole epUpdateRole = getRoleCreatedInSync.get(0);
2741 epUpdateRole.setAppRoleId(epUpdateRole.getId());
2742 dataAccessService.saveDomainObject(epUpdateRole, null);
2744 List<EPRole> roleList = new ArrayList<>();
2745 final Map<String, String> params = new HashMap<>();
2746 params.put(APP_ROLE_NAME_PARAM, roleToBeAddedInEcompDB.getName());
2747 boolean isPortalRole = false;
2748 if (app.getId() == 1) {
2749 isPortalRole = true;
2750 roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, params, null);
2752 isPortalRole = false;
2753 params.put(APP_ID, app.getId().toString());
2754 roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, params,
2757 EPRole role = roleList.get(0);
2758 Role aaFrole = new Role();
2759 aaFrole.setId(role.getId());
2760 aaFrole.setActive(role.getActive());
2761 aaFrole.setPriority(role.getPriority());
2762 aaFrole.setName(role.getName());
2763 updateRoleInExternalSystem(aaFrole, app, isPortalRole);
2764 } catch (Exception e) {
2765 logger.error(EELFLoggerDelegate.errorLogger,
2766 "SyncApplicationRolesWithEcompDB: Failed to add or update role in external auth system", e);
2773 * It checks description in External Auth System if found any
2774 * changes updates in DB
2777 * @param finalRoleList
2778 * contains list of External Auth System roles list which is
2779 * converted to EPRole
2781 @SuppressWarnings("unchecked")
2782 private void checkAndUpdateRoleInDB(EPApp app, List<EPRole> finalRoleList) {
2783 for (EPRole roleItem : finalRoleList) {
2784 final Map<String, String> roleParams = new HashMap<>();
2785 List<EPRole> currentList = null;
2786 roleParams.put(APP_ROLE_NAME_PARAM, roleItem.getName());
2787 if (app.getId() == 1) {
2788 currentList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, roleParams, null);
2790 roleParams.put(APP_ID, app.getId().toString());
2791 currentList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
2794 if (!currentList.isEmpty()) {
2796 Boolean aafRoleActive;
2797 Boolean localRoleActive;
2799 aafRoleActive = Boolean.valueOf(roleItem.getActive());
2800 localRoleActive = Boolean.valueOf(currentList.get(0).getActive());
2801 result = aafRoleActive.equals(localRoleActive);
2802 EPRole updateRole = currentList.get(0);
2804 updateRole.setActive(roleItem.getActive());
2805 dataAccessService.saveDomainObject(updateRole, null);
2807 if (roleItem.getPriority() != null
2808 && !currentList.get(0).getPriority().equals(roleItem.getPriority())) {
2809 updateRole.setPriority(roleItem.getPriority());
2810 dataAccessService.saveDomainObject(updateRole, null);
2812 } catch (Exception e) {
2813 logger.error(EELFLoggerDelegate.errorLogger,
2814 "syncApplicationRolesWithEcompDB: Failed to update role ", e);
2822 * It de-activates application roles in DB if not present in External Auth
2826 * @param finalRoleList
2827 * contains list of current roles present in External Auth System
2828 * @param applicationRolesList
2829 * contains list of current roles present in DB
2831 @SuppressWarnings("unchecked")
2832 private void inactiveRolesNotInExternalAuthSystem(EPApp app, List<EPRole> finalRoleList,
2833 List<EPRole> applicationRolesList) {
2834 final Map<String, EPRole> checkRolesInactive = new HashMap<>();
2835 for (EPRole extrole : finalRoleList) {
2836 checkRolesInactive.put(extrole.getName(), extrole);
2838 for (EPRole role : applicationRolesList) {
2840 final Map<String, String> extRoleParams = new HashMap<>();
2841 List<EPRole> roleList = null;
2842 extRoleParams.put(APP_ROLE_NAME_PARAM, role.getName());
2843 if (!checkRolesInactive.containsKey(role.getName()
2844 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
2845 if (app.getId() == 1) {
2846 roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, extRoleParams, null);
2848 extRoleParams.put(APP_ID, app.getId().toString());
2849 roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
2850 extRoleParams, null);
2852 if (!roleList.isEmpty()) {
2853 EPRole updateRoleInactive = roleList.get(0);
2854 updateRoleInactive.setActive(false);
2855 dataAccessService.saveDomainObject(updateRoleInactive, null);
2858 } catch (Exception e) {
2859 logger.error(EELFLoggerDelegate.errorLogger,
2860 "syncApplicationRolesWithEcompDB: Failed to de-activate role ", e);
2866 @SuppressWarnings("unchecked")
2867 public List<ExternalRoleDetails> getExternalRoleDetailsList(EPApp app, ObjectMapper mapper, JSONArray extRole)
2868 throws IOException {
2869 List<ExternalRoleDetails> externalRoleDetailsList = new ArrayList<>();
2870 ExternalAccessPerms externalAccessPerms = new ExternalAccessPerms();
2871 List<String> functionCodelist = new ArrayList<>();
2872 Map<String, EPRole> curRolesMap = getAppRoleNamesMap(app);
2873 Map<String, EPRole> curRolesUnderscoreMap = getAppRoleNamesWithUnderscoreMap(app);
2874 for (int i = 0; i < extRole.length(); i++) {
2875 ExternalRoleDetails externalRoleDetail = new ExternalRoleDetails();
2876 EPAppRoleFunction ePAppRoleFunction = new EPAppRoleFunction();
2877 JSONObject Role = (JSONObject) extRole.get(i);
2878 String name = extRole.getJSONObject(i).getString(ROLE_NAME);
2879 String actualRoleName = name.substring(app.getNameSpace().length() + 1);
2880 if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
2881 actualRoleName = extRole.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
2883 SortedSet<ExternalAccessPerms> externalAccessPermsOfRole = new TreeSet<>();
2884 if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_PERMS)) {
2885 JSONArray extPerm = (JSONArray) Role.get(EXTERNAL_AUTH_PERMS);
2886 for (int j = 0; j < extPerm.length(); j++) {
2887 JSONObject perms = extPerm.getJSONObject(j);
2888 boolean isNamespaceMatching = EcompPortalUtils.checkNameSpaceMatching(perms.getString("type"),
2889 app.getNameSpace());
2890 if (isNamespaceMatching) {
2891 externalAccessPerms = new ExternalAccessPerms(perms.getString("type"),
2892 perms.getString("instance"), perms.getString("action"));
2893 ePAppRoleFunction.setCode(externalAccessPerms.getInstance());
2894 functionCodelist.add(ePAppRoleFunction.getCode());
2895 externalAccessPermsOfRole.add(externalAccessPerms);
2899 externalRoleDetail.setActive(true);
2900 externalRoleDetail.setName(actualRoleName);
2901 if (app.getId() == 1) {
2902 externalRoleDetail.setAppId(null);
2904 externalRoleDetail.setAppId(app.getId());
2906 EPRole currRole = null;
2907 currRole = (!extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION))
2908 ? curRolesUnderscoreMap.get(actualRoleName)
2909 : curRolesMap.get(actualRoleName);
2911 if (currRole != null)
2912 roleId = currRole.getId();
2913 final Map<String, EPAppRoleFunction> roleFunctionsMap = new HashMap<>();
2914 final Map<String, Long> appRoleFuncsParams = new HashMap<>();
2915 if (roleId != null) {
2916 appRoleFuncsParams.put("appId", app.getId());
2917 appRoleFuncsParams.put("roleId", roleId);
2918 // get role functions from DB
2919 List<EPAppRoleFunction> appRoleFunctions = dataAccessService
2920 .executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null);
2921 if (!appRoleFunctions.isEmpty()) {
2922 for (EPAppRoleFunction roleFunc : appRoleFunctions) {
2923 roleFunctionsMap.put(roleFunc.getCode(), roleFunc);
2927 if (!externalAccessPermsOfRole.isEmpty()) {
2928 // Adding functions to role
2929 for (ExternalAccessPerms externalpermission : externalAccessPermsOfRole) {
2930 EPAppRoleFunction checkRoleFunctionExits = roleFunctionsMap.get(externalpermission.getInstance());
2931 if (checkRoleFunctionExits == null) {
2932 String funcCode = externalpermission.getType().substring(app.getNameSpace().length() + 1)
2933 + FUNCTION_PIPE + externalpermission.getInstance() + FUNCTION_PIPE
2934 + externalpermission.getAction();
2935 EPAppRoleFunction checkRoleFunctionPipeExits = roleFunctionsMap.get(funcCode);
2936 if (checkRoleFunctionPipeExits == null) {
2938 final Map<String, String> appFuncsParams = new HashMap<>();
2939 appFuncsParams.put("appId", String.valueOf(app.getId()));
2940 appFuncsParams.put("functionCd", externalpermission.getInstance());
2941 logger.debug(EELFLoggerDelegate.debugLogger,
2942 "SyncApplicationRolesWithEcompDB: Adding function to the role: {}",
2943 externalpermission.getInstance());
2944 List<CentralV2RoleFunction> roleFunction = null;
2945 roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId",
2946 appFuncsParams, null);
2947 if (roleFunction.isEmpty()) {
2948 appFuncsParams.put("functionCd", funcCode);
2949 roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId",
2950 appFuncsParams, null);
2952 if (!roleFunction.isEmpty()) {
2953 EPAppRoleFunction apRoleFunction = new EPAppRoleFunction();
2954 apRoleFunction.setAppId(app.getId());
2955 apRoleFunction.setRoleId(roleId);
2956 apRoleFunction.setCode(roleFunction.get(0).getCode());
2957 dataAccessService.saveDomainObject(apRoleFunction, null);
2959 } catch (Exception e) {
2960 logger.error(EELFLoggerDelegate.errorLogger,
2961 "SyncApplicationRolesWithEcompDB: Failed to add role function", e);
2967 externalRoleDetailsList.add(externalRoleDetail);
2969 return externalRoleDetailsList;
2973 public JSONArray getAppRolesJSONFromExtAuthSystem(EPApp app) throws Exception {
2974 ResponseEntity<String> response = null;
2975 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2976 HttpEntity<String> entity = new HttpEntity<>(headers);
2977 logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: {} ",
2978 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2979 response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
2980 + "roles/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
2981 String res = response.getBody();
2982 logger.debug(EELFLoggerDelegate.debugLogger,
2983 "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
2985 JSONObject jsonObj = new JSONObject(res);
2986 JSONArray extRole = jsonObj.getJSONArray("role");
2987 for (int i = 0; i < extRole.length(); i++) {
2988 if (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ADMIN)
2989 || extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + OWNER)
2990 || (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ACCOUNT_ADMINISTRATOR)
2991 && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
3000 public JSONArray getAllUsersByRole(String roleName) throws Exception {
3001 ResponseEntity<String> response = null;
3002 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3003 HttpEntity<String> entity = new HttpEntity<>(headers);
3004 logger.debug(EELFLoggerDelegate.debugLogger, "getAllUsersByRole: {} ",
3005 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
3006 response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
3007 + "userRoles/role/" + roleName, HttpMethod.GET, entity, String.class);
3008 String res = response.getBody();
3009 logger.debug(EELFLoggerDelegate.debugLogger,
3010 "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
3012 if (res == null || res.trim().isEmpty())
3014 JSONObject jsonObj = new JSONObject(res);
3015 JSONArray extRole = jsonObj.getJSONArray("userRole");
3021 * It converts from ExternalRoleDetails.class object to EPRole.class object
3023 * @param externalRoleDetails
3024 * @return EPRole object
3026 private EPRole convertExternalRoleDetailstoEpRole(ExternalRoleDetails externalRoleDetails) {
3027 EPRole role = new EPRole();
3028 role.setActive(true);
3029 role.setAppId(externalRoleDetails.getAppId());
3030 role.setAppRoleId(externalRoleDetails.getAppRoleId());
3031 role.setName(externalRoleDetails.getName());
3032 role.setPriority(externalRoleDetails.getPriority());
3036 @SuppressWarnings("unchecked")
3038 public Integer bulkUploadUserRoles(String uebkey) throws Exception {
3039 EPApp app = getApp(uebkey).get(0);
3040 final Map<String, String> params = new HashMap<>();
3041 params.put("uebKey", app.getUebKey());
3042 List<BulkUploadUserRoles> userRolesList = null;
3043 Integer userRolesAdded = 0;
3044 if (app.getCentralAuth()) {
3045 userRolesList = dataAccessService.executeNamedQuery("getBulkUserRoles", params, null);
3046 for (BulkUploadUserRoles userRolesUpload : userRolesList) {
3047 if (!userRolesUpload.getOrgUserId().equals("su1234")) {
3048 addUserRoleInExternalSystem(userRolesUpload);
3053 return userRolesAdded;
3057 * Its adding a user role in external auth system while doing bulk upload
3059 * @param userRolesUpload
3061 private void addUserRoleInExternalSystem(BulkUploadUserRoles userRolesUpload) {
3064 ObjectMapper mapper = new ObjectMapper();
3065 if (EPCommonSystemProperties
3066 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
3067 name = userRolesUpload.getOrgUserId()
3068 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
3070 ExternalAccessUser extUser = new ExternalAccessUser(name,
3071 userRolesUpload.getAppNameSpace() + "." + userRolesUpload.getRoleName()
3072 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
3073 String userRole = mapper.writeValueAsString(extUser);
3074 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3075 HttpEntity<String> entity = new HttpEntity<>(userRole, headers);
3077 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
3078 HttpMethod.POST, entity, String.class);
3079 } catch (HttpClientErrorException e) {
3080 logger.error(EELFLoggerDelegate.errorLogger,
3081 "HttpClientErrorException - Failed to addUserRoleInExternalSystem", e);
3082 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3083 } catch (Exception e) {
3084 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
3085 logger.error(EELFLoggerDelegate.errorLogger,
3086 "addUserRoleInExternalSystem: UserRole already exits but does not break functionality");
3088 logger.error(EELFLoggerDelegate.errorLogger,
3089 "addUserRoleInExternalSystem: Failed to addUserRoleInExternalSystem", e);
3095 public void deleteRoleDependencyRecords(Session localSession, Long roleId, Long appId, boolean isPortalRequest)
3100 // It should delete only when it portal's roleId
3101 if (appId.equals(PortalConstants.PORTAL_APP_ID)) {
3102 // Delete from fn_role_function
3103 sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
3104 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3105 query = localSession.createSQLQuery(sql);
3106 query.executeUpdate();
3107 // Delete from fn_role_composite
3108 sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId;
3109 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3110 query = localSession.createSQLQuery(sql);
3111 query.executeUpdate();
3113 // Delete from ep_app_role_function
3114 sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId;
3115 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3116 query = localSession.createSQLQuery(sql);
3117 query.executeUpdate();
3118 // Delete from ep_role_notification
3119 sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
3120 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3121 query = localSession.createSQLQuery(sql);
3122 query.executeUpdate();
3123 // Delete from fn_user_pseudo_role
3124 sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
3125 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3126 query = localSession.createSQLQuery(sql);
3127 query.executeUpdate();
3128 // Delete form EP_WIDGET_CATALOG_ROLE
3129 sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId;
3130 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3131 query = localSession.createSQLQuery(sql);
3132 query.executeUpdate();
3133 // Delete form EP_WIDGET_CATALOG_ROLE
3134 sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId;
3135 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3136 query = localSession.createSQLQuery(sql);
3137 query.executeUpdate();
3138 if (!isPortalRequest) {
3139 // Delete form fn_menu_functional_roles
3140 sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
3141 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3142 query = localSession.createSQLQuery(sql);
3143 query.executeUpdate();
3145 } catch (Exception e) {
3146 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e);
3147 throw new DeleteDomainObjectFailedException("delete Failed" + e.getMessage());
3151 @SuppressWarnings("unchecked")
3153 public List<String> getMenuFunctionsList(String uebkey) throws Exception {
3154 List<String> appMenuFunctionsList = null;
3155 List<String> appMenuFunctionsFinalList = new ArrayList<>();
3157 EPApp app = getApp(uebkey).get(0);
3158 final Map<String, Long> appParams = new HashMap<>();
3159 appParams.put(APP_ID, app.getId());
3160 appMenuFunctionsList = dataAccessService.executeNamedQuery("getMenuFunctions", appParams, null);
3161 for (String appMenuFunction : appMenuFunctionsList) {
3162 if (appMenuFunction.contains(FUNCTION_PIPE)) {
3163 appMenuFunctionsFinalList.add(EcompPortalUtils.getFunctionCode(appMenuFunction));
3165 appMenuFunctionsFinalList.add(appMenuFunction);
3168 } catch (Exception e) {
3169 logger.error(EELFLoggerDelegate.errorLogger, "getMenuFunctionsList: Failed", e);
3170 return appMenuFunctionsFinalList;
3172 return appMenuFunctionsFinalList;
3175 @SuppressWarnings({ "unchecked" })
3177 public List<EcompUser> getAllAppUsers(String uebkey) throws Exception {
3178 List<String> usersList = new ArrayList<>();
3179 List<EcompUser> usersfinalList = new ArrayList<>();
3181 EPApp app = getApp(uebkey).get(0);
3182 final Map<String, Long> appParams = new HashMap<>();
3183 appParams.put("appId", app.getId());
3184 List<EcompUserRoles> userList = (List<EcompUserRoles>) dataAccessService
3185 .executeNamedQuery("ApplicationUserRoles", appParams, null);
3186 for (EcompUserRoles ecompUserRole : userList) {
3187 boolean found = false;
3188 Set<EcompRole> roles = null;
3189 for (EcompUser user : usersfinalList) {
3190 if (user.getOrgUserId().equals(ecompUserRole.getOrgUserId())) {
3191 EcompRole ecompRole = new EcompRole();
3192 ecompRole.setId(ecompUserRole.getRoleId());
3193 ecompRole.setName(ecompUserRole.getRoleName());
3194 roles = user.getRoles();
3195 EcompRole role = roles.stream().filter(x -> x.getName().equals(ecompUserRole.getRoleName()))
3196 .findAny().orElse(null);
3197 SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
3199 roleFunctionSet = (SortedSet<EcompRoleFunction>) role.getRoleFunctions();
3201 String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
3202 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
3203 EcompRoleFunction epRoleFunction = new EcompRoleFunction();
3204 epRoleFunction.setName(ecompUserRole.getFunctionName());
3205 epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
3206 epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
3207 epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
3208 roleFunctionSet.add(epRoleFunction);
3209 ecompRole.setRoleFunctions(roleFunctionSet);
3210 roles.add(ecompRole);
3211 user.setRoles(roles);
3217 EcompUser epUser = new EcompUser();
3218 epUser.setOrgId(ecompUserRole.getOrgId());
3219 epUser.setManagerId(ecompUserRole.getManagerId());
3220 epUser.setFirstName(ecompUserRole.getFirstName());
3221 epUser.setLastName(ecompUserRole.getLastName());
3222 epUser.setPhone(ecompUserRole.getPhone());
3223 epUser.setEmail(ecompUserRole.getEmail());
3224 epUser.setOrgUserId(ecompUserRole.getOrgUserId());
3225 epUser.setOrgCode(ecompUserRole.getOrgCode());
3226 epUser.setOrgManagerUserId(ecompUserRole.getOrgManagerUserId());
3227 epUser.setJobTitle(ecompUserRole.getJobTitle());
3228 epUser.setLoginId(ecompUserRole.getLoginId());
3229 epUser.setActive(true);
3230 roles = new HashSet<>();
3231 EcompRole ecompRole = new EcompRole();
3232 ecompRole.setId(ecompUserRole.getRoleId());
3233 ecompRole.setName(ecompUserRole.getRoleName());
3234 SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
3235 String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
3236 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
3237 EcompRoleFunction epRoleFunction = new EcompRoleFunction();
3238 epRoleFunction.setName(ecompUserRole.getFunctionName());
3239 epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
3240 epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
3241 epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
3242 roleFunctionSet.add(epRoleFunction);
3243 ecompRole.setRoleFunctions(roleFunctionSet);
3244 roles.add(ecompRole);
3245 epUser.setRoles(roles);
3246 usersfinalList.add(epUser);
3249 ObjectMapper mapper = new ObjectMapper();
3250 for (EcompUser u1 : usersfinalList) {
3251 String str = mapper.writeValueAsString(u1);
3254 } catch (Exception e) {
3255 logger.error(EELFLoggerDelegate.errorLogger, "getAllUsers failed", e);
3258 return usersfinalList;
3262 public Role ConvertCentralRoleToRole(String result) {
3263 ObjectMapper mapper = new ObjectMapper();
3264 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
3265 Role newRole = new Role();
3267 newRole = mapper.readValue(result, Role.class);
3268 } catch (IOException e) {
3269 logger.error(EELFLoggerDelegate.errorLogger, "Failed to convert the result to Role Object", e);
3271 if (newRole.getRoleFunctions() != null) {
3272 @SuppressWarnings("unchecked")
3273 Set<RoleFunction> roleFunctionList = newRole.getRoleFunctions();
3274 Set<RoleFunction> roleFunctionListNew = new HashSet<>();
3275 Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
3276 while (itetaror.hasNext()) {
3277 Object nextValue = itetaror.next();
3278 RoleFunction roleFun = mapper.convertValue(nextValue, RoleFunction.class);
3279 roleFunctionListNew.add(roleFun);
3281 newRole.setRoleFunctions(roleFunctionListNew);
3287 @SuppressWarnings("unchecked")
3288 public List<CentralizedApp> getCentralizedAppsOfUser(String userId) {
3289 Map<String, String> params = new HashMap<>();
3290 params.put("userId", userId);
3291 List<CentralizedApp> centralizedAppsList = new ArrayList<>();
3293 centralizedAppsList = dataAccessService.executeNamedQuery("getCentralizedAppsOfUser", params, null);
3294 } catch (Exception e) {
3295 logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
3297 return centralizedAppsList;
3300 @SuppressWarnings("unchecked")
3301 public List<CentralV2Role> getGlobalRolesOfApplication(Long appId) {
3302 Map<String, Long> params = new HashMap<>();
3303 params.put("appId", appId);
3304 List<GlobalRoleWithApplicationRoleFunction> globalRoles = new ArrayList<>();
3306 globalRoles = dataAccessService.executeNamedQuery("getGlobalRoleWithApplicationRoleFunctions", params,
3308 } catch (Exception e) {
3309 logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
3311 List<CentralV2Role> rolesfinalList = new ArrayList<>();
3312 if (globalRoles.size() > 0)
3313 rolesfinalList = finalListOfCentralRoles(globalRoles);
3314 return rolesfinalList;
3317 @SuppressWarnings("unchecked")
3318 private CentralV2Role getGlobalRoleForRequestedApp(long requestedAppId, long roleId) {
3319 CentralV2Role finalGlobalrole = null;
3320 List<GlobalRoleWithApplicationRoleFunction> roleWithApplicationRoleFucntions = new ArrayList<>();
3321 Map<String, Long> params = new HashMap<>();
3322 params.put("roleId", roleId);
3323 params.put("requestedAppId", requestedAppId);
3325 roleWithApplicationRoleFucntions = dataAccessService.executeNamedQuery("getGlobalRoleForRequestedApp",
3327 } catch (Exception e) {
3328 logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRoleForRequestedApp failed", e);
3330 if (roleWithApplicationRoleFucntions.size() > 0) {
3331 List<CentralV2Role> rolesfinalList = finalListOfCentralRoles(roleWithApplicationRoleFucntions);
3332 finalGlobalrole = rolesfinalList.get(0);
3334 List<EPRole> roleList = getPortalAppRoleInfo(roleId);
3335 finalGlobalrole = convertRoleToCentralV2Role(roleList.get(0));
3337 return finalGlobalrole;
3340 private List<CentralV2Role> finalListOfCentralRoles(List<GlobalRoleWithApplicationRoleFunction> globalRoles) {
3341 List<CentralV2Role> rolesfinalList = new ArrayList<>();
3342 for (GlobalRoleWithApplicationRoleFunction role : globalRoles) {
3343 boolean found = false;
3344 for (CentralV2Role cenRole : rolesfinalList) {
3345 if (role.getRoleId().equals(cenRole.getId())) {
3346 SortedSet<CentralV2RoleFunction> roleFunctions = cenRole.getRoleFunctions();
3347 CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
3348 roleFunctions.add(cenRoleFun);
3349 cenRole.setRoleFunctions(roleFunctions);
3355 CentralV2Role cenrole = new CentralV2Role();
3356 cenrole.setName(role.getRoleName());
3357 cenrole.setId(role.getRoleId());
3358 cenrole.setActive(role.isActive());
3359 cenrole.setPriority(role.getPriority());
3360 SortedSet<CentralV2RoleFunction> roleFunctions = new TreeSet<>();
3361 CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
3362 roleFunctions.add(cenRoleFun);
3363 cenrole.setRoleFunctions(roleFunctions);
3364 rolesfinalList.add(cenrole);
3367 return rolesfinalList;
3370 private CentralV2RoleFunction createCentralRoleFunctionForGlobalRole(GlobalRoleWithApplicationRoleFunction role) {
3374 CentralV2RoleFunction cenRoleFun;
3375 if (role.getFunctionCd().contains(FUNCTION_PIPE)) {
3376 instance = EcompPortalUtils.getFunctionCode(role.getFunctionCd());
3377 type = EcompPortalUtils.getFunctionType(role.getFunctionCd());
3378 action = EcompPortalUtils.getFunctionAction(role.getFunctionCd());
3379 cenRoleFun = new CentralV2RoleFunction(null, instance, role.getFunctionName(), null, type, action, null);
3381 type = getFunctionCodeType(role.getFunctionCd());
3382 action = getFunctionCodeAction(role.getFunctionCd());
3383 cenRoleFun = new CentralV2RoleFunction(null, role.getFunctionCd(), role.getFunctionName(), null, type,
3389 @SuppressWarnings("unchecked")
3391 public List<EPRole> getGlobalRolesOfPortal() {
3392 List<EPRole> globalRoles = new ArrayList<>();
3394 globalRoles = dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null);
3395 } catch (Exception e) {
3396 logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRolesOfPortal failed", e);
3401 private CentralV2Role convertRoleToCentralV2Role(EPRole role) {
3402 return new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
3403 role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
3404 new TreeSet<>(), new TreeSet<>(), new TreeSet<>());
3408 public List<CentralRoleFunction> convertCentralRoleFunctionToRoleFunctionObject(
3409 List<CentralV2RoleFunction> answer) {
3410 List<CentralRoleFunction> addRoleFuncList = new ArrayList<>();
3411 for (CentralV2RoleFunction cenRoleFunc : answer) {
3412 CentralRoleFunction setRoleFunc = new CentralRoleFunction();
3413 setRoleFunc.setCode(cenRoleFunc.getCode());
3414 setRoleFunc.setName(cenRoleFunc.getName());
3415 addRoleFuncList.add(setRoleFunc);
3417 return addRoleFuncList;
3421 public CentralUser getUserRoles(String loginId, String uebkey) throws Exception {
3422 CentralUser sendUserRoles = null;
3424 CentralV2User cenV2User = getV2UserAppRoles(loginId, uebkey);
3425 sendUserRoles = convertV2UserRolesToOlderVersion(cenV2User);
3426 } catch (Exception e) {
3427 logger.error(EELFLoggerDelegate.errorLogger, "getUserRoles: failed", e);
3430 return sendUserRoles;
3435 * It returns V2 CentralUser object if user has any roles and permissions
3439 * @return CentralUser object
3442 private CentralV2User getV2UserAppRoles(String loginId, String uebkey) throws Exception {
3444 List<EPUser> epUserList;
3445 List<EPApp> appList = getApp(uebkey);
3446 app = appList.get(0);
3447 epUserList = getUser(loginId);
3448 EPUser user = epUserList.get(0);
3449 Set<EPUserApp> userAppSet = user.getEPUserApps();
3450 return createEPUser(user, userAppSet, app);
3453 private List<EcompRole> getUserAppRoles(EPApp app, EPUser user) {
3454 final Map<String, Long> userParams = new HashMap<>();
3455 userParams.put("appId", app.getId());
3456 userParams.put("userId", user.getId());
3457 @SuppressWarnings("unchecked")
3458 List<EPUserAppCurrentRoles> userAppsRolesList = dataAccessService.executeNamedQuery("getUserAppCurrentRoles",
3460 List<EcompRole> setUserRoles = new ArrayList<>();
3461 for (EPUserAppCurrentRoles role : userAppsRolesList) {
3462 logger.debug(EELFLoggerDelegate.debugLogger, "In getUserAppRoles()- get userRolename = {}",
3463 role.getRoleName());
3464 EcompRole ecompRole = new EcompRole();
3465 ecompRole.setId(role.getRoleId());
3466 ecompRole.setName(role.getRoleName());
3467 setUserRoles.add(ecompRole);
3469 logger.debug(EELFLoggerDelegate.debugLogger, "In getUserAppRoles()- get userrole list size = {}",
3470 setUserRoles.size());
3471 return setUserRoles;
3475 public List<EcompRole> missingUserApplicationRoles(String uebkey, String loginId, Set<EcompRole> CurrentUserRoles)
3477 List<EPApp> appList = getApp(uebkey);
3478 EPApp app = appList.get(0);
3479 List<EPUser> epUserList;
3480 epUserList = getUser(loginId);
3481 List<EcompRole> missingUserAppRoles = new ArrayList<>();
3482 List<String> roleNamesList = CurrentUserRoles.stream().map(EcompRole::getName).collect(Collectors.toList());
3483 logger.debug(EELFLoggerDelegate.debugLogger, "Roles of User from hibernate :" + roleNamesList);
3484 List<EcompRole> userApplicationsRolesfromDB = getUserAppRoles(app, epUserList.get(0));
3485 if (userApplicationsRolesfromDB.size() > 0) {
3486 missingUserAppRoles = userApplicationsRolesfromDB.stream().filter(x -> !roleNamesList.contains(x.getName()))
3487 .collect(Collectors.toList());
3489 List<String> MissingroleNamesList = missingUserAppRoles.stream().map(EcompRole::getName)
3490 .collect(Collectors.toList());
3491 logger.debug(EELFLoggerDelegate.debugLogger, "MissingUserAppRoles():" + MissingroleNamesList);
3493 List<EcompRole> finalMissingRoleList = new ArrayList<>();
3494 if (missingUserAppRoles.size() > 0) {
3495 final Map<String, Long> params = new HashMap<>();
3496 for (EcompRole role : missingUserAppRoles) {
3497 params.put("roleId", role.getId());
3498 params.put(APP_ID, app.getId());
3500 EcompRole epRole = new EcompRole();
3501 epRole.setId(role.getId());
3502 epRole.setName(role.getName());
3503 @SuppressWarnings("unchecked")
3504 List<CentralV2RoleFunction> appRoleFunctionList = dataAccessService
3505 .executeNamedQuery("getAppRoleFunctionList", params, null);
3506 SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
3507 for (CentralV2RoleFunction roleFunc : appRoleFunctionList) {
3508 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
3509 String type = getFunctionCodeType(roleFunc.getCode());
3510 String action = getFunctionCodeAction(roleFunc.getCode());
3511 EcompRoleFunction fun = new EcompRoleFunction();
3512 fun.setAction(action);
3513 fun.setCode(functionCode);
3515 fun.setName(roleFunc.getName());
3516 roleFunctionSet.add(fun);
3519 epRole.setRoleFunctions(roleFunctionSet);
3520 finalMissingRoleList.add(epRole);
3524 return finalMissingRoleList;
3528 * It converts V2 CentralUser object to old version CentralUser object
3531 * @return EPUser object
3533 private CentralUser convertV2UserRolesToOlderVersion(CentralV2User cenV2User) {
3534 Set<CentralV2UserApp> userV2Apps = cenV2User.getUserApps();
3535 Set<CentralUserApp> userApps = new TreeSet<>();
3536 for (CentralV2UserApp userApp : userV2Apps) {
3537 CentralApp app = userApp.getApp();
3538 CentralUserApp cua = new CentralUserApp();
3539 cua.setUserId(null);
3541 SortedSet<CentralRoleFunction> cenRoleFunction = new TreeSet<>();
3542 for (CentralV2RoleFunction cenV2RoleFunc : userApp.getRole().getRoleFunctions()) {
3543 CentralRoleFunction cenRoleFunc = new CentralRoleFunction(cenV2RoleFunc.getCode(),
3544 cenV2RoleFunc.getName());
3545 cenRoleFunction.add(cenRoleFunc);
3547 CentralRole role = new CentralRole(userApp.getRole().getId(), userApp.getRole().getName(),
3548 userApp.getRole().getActive(), userApp.getRole().getPriority(), cenRoleFunction);
3552 return new CentralUser(cenV2User.getId(), cenV2User.getCreated(), cenV2User.getModified(),
3553 cenV2User.getCreatedId(), cenV2User.getModifiedId(), cenV2User.getRowNum(), cenV2User.getOrgId(),
3554 cenV2User.getManagerId(), cenV2User.getFirstName(), cenV2User.getMiddleInitial(),
3555 cenV2User.getLastName(), cenV2User.getPhone(), cenV2User.getFax(), cenV2User.getCellular(),
3556 cenV2User.getEmail(), cenV2User.getAddressId(), cenV2User.getAlertMethodCd(), cenV2User.getHrid(),
3557 cenV2User.getOrgUserId(), cenV2User.getOrgCode(), cenV2User.getAddress1(), cenV2User.getAddress2(),
3558 cenV2User.getCity(), cenV2User.getState(), cenV2User.getZipCode(), cenV2User.getCountry(),
3559 cenV2User.getOrgManagerUserId(), cenV2User.getLocationClli(), cenV2User.getBusinessCountryCode(),
3560 cenV2User.getBusinessCountryName(), cenV2User.getBusinessUnit(), cenV2User.getBusinessUnitName(),
3561 cenV2User.getDepartment(), cenV2User.getDepartmentName(), cenV2User.getCompanyCode(),
3562 cenV2User.getCompany(), cenV2User.getZipCodeSuffix(), cenV2User.getJobTitle(),
3563 cenV2User.getCommandChain(), cenV2User.getSiloStatus(), cenV2User.getCostCenter(),
3564 cenV2User.getFinancialLocCode(), cenV2User.getLoginId(), cenV2User.getLoginPwd(),
3565 cenV2User.getLastLoginDate(), cenV2User.isActive(), cenV2User.isInternal(),
3566 cenV2User.getSelectedProfileId(), cenV2User.getTimeZoneId(), cenV2User.isOnline(),
3567 cenV2User.getChatId(), userApps);
3571 public List<CentralRole> convertV2CentralRoleListToOldVerisonCentralRoleList(List<CentralV2Role> v2CenRoleList) {
3572 List<CentralRole> cenRoleList = new ArrayList<>();
3573 for (CentralV2Role v2CenRole : v2CenRoleList) {
3574 SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
3575 for (CentralV2RoleFunction v2CenRoleFunc : v2CenRole.getRoleFunctions()) {
3576 CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(),
3577 v2CenRoleFunc.getName());
3578 cenRoleFuncList.add(roleFunc);
3580 CentralRole role = new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.getActive(),
3581 v2CenRole.getPriority(), cenRoleFuncList);
3582 cenRoleList.add(role);
3588 public ResponseEntity<String> getNameSpaceIfExists(EPApp app) throws Exception {
3589 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3590 HttpEntity<String> entity = new HttpEntity<>(headers);
3591 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Connecting to External Auth system");
3592 ResponseEntity<String> response = null;
3595 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
3596 + "nss/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
3597 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Finished ",
3598 response.getStatusCode().value());
3599 } catch (HttpClientErrorException e) {
3600 logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e);
3601 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3602 if (e.getStatusCode() == HttpStatus.NOT_FOUND)
3603 throw new InvalidApplicationException("Invalid NameSpace");
3611 public CentralRole convertV2CentralRoleToOldVerisonCentralRole(CentralV2Role v2CenRole) {
3612 SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
3613 for (CentralV2RoleFunction v2CenRoleFunc : v2CenRole.getRoleFunctions()) {
3614 CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName());
3615 cenRoleFuncList.add(roleFunc);
3617 return new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.getActive(), v2CenRole.getPriority(),
3621 @SuppressWarnings("unchecked")
3623 public Integer bulkUploadUsersSingleRole(String uebkey, Long roleId, String modifiedRoleName) throws Exception {
3624 EPApp app = getApp(uebkey).get(0);
3625 final Map<String, String> params = new HashMap<>();
3626 params.put("uebKey", app.getUebKey());
3627 params.put("roleId", String.valueOf(roleId));
3628 List<BulkUploadUserRoles> userRolesList = null;
3629 Integer userRolesAdded = 0;
3630 if (app.getCentralAuth()) {
3631 userRolesList = dataAccessService.executeNamedQuery("getBulkUsersForSingleRole", params, null);
3632 for (BulkUploadUserRoles userRolesUpload : userRolesList) {
3633 userRolesUpload.setRoleName(modifiedRoleName);
3634 if (!userRolesUpload.getOrgUserId().equals("su1234")) {
3635 addUserRoleInExternalSystem(userRolesUpload);
3640 return userRolesAdded;
3644 public String encodeFunctionCode(String funCode) {
3645 String encodedString = funCode;
3646 List<Pattern> encodingList = new ArrayList<>();
3647 encodingList.add(Pattern.compile("/"));
3648 encodingList.add(Pattern.compile("-"));
3649 for (Pattern xssInputPattern : encodingList) {
3650 encodedString = xssInputPattern.matcher(encodedString)
3651 .replaceAll("%" + Hex.encodeHexString(xssInputPattern.toString().getBytes()));
3653 encodedString = encodedString.replaceAll("\\*", "%" + Hex.encodeHexString("*".getBytes()));
3654 return encodedString;
3658 public void bulkUploadRoleFunc(UploadRoleFunctionExtSystem data, EPApp app) throws Exception {
3659 ObjectMapper mapper = new ObjectMapper();
3660 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3662 ExternalAccessRolePerms extRolePerms;
3663 ExternalAccessPerms extPerms;
3664 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + data.getType(),
3665 encodeFunctionCode(data.getInstance()), data.getAction());
3666 String appNameSpace = "";
3667 if (data.getIsGlobalRolePartnerFunc()) {
3668 appNameSpace = epAppService.getApp(1l).getNameSpace();
3670 appNameSpace = app.getNameSpace();
3672 extRolePerms = new ExternalAccessRolePerms(extPerms, appNameSpace + "." + data.getRoleName()
3673 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
3674 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
3675 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
3676 updateRoleFunctionInExternalSystem(updateRolePerms, entity);
3677 } catch (HttpClientErrorException e) {
3678 logger.error(EELFLoggerDelegate.errorLogger,
3679 "HttpClientErrorException - Failed to add role function in external central auth system", e);
3680 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3682 } catch (Exception e) {
3683 logger.error(EELFLoggerDelegate.errorLogger,
3684 "addFunctionInExternalSystem: Failed to add role fucntion in external central auth system", e);
3689 private void updateRoleFunctionInExternalSystem(String updateRolePerms, HttpEntity<String> entity) {
3690 logger.debug(EELFLoggerDelegate.debugLogger, "bulkUploadRoleFunc: {} for POST: {}",
3691 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
3692 ResponseEntity<String> addPermResponse = template.exchange(
3693 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
3694 HttpMethod.POST, entity, String.class);
3695 logger.debug(EELFLoggerDelegate.debugLogger,
3696 "bulkUploadRoleFunc: Finished adding permission for POST: {} and status code: {} ",
3697 addPermResponse.getStatusCode().value(), updateRolePerms);
3701 public void syncApplicationUserRolesFromExtAuthSystem(String loginId) throws Exception {
3703 if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
3704 name = loginId + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
3706 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3707 HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
3708 ResponseEntity<String> getResponse = getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
3709 List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
3710 String res = getResponse.getBody();
3711 JSONObject jsonObj = null;
3712 JSONArray extRoles = null;
3713 if (!res.equals("{}")) {
3714 jsonObj = new JSONObject(res);
3715 extRoles = jsonObj.getJSONArray("role");
3717 updateUserRolesInLocal(userRoleDetailList, extRoles, loginId);
3720 @SuppressWarnings("unchecked")
3721 private void updateUserRolesInLocal(List<ExternalAccessUserRoleDetail> userRoleDetailList, JSONArray extRoles,
3722 String loginId) throws InvalidUserException {
3723 HashMap<String, String> userParams = new HashMap<>();
3724 userParams.put("orgUserId", loginId);
3725 // Get all centralized applications existing user roles from local
3726 List<CentralizedAppRoles> currentUserAppRoles = dataAccessService
3727 .executeNamedQuery("getUserCentralizedAppRoles", userParams, null);
3728 EPUser user = getUser(loginId).get(0);
3729 // Get all centralized applications roles from local
3730 HashMap<String, CentralizedAppRoles> cenAppRolesMap = getCentralizedAppRoleList();
3731 HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap = getCurrentUserCentralizedAppRoles(
3732 currentUserAppRoles);
3733 // Get all centralized applications + admin role from local
3734 HashMap<String, EPApp> centralisedAppsMap = getCentralizedAdminAppsInfo();
3735 if (extRoles != null) {
3736 ExternalAccessUserRoleDetail userRoleDetail = null;
3737 for (int i = 0; i < extRoles.length(); i++) {
3738 if (!extRoles.getJSONObject(i).getString("name").endsWith(ADMIN)
3739 && !extRoles.getJSONObject(i).getString("name").endsWith(OWNER)) {
3740 userRoleDetail = new ExternalAccessUserRoleDetail(extRoles.getJSONObject(i).getString("name"),
3742 userRoleDetailList.add(userRoleDetail);
3745 addUserRolesInLocal(userRoleDetailList, user, cenAppRolesMap, currentCentralizedUserAppRolesMap,
3746 centralisedAppsMap);
3750 private void addUserRolesInLocal(List<ExternalAccessUserRoleDetail> userRoleDetailList, EPUser user,
3751 HashMap<String, CentralizedAppRoles> cenAppRolesMap,
3752 HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap,
3753 HashMap<String, EPApp> centralisedAppsMap) {
3754 for (ExternalAccessUserRoleDetail extUserRoleDetail : userRoleDetailList) {
3756 // check if user already has role in local
3757 if (!currentCentralizedUserAppRolesMap.containsKey(extUserRoleDetail.getName())) {
3758 CentralizedAppRoles getCenAppRole = cenAppRolesMap.get(extUserRoleDetail.getName());
3759 if (getCenAppRole != null) {
3760 logger.debug(EELFLoggerDelegate.debugLogger,
3761 "addUserRolesInLocal: Adding user role from external auth system {}",
3762 extUserRoleDetail.toString());
3763 EPUserApp userApp = new EPUserApp();
3764 EPApp app = new EPApp();
3765 app.setId(getCenAppRole.getAppId());
3766 EPRole epRole = new EPRole();
3767 epRole.setId(getCenAppRole.getRoleId());
3768 userApp.setApp(app);
3769 userApp.setUserId(user.getId());
3770 userApp.setRole(epRole);
3771 dataAccessService.saveDomainObject(userApp, null);
3772 logger.debug(EELFLoggerDelegate.debugLogger,
3773 "addUserRolesInLocal: Finished user role from external auth system {}",
3774 extUserRoleDetail.toString());
3775 } else if (getCenAppRole == null // check if user has app
3776 // account admin role
3777 && extUserRoleDetail.getName().endsWith(PortalConstants.ADMIN_ROLE.replaceAll(
3778 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
3779 EPApp app = centralisedAppsMap.get(extUserRoleDetail.getName());
3781 logger.debug(EELFLoggerDelegate.debugLogger,
3782 "addUserRolesInLocal: Adding user role from external auth system {}",
3783 extUserRoleDetail.toString());
3784 EPUserApp userApp = new EPUserApp();
3785 EPRole epRole = new EPRole();
3786 epRole.setId(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
3787 userApp.setApp(app);
3788 userApp.setUserId(user.getId());
3789 userApp.setRole(epRole);
3790 dataAccessService.saveDomainObject(userApp, null);
3791 logger.debug(EELFLoggerDelegate.debugLogger,
3792 "addUserRolesInLocal: Finished user role from external auth system {}",
3793 extUserRoleDetail.toString());
3797 } catch (Exception e) {
3798 logger.error(EELFLoggerDelegate.errorLogger,
3799 "addUserRolesInLocal - Failed to update user role in local from external auth system {} ",
3800 extUserRoleDetail.toString(), e);
3805 @SuppressWarnings("unchecked")
3806 private HashMap<String, EPApp> getCentralizedAdminAppsInfo() {
3807 List<EPApp> centralizedApps = dataAccessService.executeNamedQuery("getCentralizedApps", null, null);
3808 HashMap<String, EPApp> centralisedAppsMap = new HashMap<>();
3809 for (EPApp cenApp : centralizedApps) {
3810 centralisedAppsMap.put(
3811 cenApp.getNameSpace() + "."
3812 + PortalConstants.ADMIN_ROLE.replaceAll(
3813 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
3816 return centralisedAppsMap;
3819 private HashMap<String, CentralizedAppRoles> getCurrentUserCentralizedAppRoles(
3820 List<CentralizedAppRoles> currentUserAppRoles) {
3821 HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap = new HashMap<>();
3822 for (CentralizedAppRoles cenAppUserRole : currentUserAppRoles) {
3823 currentCentralizedUserAppRolesMap.put(
3824 cenAppUserRole.getAppNameSpace() + "."
3825 + cenAppUserRole.getRoleName().replaceAll(
3826 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
3829 return currentCentralizedUserAppRolesMap;
3832 @SuppressWarnings("unchecked")
3833 private HashMap<String, CentralizedAppRoles> getCentralizedAppRoleList() {
3834 List<CentralizedAppRoles> centralizedAppRoles = dataAccessService
3835 .executeNamedQuery("getAllCentralizedAppsRoles", null, null);
3836 HashMap<String, CentralizedAppRoles> cenAppRolesMap = new HashMap<>();
3837 for (CentralizedAppRoles CentralizedAppRole : centralizedAppRoles) {
3839 CentralizedAppRole.getAppNameSpace() + "."
3840 + CentralizedAppRole.getRoleName().replaceAll(
3841 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
3842 CentralizedAppRole);
3844 return cenAppRolesMap;
3848 public ResponseEntity<String> getUserRolesFromExtAuthSystem(String name, HttpEntity<String> getUserRolesEntity) {
3849 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles");
3850 ResponseEntity<String> getResponse = template
3851 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
3852 + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class);
3853 if (getResponse.getStatusCode().value() == 200) {
3854 logger.debug(EELFLoggerDelegate.debugLogger,
3855 "getAllUserRoleFromExtAuthSystem: Finished GET user roles from external system and received user roles {}",
3856 getResponse.getBody());
3858 logger.error(EELFLoggerDelegate.errorLogger,
3859 "getAllUserRoleFromExtAuthSystem: Failed GET user roles from external system and received user roles {}",
3860 getResponse.getBody());
3861 EPLogUtil.logExternalAuthAccessAlarm(logger, getResponse.getStatusCode());
3867 public Integer updateAppRoleDescription(String uebkey) {
3868 Integer roleDescUpdated = 0;
3871 app = getApp(uebkey).get(0);
3872 List<EPRole> roles = getAppRoles(app.getId());
3873 for (EPRole epRole : roles) {
3874 Role role = new Role();
3875 role.setName(epRole.getName());
3876 boolean status = addRoleDescriptionInExtSystem(role, app);
3880 } catch (Exception e) {
3881 logger.error(EELFLoggerDelegate.errorLogger, "updateAppRoleDescription: Failed! ", e);
3883 return roleDescUpdated;