2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2017 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.LinkedHashMap;
46 import java.util.List;
49 import java.util.SortedSet;
50 import java.util.TreeSet;
51 import java.util.regex.Pattern;
52 import java.util.stream.Collectors;
54 import org.apache.commons.codec.DecoderException;
55 import org.apache.commons.codec.binary.Hex;
56 import org.apache.commons.lang.StringUtils;
57 import org.hibernate.Query;
58 import org.hibernate.Session;
59 import org.hibernate.SessionFactory;
60 import org.hibernate.Transaction;
61 import org.hibernate.criterion.Criterion;
62 import org.hibernate.criterion.Restrictions;
63 import org.json.JSONArray;
64 import org.json.JSONObject;
65 import org.onap.portalapp.portal.domain.CentralV2RoleFunction;
66 import org.onap.portalapp.portal.domain.CentralizedApp;
67 import org.onap.portalapp.portal.domain.EPApp;
68 import org.onap.portalapp.portal.domain.EPAppRoleFunction;
69 import org.onap.portalapp.portal.domain.EPRole;
70 import org.onap.portalapp.portal.domain.EPUser;
71 import org.onap.portalapp.portal.domain.EPUserApp;
72 import org.onap.portalapp.portal.domain.ExternalRoleDetails;
73 import org.onap.portalapp.portal.ecomp.model.UploadRoleFunctionExtSystem;
74 import org.onap.portalapp.portal.exceptions.DeleteDomainObjectFailedException;
75 import org.onap.portalapp.portal.exceptions.ExternalAuthSystemException;
76 import org.onap.portalapp.portal.exceptions.InactiveApplicationException;
77 import org.onap.portalapp.portal.exceptions.InvalidApplicationException;
78 import org.onap.portalapp.portal.exceptions.InvalidUserException;
79 import org.onap.portalapp.portal.exceptions.RoleFunctionException;
80 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
81 import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
82 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
83 import org.onap.portalapp.portal.transport.BulkUploadRoleFunction;
84 import org.onap.portalapp.portal.transport.BulkUploadUserRoles;
85 import org.onap.portalapp.portal.transport.CentralApp;
86 import org.onap.portalapp.portal.transport.CentralRole;
87 import org.onap.portalapp.portal.transport.CentralRoleFunction;
88 import org.onap.portalapp.portal.transport.CentralUser;
89 import org.onap.portalapp.portal.transport.CentralUserApp;
90 import org.onap.portalapp.portal.transport.CentralV2Role;
91 import org.onap.portalapp.portal.transport.CentralV2User;
92 import org.onap.portalapp.portal.transport.CentralV2UserApp;
93 import org.onap.portalapp.portal.transport.CentralizedAppRoles;
94 import org.onap.portalapp.portal.transport.EcompUserRoles;
95 import org.onap.portalapp.portal.transport.ExternalAccessPerms;
96 import org.onap.portalapp.portal.transport.ExternalAccessPermsDetail;
97 import org.onap.portalapp.portal.transport.ExternalAccessRole;
98 import org.onap.portalapp.portal.transport.ExternalAccessRolePerms;
99 import org.onap.portalapp.portal.transport.ExternalAccessUser;
100 import org.onap.portalapp.portal.transport.ExternalAccessUserRoleDetail;
101 import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator;
102 import org.onap.portalapp.portal.transport.ExternalRoleDescription;
103 import org.onap.portalapp.portal.transport.GlobalRoleWithApplicationRoleFunction;
104 import org.onap.portalapp.portal.transport.LocalRole;
105 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
106 import org.onap.portalapp.portal.utils.EcompPortalUtils;
107 import org.onap.portalapp.portal.utils.PortalConstants;
108 import org.onap.portalapp.util.EPUserUtils;
109 import org.onap.portalsdk.core.domain.Role;
110 import org.onap.portalsdk.core.domain.RoleFunction;
111 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
112 import org.onap.portalsdk.core.restful.domain.EcompRole;
113 import org.onap.portalsdk.core.restful.domain.EcompRoleFunction;
114 import org.onap.portalsdk.core.restful.domain.EcompUser;
115 import org.onap.portalsdk.core.service.DataAccessService;
116 import org.onap.portalsdk.core.util.SystemProperties;
117 import org.springframework.beans.factory.annotation.Autowired;
118 import org.springframework.context.annotation.EnableAspectJAutoProxy;
119 import org.springframework.http.HttpEntity;
120 import org.springframework.http.HttpHeaders;
121 import org.springframework.http.HttpMethod;
122 import org.springframework.http.HttpStatus;
123 import org.springframework.http.ResponseEntity;
124 import org.springframework.stereotype.Service;
125 import org.springframework.transaction.annotation.Transactional;
126 import org.springframework.web.client.HttpClientErrorException;
127 import org.springframework.web.client.RestTemplate;
129 import com.fasterxml.jackson.core.JsonProcessingException;
130 import com.fasterxml.jackson.databind.DeserializationFeature;
131 import com.fasterxml.jackson.databind.ObjectMapper;
132 import com.fasterxml.jackson.databind.type.TypeFactory;
134 @Service("externalAccessRolesService")
135 @EnableAspectJAutoProxy
138 public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesService {
140 private static final String APP_ROLE_NAME_PARAM = "appRoleName";
142 private static final String GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM = "getRoletoUpdateInExternalAuthSystem";
144 private static final String GET_PORTAL_APP_ROLES_QUERY = "getPortalAppRoles";
146 private static final String GET_ROLE_FUNCTION_QUERY = "getRoleFunction";
148 private static final String FUNCTION_CODE_PARAMS = "functionCode";
150 private static final String AND_FUNCTION_CD_EQUALS = " and function_cd = '";
152 private static final String OWNER = ".owner";
154 private static final String ADMIN = ".admin";
156 private static final String ACCOUNT_ADMINISTRATOR = ".Account_Administrator";
158 private static final String FUNCTION_PIPE = "|";
160 private static final String IS_NULL_STRING = "null";
162 private static final String EXTERNAL_AUTH_PERMS = "perms";
164 private static final String EXTERNAL_AUTH_ROLE_DESCRIPTION = "description";
166 private static final String IS_EMPTY_JSON_STRING = "{}";
168 private static final String CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE = "Connecting to External Auth system";
170 private static final String APP_ROLE_ID = "appRoleId";
172 private static final String APP_ID = "appId";
174 private static final String PRIORITY = "priority";
176 private static final String ACTIVE = "active";
178 private static final String ROLE_NAME = "name";
180 private static final String ID = "id";
182 private static final String APP_ID_EQUALS = " app_id = ";
184 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesServiceImpl.class);
187 private DataAccessService dataAccessService;
190 private EPAppService epAppService;
193 private SessionFactory sessionFactory;
196 EPRoleService ePRoleService;
198 RestTemplate template = new RestTemplate();
201 // These decode values are based on HexDecoder
202 static final String decodeValueOfForwardSlash = "2f";
203 static final String decodeValueOfHiphen = "2d";
204 static final String decodeValueOfStar = "2a";
206 @SuppressWarnings("unchecked")
207 public List<EPRole> getAppRoles(Long appId) throws Exception {
208 List<EPRole> applicationRoles = null;
209 final Map<String, Long> appParams = new HashMap<>();
212 applicationRoles = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
214 appParams.put("appId", appId);
215 applicationRoles = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
217 } catch (Exception e) {
218 logger.error(EELFLoggerDelegate.errorLogger, "getAppRoles: failed", e);
221 return applicationRoles;
224 @SuppressWarnings("unchecked")
226 public List<EPApp> getApp(String uebkey) throws Exception {
227 List<EPApp> app = null;
229 final Map<String, String> appUebkeyParams = new HashMap<>();
230 appUebkeyParams.put("appKey", uebkey);
231 app = dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null);
232 if(!app.isEmpty() && !app.get(0).getEnabled() && !app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)){
233 throw new InactiveApplicationException("Application:"+app.get(0).getName()+" is Unavailable");
235 } catch (Exception e) {
236 logger.error(EELFLoggerDelegate.errorLogger, "getApp: failed", e);
243 * It returns single application role from external auth system
246 * @return JSON string which contains application role details
249 private String getSingleAppRole(String addRole, EPApp app) throws Exception {
250 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
251 HttpEntity<String> entity = new HttpEntity<>(headers);
252 ResponseEntity<String> response = null;
253 logger.debug(EELFLoggerDelegate.debugLogger, "getSingleAppRole: Connecting to External Auth system");
254 response = template.exchange(
255 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
258 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
259 HttpMethod.GET, entity, String.class);
260 logger.debug(EELFLoggerDelegate.debugLogger,
261 "getSingleAppRole: Finished GET app role from External Auth system and status code: {} ",
262 response.getStatusCode().value());
263 return response.getBody();
267 public boolean addRole(Role addRole, String uebkey) throws Exception {
268 boolean response = false;
269 ResponseEntity<String> addResponse = null;
270 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
271 EPApp app = getApp(uebkey).get(0);
272 String newRole = updateExistingRoleInExternalSystem(addRole, app);
273 HttpEntity<String> entity = new HttpEntity<>(newRole, headers);
274 logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Connecting to External Auth system");
275 addResponse = template.exchange(
276 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
277 HttpMethod.POST, entity, String.class);
278 if (addResponse.getStatusCode().value() == 201) {
280 logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Finished adding role in the External Auth system and response code: {} ", addResponse.getStatusCode().value());
282 if (addResponse.getStatusCode().value() == 406) {
283 logger.error(EELFLoggerDelegate.errorLogger,
284 "addRole: Failed to add in the External Auth system due to {} and status code: {}", addResponse.getBody(), addResponse.getStatusCode().value());
291 * It deletes record in external auth system
294 * @return JSON String which has status code and response body
297 private ResponseEntity<String> deleteRoleInExternalSystem(String delRole) throws Exception {
298 ResponseEntity<String> delResponse = null;
299 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
300 HttpEntity<String> entity = new HttpEntity<>(delRole, headers);
301 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: {} for DELETE: {}" , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, delRole);
302 delResponse = template.exchange(
303 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role?force=true",
304 HttpMethod.DELETE, entity, String.class);
305 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: Finished DELETE operation in the External Auth system {} and status code: {} ", delRole, delResponse.getStatusCode().value());
310 * It updates role in external auth system
312 * @param updateExtRole
314 * @return true if success else false
316 * If updateRoleInExternalSystem fails we catch it in logger for detail message
318 @SuppressWarnings("unchecked")
319 private boolean updateRoleInExternalSystem(Role updateExtRole, EPApp app, boolean isGlobalRole) throws Exception {
320 boolean response = false;
321 ObjectMapper mapper = new ObjectMapper();
322 ResponseEntity<String> deleteResponse = null;
323 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
324 List<EPRole> epRoleList = null;
325 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)
326 || (isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
327 epRoleList = getPortalAppRoleInfo(updateExtRole.getId());
329 epRoleList = getPartnerAppRoleInfo(updateExtRole.getId(), app);
332 // Assigning functions to global role
333 if ((isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
334 List<RoleFunction> globalRoleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole);
335 EPApp portalAppInfo = epAppService.getApp(PortalConstants.PORTAL_APP_ID);
336 addFunctionsTOGlobalRole(epRoleList, updateExtRole, globalRoleFunctionListNew, mapper, app, portalAppInfo);
339 String appRole = getSingleAppRole(epRoleList.get(0).getName(), app);
340 List<RoleFunction> roleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole);
341 if (!appRole.equals(IS_EMPTY_JSON_STRING)) {
342 JSONObject jsonObj = new JSONObject(appRole);
343 JSONArray extRole = jsonObj.getJSONArray("role");
344 if (!extRole.getJSONObject(0).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
345 String roleName = extRole.getJSONObject(0).getString(ROLE_NAME);
346 Map<String, String> delRoleKeyMapper = new HashMap<>();
347 delRoleKeyMapper.put(ROLE_NAME, roleName);
348 String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
349 deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
350 if (deleteResponse.getStatusCode().value() != 200) {
351 throw new ExternalAuthSystemException(deleteResponse.getBody());
353 addRole(updateExtRole, app.getUebKey());
355 String desc = extRole.getJSONObject(0).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
356 String name = extRole.getJSONObject(0).getString(ROLE_NAME);
357 List<ExternalAccessPerms> list = new ArrayList<>();
358 if (extRole.getJSONObject(0).has(EXTERNAL_AUTH_PERMS)) {
359 JSONArray perms = extRole.getJSONObject(0).getJSONArray(EXTERNAL_AUTH_PERMS);
360 list = mapper.readValue(perms.toString(), TypeFactory.defaultInstance()
361 .constructCollectionType(List.class, ExternalAccessPerms.class));
363 ExternalRoleDescription sysRoleList = mapper.readValue(desc, ExternalRoleDescription.class);
364 // If role name or role functions are updated then delete
365 // record in External System and add new record to avoid
367 Boolean existingRoleActive;
368 boolean isActiveValueChanged;
369 // check role active status
370 existingRoleActive = new Boolean(sysRoleList.getActive());
371 isActiveValueChanged = existingRoleActive.equals(updateExtRole.getActive());
372 boolean isRoleNameChanged = false;
373 if (!sysRoleList.getName().equals(updateExtRole.getName())) {
374 isRoleNameChanged = true;
375 Map<String, String> delRoleKeyMapper = new HashMap<>();
376 delRoleKeyMapper.put(ROLE_NAME, name);
377 String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
378 deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
379 if (deleteResponse.getStatusCode().value() != 200) {
380 logger.error(EELFLoggerDelegate.errorLogger,
381 "updateRoleInExternalSystem: Failed to delete role in external system due to {} ",
382 deleteResponse.getBody());
383 throw new ExternalAuthSystemException(deleteResponse.getBody());
385 addRole(updateExtRole, app.getUebKey());
386 // add partner functions to the global role in External Auth System
387 if(!list.isEmpty() && isGlobalRole){
388 addPartnerHasRoleFunctionsToGlobalRole(list, mapper, app, updateExtRole);
390 list.removeIf(perm -> EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace()));
391 // if role name is changes please ignore the previous functions in External Auth and update with user requested functions
392 addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name,
395 boolean checkPriorityStatus = StringUtils.equals(String.valueOf(sysRoleList.getPriority()),
396 String.valueOf(updateExtRole.getPriority()));
397 ExternalAccessRole updateRole = new ExternalAccessRole();
398 if (!isActiveValueChanged || !checkPriorityStatus || sysRoleList.getId().equals(IS_NULL_STRING)
399 || !sysRoleList.getId().equals(String.valueOf(epRoleList.get(0).getId()))) {
400 String updateDesc = "";
401 List<EPRole> getRole;
402 final Map<String, String> getAppRoleByName = new HashMap<>();
403 getAppRoleByName.put(APP_ROLE_NAME_PARAM, updateExtRole.getName());
404 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
405 getRole = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, getAppRoleByName,
408 getAppRoleByName.put("appId", String.valueOf(app.getId()));
409 getRole = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
410 getAppRoleByName, null);
412 Map<String, String> extSystemUpdateRoleJsonMapper = new LinkedHashMap<>();
413 extSystemUpdateRoleJsonMapper.put(ID, String.valueOf(getRole.get(0).getId()));
414 extSystemUpdateRoleJsonMapper.put(ROLE_NAME, String.valueOf(updateExtRole.getName()));
415 extSystemUpdateRoleJsonMapper.put(ACTIVE, String.valueOf(updateExtRole.getActive()));
416 extSystemUpdateRoleJsonMapper.put(PRIORITY, String.valueOf(updateExtRole.getPriority()));
417 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
418 extSystemUpdateRoleJsonMapper.put(APP_ID, "null");
419 extSystemUpdateRoleJsonMapper.put(APP_ROLE_ID, "null");
421 extSystemUpdateRoleJsonMapper.put(APP_ID, String.valueOf(app.getId()));
422 extSystemUpdateRoleJsonMapper.put(APP_ROLE_ID,
423 String.valueOf(getRole.get(0).getAppRoleId()));
426 updateDesc = mapper.writeValueAsString(extSystemUpdateRoleJsonMapper);
427 updateRole.setName(app.getNameSpace() + "." + updateExtRole.getName().replaceAll(
428 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
429 updateRole.setDescription(updateDesc);
430 String updateRoleDesc = mapper.writeValueAsString(updateRole);
431 HttpEntity<String> entity = new HttpEntity<>(updateRoleDesc, headers);
432 logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: {} for PUT: {}",
433 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRoleDesc);
434 ResponseEntity<String> updatePermsResponse = template.exchange(
435 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
437 HttpMethod.PUT, entity, String.class);
438 logger.debug(EELFLoggerDelegate.debugLogger,
439 "updateRoleInExternalSystem: Finished updating in External Auth system {} and status code: {} ",
440 updateRoleDesc, updatePermsResponse.getStatusCode().value());
442 if(!isRoleNameChanged) {
443 response = addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name,
448 // It seems like role exists in local DB but not in External
450 addRole(updateExtRole, app.getUebKey());
451 List<RoleFunction> roleFunctionListUpdate = convertSetToListOfRoleFunctions(updateExtRole);
453 if (!roleFunctionListUpdate.isEmpty()) {
454 addRoleFunctionsInExternalSystem(updateExtRole, mapper, app);
461 private boolean addRemoveFunctionsToRole(Role updateExtRole, EPApp app, ObjectMapper mapper,
462 List<RoleFunction> roleFunctionListNew, String name, List<ExternalAccessPerms> list) throws Exception {
464 Map<String, RoleFunction> updateRoleFunc = new HashMap<>();
465 for (RoleFunction addPerm : roleFunctionListNew) {
466 updateRoleFunc.put(addPerm.getCode(), addPerm);
468 final Map<String, ExternalAccessPerms> extRolePermMap = new HashMap<>();
469 final Map<String, ExternalAccessPerms> extRolePermMapPipes = new HashMap<>();
470 list.removeIf(perm -> !EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace()));
471 // Update permissions in the ExternalAccess System
472 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
473 if (!list.isEmpty()) {
474 for (ExternalAccessPerms perm : list) {
475 RoleFunction roleFunc = updateRoleFunc.get(perm.getType().substring(app.getNameSpace().length()+1) + FUNCTION_PIPE + perm.getInstance() + FUNCTION_PIPE + perm.getAction());
476 if (roleFunc==null) {
477 RoleFunction roleFuncPipeFilter = updateRoleFunc.get(perm.getInstance());
478 if(roleFuncPipeFilter == null)
479 removePermForRole(perm, mapper, name, headers);
481 extRolePermMap.put(perm.getInstance(), perm);
482 extRolePermMapPipes.put(
483 perm.getType().substring(app.getNameSpace().length()+1) + FUNCTION_PIPE + perm.getInstance() + FUNCTION_PIPE + perm.getAction(), perm);
487 if (!roleFunctionListNew.isEmpty()) {
488 for (RoleFunction roleFunc : roleFunctionListNew) {
489 if(roleFunc.getCode().contains(FUNCTION_PIPE)) {
490 ExternalAccessPerms perm = extRolePermMapPipes.get(roleFunc.getCode());
492 response = addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers,
496 if (!extRolePermMap.containsKey(EcompPortalUtils.getFunctionCode(roleFunc.getCode()))) {
497 response = addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers,
507 * Adds function to the role in the external auth system while editing a role or updating new functions to a role
510 private boolean addFunctionsToRoleInExternalAuthSystem(Role updateExtRole, EPApp app, ObjectMapper mapper,
511 HttpHeaders headers, RoleFunction roleFunc) throws JsonProcessingException {
513 ExternalAccessRolePerms extRolePerms;
514 ExternalAccessPerms extPerms;
518 if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
519 code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
520 type = getFunctionCodeType(roleFunc.getCode());
521 action = getFunctionCodeAction(roleFunc.getCode());
523 code = roleFunc.getCode();
524 type = roleFunc.getCode().contains("menu") ? "menu" : "url";
527 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, code, action);
528 extRolePerms = new ExternalAccessRolePerms(extPerms,
529 app.getNameSpace() + "."
530 + updateExtRole.getName().replaceAll(
531 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
533 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
534 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
535 logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: {} for POST: {}",
536 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
537 ResponseEntity<String> addResponse = template.exchange(
538 SystemProperties.getProperty(
539 EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
540 HttpMethod.POST, entity, String.class);
541 if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value()!= 409) {
543 logger.debug(EELFLoggerDelegate.debugLogger,
544 "updateRoleInExternalSystem: Connected to External Auth system but something went wrong! due to {} and statuscode: {}",
545 addResponse.getStatusCode().getReasonPhrase(),
546 addResponse.getStatusCode().value());
549 logger.debug(EELFLoggerDelegate.debugLogger,
550 "updateRoleInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ",
551 updateRolePerms, addResponse.getStatusCode().value());
556 private void addPartnerHasRoleFunctionsToGlobalRole(List<ExternalAccessPerms> permslist, ObjectMapper mapper,
557 EPApp app, Role updateExtRole) throws Exception {
558 for (ExternalAccessPerms perm : permslist) {
559 if (!EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace())) {
560 ExternalAccessRolePerms extAddGlobalRolePerms = null;
561 ExternalAccessPerms extAddPerms = null;
562 extAddPerms = new ExternalAccessPerms(perm.getType(), perm.getInstance(), perm.getAction());
563 extAddGlobalRolePerms = new ExternalAccessRolePerms(extAddPerms,
564 app.getNameSpace() + "." + updateExtRole.getName().replaceAll(
565 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
566 String addPerms = mapper.writeValueAsString(extAddGlobalRolePerms);
567 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
568 HttpEntity<String> entity = new HttpEntity<>(addPerms, headers);
569 logger.debug(EELFLoggerDelegate.debugLogger, "addPartnerHasRoleFunctionsToGlobalRole: {} ",
570 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
572 ResponseEntity<String> addResponse = template
573 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
574 + "role/perm", HttpMethod.POST, entity, String.class);
575 if (addResponse.getStatusCode().value() != 201) {
576 logger.debug(EELFLoggerDelegate.debugLogger,
577 "addPartnerHasRoleFunctionsToGlobalRole: While adding permission to the role in External Auth system something went wrong! due to {} and statuscode: {}",
578 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
580 logger.debug(EELFLoggerDelegate.debugLogger,
581 "addPartnerHasRoleFunctionsToGlobalRole: Finished adding permissions to roles in External Auth system and status code: {} ",
582 addResponse.getStatusCode().value());
584 } catch (Exception e) {
585 logger.error(EELFLoggerDelegate.errorLogger, "addPartnerHasRoleFunctionsToGlobalRole: Failed for POST request: {} due to ",
592 @SuppressWarnings("unchecked")
593 private void addFunctionsTOGlobalRole(List<EPRole> epRoleList, Role updateExtRole, List<RoleFunction> roleFunctionListNew, ObjectMapper mapper, EPApp app, EPApp portalAppInfo)
596 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addFunctionsTOGlobalRole");
597 //GET Permissions from External Auth System
598 JSONArray extPerms = getExtAuthPermissions(app);
599 List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);
600 final Map<String, ExternalAccessPermsDetail> existingPermsWithRoles = new HashMap<>();
601 final Map<String, ExternalAccessPermsDetail> existingPermsWithRolesWithPipes = new HashMap<>();
602 final Map<String, RoleFunction> userRquestedFunctionsMap = new HashMap<>();
603 final Map<String, RoleFunction> userRquestedFunctionsMapPipesFilter = new HashMap<>();
604 for (ExternalAccessPermsDetail permDetail : permsDetailList) {
605 existingPermsWithRoles.put(EcompPortalUtils.getFunctionCode(permDetail.getInstance()), permDetail);
606 existingPermsWithRolesWithPipes.put(permDetail.getInstance(), permDetail);
609 // Add If function does not exists for role in External Auth System
610 for (RoleFunction roleFunc : roleFunctionListNew) {
611 String roleFuncCode = "";
612 ExternalAccessPermsDetail permsDetail;
613 if(roleFunc.getCode().contains(FUNCTION_PIPE)) {
614 roleFuncCode = roleFunc.getCode();
615 permsDetail = existingPermsWithRolesWithPipes.get(roleFunc.getCode());
617 roleFuncCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
618 permsDetail = existingPermsWithRoles.get(roleFuncCode);
620 if (null == permsDetail.getRoles() || !permsDetail.getRoles()
621 .contains(portalAppInfo.getNameSpace() + FUNCTION_PIPE + epRoleList.get(0).getName().replaceAll(
622 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
623 addRoleFunctionsToGlobalRoleInExternalSystem(roleFunc, updateExtRole, mapper, app, portalAppInfo);
625 userRquestedFunctionsMap.put(roleFuncCode, roleFunc);
626 userRquestedFunctionsMapPipesFilter.put(EcompPortalUtils.getFunctionCode(roleFuncCode), roleFunc);
628 // Delete functions if exists in External Auth System but not in incoming request
629 final Map<String, Long> epAppRoleFuncParams = new HashMap<>();
630 epAppRoleFuncParams.put("requestedAppId", app.getId());
631 epAppRoleFuncParams.put("roleId",updateExtRole.getId());
632 List<GlobalRoleWithApplicationRoleFunction> globalRoleFunctionList = dataAccessService.executeNamedQuery("getGlobalRoleForRequestedApp", epAppRoleFuncParams, null);
633 for(GlobalRoleWithApplicationRoleFunction globalRoleFunc: globalRoleFunctionList){
634 String globalRoleFuncWithoutPipes = "";
635 RoleFunction roleFunc = null;
636 if(globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
637 globalRoleFuncWithoutPipes = globalRoleFunc.getFunctionCd();
638 roleFunc = userRquestedFunctionsMap.get(globalRoleFuncWithoutPipes);
640 globalRoleFuncWithoutPipes = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd());
641 roleFunc = userRquestedFunctionsMapPipesFilter.get(globalRoleFuncWithoutPipes);
643 if(roleFunc == null){
644 ExternalAccessPermsDetail permDetailFromMap = globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE) ? existingPermsWithRolesWithPipes.get(globalRoleFuncWithoutPipes) : existingPermsWithRoles.get(globalRoleFuncWithoutPipes);
645 ExternalAccessPerms perm = new ExternalAccessPerms(permDetailFromMap.getType(), EcompPortalUtils.getFunctionCode(permDetailFromMap.getInstance()), permDetailFromMap.getAction());
646 String roleName = portalAppInfo.getNameSpace()+"."+globalRoleFunc.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_");
647 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
648 removePermForRole(perm, mapper, roleName, headers);
651 logger.debug(EELFLoggerDelegate.debugLogger, "Finished addFunctionsTOGlobalRole");
652 } catch (Exception e) {
653 logger.error(EELFLoggerDelegate.errorLogger, "addFunctionsTOGlobalRole: Failed",e);
658 private void addRoleFunctionsToGlobalRoleInExternalSystem(RoleFunction addFunction, Role globalRole, ObjectMapper mapper, EPApp app,
659 EPApp portalAppInfo) throws Exception {
661 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addRoleFunctionsToGlobalRoleInExternalSystem");
662 ExternalAccessRolePerms extAddRolePerms = null;
663 ExternalAccessPerms extAddPerms = null;
664 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
668 if (addFunction.getCode().contains(FUNCTION_PIPE)) {
669 code = EcompPortalUtils.getFunctionCode(addFunction.getCode());
670 type = getFunctionCodeType(addFunction.getCode());
671 action = getFunctionCodeAction(addFunction.getCode());
673 code = addFunction.getCode();
674 type = addFunction.getCode().contains("menu") ? "menu" : "url";
677 extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, code, action);
678 extAddRolePerms = new ExternalAccessRolePerms(extAddPerms,
679 portalAppInfo.getNameSpace() + "." + globalRole.getName().replaceAll(
680 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
681 String updateRolePerms = mapper.writeValueAsString(extAddRolePerms);
682 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
683 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} ",
684 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
685 ResponseEntity<String> addResponse = template
686 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
687 + "role/perm", HttpMethod.POST, entity, String.class);
688 if (addResponse.getStatusCode().value() != 201) {
689 logger.debug(EELFLoggerDelegate.debugLogger,
690 "addRoleFunctionsInExternalSystem: While adding permission to the role in External Auth system something went wrong! due to {} and statuscode: {}",
691 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
693 logger.debug(EELFLoggerDelegate.debugLogger,
694 "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system and status code: {} ",
695 addResponse.getStatusCode().value());
697 logger.debug(EELFLoggerDelegate.debugLogger, "Finished addRoleFunctionsToGlobalRoleInExternalSystem");
699 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionsToGlobalRoleInExternalSystem: Failed",e);
706 * It adds functions to the role in external auth system
708 * @param updateExtRole
709 * @param addPermsMapper
711 * @return true if success else false
714 private boolean addRoleFunctionsInExternalSystem(Role updateExtRole, ObjectMapper addPermsMapper, EPApp app)
716 boolean response = false;
717 ExternalAccessRolePerms extAddRolePerms = null;
718 ExternalAccessPerms extAddPerms = null;
719 List<RoleFunction> roleFunctionListAdd = convertSetToListOfRoleFunctions(updateExtRole);
720 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
721 for (RoleFunction roleFunc : roleFunctionListAdd) {
725 if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
726 code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
727 type = getFunctionCodeType(roleFunc.getCode());
728 action = getFunctionCodeAction(roleFunc.getCode());
730 code = roleFunc.getCode();
731 type = roleFunc.getCode().contains("menu") ? "menu" : "url";
734 extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, code, action);
735 extAddRolePerms = new ExternalAccessRolePerms(extAddPerms,
736 app.getNameSpace() + "." + updateExtRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
737 String updateRolePerms = addPermsMapper.writeValueAsString(extAddRolePerms);
738 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
739 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} for POST: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
740 ResponseEntity<String> addResponse = template.exchange(
741 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
742 HttpMethod.POST, entity, String.class);
743 if (addResponse.getStatusCode().value() != 201) {
745 logger.debug(EELFLoggerDelegate.debugLogger,
746 "addRoleFunctionsInExternalSystem: While adding permission to the role in External Auth system something went wrong! due to {} and statuscode: {}",
747 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
750 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ", updateRolePerms, addResponse.getStatusCode().value());
758 * It converts list of functions in updateExtRole parameter to the RoleFunction object
760 * @param updateExtRole
761 * @return list of functions
763 @SuppressWarnings("unchecked")
764 private List<RoleFunction> convertSetToListOfRoleFunctions(Role updateExtRole) {
765 Set<RoleFunction> roleFunctionSetList = updateExtRole.getRoleFunctions();
766 List<RoleFunction> roleFunctionList = new ArrayList<>();
767 ObjectMapper roleFuncMapper = new ObjectMapper();
768 Iterator<RoleFunction> itetaror = roleFunctionSetList.iterator();
769 while (itetaror.hasNext()) {
770 Object nextValue = itetaror.next();
771 RoleFunction roleFunction = roleFuncMapper.convertValue(nextValue, RoleFunction.class);
772 roleFunctionList.add(roleFunction);
774 return roleFunctionList.stream().distinct().collect(Collectors.toList());
778 * It delete permissions/functions in the external auth system
784 * @throws JsonProcessingException
787 private void removePermForRole(ExternalAccessPerms perm, ObjectMapper permMapper, String name, HttpHeaders headers)
788 throws ExternalAuthSystemException, JsonProcessingException {
789 ExternalAccessRolePerms extAccessRolePerms = new ExternalAccessRolePerms(perm, name);
790 String permDetails = permMapper.writeValueAsString(extAccessRolePerms);
792 HttpEntity<String> deleteEntity = new HttpEntity<>(permDetails, headers);
793 logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: {} for DELETE: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, permDetails);
794 ResponseEntity<String> deletePermResponse = template
795 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/"
796 + name + "/perm", HttpMethod.DELETE, deleteEntity, String.class);
797 if (deletePermResponse.getStatusCode().value() != 200) {
798 throw new ExternalAuthSystemException(deletePermResponse.getBody());
800 logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: Finished deleting permission to role in External Auth system: {} and status code: {}",
801 permDetails, deletePermResponse.getStatusCode().value());
802 } catch(Exception e){
803 if(e.getMessage().contains("404")){
804 logger.error(EELFLoggerDelegate.errorLogger, "Failed to add role for DELETE request: {} due to {}", permDetails, e.getMessage());
812 * It will create new role in the External Auth System
816 * @return true if successfully added in the system else false
818 * If fails to add role in the system
820 private void addNewRoleInExternalSystem(List<EPRole> newRole, EPApp app) throws Exception, HttpClientErrorException {
822 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
823 ObjectMapper mapper = new ObjectMapper();
824 String addNewRole = "";
825 ExternalAccessRole extRole = new ExternalAccessRole();
826 String addDesc = null;
827 Map<String, String> extSystemJsonMapper = new LinkedHashMap<>();
828 extSystemJsonMapper.put(ID, String.valueOf(newRole.get(0).getId()));
829 extSystemJsonMapper.put(ROLE_NAME, String.valueOf(newRole.get(0).getName()));
830 extSystemJsonMapper.put(ACTIVE, String.valueOf(newRole.get(0).getActive()));
831 extSystemJsonMapper.put(PRIORITY, String.valueOf(newRole.get(0).getPriority()));
832 extSystemJsonMapper.put(APP_ID, String.valueOf(newRole.get(0).getAppId()));
833 extSystemJsonMapper.put(APP_ROLE_ID, String.valueOf(newRole.get(0).getAppRoleId()));
834 addDesc = mapper.writeValueAsString(extSystemJsonMapper);
835 extRole.setName(app.getNameSpace() + "." + newRole.get(0).getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
836 extRole.setDescription(addDesc);
837 addNewRole = mapper.writeValueAsString(extRole);
838 HttpEntity<String> postEntity = new HttpEntity<>(addNewRole, headers);
839 logger.debug(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: {} for POST: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addNewRole);
840 ResponseEntity<String> addNewRoleInExternalSystem = template.exchange(
841 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
842 HttpMethod.POST, postEntity, String.class);
843 if (addNewRoleInExternalSystem.getStatusCode().value() == 201) {
844 logger.debug(EELFLoggerDelegate.debugLogger,
845 "addNewRoleInExternalSystem: Finished adding into External Auth system for POST: {} and status code: {}",
846 addNewRole, addNewRoleInExternalSystem.getStatusCode().value());
848 }catch(HttpClientErrorException ht){
849 dataAccessService.deleteDomainObjects(EPRole.class, " role_id = "+ newRole.get(0).getId(), null);
850 logger.error(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: Failed to add in External Auth system and status code: {}",
852 throw new HttpClientErrorException(ht.getStatusCode());
858 * It updates existing role in the External Auth System
861 * It Contains role information
863 * @return string which is formatted to match with the external auth system
864 * @throws JsonProcessingException
866 private String updateExistingRoleInExternalSystem(Role addRole, EPApp app) throws JsonProcessingException {
867 ObjectMapper mapper = new ObjectMapper();
868 String addNewRole = "";
869 ExternalAccessRole extRole = new ExternalAccessRole();
870 List<EPRole> role = null;
871 String addDesc = null;
872 Map<String, String> extSystemUpdateRole = new LinkedHashMap<>();
873 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
874 role = getPortalAppRoleInfo(addRole.getId());
876 role = getPartnerAppRoleInfo(addRole.getId(), app);
878 extSystemUpdateRole.put(ID, String.valueOf(role.get(0).getId()));
879 extSystemUpdateRole.put(ROLE_NAME, String.valueOf(addRole.getName()));
880 extSystemUpdateRole.put(ACTIVE, String.valueOf(role.get(0).getActive()));
881 extSystemUpdateRole.put(PRIORITY, String.valueOf(role.get(0).getPriority()));
882 extSystemUpdateRole.put(APP_ID, String.valueOf(role.get(0).getAppId()));
883 extSystemUpdateRole.put(APP_ROLE_ID, String.valueOf(role.get(0).getAppRoleId()));
884 addDesc = mapper.writeValueAsString(extSystemUpdateRole);
885 extRole.setName(app.getNameSpace() + "." + addRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
886 extRole.setDescription(addDesc);
887 addNewRole = mapper.writeValueAsString(extRole);
892 * It create a role in the external auth system and then in our local
896 * @return true else false
899 @SuppressWarnings("unchecked")
900 @Transactional(rollbackFor = Exception.class)
901 private boolean addRoleInEcompDB(Role addRoleInDB, EPApp app) throws Exception {
902 boolean result = false;
903 EPRole epRole = null;
904 Set<RoleFunction> roleFunctionList = addRoleInDB.getRoleFunctions();
905 List<RoleFunction> roleFunctionListNew = new ArrayList<>();
906 ObjectMapper mapper = new ObjectMapper();
907 Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
908 while (itetaror.hasNext()) {
909 Object nextValue = itetaror.next();
910 RoleFunction roleFunction = mapper.convertValue(nextValue, RoleFunction.class);
911 roleFunctionListNew.add(roleFunction);
913 List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct().collect(Collectors.toList());
915 if (addRoleInDB.getId() == null) { // check if it is new role
916 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
917 checkIfRoleExitsInExternalSystem(addRoleInDB, app);
919 EPRole epRoleNew = new EPRole();
920 epRoleNew.setActive(addRoleInDB.getActive());
921 epRoleNew.setName(addRoleInDB.getName());
922 epRoleNew.setPriority(addRoleInDB.getPriority());
923 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
924 epRoleNew.setAppId(null);
926 epRoleNew.setAppId(app.getId());
928 dataAccessService.saveDomainObject(epRoleNew, null);
929 List<EPRole> getRoleCreated = null;
930 final Map<String, String> epAppRoleParams = new HashMap<>();
931 final Map<String, String> epAppPortalRoleParams = new HashMap<>();
932 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
933 epAppRoleParams.put("appId", String.valueOf(app.getId()));
934 epAppRoleParams.put(APP_ROLE_NAME_PARAM, addRoleInDB.getName());
935 List<EPRole> roleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, epAppRoleParams, null);
936 EPRole epUpdateRole = roleCreated.get(0);
937 epUpdateRole.setAppRoleId(epUpdateRole.getId());
938 dataAccessService.saveDomainObject(epUpdateRole, null);
939 getRoleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, epAppRoleParams, null);
941 epAppPortalRoleParams.put(APP_ROLE_NAME_PARAM, addRoleInDB.getName());
942 getRoleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, epAppPortalRoleParams, null);
944 // Add role in External Auth system
945 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
946 addNewRoleInExternalSystem(getRoleCreated, app);
948 } else { // if role already exists then update it
949 EPRole globalRole = null;
950 List<EPRole> applicationRoles;
951 List<EPRole> globalRoleList = getGlobalRolesOfPortal();
952 boolean isGlobalRole = false;
953 if (!globalRoleList.isEmpty()) {
954 EPRole role = globalRoleList.stream().filter(x -> addRoleInDB.getId().equals(x.getId())).findAny()
961 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)
962 || (globalRole != null && app.getId() != globalRole.getAppId())) {
963 applicationRoles = getPortalAppRoleInfo(addRoleInDB.getId());
965 applicationRoles = getPartnerAppRoleInfo(addRoleInDB.getId(), app);
967 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
968 updateRoleInExternalSystem(addRoleInDB, app, isGlobalRole);
969 // Add all user to the re-named role in external auth system
970 if (!applicationRoles.isEmpty()
971 && !addRoleInDB.getName().equals(applicationRoles.get(0).getName())) {
972 bulkUploadUsersSingleRole(app.getUebKey(), applicationRoles.get(0).getId(),
973 addRoleInDB.getName());
976 deleteRoleFunction(app, applicationRoles);
977 if (!applicationRoles.isEmpty()) {
978 epRole = applicationRoles.get(0);
979 epRole.setName(addRoleInDB.getName());
980 epRole.setPriority(addRoleInDB.getPriority());
981 epRole.setActive(addRoleInDB.getActive());
982 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
983 epRole.setAppId(null);
984 epRole.setAppRoleId(null);
985 } else if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)
986 && applicationRoles.get(0).getAppRoleId() == null) {
987 epRole.setAppRoleId(epRole.getId());
989 dataAccessService.saveDomainObject(epRole, null);
991 Long roleAppId = null;
992 if (globalRole != null && !app.getId().equals(globalRole.getAppId()))
993 roleAppId = PortalConstants.PORTAL_APP_ID;
994 saveRoleFunction(listWithoutDuplicates, app, applicationRoles, roleAppId);
997 } catch (Exception e) {
998 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInEcompDB is failed", e);
1006 * It validates whether role exists in external auth system
1013 private void checkIfRoleExitsInExternalSystem(Role checkRole, EPApp app) throws Exception {
1014 getNameSpaceIfExists(app);
1015 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1016 String roleName = app.getNameSpace() + "." + checkRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_");
1017 HttpEntity<String> checkRoleEntity = new HttpEntity<>(headers);
1018 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRoleExitsInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1019 ResponseEntity<String> checkRoleInExternalSystem = template
1020 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
1021 + roleName, HttpMethod.GET, checkRoleEntity, String.class);
1022 if (!checkRoleInExternalSystem.getBody().equals(IS_EMPTY_JSON_STRING)) {
1023 logger.debug("checkIfRoleExitsInExternalSystem: Role already exists in external system {} and status code: {} ", checkRoleInExternalSystem.getBody(), checkRoleInExternalSystem.getStatusCode().value());
1024 throw new ExternalAuthSystemException(" Role already exists in external system");
1029 * It saves list of functions to the role in portal
1031 * @param roleFunctionListNew
1033 * @param applicationRoles
1036 @SuppressWarnings("unchecked")
1037 private void saveRoleFunction(List<RoleFunction> roleFunctionListNew, EPApp app, List<EPRole> applicationRoles ,Long roleAppId)
1039 final Map<String, String> getAppFunctionParams = new HashMap<>();
1041 for (RoleFunction roleFunc : roleFunctionListNew) {
1042 String code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1043 EPAppRoleFunction appRoleFunc = new EPAppRoleFunction();
1044 appRoleFunc.setAppId(app.getId());
1045 appRoleFunc.setRoleId(applicationRoles.get(0).getId());
1046 appRoleFunc.setRoleAppId(String.valueOf(roleAppId));
1047 getAppFunctionParams.put("appId", String.valueOf(app.getId()));
1048 getAppFunctionParams.put(FUNCTION_CODE_PARAMS, roleFunc.getCode());
1049 // query to check if function code has pipes
1050 List<CentralV2RoleFunction> roleFunction = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null);
1051 if(roleFunction.isEmpty()){
1052 getAppFunctionParams.put(FUNCTION_CODE_PARAMS, code);
1053 roleFunction = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null);
1055 if(roleFunction.size() > 1){
1056 CentralV2RoleFunction getExactFunctionCode = appFunctionListFilter(code, roleFunction);
1057 appRoleFunc.setCode(getExactFunctionCode.getCode());
1059 appRoleFunc.setCode(roleFunction.get(0).getCode());
1062 dataAccessService.saveDomainObject(appRoleFunc, null);
1068 * It filters the app functions which starts with similar name in the result set
1071 * @param roleFunction
1072 * @return CentralRoleFunction
1074 private CentralV2RoleFunction appFunctionListFilter(String roleFuncCode, List<CentralV2RoleFunction> roleFunction) {
1075 final Map<String, CentralV2RoleFunction> appFunctionsFilter = new HashMap<>();
1076 final Map<String, CentralV2RoleFunction> appFunctionsFilterPipes = new HashMap<>();
1077 CentralV2RoleFunction getExactFunctionCode = null;
1078 for(CentralV2RoleFunction cenRoleFunction : roleFunction){
1079 appFunctionsFilter.put(cenRoleFunction.getCode(), cenRoleFunction);
1080 appFunctionsFilterPipes.put(EcompPortalUtils.getFunctionCode(cenRoleFunction.getCode()), cenRoleFunction);
1082 getExactFunctionCode = appFunctionsFilter.get(roleFuncCode);
1083 if(getExactFunctionCode == null){
1084 getExactFunctionCode = appFunctionsFilterPipes.get(roleFuncCode);
1086 return getExactFunctionCode;
1090 * It deletes all EPAppRoleFunction records in the portal
1095 @SuppressWarnings("unchecked")
1096 private void deleteRoleFunction(EPApp app, List<EPRole> role) {
1097 final Map<String, Long> appRoleFuncsParams = new HashMap<>();
1098 appRoleFuncsParams.put("appId", app.getId());
1099 appRoleFuncsParams.put("roleId", role.get(0).getId());
1100 List<EPAppRoleFunction> appRoleFunctionList = dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null);
1101 if (!appRoleFunctionList.isEmpty()) {
1102 for (EPAppRoleFunction approleFunction : appRoleFunctionList) {
1103 dataAccessService.deleteDomainObject(approleFunction, null);
1109 @SuppressWarnings("unchecked")
1110 public List<EPUser> getUser(String loginId) throws InvalidUserException{
1111 final Map<String, String> userParams = new HashMap<>();
1112 userParams.put("org_user_id", loginId);
1113 List<EPUser> userList = dataAccessService.executeNamedQuery("getEPUserByOrgUserId", userParams, null);
1114 if (userList.isEmpty()) {
1115 throw new InvalidUserException("User not found");
1121 public String getV2UserWithRoles(String loginId, String uebkey) throws Exception {
1122 final Map<String, String> params = new HashMap<>();
1123 List<EPUser> userList = null;
1124 CentralV2User cenV2User = null;
1125 String result = null;
1127 params.put("orgUserIdValue", loginId);
1128 List<EPApp> appList = getApp(uebkey);
1129 if (!appList.isEmpty()) {
1130 userList = getUser(loginId);
1131 if (!userList.isEmpty()) {
1132 ObjectMapper mapper = new ObjectMapper();
1133 cenV2User = getV2UserAppRoles(loginId, uebkey);
1134 result = mapper.writeValueAsString(cenV2User);
1135 } else if (userList.isEmpty()) {
1136 throw new InvalidUserException("User not found");
1139 throw new InactiveApplicationException("Application not found");
1141 } catch (Exception e) {
1142 logger.error(EELFLoggerDelegate.errorLogger, "getUser: failed", e);
1149 public List<CentralV2Role> getRolesForApp(String uebkey) throws Exception {
1150 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Entering into getRolesForApp");
1151 List<CentralV2Role> roleList = new ArrayList<>();
1152 final Map<String, Long> params = new HashMap<>();
1154 List<EPApp> app = getApp(uebkey);
1155 List<EPRole> appRolesList = getAppRoles(app.get(0).getId());
1156 roleList = createCentralRoleObject(app, appRolesList, roleList, params);
1157 if(app.get(0).getId() != PortalConstants.PORTAL_APP_ID){
1158 List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
1159 List<EPRole> globalRolesList = getGlobalRolesOfPortal();
1160 List<CentralV2Role> portalsGlobalRolesFinlaList = new ArrayList<>();
1161 if (!globalRolesList.isEmpty()) {
1162 for (EPRole eprole : globalRolesList) {
1163 CentralV2Role cenRole = convertRoleToCentralV2Role(eprole);
1164 portalsGlobalRolesFinlaList.add(cenRole);
1166 roleList.addAll(globalRoleList);
1167 for (CentralV2Role role : portalsGlobalRolesFinlaList) {
1168 CentralV2Role result = roleList.stream()
1169 .filter(x -> role.getId().equals(x.getId())).findAny().orElse(null);
1174 for (EPRole role : globalRolesList) {
1175 CentralV2Role cenRole = convertRoleToCentralV2Role(role);
1176 roleList.add(cenRole);
1180 } catch (Exception e) {
1181 logger.error(EELFLoggerDelegate.errorLogger, "getRolesForApp: Failed!", e);
1184 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Finished!");
1185 return roleList.stream().distinct().collect(Collectors.toList());
1188 @SuppressWarnings("unchecked")
1190 public List<CentralV2RoleFunction> getRoleFuncList(String uebkey) throws Exception {
1191 EPApp app = getApp(uebkey).get(0);
1192 List<CentralV2RoleFunction> finalRoleList = new ArrayList<>();
1193 final Map<String, Long> params = new HashMap<>();
1194 params.put(APP_ID, app.getId());
1195 List<CentralV2RoleFunction> getRoleFuncList = dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null);
1196 for (CentralV2RoleFunction roleFuncItem : getRoleFuncList) {
1197 String code = EcompPortalUtils.getFunctionCode(roleFuncItem.getCode());
1198 String type = getFunctionCodeType(roleFuncItem.getCode());
1199 String action = getFunctionCodeAction(roleFuncItem.getCode());
1200 roleFuncItem.setCode(EPUserUtils.decodeFunctionCode(code));
1201 roleFuncItem.setType(type);
1202 roleFuncItem.setAction(action);
1203 finalRoleList.add(roleFuncItem);
1205 return finalRoleList;
1210 public String getFunctionCodeAction(String roleFuncItem) {
1211 return (!roleFuncItem.contains(FUNCTION_PIPE)) ? "*"
1212 : EcompPortalUtils.getFunctionAction(roleFuncItem);
1216 public String getFunctionCodeType(String roleFuncItem) {
1218 if ((roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))
1219 || (!roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))) {
1221 } else if (checkIfCodeHasNoPipesAndHasTypeUrl(roleFuncItem)
1222 ||checkIfCodeHasPipesAndHasTypeUrl(roleFuncItem)
1223 ||checkIfCodeHasNoPipesAndHasNoTypeUrl(roleFuncItem)) {
1225 } else if (roleFuncItem.contains(FUNCTION_PIPE)
1226 && (!roleFuncItem.contains("menu") || roleFuncItem.contains("url"))) {
1227 type = EcompPortalUtils.getFunctionType(roleFuncItem);
1234 * It check whether function code has no pipes and no url string in it
1236 * @param roleFuncItem
1237 * @return true or false
1239 private boolean checkIfCodeHasNoPipesAndHasNoTypeUrl(String roleFuncItem) {
1240 return !roleFuncItem.contains(FUNCTION_PIPE) && !roleFuncItem.contains("url");
1245 * It check whether function code has pipes and url string in it
1247 * @param roleFuncItem
1248 * @return true or false
1250 private boolean checkIfCodeHasPipesAndHasTypeUrl(String roleFuncItem) {
1251 return roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
1256 * It check whether function code has no pipes and has url string in it
1258 * @param roleFuncItem
1259 * @return true or false
1261 private boolean checkIfCodeHasNoPipesAndHasTypeUrl(String roleFuncItem) {
1262 return !roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
1266 * It returns user detail information which is deep copy of EPUser.class object
1274 @SuppressWarnings("unchecked")
1275 private CentralV2User createEPUser(EPUser userInfo, Set<EPUserApp> userAppSet, EPApp app) throws Exception {
1277 final Map<String, Long> params = new HashMap<>();
1278 CentralV2User userAppList = new CentralV2User();
1279 CentralV2User user1 = null;
1280 final Map<String, Long> params1 = new HashMap<>();
1281 List<EPRole> globalRoleList = new ArrayList<>();
1284 if (app.getId() != PortalConstants.PORTAL_APP_ID) {
1285 params1.put("userId", userInfo.getId());
1286 params1.put("appId", app.getId());
1287 globalRoleList = dataAccessService.executeNamedQuery("userAppGlobalRoles", params1, null);
1289 userAppList.setUserApps(new TreeSet<CentralV2UserApp>());
1290 for (EPUserApp userApp : userAppSet) {
1291 if (userApp.getRole().getActive()) {
1292 EPApp epApp = userApp.getApp();
1293 String globalRole = userApp.getRole().getName().toLowerCase();
1294 if (((epApp.getId().equals(app.getId()))
1295 && (!userApp.getRole().getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)))
1296 || ((epApp.getId().equals(PortalConstants.PORTAL_APP_ID))
1297 && (globalRole.toLowerCase().startsWith("global_")))) {
1298 CentralV2UserApp cua = new CentralV2UserApp();
1299 cua.setUserId(null);
1300 CentralApp cenApp = new CentralApp(1L, epApp.getCreated(), epApp.getModified(),
1301 epApp.getCreatedId(), epApp.getModifiedId(), epApp.getRowNum(), epApp.getName(),
1302 epApp.getImageUrl(), epApp.getDescription(), epApp.getNotes(), epApp.getUrl(),
1303 epApp.getAlternateUrl(), epApp.getAppRestEndpoint(), epApp.getMlAppName(),
1304 epApp.getMlAppAdminId(), String.valueOf(epApp.getMotsId()), epApp.getAppPassword(),
1305 String.valueOf(epApp.getOpen()), String.valueOf(epApp.getEnabled()),
1306 epApp.getThumbnail(), epApp.getUsername(), epApp.getUebKey(), epApp.getUebSecret(),
1307 epApp.getUebTopicName());
1310 if (globalRole.toLowerCase().startsWith("global_")
1311 && epApp.getId().equals(PortalConstants.PORTAL_APP_ID)
1312 && !epApp.getId().equals(app.getId())) {
1313 appId = app.getId();
1314 EPRole result = null;
1315 if (globalRoleList.size() > 0)
1316 result = globalRoleList.stream()
1317 .filter(x -> userApp.getRole().getId().equals(x.getId())).findAny()
1322 appId = userApp.getApp().getId();
1324 params.put("roleId", userApp.getRole().getId());
1325 params.put(APP_ID, appId);
1326 List<CentralV2RoleFunction> appRoleFunctionList = dataAccessService
1327 .executeNamedQuery("getAppRoleFunctionList", params, null);
1328 SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>();
1329 for (CentralV2RoleFunction roleFunc : appRoleFunctionList) {
1330 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1331 String type = getFunctionCodeType(roleFunc.getCode());
1332 String action = getFunctionCodeAction(roleFunc.getCode());
1333 CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(roleFunc.getId(),
1334 functionCode, roleFunc.getName(), null, type, action, null);
1335 roleFunctionSet.add(cenRoleFunc);
1337 Long userRoleId = null;
1338 if (globalRole.toLowerCase().startsWith("global_")
1339 || epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1340 userRoleId = userApp.getRole().getId();
1342 userRoleId = userApp.getRole().getAppRoleId();
1344 CentralV2Role cenRole = new CentralV2Role(userRoleId, userApp.getRole().getCreated(),
1345 userApp.getRole().getModified(), userApp.getRole().getCreatedId(),
1346 userApp.getRole().getModifiedId(), userApp.getRole().getRowNum(),
1347 userApp.getRole().getName(), userApp.getRole().getActive(),
1348 userApp.getRole().getPriority(), roleFunctionSet, null, null);
1349 cua.setRole(cenRole);
1351 userAppList.getUserApps().add(cua);
1356 user1 = new CentralV2User(null, userInfo.getCreated(), userInfo.getModified(), userInfo.getCreatedId(),
1357 userInfo.getModifiedId(), userInfo.getRowNum(), userInfo.getOrgId(), userInfo.getManagerId(),
1358 userInfo.getFirstName(), userInfo.getMiddleInitial(), userInfo.getLastName(), userInfo.getPhone(),
1359 userInfo.getFax(), userInfo.getCellular(), userInfo.getEmail(), userInfo.getAddressId(),
1360 userInfo.getAlertMethodCd(), userInfo.getHrid(), userInfo.getOrgUserId(), userInfo.getOrgCode(),
1361 userInfo.getAddress1(), userInfo.getAddress2(), userInfo.getCity(), userInfo.getState(),
1362 userInfo.getZipCode(), userInfo.getCountry(), userInfo.getOrgManagerUserId(),
1363 userInfo.getLocationClli(), userInfo.getBusinessCountryCode(), userInfo.getBusinessCountryName(),
1364 userInfo.getBusinessUnit(), userInfo.getBusinessUnitName(), userInfo.getDepartment(),
1365 userInfo.getDepartmentName(), userInfo.getCompanyCode(), userInfo.getCompany(),
1366 userInfo.getZipCodeSuffix(), userInfo.getJobTitle(), userInfo.getCommandChain(),
1367 userInfo.getSiloStatus(), userInfo.getCostCenter(), userInfo.getFinancialLocCode(),
1368 userInfo.getLoginId(), userInfo.getLoginPwd(), userInfo.getLastLoginDate(), userInfo.getActive(),
1369 userInfo.getInternal(), userInfo.getSelectedProfileId(), userInfo.getTimeZoneId(),
1370 userInfo.isOnline(), userInfo.getChatId(), userAppList.getUserApps(), null);
1371 } catch (Exception e) {
1372 logger.error(EELFLoggerDelegate.errorLogger, "createEPUser: createEPUser failed", e);
1379 public CentralV2Role getRoleInfo(Long roleId, String uebkey) throws Exception {
1380 final Map<String, Long> params = new HashMap<>();
1381 List<CentralV2Role> roleList = new ArrayList<>();
1382 CentralV2Role cenRole = new CentralV2Role();
1383 List<EPRole> roleInfo = null;
1384 List<EPApp> app = null;
1386 app = getApp(uebkey);
1387 if (app.isEmpty()) {
1388 throw new InactiveApplicationException("Application not found");
1390 if (app.get(0).getId() != PortalConstants.PORTAL_APP_ID) {
1391 List<EPRole> globalRoleList = new ArrayList<>();
1392 globalRoleList = getGlobalRolesOfPortal();
1393 if (globalRoleList.size() > 0) {
1394 EPRole result = globalRoleList.stream().filter(x -> roleId.equals(x.getId())).findAny()
1397 return getGlobalRoleForRequestedApp(app.get(0).getId(), roleId);
1400 if (app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
1401 roleInfo = getPortalAppRoleInfo(roleId);
1403 roleInfo = getPartnerAppRoleInfo(roleId, app.get(0));
1405 roleList = createCentralRoleObject(app, roleInfo, roleList, params);
1406 if (roleList.isEmpty()) {
1410 } catch (Exception e) {
1411 logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo: failed", e);
1415 return roleList.get(0);
1418 @SuppressWarnings("unchecked")
1419 private List<EPRole> getPartnerAppRoleInfo(Long roleId, EPApp app) {
1420 List<EPRole> roleInfo;
1421 final Map<String, Long> getPartnerAppRoleParams = new HashMap<>();
1422 getPartnerAppRoleParams.put("appRoleId", roleId);
1423 getPartnerAppRoleParams.put("appId", app.getId());
1424 roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams, null);
1425 if(roleInfo.isEmpty()) {
1426 getPartnerAppRoleParams.put("appRoleId", roleId);
1427 roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleById", getPartnerAppRoleParams, null);
1432 @SuppressWarnings("unchecked")
1433 private List<EPRole> getPortalAppRoleInfo(Long roleId) {
1434 List<EPRole> roleInfo;
1435 final Map<String, Long> getPortalAppRoleParams = new HashMap<>();
1436 getPortalAppRoleParams.put("roleId", roleId);
1437 roleInfo = dataAccessService.executeNamedQuery("getPortalAppRoleByRoleId", getPortalAppRoleParams, null);
1443 * It returns list of app roles along with role functions and which went through deep copy
1450 * @throws DecoderException
1452 @SuppressWarnings("unchecked")
1453 private List<CentralV2Role> createCentralRoleObject(List<EPApp> app, List<EPRole> roleInfo,
1454 List<CentralV2Role> roleList, Map<String, Long> params) throws RoleFunctionException {
1455 for (EPRole role : roleInfo) {
1456 params.put("roleId", role.getId());
1457 params.put(APP_ID, app.get(0).getId());
1458 List<CentralV2RoleFunction> cenRoleFuncList = dataAccessService.executeNamedQuery("getAppRoleFunctionList",
1460 SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>();
1461 for (CentralV2RoleFunction roleFunc : cenRoleFuncList) {
1462 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1463 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
1464 String type = getFunctionCodeType(roleFunc.getCode());
1465 String action = getFunctionCodeAction(roleFunc.getCode());
1466 CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(role.getId(), functionCode,
1467 roleFunc.getName(), null, type, action, null);
1468 roleFunctionSet.add(cenRoleFunc);
1470 SortedSet<CentralV2Role> childRoles = new TreeSet<>();
1471 SortedSet<CentralV2Role> parentRoles = new TreeSet<>();
1472 CentralV2Role cenRole = null;
1473 if (role.getAppRoleId() == null) {
1474 cenRole = new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
1475 role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
1476 roleFunctionSet, childRoles, parentRoles);
1478 cenRole = new CentralV2Role(role.getAppRoleId(), role.getCreated(), role.getModified(),
1479 role.getCreatedId(), role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(),
1480 role.getPriority(), roleFunctionSet, childRoles, parentRoles);
1482 roleList.add(cenRole);
1487 @SuppressWarnings("unchecked")
1489 public CentralV2RoleFunction getRoleFunction(String functionCode, String uebkey) throws Exception {
1490 String code = EcompPortalUtils.getFunctionCode(functionCode);
1491 String encodedCode = encodeFunctionCode(code);
1492 CentralV2RoleFunction roleFunc = null;
1493 EPApp app = getApp(uebkey).get(0);
1494 List<CentralV2RoleFunction> getRoleFuncList = null;
1495 final Map<String, String> params = new HashMap<>();
1497 params.put(FUNCTION_CODE_PARAMS, functionCode);
1498 params.put(APP_ID, String.valueOf(app.getId()));
1499 getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
1500 if (getRoleFuncList.isEmpty()) {
1501 params.put(FUNCTION_CODE_PARAMS, encodedCode);
1502 getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
1503 if (getRoleFuncList.isEmpty()) {
1507 if (getRoleFuncList.size() > 1) {
1508 CentralV2RoleFunction cenV2RoleFunction = appFunctionListFilter(encodedCode, getRoleFuncList);
1509 if (cenV2RoleFunction == null)
1511 roleFunc = checkIfPipesExitsInFunctionCode(cenV2RoleFunction);
1513 // Check even if single record have pipes
1514 if (!getRoleFuncList.isEmpty() && getRoleFuncList.get(0).getCode().contains(FUNCTION_PIPE)) {
1515 roleFunc = checkIfPipesExitsInFunctionCode(getRoleFuncList.get(0));
1517 roleFunc = getRoleFuncList.get(0);
1520 } catch (Exception e) {
1521 logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction: failed", e);
1527 private CentralV2RoleFunction checkIfPipesExitsInFunctionCode(CentralV2RoleFunction getRoleFuncList) {
1528 CentralV2RoleFunction roleFunc;
1529 String functionCodeFormat = getRoleFuncList.getCode();
1530 if (functionCodeFormat.contains(FUNCTION_PIPE)) {
1531 String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(functionCodeFormat);
1532 String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(functionCodeFormat);
1533 String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(functionCodeFormat);
1534 roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), newfunctionCodeFormat,
1535 getRoleFuncList.getName(), getRoleFuncList.getAppId(), newfunctionTypeFormat, newfunctionActionFormat,
1536 getRoleFuncList.getEditUrl());
1538 roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), functionCodeFormat,
1539 getRoleFuncList.getName(), getRoleFuncList.getAppId(),
1540 getRoleFuncList.getEditUrl());
1546 public boolean saveCentralRoleFunction(CentralV2RoleFunction domainCentralRoleFunction, EPApp app) throws Exception {
1547 boolean saveOrUpdateFunction = false;
1549 domainCentralRoleFunction.setCode(encodeFunctionCode(domainCentralRoleFunction.getCode()));
1550 final Map<String, String> functionParams = new HashMap<>();
1551 functionParams.put("appId", String.valueOf(app.getId()));
1552 if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1553 addRoleFunctionInExternalSystem(domainCentralRoleFunction, app);
1555 if(domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null){
1556 domainCentralRoleFunction.setCode(domainCentralRoleFunction.getType()+
1557 FUNCTION_PIPE+domainCentralRoleFunction.getCode()+FUNCTION_PIPE+domainCentralRoleFunction.getAction());
1559 domainCentralRoleFunction.setAppId(app.getId());
1560 dataAccessService.saveDomainObject(domainCentralRoleFunction, null);
1561 saveOrUpdateFunction = true;
1562 } catch (Exception e) {
1563 logger.error(EELFLoggerDelegate.errorLogger, "saveCentralRoleFunction: failed", e);
1566 return saveOrUpdateFunction;
1570 * It creates application permission in external auth system
1572 * @param domainCentralRoleFunction
1576 private void addRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
1578 ObjectMapper mapper = new ObjectMapper();
1579 ExternalAccessPerms extPerms = new ExternalAccessPerms();
1580 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1582 String instance = "";
1584 if((domainCentralRoleFunction.getType()!=null && domainCentralRoleFunction.getAction()!=null) || domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)){
1585 type = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) ? EcompPortalUtils.getFunctionType(domainCentralRoleFunction.getCode()) : domainCentralRoleFunction.getType();
1586 instance = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) ? EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode()) : domainCentralRoleFunction.getCode();
1587 action = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) ? EcompPortalUtils.getFunctionAction(domainCentralRoleFunction.getCode()) : domainCentralRoleFunction.getAction();
1589 type = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url";
1590 instance = domainCentralRoleFunction.getCode();
1593 // get Permissions from External Auth System
1594 JSONArray extPermsList = getExtAuthPermissions(app);
1595 List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPermsList);
1596 String requestedPerm = type+FUNCTION_PIPE+instance+FUNCTION_PIPE+action;
1597 boolean checkIfFunctionsExits = permsDetailList.stream().anyMatch(permsDetail -> permsDetail.getInstance().equals(requestedPerm));
1598 if (!checkIfFunctionsExits) {
1600 extPerms.setAction(action);
1601 extPerms.setInstance(instance);
1602 extPerms.setType(app.getNameSpace() + "." + type);
1603 extPerms.setDescription(domainCentralRoleFunction.getName());
1604 String addFunction = mapper.writeValueAsString(extPerms);
1605 HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
1606 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for POST: {}" , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
1607 ResponseEntity<String> addPermResponse= template.exchange(
1608 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
1609 HttpMethod.POST, entity, String.class);
1610 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ", addPermResponse.getStatusCode().value(), addFunction);
1611 } catch(HttpClientErrorException e){
1612 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to add function in external central auth system", e);
1613 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1615 }catch (Exception e) {
1616 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionInExternalSystem: Failed to add fucntion in external central auth system",
1622 extPerms.setAction(action);
1623 extPerms.setInstance(instance);
1624 extPerms.setType(app.getNameSpace() + "." + type);
1625 extPerms.setDescription(domainCentralRoleFunction.getName());
1626 String updateRoleFunction = mapper.writeValueAsString(extPerms);
1627 HttpEntity<String> entity = new HttpEntity<>(updateRoleFunction, headers);
1628 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for PUT: {}" , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRoleFunction);
1629 ResponseEntity<String> updatePermResponse = template.exchange(
1630 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
1631 HttpMethod.PUT, entity, String.class);
1632 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished updating permission in External Auth system {} and response: {} ", updateRoleFunction, updatePermResponse.getStatusCode().value());
1633 } catch(HttpClientErrorException e){
1634 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to add function in external central auth system", e);
1635 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1637 } catch (Exception e) {
1638 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionInExternalSystem: Failed to update function in external central auth system",e);
1644 @SuppressWarnings("unchecked")
1646 @Transactional(rollbackFor = Exception.class)
1647 public boolean deleteCentralRoleFunction(String code, EPApp app) {
1648 boolean deleteFunctionResponse = false;
1650 final Map<String, String> params = new HashMap<>();
1651 params.put(FUNCTION_CODE_PARAMS, code);
1652 params.put(APP_ID, String.valueOf(app.getId()));
1653 List<CentralV2RoleFunction> domainCentralRoleFunction = dataAccessService
1654 .executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
1655 CentralV2RoleFunction appFunctionCode = appFunctionListFilter(code, domainCentralRoleFunction);
1656 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1657 deleteRoleFunctionInExternalSystem(appFunctionCode, app);
1658 // Delete role function dependency records
1659 deleteAppRoleFunctions(appFunctionCode.getCode(), app);
1661 dataAccessService.deleteDomainObject(appFunctionCode, null);
1662 deleteFunctionResponse = true;
1663 } catch (Exception e) {
1664 logger.error(EELFLoggerDelegate.errorLogger, "deleteCentralRoleFunction: failed", e);
1666 return deleteFunctionResponse;
1670 * It deletes app function record in portal
1675 private void deleteAppRoleFunctions(String code, EPApp app) {
1676 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
1677 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + code + "'", null);
1682 * It deletes permission in the external auth system
1684 * @param domainCentralRoleFunction
1688 private void deleteRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
1691 ObjectMapper mapper = new ObjectMapper();
1692 ExternalAccessPerms extPerms = new ExternalAccessPerms();
1693 String instanceValue = EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode());
1694 String checkType = getFunctionCodeType(domainCentralRoleFunction.getCode());
1695 String actionValue = getFunctionCodeAction(domainCentralRoleFunction.getCode());
1696 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1697 extPerms.setAction(actionValue);
1698 extPerms.setInstance(instanceValue);
1699 extPerms.setType(app.getNameSpace() + "." + checkType);
1700 extPerms.setDescription(domainCentralRoleFunction.getName());
1701 String deleteRoleFunction = mapper.writeValueAsString(extPerms);
1702 HttpEntity<String> entity = new HttpEntity<>(deleteRoleFunction, headers);
1703 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleFunctionInExternalSystem: {} for DELETE: {} ",
1704 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, deleteRoleFunction);
1705 ResponseEntity<String> delPermResponse = template
1706 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1707 + "perm?force=true", HttpMethod.DELETE, entity, String.class);
1708 logger.debug(EELFLoggerDelegate.debugLogger,
1709 "deleteRoleFunctionInExternalSystem: Finished deleting permission in External Auth system {} and status code: {} ",
1710 deleteRoleFunction, delPermResponse.getStatusCode().value());
1711 } catch(HttpClientErrorException e){
1712 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to delete functions in External System", e);
1713 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1714 } catch (Exception e) {
1715 if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
1716 logger.debug(EELFLoggerDelegate.debugLogger,
1717 " deleteRoleFunctionInExternalSystem: It seems like function is already deleted in external central auth system but exists in local DB",
1720 logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleFunctionInExternalSystem: Failed to delete functions in External System", e);
1726 public ExternalRequestFieldsValidator saveRoleForApplication(Role saveRole, String uebkey) throws Exception {
1727 boolean response = false;
1728 String message = "";
1730 EPApp app = getApp(uebkey).get(0);
1731 addRoleInEcompDB(saveRole, app);
1733 } catch (Exception e) {
1734 message = e.getMessage();
1735 logger.error(EELFLoggerDelegate.errorLogger, "saveRoleForApplication failed", e);
1737 return new ExternalRequestFieldsValidator(response,message);
1740 @SuppressWarnings("unchecked")
1742 public boolean deleteRoleForApplication(String deleteRole, String uebkey) throws Exception {
1743 Session localSession = sessionFactory.openSession();
1744 Transaction transaction = null;
1745 boolean result = false;
1747 List<EPRole> epRoleList = null;
1748 EPApp app = getApp(uebkey).get(0);
1749 final Map<String, String> deleteRoleParams = new HashMap<>();
1750 deleteRoleParams.put(APP_ROLE_NAME_PARAM, deleteRole);
1751 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1752 epRoleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, deleteRoleParams, null);
1754 deleteRoleParams.put(APP_ID, String.valueOf(app.getId()));
1755 epRoleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, deleteRoleParams, null);
1757 if (!epRoleList.isEmpty()) {
1758 transaction = localSession.beginTransaction();
1759 // Delete app role functions before deleting role
1760 deleteRoleFunction(app, epRoleList);
1761 if (app.getId() == 1) {
1762 // Delete fn_user_ role
1763 dataAccessService.deleteDomainObjects(EPUserApp.class,
1764 APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
1765 boolean isPortalRequest = false;
1766 deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest);
1768 deleteRoleInExternalAuthSystem(epRoleList, app);
1769 transaction.commit();
1770 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: committed the transaction");
1771 dataAccessService.deleteDomainObject(epRoleList.get(0), null);
1774 } catch (Exception e) {
1775 logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleForApplication: failed", e);
1778 localSession.close();
1785 * It deletes role for application in external auth system
1787 * @param epRoleList contains role information
1788 * @param app contains application information
1791 private void deleteRoleInExternalAuthSystem(List<EPRole> epRoleList, EPApp app) throws Exception {
1792 ResponseEntity<String> deleteResponse;
1793 ResponseEntity<String> res = getNameSpaceIfExists(app);
1794 if (res.getStatusCode() == HttpStatus.OK) {
1795 // Delete Role in External System
1796 String deleteRoleKey = "{\"name\":\"" + app.getNameSpace() + "." + epRoleList.get(0).getName()
1797 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_") + "\"}";
1798 deleteResponse = deleteRoleInExternalSystem(deleteRoleKey);
1799 if (deleteResponse.getStatusCode().value() != 200 || deleteResponse.getStatusCode().value() != 404) {
1800 EPLogUtil.logExternalAuthAccessAlarm(logger, deleteResponse.getStatusCode());
1801 logger.error(EELFLoggerDelegate.errorLogger,
1802 "deleteRoleForApplication: Failed to delete role in external auth system! due to {} ",
1803 deleteResponse.getBody());
1805 logger.debug(EELFLoggerDelegate.debugLogger,
1806 "deleteRoleForApplication: about to commit the transaction");
1812 * It deletes application user role in external auth system
1819 private void deleteUserRoleInExternalSystem(EPRole role, EPApp app, String LoginId) throws Exception {
1820 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1821 HttpEntity<String> entity = new HttpEntity<>(headers);
1822 getNameSpaceIfExists(app);
1823 logger.debug(EELFLoggerDelegate.debugLogger,"deleteUserRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1824 ResponseEntity<String> getResponse = template
1826 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
1829 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
1830 + "/" + app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
1831 HttpMethod.GET, entity, String.class);
1832 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: Finished GET user roles from External Auth system and response: {} ", getResponse.getBody());
1833 if (getResponse.getStatusCode().value() != 200) {
1834 throw new ExternalAuthSystemException(getResponse.getBody());
1836 String res = getResponse.getBody();
1837 if (!res.equals(IS_EMPTY_JSON_STRING)) {
1838 HttpEntity<String> userRoleentity = new HttpEntity<>(headers);
1839 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1840 ResponseEntity<String> deleteResponse = template
1842 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1843 + "userRole/" + LoginId
1845 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
1846 + "/" + app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
1847 HttpMethod.DELETE, userRoleentity, String.class);
1848 if (deleteResponse.getStatusCode().value() != 200) {
1849 throw new ExternalAuthSystemException("Failed to delete user role");
1851 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: Finished deleting user role in External Auth system and status code: {} ", deleteResponse.getStatusCode().value());
1855 @SuppressWarnings("unchecked")
1857 public List<CentralV2Role> getActiveRoles(String uebkey) throws Exception {
1858 List<CentralV2Role> roleList = new ArrayList<>();
1860 List<EPApp> app = getApp(uebkey);
1861 final Map<String, Long> params = new HashMap<>();
1864 if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
1865 appId = app.get(0).getId();
1867 List<Criterion> restrictionsList = new ArrayList<Criterion>();
1868 Criterion active_ynCrt = Restrictions.eq("active", Boolean.TRUE);
1871 appIdCrt = Restrictions.isNull("appId");
1873 appIdCrt = Restrictions.eq("appId", appId);
1874 Criterion andCrit = Restrictions.and(active_ynCrt, appIdCrt);
1875 restrictionsList.add(andCrit);
1876 List<EPRole> epRole = (List<EPRole>) dataAccessService.getList(EPRole.class, null, restrictionsList, null);
1877 roleList = createCentralRoleObject(app, epRole, roleList, params);
1878 List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
1879 if (globalRoleList.size() > 0)
1880 roleList.addAll(globalRoleList);
1881 } catch (Exception e) {
1882 logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles: failed", e);
1890 @Transactional(rollbackFor = Exception.class)
1891 public ExternalRequestFieldsValidator deleteDependencyRoleRecord(Long roleId, String uebkey, String LoginId) throws Exception {
1892 Session localSession = sessionFactory.openSession();
1893 String message = "";
1894 Transaction transaction = null;
1895 boolean response = false;
1898 transaction = localSession.beginTransaction();
1899 List<EPRole> epRoleList = null;
1900 app = getApp(uebkey).get(0);
1901 if(app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1902 epRoleList = getPortalAppRoleInfo(roleId);
1904 epRoleList = getPartnerAppRoleInfo(roleId, app);
1906 if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1907 // Delete User Role in External System before deleting role
1908 deleteUserRoleInExternalSystem(epRoleList.get(0), app, LoginId);
1910 // Delete user app roles
1911 dataAccessService.deleteDomainObjects(EPUserApp.class,
1912 APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
1913 boolean isPortalRequest = false;
1914 deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest);
1915 transaction.commit();
1916 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1917 // Final call to delete role once all dependencies has been deleted
1918 deleteRoleInExternalAuthSystem(epRoleList, app);
1920 dataAccessService.deleteDomainObjects(EPRole.class, " role_id = "+ epRoleList.get(0).getId(), null);
1921 logger.debug(EELFLoggerDelegate.debugLogger, "deleteDependencyRoleRecord: committed the transaction");
1923 } catch(HttpClientErrorException e){
1924 logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord: HttpClientErrorException", e);
1925 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1926 message = e.getMessage();
1927 } catch (Exception e) {
1928 logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord failed", e);
1929 EcompPortalUtils.rollbackTransaction(transaction,
1930 "deleteDependencyRoleRecord rollback, exception = " + e.toString());
1931 message = e.getMessage();
1933 localSession.close();
1935 return new ExternalRequestFieldsValidator(response,message);
1939 @SuppressWarnings("unchecked")
1941 public void syncRoleFunctionFromExternalAccessSystem(EPApp app) {
1944 // get Permissions from External Auth System
1945 JSONArray extPerms = getExtAuthPermissions(app);
1946 List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);
1948 // get functions in DB
1949 final Map<String, Long> params = new HashMap<>();
1950 final Map<String, CentralV2RoleFunction> roleFuncMap = new HashMap<>();
1951 params.put(APP_ID, app.getId());
1952 List<CentralV2RoleFunction> appFunctions = dataAccessService.executeNamedQuery("getAllRoleFunctions", params,
1954 if (!appFunctions.isEmpty()) {
1955 for (CentralV2RoleFunction roleFunc : appFunctions) {
1956 roleFuncMap.put(roleFunc.getCode(), roleFunc);
1960 // get Roles for portal in DB
1961 List<EPRole> portalRoleList = getGlobalRolesOfPortal();
1962 final Map<String, EPRole> existingPortalRolesMap = new HashMap<>();
1963 for(EPRole epRole : portalRoleList){
1964 existingPortalRolesMap.put(epRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), epRole);
1968 final Map<String, EPRole> currentRolesInDB = getCurrentRolesInDB(app);
1970 // store External Permissions with Pipe and without Pipe (just instance)
1971 final Map<String, ExternalAccessPermsDetail> extAccessPermsContainsPipeMap = new HashMap<>();
1972 final Map<String, ExternalAccessPermsDetail> extAccessPermsMap = new HashMap<>();
1973 for (ExternalAccessPermsDetail permsDetailInfoWithPipe : permsDetailList) {
1974 extAccessPermsContainsPipeMap.put(permsDetailInfoWithPipe.getInstance(), permsDetailInfoWithPipe);
1975 String finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetailInfoWithPipe.getInstance());
1976 extAccessPermsMap.put(finalFunctionCodeVal, permsDetailInfoWithPipe);
1979 // Add if new functions and app role functions were added in
1980 // external auth system
1981 for (ExternalAccessPermsDetail permsDetail : permsDetailList) {
1982 String code = permsDetail.getInstance();
1983 CentralV2RoleFunction getFunctionCodeKey = roleFuncMap.get(permsDetail.getInstance());
1984 List<CentralV2RoleFunction> roleFunctionList = addGetLocalFunction(app, roleFuncMap, permsDetail, code,
1985 getFunctionCodeKey);
1986 List<String> roles = permsDetail.getRoles();
1987 if (roles != null) {
1988 // Check if function has any roles and which does not exist
1989 // in External Auth System. If exists delete in local
1990 addRemoveIfFunctionsRolesIsSyncWithExternalAuth(app, currentRolesInDB, roleFunctionList, roles, existingPortalRolesMap);
1994 // Check if function does exits in External Auth System but exits in
1995 // local then delete function and its dependencies
1996 for (CentralV2RoleFunction roleFunc : appFunctions) {
1998 ExternalAccessPermsDetail getFunctionCodeContainsPipeKey = extAccessPermsContainsPipeMap
1999 .get(roleFunc.getCode());
2000 if (null == getFunctionCodeContainsPipeKey) {
2001 ExternalAccessPermsDetail getFunctionCodeKey = extAccessPermsMap.get(roleFunc.getCode());
2002 if (null == getFunctionCodeKey) {
2003 deleteAppRoleFuncDoesNotExitsInExtSystem(app, roleFunc);
2006 } catch (Exception e) {
2007 logger.error(EELFLoggerDelegate.errorLogger,
2008 "syncRoleFunctionFromExternalAccessSystem: Failed to delete function", e);
2013 logger.debug(EELFLoggerDelegate.debugLogger,
2014 "syncRoleFunctionFromExternalAccessSystem: Finished syncRoleFunctionFromExternalAccessSystem");
2015 } catch (Exception e) {
2016 logger.error(EELFLoggerDelegate.errorLogger,
2017 "syncRoleFunctionFromExternalAccessSystem: Failed syncRoleFunctionFromExternalAccessSystem", e);
2022 @SuppressWarnings("unchecked")
2023 private void addRemoveIfFunctionsRolesIsSyncWithExternalAuth(EPApp app, final Map<String, EPRole> currentRolesInDB,
2024 List<CentralV2RoleFunction> roleFunctionList, List<String> roles, Map<String, EPRole> existingPortalRolesMap)
2026 if (!roleFunctionList.isEmpty()) {
2027 final Map<String, String> appRoleFuncParams = new HashMap<>();
2028 final Map<String, LocalRole> currentAppRoleFunctionsMap = new HashMap<>();
2029 final Map<String, String> currentRolesInExtSystem = new HashMap<>();
2030 appRoleFuncParams.put("functionCd", roleFunctionList.get(0).getCode());
2031 appRoleFuncParams.put("appId", String.valueOf(app.getId()));
2032 List<LocalRole> localRoleList = dataAccessService.executeNamedQuery("getCurrentAppRoleFunctions",
2033 appRoleFuncParams, null);
2034 for (LocalRole localRole : localRoleList) {
2035 currentAppRoleFunctionsMap.put(localRole.getRolename().replaceAll(
2036 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), localRole);
2038 for (String addRole : roles) {
2039 currentRolesInExtSystem.put(addRole.substring(addRole.indexOf(FUNCTION_PIPE)+1), addRole);
2041 for (String extAuthrole : roles) {
2042 String roleNameSpace = extAuthrole.substring(0, extAuthrole.indexOf(FUNCTION_PIPE));
2043 boolean isNameSpaceMatching = EcompPortalUtils.checkNameSpaceMatching(roleNameSpace, app.getNameSpace());
2044 if (isNameSpaceMatching) {
2045 if (!currentAppRoleFunctionsMap
2046 .containsKey(extAuthrole.substring(app.getNameSpace().length() + 1))) {
2047 EPRole localAddFuntionRole = currentRolesInDB
2048 .get(extAuthrole.substring(app.getNameSpace().length() + 1));
2049 if (localAddFuntionRole == null) {
2050 checkAndAddRoleInDB(app, currentRolesInDB, roleFunctionList, extAuthrole);
2052 EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
2053 addAppRoleFunc.setAppId(app.getId());
2054 addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
2055 addAppRoleFunc.setRoleId(localAddFuntionRole.getId());
2056 dataAccessService.saveDomainObject(addAppRoleFunc, null);
2059 // This block is to save global role function if exists
2061 String extAuthAppRoleName = extAuthrole.substring(extAuthrole.indexOf(FUNCTION_PIPE) + 1);
2062 boolean checkIfGlobalRoleExists = existingPortalRolesMap.containsKey(extAuthAppRoleName);
2063 if (checkIfGlobalRoleExists) {
2064 final Map<String, Long> params = new HashMap<>();
2065 EPRole role = existingPortalRolesMap.get(extAuthAppRoleName);
2066 EPAppRoleFunction addGlobalRoleFunctions = new EPAppRoleFunction();
2067 params.put("appId", app.getId());
2068 params.put("roleId", role.getId());
2069 List<EPAppRoleFunction> currentGlobalRoleFunctionsList = dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", params, null);
2070 boolean checkIfRoleFunctionExists = currentGlobalRoleFunctionsList.stream().anyMatch(currentGlobalRoleFunction -> currentGlobalRoleFunction.getCode().equals(roleFunctionList.get(0).getCode()));
2071 if (role != null && !checkIfRoleFunctionExists) {
2072 addGlobalRoleFunctions.setAppId(app.getId());
2073 addGlobalRoleFunctions.setRoleId(role.getId());
2074 if (!app.getId().equals(role.getAppRoleId())) {
2075 addGlobalRoleFunctions.setRoleAppId((PortalConstants.PORTAL_APP_ID).toString());
2077 addGlobalRoleFunctions.setRoleAppId(null);
2079 addGlobalRoleFunctions.setCode(roleFunctionList.get(0).getCode());
2080 dataAccessService.saveDomainObject(addGlobalRoleFunctions, null);
2085 for (LocalRole localRoleDelete : localRoleList) {
2086 if (!currentRolesInExtSystem.containsKey(localRoleDelete.getRolename()
2087 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
2088 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
2089 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunctionList.get(0).getCode()
2090 + "'" + " and role_id = " + localRoleDelete.getRoleId().longValue(),
2097 private void deleteAppRoleFuncDoesNotExitsInExtSystem(EPApp app, CentralV2RoleFunction roleFunc) {
2098 logger.debug(EELFLoggerDelegate.debugLogger,
2099 "syncRoleFunctionFromExternalAccessSystem: Deleting app role function {}",
2100 roleFunc.getCode());
2101 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
2102 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() +"'", null);
2103 logger.debug(EELFLoggerDelegate.debugLogger,
2104 "syncRoleFunctionFromExternalAccessSystem: Deleted app role function {}",
2105 roleFunc.getCode());
2107 logger.debug(EELFLoggerDelegate.debugLogger,
2108 "syncRoleFunctionFromExternalAccessSystem: Deleting app function {}",
2109 roleFunc.getCode());
2110 dataAccessService.deleteDomainObjects(CentralV2RoleFunction.class,
2111 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() +"'", null);
2112 logger.debug(EELFLoggerDelegate.debugLogger,
2113 "syncRoleFunctionFromExternalAccessSystem: Deleted app function {}",
2114 roleFunc.getCode());
2117 private void checkAndAddRoleInDB(EPApp app, final Map<String, EPRole> currentRolesInDB,
2118 List<CentralV2RoleFunction> roleFunctionList, String roleList) throws Exception {
2119 if (!currentRolesInDB.containsKey(
2120 roleList.substring(app.getNameSpace().length() + 1))) {
2121 Role role = addRoleInDBIfDoesNotExists(app,
2122 roleList.substring(app.getNameSpace().length() + 1));
2123 addIfRoleDescriptionNotExitsInExtSystem(role, app);
2124 if (!roleFunctionList.isEmpty()) {
2126 if (!roleFunctionList.isEmpty()) {
2127 EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
2128 addAppRoleFunc.setAppId(app.getId());
2129 addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
2130 addAppRoleFunc.setRoleId(role.getId());
2131 dataAccessService.saveDomainObject(addAppRoleFunc, null);
2133 } catch (Exception e) {
2134 logger.error(EELFLoggerDelegate.errorLogger,
2135 "syncRoleFunctionFromExternalAccessSystem: Failed to save app role function ",
2142 @SuppressWarnings("unchecked")
2143 private List<CentralV2RoleFunction> addGetLocalFunction(EPApp app, final Map<String, CentralV2RoleFunction> roleFuncMap,
2144 ExternalAccessPermsDetail permsDetail, String code, CentralV2RoleFunction getFunctionCodeKey) {
2145 String finalFunctionCodeVal = addToLocalIfFunctionNotExists(app, roleFuncMap, permsDetail, code,
2146 getFunctionCodeKey);
2147 final Map<String, String> appSyncFuncsParams = new HashMap<>();
2148 appSyncFuncsParams.put("appId", String.valueOf(app.getId()));
2149 appSyncFuncsParams.put("functionCd", finalFunctionCodeVal);
2150 List<CentralV2RoleFunction> roleFunctionList = null;
2151 roleFunctionList = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams,
2153 if (roleFunctionList.isEmpty()) {
2154 appSyncFuncsParams.put("functionCd", code);
2155 roleFunctionList = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams,
2158 return roleFunctionList;
2161 private String addToLocalIfFunctionNotExists(EPApp app, final Map<String, CentralV2RoleFunction> roleFuncMap,
2162 ExternalAccessPermsDetail permsDetail, String code, CentralV2RoleFunction getFunctionCodeKey
2164 String finalFunctionCodeVal = "";
2165 if (null == getFunctionCodeKey) {
2166 finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetail.getInstance());
2167 CentralV2RoleFunction checkIfCodeStillExits = roleFuncMap.get(finalFunctionCodeVal);
2168 // If function does not exist in local then add!
2169 if (null == checkIfCodeStillExits) {
2170 logger.debug(EELFLoggerDelegate.debugLogger,
2171 "syncRoleFunctionFromExternalAccessSystem: Adding function: {} ", code);
2172 addFunctionInEcompDB(app, permsDetail, code);
2173 logger.debug(EELFLoggerDelegate.debugLogger,
2174 "syncRoleFunctionFromExternalAccessSystem: Finished adding function: {} ", code);
2177 return finalFunctionCodeVal;
2180 @SuppressWarnings("unchecked")
2182 public Map<String, EPRole> getCurrentRolesInDB(EPApp app) {
2183 final Map<String, EPRole> currentRolesInDB = new HashMap<>();
2184 List<EPRole> getCurrentRoleList = null;
2185 final Map<String, Long> appParams = new HashMap<>();
2186 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2187 getCurrentRoleList = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
2189 appParams.put("appId", app.getId());
2190 getCurrentRoleList = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
2192 for (EPRole role : getCurrentRoleList) {
2193 currentRolesInDB.put(role.getName()
2194 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), role);
2196 return currentRolesInDB;
2199 private List<ExternalAccessPermsDetail> getExtAuthPerrmissonList(EPApp app, JSONArray extPerms)
2201 ExternalAccessPermsDetail permDetails = null;
2202 List<ExternalAccessPermsDetail> permsDetailList = new ArrayList<>();
2203 for (int i = 0; i < extPerms.length(); i++) {
2204 String description = null;
2205 if (extPerms.getJSONObject(i).has("description")) {
2206 description = extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
2208 description = extPerms.getJSONObject(i).getString("instance");
2210 if (extPerms.getJSONObject(i).has("roles")) {
2211 ObjectMapper rolesListMapper = new ObjectMapper();
2212 JSONArray resRoles = extPerms.getJSONObject(i).getJSONArray("roles");
2213 List<String> list = rolesListMapper.readValue(resRoles.toString(),
2214 TypeFactory.defaultInstance().constructCollectionType(List.class, String.class));
2215 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
2216 extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
2217 + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
2218 + extPerms.getJSONObject(i).getString("action"),
2219 extPerms.getJSONObject(i).getString("action"), list, description);
2220 permsDetailList.add(permDetails);
2222 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
2223 extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
2224 + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
2225 + extPerms.getJSONObject(i).getString("action"),
2226 extPerms.getJSONObject(i).getString("action"), description);
2227 permsDetailList.add(permDetails);
2230 return permsDetailList;
2233 private JSONArray getExtAuthPermissions(EPApp app) throws Exception {
2234 ResponseEntity<String> response = null;
2235 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2236 HttpEntity<String> entity = new HttpEntity<>(headers);
2237 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: {} ",
2238 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2240 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
2241 + "perms/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
2243 String res = response.getBody();
2244 logger.debug(EELFLoggerDelegate.debugLogger,
2245 "syncRoleFunctionFromExternalAccessSystem: Finished GET permissions from External Auth system and response: {} ",
2246 response.getBody());
2247 JSONObject jsonObj = new JSONObject(res);
2248 JSONArray extPerms = jsonObj.getJSONArray("perm");
2249 for (int i = 0; i < extPerms.length(); i++) {
2250 if (extPerms.getJSONObject(i).getString("type").equals(app.getNameSpace() + ".access")) {
2260 * Add function into local DB
2263 * @param permsDetail
2266 private void addFunctionInEcompDB(EPApp app, ExternalAccessPermsDetail permsDetail, String code) {
2268 CentralV2RoleFunction addFunction = new CentralV2RoleFunction();
2269 addFunction.setAppId(app.getId());
2270 addFunction.setCode(code);
2271 addFunction.setName(permsDetail.getDescription());
2272 dataAccessService.saveDomainObject(addFunction, null);
2273 } catch(Exception e){
2274 logger.error(EELFLoggerDelegate.errorLogger, "addFunctionInEcompDB: Failed to add function", e);
2280 * It updates description of a role in external auth system
2286 private void addIfRoleDescriptionNotExitsInExtSystem(Role role, EPApp app) throws Exception {
2287 String addRoleNew = updateExistingRoleInExternalSystem(role, app);
2288 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2290 HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
2292 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
2293 HttpMethod.PUT, entity, String.class);
2294 } catch (HttpClientErrorException e) {
2295 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addIfRoleDescriptionNotExitsInExtSystem",
2297 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2298 } catch (Exception e) {
2299 logger.error(EELFLoggerDelegate.errorLogger, "addIfRoleDescriptionNotExitsInExtSystem: Failed",
2306 * While sync functions form external auth system if new role found we should add in local and return Role.class object
2312 @SuppressWarnings("unchecked")
2313 private Role addRoleInDBIfDoesNotExists(EPApp app, String role) {
2314 Role setNewRole = new Role();
2316 // functions can have new role created in External Auth System prevent
2318 boolean isCreated = checkIfRoleExitsElseCreateInSyncFunctions(role, app);
2319 final Map<String, String> getRoleByNameParams = new HashMap<>();
2320 List<EPRole> getRoleCreated = null;
2321 getRoleByNameParams.put(APP_ROLE_NAME_PARAM, role);
2322 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2323 getRoleByNameParams.put("appId", String.valueOf(app.getId()));
2324 List<EPRole> roleCreated = dataAccessService
2325 .executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, getRoleByNameParams, null);
2327 EPRole epUpdateRole = roleCreated.get(0);
2328 epUpdateRole.setAppRoleId(epUpdateRole.getId());
2329 dataAccessService.saveDomainObject(epUpdateRole, null);
2330 getRoleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
2331 getRoleByNameParams, null);
2333 getRoleCreated = roleCreated;
2336 getRoleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, getRoleByNameParams,
2339 if (getRoleCreated != null && !getRoleCreated.isEmpty()) {
2340 EPRole roleObject = getRoleCreated.get(0);
2341 setNewRole.setId(roleObject.getId());
2342 setNewRole.setName(roleObject.getName());
2343 setNewRole.setActive(roleObject.getActive());
2344 setNewRole.setPriority(roleObject.getPriority());
2346 } catch (Exception e) {
2347 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInDBIfDoesNotExists: Failed", e);
2352 @SuppressWarnings("unchecked")
2353 private boolean checkIfRoleExitsElseCreateInSyncFunctions(String role, EPApp app) {
2354 boolean isCreated = false;
2355 final Map<String, String> roleParams = new HashMap<>();
2356 roleParams.put(APP_ROLE_NAME_PARAM, role);
2357 List<EPRole> roleCreated = null;
2358 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2359 roleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams,
2362 roleParams.put("appId", String.valueOf(app.getId()));
2363 roleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams,
2366 if (roleCreated == null || roleCreated.isEmpty()) {
2367 roleParams.put("appId", String.valueOf(app.getId()));
2368 EPRole epRoleNew = new EPRole();
2369 epRoleNew.setActive(true);
2370 epRoleNew.setName(role);
2371 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2372 epRoleNew.setAppId(null);
2374 epRoleNew.setAppId(app.getId());
2376 dataAccessService.saveDomainObject(epRoleNew, null);
2385 @SuppressWarnings("unchecked")
2386 public Integer bulkUploadFunctions(String uebkey) throws Exception {
2387 EPApp app = getApp(uebkey).get(0);
2388 List<RoleFunction> roleFuncList = dataAccessService.executeNamedQuery("getAllFunctions", null, null);
2389 CentralV2RoleFunction cenRoleFunc = null;
2390 Integer functionsAdded = 0;
2392 for (RoleFunction roleFunc : roleFuncList) {
2393 cenRoleFunc = new CentralV2RoleFunction(roleFunc.getCode(), roleFunc.getName());
2394 addRoleFunctionInExternalSystem(cenRoleFunc, app);
2397 } catch(HttpClientErrorException e){
2398 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadFunctions failed", e);
2399 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2400 } catch (Exception e) {
2401 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions: failed", e.getMessage(), e);
2403 return functionsAdded;
2407 public Integer bulkUploadRoles(String uebkey) throws Exception {
2408 List<EPApp> app = getApp(uebkey);
2409 List<EPRole> roles = getAppRoles(app.get(0).getId());
2410 List<CentralV2Role> cenRoleList = new ArrayList<>();
2411 final Map<String, Long> params = new HashMap<>();
2412 Integer rolesListAdded = 0;
2414 cenRoleList = createCentralRoleObject(app, roles, cenRoleList, params);
2415 ObjectMapper mapper = new ObjectMapper();
2416 mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
2417 String roleList = mapper.writeValueAsString(cenRoleList);
2418 List<Role> roleObjectList = mapper.readValue(roleList,
2419 TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
2420 for (Role role : roleObjectList) {
2421 addRoleInExternalSystem(role, app.get(0));
2424 if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
2425 // Add Account Admin role in External AUTH System
2427 String addAccountAdminRole = "";
2428 ExternalAccessRole extRole = new ExternalAccessRole();
2429 extRole.setName(app.get(0).getNameSpace() + "." + PortalConstants.ADMIN_ROLE
2430 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2431 addAccountAdminRole = mapper.writeValueAsString(extRole);
2432 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2433 HttpEntity<String> entity = new HttpEntity<>(addAccountAdminRole, headers);
2435 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
2436 HttpMethod.POST, entity, String.class);
2438 } catch (HttpClientErrorException e) {
2439 logger.error(EELFLoggerDelegate.errorLogger,
2440 "HttpClientErrorException - Failed to create Account Admin role", e);
2441 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2442 } catch (Exception e) {
2443 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2444 logger.error(EELFLoggerDelegate.errorLogger,
2445 "bulkUploadRoles: Account Admin Role already exits but does not break functionality",
2448 logger.error(EELFLoggerDelegate.errorLogger,
2449 "bulkUploadRoles: Failed to create Account Admin role", e.getMessage());
2453 } catch (Exception e) {
2454 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles: failed", e);
2457 return rolesListAdded;
2461 * It creating new role in external auth system while doing bulk upload
2467 private void addRoleInExternalSystem(Role role, EPApp app) throws Exception {
2468 String addRoleNew = updateExistingRoleInExternalSystem(role, app);
2469 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2471 HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
2473 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
2474 HttpMethod.POST, entity, String.class);
2475 } catch(HttpClientErrorException e){
2476 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addRoleInExternalSystem", e);
2477 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2478 } catch (Exception e) {
2479 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2480 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInExternalSystem: Role already exits but does not break functionality", e);
2482 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInExternalSystem: Failed to addRoleInExternalSystem", e.getMessage());
2488 @SuppressWarnings("unchecked")
2489 public Integer bulkUploadRolesFunctions(String uebkey) throws Exception {
2490 EPApp app = getApp(uebkey).get(0);
2491 List<EPRole> roles = getAppRoles(app.getId());
2492 final Map<String, Long> params = new HashMap<>();
2493 Integer roleFunctions = 0;
2495 for (EPRole role : roles) {
2496 params.put("roleId", role.getId());
2497 List<BulkUploadRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("uploadAllRoleFunctions",
2499 if (!appRoleFunc.isEmpty()) {
2500 for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
2501 addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
2506 } catch(HttpClientErrorException e){
2507 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
2508 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2509 } catch (Exception e) {
2510 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
2512 return roleFunctions;
2516 * Its adding a role function while doing bulk upload
2518 * @param addRoleFunc
2522 private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, EPRole role, EPApp app) {
2524 String instance = "";
2526 if(addRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)){
2527 type = EcompPortalUtils.getFunctionType(addRoleFunc.getFunctionCd());
2528 instance = EcompPortalUtils.getFunctionCode(addRoleFunc.getFunctionCd());
2529 action = EcompPortalUtils.getFunctionAction(addRoleFunc.getFunctionCd());
2531 type = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
2532 instance = addRoleFunc.getFunctionCd();
2535 ExternalAccessRolePerms extRolePerms = null;
2536 ExternalAccessPerms extPerms = null;
2537 ObjectMapper mapper = new ObjectMapper();
2539 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2540 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, instance, action,
2541 addRoleFunc.getFunctionName());
2542 extRolePerms = new ExternalAccessRolePerms(extPerms,
2543 app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2544 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
2545 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
2547 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
2548 HttpMethod.POST, entity, String.class);
2549 } catch (Exception e) {
2550 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2551 logger.error(EELFLoggerDelegate.errorLogger,
2552 "addRoleFunctionsInExternalSystem: RoleFunction already exits but does not break functionality", e);
2554 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionsInExternalSystem: Failed to addRoleFunctionsInExternalSystem",
2560 @SuppressWarnings("unchecked")
2562 public Integer bulkUploadPartnerFunctions(String uebkey) throws Exception {
2563 EPApp app = getApp(uebkey).get(0);
2564 final Map<String, Long> params = new HashMap<>();
2565 params.put("appId", app.getId());
2566 List<CentralV2RoleFunction> roleFuncList = dataAccessService.executeNamedQuery("getPartnerAppFunctions", params,
2568 Integer functionsAdded = 0;
2570 for (CentralV2RoleFunction roleFunc : roleFuncList) {
2571 addFunctionInExternalSystem(roleFunc, app);
2574 } catch (HttpClientErrorException e) {
2575 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadPartnerFunctions failed", e);
2576 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2577 } catch (Exception e) {
2578 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerFunctions: failed", e.getMessage(), e);
2580 return functionsAdded;
2583 private void addFunctionInExternalSystem(CentralV2RoleFunction roleFunc, EPApp app) throws Exception {
2584 ObjectMapper mapper = new ObjectMapper();
2585 ExternalAccessPerms extPerms = new ExternalAccessPerms();
2586 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2588 String instance = "";
2590 if ((roleFunc.getCode().contains(FUNCTION_PIPE))
2591 || (roleFunc.getType() != null && roleFunc.getAction() != null)) {
2592 type = EcompPortalUtils.getFunctionType(roleFunc.getCode());
2593 instance = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
2594 action = EcompPortalUtils.getFunctionAction(roleFunc.getCode());
2596 type = roleFunc.getCode().contains("menu") ? "menu" : "url";
2597 instance = roleFunc.getCode();
2601 extPerms.setAction(action);
2602 extPerms.setInstance(instance);
2603 extPerms.setType(app.getNameSpace() + "." + type);
2604 extPerms.setDescription(roleFunc.getName());
2605 String addFunction = mapper.writeValueAsString(extPerms);
2606 HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
2607 logger.debug(EELFLoggerDelegate.debugLogger, "addFunctionInExternalSystem: {} for POST: {}",
2608 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
2609 ResponseEntity<String> addPermResponse = template.exchange(
2610 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
2611 HttpMethod.POST, entity, String.class);
2612 logger.debug(EELFLoggerDelegate.debugLogger,
2613 "addFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ",
2614 addPermResponse.getStatusCode().value(), addFunction);
2615 } catch (HttpClientErrorException e) {
2616 logger.error(EELFLoggerDelegate.errorLogger,
2617 "HttpClientErrorException - Failed to add function in external central auth system", e);
2618 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2620 } catch (Exception e) {
2621 logger.error(EELFLoggerDelegate.errorLogger,
2622 "addFunctionInExternalSystem: Failed to add fucntion in external central auth system", e);
2628 public void bulkUploadPartnerRoles(String uebkey, List<Role> roleList) throws Exception {
2629 EPApp app = getApp(uebkey).get(0);
2630 for (Role role : roleList) {
2631 addRoleInExternalSystem(role, app);
2635 @SuppressWarnings("unchecked")
2637 public Integer bulkUploadPartnerRoleFunctions(String uebkey) throws Exception {
2638 EPApp app = getApp(uebkey).get(0);
2639 List<EPRole> roles = getAppRoles(app.getId());
2640 final Map<String, Long> params = new HashMap<>();
2641 Integer roleFunctions = 0;
2643 for (EPRole role : roles) {
2644 params.put("roleId", role.getId());
2645 List<BulkUploadRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("uploadPartnerRoleFunctions",
2647 if (!appRoleFunc.isEmpty()) {
2648 for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
2649 addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
2654 // upload global role functions to ext auth system
2655 if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2656 roleFunctions = bulkUploadGlobalRoleFunctions(app, roleFunctions);
2658 } catch(HttpClientErrorException e){
2659 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
2660 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2661 } catch (Exception e) {
2662 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
2664 return roleFunctions;
2667 @SuppressWarnings("unchecked")
2668 private Integer bulkUploadGlobalRoleFunctions(EPApp app, Integer roleFunctions) throws Exception {
2670 EPApp portalApp = epAppService.getApp(1l);
2671 final Map<String, Long> params = new HashMap<>();
2672 params.put("appId", app.getId());
2673 List<GlobalRoleWithApplicationRoleFunction> globalRoleFuncs = dataAccessService
2674 .executeNamedQuery("getBulkUploadPartnerGlobalRoleFunctions", params, null);
2675 ObjectMapper mapper = new ObjectMapper();
2676 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2677 for (GlobalRoleWithApplicationRoleFunction globalRoleFunc : globalRoleFuncs) {
2678 ExternalAccessRolePerms extRolePerms;
2679 ExternalAccessPerms extPerms;
2681 String instance = "";
2683 if (globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
2684 type = EcompPortalUtils.getFunctionType(globalRoleFunc.getFunctionCd());
2685 instance = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd());
2686 action = EcompPortalUtils.getFunctionAction(globalRoleFunc.getFunctionCd());
2688 type = globalRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
2689 instance = globalRoleFunc.getFunctionCd();
2692 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, instance, action);
2693 extRolePerms = new ExternalAccessRolePerms(extPerms, portalApp.getNameSpace() + "." + globalRoleFunc.getRoleName()
2694 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2695 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
2696 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
2697 updateRoleFunctionInExternalSystem(updateRolePerms, entity);
2700 } catch (HttpClientErrorException e) {
2701 logger.error(EELFLoggerDelegate.errorLogger,
2702 "HttpClientErrorException - Failed to add role function in external central auth system", e);
2703 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2705 } catch (Exception e) {
2706 logger.error(EELFLoggerDelegate.errorLogger,
2707 "bulkUploadGlobalRoleFunctions: Failed to add role fucntion in external central auth system", e);
2710 return roleFunctions;
2715 public void syncApplicationRolesWithEcompDB(EPApp app) {
2717 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Started");
2718 //Sync functions and roles assigned to it which also creates new roles if does not exits in portal
2719 syncRoleFunctionFromExternalAccessSystem(app);
2720 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Finished");
2722 ObjectMapper mapper = new ObjectMapper();
2723 logger.debug(EELFLoggerDelegate.debugLogger, "Entering to getAppRolesJSONFromExtAuthSystem");
2724 // Get Permissions from External Auth System
2725 JSONArray extRole = getAppRolesJSONFromExtAuthSystem(app);
2727 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into getExternalRoleDetailsList");
2728 List<ExternalRoleDetails> externalRoleDetailsList = getExternalRoleDetailsList(app,
2731 List<EPRole> finalRoleList = new ArrayList<>();
2732 for (ExternalRoleDetails externalRole : externalRoleDetailsList) {
2733 EPRole ecompRole = convertExternalRoleDetailstoEpRole(externalRole);
2734 finalRoleList.add(ecompRole);
2737 List<EPRole> applicationRolesList;
2738 applicationRolesList = getAppRoles(app.getId());
2739 List<String> applicationRoleIdList = new ArrayList<>();
2740 for (EPRole applicationRole : applicationRolesList) {
2741 applicationRoleIdList.add(applicationRole.getName());
2744 List<EPRole> roleListToBeAddInEcompDB = new ArrayList<>();
2745 for (EPRole aafRole : finalRoleList) {
2746 if (!applicationRoleIdList.contains(aafRole.getName())) {
2747 roleListToBeAddInEcompDB.add(aafRole);
2751 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into inactiveRolesNotInExternalAuthSystem");
2752 // Check if roles exits in external Access system and if not make inactive in DB
2753 inactiveRolesNotInExternalAuthSystem(app, finalRoleList, applicationRolesList);
2755 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into checkAndUpdateRoleInDB");
2756 // It checks properties in the external auth system app role description and updates role in local
2757 checkAndUpdateRoleInDB(app, finalRoleList);
2759 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addNewRoleInEcompDBUpdateDescInExtAuthSystem");
2760 // Add new roles in DB and updates role description in External Auth System
2761 addNewRoleInEcompDBUpdateDescInExtAuthSystem(app, roleListToBeAddInEcompDB);
2762 logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: Finished");
2763 } catch (HttpClientErrorException e) {
2764 logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed due to the External Auth System", e);
2765 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2766 } catch (Exception e) {
2767 logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed ", e);
2773 * It adds new roles in DB and updates description in External Auth System
2776 * @param roleListToBeAddInEcompDB
2778 @SuppressWarnings("unchecked")
2779 private void addNewRoleInEcompDBUpdateDescInExtAuthSystem(EPApp app, List<EPRole> roleListToBeAddInEcompDB) {
2780 EPRole roleToBeAddedInEcompDB;
2781 for (int i = 0; i < roleListToBeAddInEcompDB.size(); i++) {
2783 roleToBeAddedInEcompDB = roleListToBeAddInEcompDB.get(i);
2784 if (app.getId() == 1) {
2785 roleToBeAddedInEcompDB.setAppRoleId(null);
2787 dataAccessService.saveDomainObject(roleToBeAddedInEcompDB, null);
2788 List<EPRole> getRoleCreatedInSync = null;
2789 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2790 final Map<String, String> globalRoleParams = new HashMap<>();
2791 globalRoleParams.put("appId", String.valueOf(app.getId()));
2792 globalRoleParams.put("appRoleName", roleToBeAddedInEcompDB.getName());
2793 getRoleCreatedInSync = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, globalRoleParams, null);
2794 EPRole epUpdateRole = getRoleCreatedInSync.get(0);
2795 epUpdateRole.setAppRoleId(epUpdateRole.getId());
2796 dataAccessService.saveDomainObject(epUpdateRole, null);
2798 List<EPRole> roleList = new ArrayList<>();
2799 final Map<String, String> params = new HashMap<>();
2801 params.put(APP_ROLE_NAME_PARAM, roleToBeAddedInEcompDB.getName());
2802 boolean isPortalRole = false;
2803 if (app.getId() == 1) {
2804 isPortalRole = true;
2805 roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, params, null);
2807 isPortalRole = false;
2808 params.put(APP_ID, app.getId().toString());
2809 roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, params, null);
2811 EPRole role = roleList.get(0);
2812 Role aaFrole = new Role();
2813 aaFrole.setId(role.getId());
2814 aaFrole.setActive(role.getActive());
2815 aaFrole.setPriority(role.getPriority());
2816 aaFrole.setName(role.getName());
2817 updateRoleInExternalSystem(aaFrole, app, isPortalRole);
2818 } catch (Exception e) {
2819 logger.error(EELFLoggerDelegate.errorLogger,
2820 "SyncApplicationRolesWithEcompDB: Failed to add or update role in external auth system", e);
2827 * It checks description in External Auth System if found any changes updates in DB
2830 * @param finalRoleList contains list of External Auth System roles list which is converted to EPRole
2832 @SuppressWarnings("unchecked")
2833 private void checkAndUpdateRoleInDB(EPApp app, List<EPRole> finalRoleList) {
2834 for (EPRole roleItem : finalRoleList) {
2835 final Map<String, String> roleParams = new HashMap<>();
2836 List<EPRole> currentList = null;
2837 roleParams.put(APP_ROLE_NAME_PARAM, roleItem.getName());
2838 if (app.getId() == 1) {
2839 currentList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, roleParams, null);
2841 roleParams.put(APP_ID, app.getId().toString());
2842 currentList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams, null);
2845 if (!currentList.isEmpty()) {
2847 Boolean aafRoleActive;
2848 Boolean localRoleActive;
2850 aafRoleActive = Boolean.valueOf(roleItem.getActive());
2851 localRoleActive = Boolean.valueOf(currentList.get(0).getActive());
2852 result = aafRoleActive.equals(localRoleActive);
2853 EPRole updateRole = currentList.get(0);
2856 updateRole.setActive(roleItem.getActive());
2857 dataAccessService.saveDomainObject(updateRole, null);
2859 if (roleItem.getPriority() != null
2860 && !currentList.get(0).getPriority().equals(roleItem.getPriority())) {
2861 updateRole.setPriority(roleItem.getPriority());
2862 dataAccessService.saveDomainObject(updateRole, null);
2864 } catch (Exception e) {
2865 logger.error(EELFLoggerDelegate.errorLogger,
2866 "syncApplicationRolesWithEcompDB: Failed to update role ", e);
2873 * It de-activates application roles in DB if not present in External Auth system
2876 * @param finalRoleList contains list of current roles present in External Auth System
2877 * @param applicationRolesList contains list of current roles present in DB
2879 @SuppressWarnings("unchecked")
2880 private void inactiveRolesNotInExternalAuthSystem(EPApp app, List<EPRole> finalRoleList,
2881 List<EPRole> applicationRolesList) {
2882 final Map<String, EPRole> checkRolesInactive = new HashMap<>();
2883 for (EPRole extrole : finalRoleList) {
2884 checkRolesInactive.put(extrole.getName(), extrole);
2886 for (EPRole role : applicationRolesList) {
2888 final Map<String, String> extRoleParams = new HashMap<>();
2889 List<EPRole> roleList = null;
2890 extRoleParams.put(APP_ROLE_NAME_PARAM, role.getName());
2891 if (!checkRolesInactive.containsKey(role.getName())) {
2892 if (app.getId() == 1) {
2893 roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, extRoleParams, null);
2895 extRoleParams.put(APP_ID, app.getId().toString());
2896 roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, extRoleParams, null);
2898 if(!roleList.isEmpty()) {
2899 EPRole updateRoleInactive = roleList.get(0);
2900 updateRoleInactive.setActive(false);
2901 dataAccessService.saveDomainObject(updateRoleInactive, null);
2904 } catch (Exception e) {
2905 logger.error(EELFLoggerDelegate.errorLogger,
2906 "syncApplicationRolesWithEcompDB: Failed to de-activate role ", e);
2912 @SuppressWarnings("unchecked")
2913 public List<ExternalRoleDetails> getExternalRoleDetailsList(EPApp app,
2914 ObjectMapper mapper, JSONArray extRole)
2915 throws IOException {
2916 List<ExternalRoleDetails> externalRoleDetailsList = new ArrayList<>();
2917 ExternalRoleDescription ApplicationRole = new ExternalRoleDescription();
2918 ExternalAccessPerms externalAccessPerms = new ExternalAccessPerms();
2919 List<String> functionCodelist = new ArrayList<>();
2920 for (int i = 0; i < extRole.length(); i++) {
2921 ExternalRoleDetails externalRoleDetail = new ExternalRoleDetails();
2922 EPAppRoleFunction ePAppRoleFunction = new EPAppRoleFunction();
2923 JSONObject Role = (JSONObject) extRole.get(i);
2924 if (!extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
2925 ApplicationRole.setActive("true");
2926 ApplicationRole.setAppId(IS_NULL_STRING);
2927 ApplicationRole.setPriority(IS_NULL_STRING);
2928 ApplicationRole.setAppRoleId(IS_NULL_STRING);
2929 String roleName = extRole.getJSONObject(i).getString(ROLE_NAME);
2930 ApplicationRole.setName(roleName.substring(app.getNameSpace().length() + 1));
2932 String desc = extRole.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
2933 ApplicationRole = mapper.readValue(desc, ExternalRoleDescription.class);
2936 SortedSet<ExternalAccessPerms> externalAccessPermsOfRole = new TreeSet<>();
2937 if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_PERMS)) {
2938 JSONArray extPerm = (JSONArray) Role.get(EXTERNAL_AUTH_PERMS);
2939 for (int j = 0; j < extPerm.length(); j++) {
2940 JSONObject perms = extPerm.getJSONObject(j);
2941 boolean isNamespaceMatching = EcompPortalUtils.checkNameSpaceMatching(perms.getString("type"), app.getNameSpace());
2942 if (isNamespaceMatching) {
2943 externalAccessPerms = new ExternalAccessPerms(perms.getString("type"),
2944 perms.getString("instance"), perms.getString("action"));
2945 ePAppRoleFunction.setCode(externalAccessPerms.getInstance());
2946 functionCodelist.add(ePAppRoleFunction.getCode());
2947 externalAccessPermsOfRole.add(externalAccessPerms);
2953 if (ApplicationRole.getActive().equals(IS_NULL_STRING)) {
2954 externalRoleDetail.setActive(false);
2956 externalRoleDetail.setActive(Boolean.parseBoolean(ApplicationRole.getActive()));
2958 externalRoleDetail.setName(ApplicationRole.getName());
2960 if (ApplicationRole.getAppId().equals(IS_NULL_STRING) && app.getId() == 1) {
2961 externalRoleDetail.setAppId(null);
2962 } else if (ApplicationRole.getAppId().equals(IS_NULL_STRING)) {
2963 externalRoleDetail.setAppId(app.getId());
2965 externalRoleDetail.setAppId(Long.parseLong(ApplicationRole.getAppId()));
2968 if (ApplicationRole.getPriority().equals(IS_NULL_STRING)) {
2969 externalRoleDetail.setPriority(null);
2971 externalRoleDetail.setPriority(Integer.parseInt(ApplicationRole.getPriority()));
2974 if (ApplicationRole.getAppRoleId().equals(IS_NULL_STRING) && app.getId() == 1) {
2975 externalRoleDetail.setAppRoleId(null);
2978 // get role functions from DB
2979 final Map<String, EPAppRoleFunction> roleFunctionsMap = new HashMap<>();
2980 if (!ApplicationRole.getId().equals(IS_NULL_STRING)) {
2981 final Map<String, Long> appRoleFuncsParams = new HashMap<>();
2982 appRoleFuncsParams.put("appId", app.getId());
2983 appRoleFuncsParams.put("roleId", Long.valueOf(ApplicationRole.getId()));
2984 List<EPAppRoleFunction> appRoleFunctions = dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null);
2985 if (!appRoleFunctions.isEmpty()) {
2986 for (EPAppRoleFunction roleFunc : appRoleFunctions) {
2987 roleFunctionsMap.put(roleFunc.getCode(), roleFunc);
2992 if (!externalAccessPermsOfRole.isEmpty()) {
2993 // Adding functions to role
2994 for (ExternalAccessPerms externalpermission : externalAccessPermsOfRole) {
2995 EPAppRoleFunction checkRoleFunctionExits = roleFunctionsMap.get(externalpermission.getInstance());
2996 if (checkRoleFunctionExits == null) {
2997 String funcCode = externalpermission.getType().substring(app.getNameSpace().length() + 1)
2998 + FUNCTION_PIPE + externalpermission.getInstance() + FUNCTION_PIPE
2999 + externalpermission.getAction();
3000 EPAppRoleFunction checkRoleFunctionPipeExits = roleFunctionsMap.get(funcCode);
3001 if (checkRoleFunctionPipeExits == null) {
3003 final Map<String, String> appFuncsParams = new HashMap<>();
3004 appFuncsParams.put("appId", String.valueOf(app.getId()));
3005 appFuncsParams.put("functionCd", externalpermission.getInstance());
3006 logger.debug(EELFLoggerDelegate.debugLogger,
3007 "SyncApplicationRolesWithEcompDB: Adding function to the role: {}",
3008 externalpermission.getInstance());
3009 List<CentralV2RoleFunction> roleFunction = null;
3010 roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appFuncsParams, null);
3011 if (roleFunction.isEmpty()) {
3012 appFuncsParams.put("functionCd", funcCode);
3013 roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appFuncsParams, null);
3015 if (!roleFunction.isEmpty()) {
3016 EPAppRoleFunction apRoleFunction = new EPAppRoleFunction();
3017 apRoleFunction.setAppId(app.getId());
3018 apRoleFunction.setRoleId(Long.parseLong(ApplicationRole.getId()));
3019 apRoleFunction.setCode(roleFunction.get(0).getCode());
3020 dataAccessService.saveDomainObject(apRoleFunction, null);
3022 } catch (Exception e) {
3023 logger.error(EELFLoggerDelegate.errorLogger,
3024 "SyncApplicationRolesWithEcompDB: Failed to add role function", e);
3030 externalRoleDetailsList.add(externalRoleDetail);
3032 return externalRoleDetailsList;
3036 public JSONArray getAppRolesJSONFromExtAuthSystem(EPApp app) throws Exception {
3037 ResponseEntity<String> response = null;
3038 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3039 HttpEntity<String> entity = new HttpEntity<>(headers);
3040 logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: {} ",
3041 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
3043 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
3044 + "roles/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
3045 String res = response.getBody();
3046 logger.debug(EELFLoggerDelegate.debugLogger,
3047 "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
3049 JSONObject jsonObj = new JSONObject(res);
3050 JSONArray extRole = jsonObj.getJSONArray("role");
3051 for (int i = 0; i < extRole.length(); i++) {
3052 if (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ADMIN)
3053 || extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + OWNER)
3054 || (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ACCOUNT_ADMINISTRATOR)
3055 && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
3064 public JSONArray getAllUsersByRole(String roleName) throws Exception{
3065 ResponseEntity<String> response = null;
3066 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3067 HttpEntity<String> entity = new HttpEntity<>(headers);
3068 logger.debug(EELFLoggerDelegate.debugLogger, "getAllUsersByRole: {} ",
3069 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
3071 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
3072 + "userRoles/role/" + roleName, HttpMethod.GET, entity, String.class);
3073 String res = response.getBody();
3074 logger.debug(EELFLoggerDelegate.debugLogger,
3075 "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
3077 JSONObject jsonObj = new JSONObject(res);
3078 JSONArray extRole = jsonObj.getJSONArray("userRole");
3085 * It converts from ExternalRoleDetails.class object to EPRole.class object
3087 * @param externalRoleDetails
3088 * @return EPRole object
3090 private EPRole convertExternalRoleDetailstoEpRole(ExternalRoleDetails externalRoleDetails) {
3091 EPRole role = new EPRole();
3092 role.setActive(externalRoleDetails.isActive());
3093 role.setAppId(externalRoleDetails.getAppId());
3094 role.setAppRoleId(externalRoleDetails.getAppRoleId());
3095 role.setName(externalRoleDetails.getName());
3096 role.setPriority(externalRoleDetails.getPriority());
3100 @SuppressWarnings("unchecked")
3102 public Integer bulkUploadUserRoles(String uebkey) throws Exception {
3103 EPApp app = getApp(uebkey).get(0);
3104 final Map<String, String> params = new HashMap<>();
3105 params.put("uebKey", app.getUebKey());
3106 List<BulkUploadUserRoles> userRolesList = null;
3107 Integer userRolesAdded = 0;
3108 if (app.getCentralAuth()) {
3109 userRolesList = dataAccessService.executeNamedQuery("getBulkUserRoles", params, null);
3110 for (BulkUploadUserRoles userRolesUpload : userRolesList) {
3111 if(!userRolesUpload.getOrgUserId().equals("su1234")){
3112 addUserRoleInExternalSystem(userRolesUpload);
3117 return userRolesAdded;
3121 * Its adding a user role in external auth system while doing bulk upload
3123 * @param userRolesUpload
3125 private void addUserRoleInExternalSystem(BulkUploadUserRoles userRolesUpload) {
3128 ObjectMapper mapper = new ObjectMapper();
3129 if (EPCommonSystemProperties
3130 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
3131 name = userRolesUpload.getOrgUserId()
3132 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
3134 ExternalAccessUser extUser = new ExternalAccessUser(name,
3135 userRolesUpload.getAppNameSpace() + "." + userRolesUpload.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
3136 String userRole = mapper.writeValueAsString(extUser);
3137 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3138 HttpEntity<String> entity = new HttpEntity<>(userRole, headers);
3140 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
3141 HttpMethod.POST, entity, String.class);
3142 } catch(HttpClientErrorException e){
3143 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addUserRoleInExternalSystem", e);
3144 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3145 } catch (Exception e) {
3146 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
3147 logger.error(EELFLoggerDelegate.errorLogger, "addUserRoleInExternalSystem: UserRole already exits but does not break functionality");
3149 logger.error(EELFLoggerDelegate.errorLogger, "addUserRoleInExternalSystem: Failed to addUserRoleInExternalSystem", e);
3155 public void deleteRoleDependencyRecords(Session localSession, Long roleId, Long appId, boolean isPortalRequest) throws Exception {
3160 //It should delete only when it portal's roleId
3161 if(appId.equals(PortalConstants.PORTAL_APP_ID)){
3162 // Delete from fn_role_function
3163 sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
3164 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3165 query = localSession.createSQLQuery(sql);
3166 query.executeUpdate();
3168 // Delete from fn_role_composite
3169 sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId;
3170 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3171 query = localSession.createSQLQuery(sql);
3172 query.executeUpdate();
3175 // Delete from ep_app_role_function
3176 sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId;
3177 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3178 query = localSession.createSQLQuery(sql);
3179 query.executeUpdate();
3181 // Delete from ep_role_notification
3182 sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
3183 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3184 query = localSession.createSQLQuery(sql);
3185 query.executeUpdate();
3187 // Delete from fn_user_pseudo_role
3188 sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
3189 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3190 query = localSession.createSQLQuery(sql);
3191 query.executeUpdate();
3193 // Delete form EP_WIDGET_CATALOG_ROLE
3194 sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId;
3195 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3196 query = localSession.createSQLQuery(sql);
3197 query.executeUpdate();
3199 // Delete form EP_WIDGET_CATALOG_ROLE
3200 sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId;
3201 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3202 query = localSession.createSQLQuery(sql);
3203 query.executeUpdate();
3205 if(!isPortalRequest) {
3206 // Delete form fn_menu_functional_roles
3207 sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
3208 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3209 query = localSession.createSQLQuery(sql);
3210 query.executeUpdate();
3212 } catch (Exception e) {
3213 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e);
3214 throw new DeleteDomainObjectFailedException("delete Failed" + e.getMessage());
3219 @SuppressWarnings("unchecked")
3221 public List<String> getMenuFunctionsList(String uebkey) throws Exception {
3222 List<String> appMenuFunctionsList = null;
3223 List<String> appMenuFunctionsFinalList = new ArrayList<>();
3225 EPApp app = getApp(uebkey).get(0);
3226 final Map<String, Long> appParams = new HashMap<>();
3227 appParams.put(APP_ID, app.getId());
3228 appMenuFunctionsList = dataAccessService.executeNamedQuery("getMenuFunctions", appParams, null);
3229 for(String appMenuFunction : appMenuFunctionsList) {
3230 if(appMenuFunction.contains(FUNCTION_PIPE)) {
3231 appMenuFunctionsFinalList.add(EcompPortalUtils.getFunctionCode(appMenuFunction));
3233 appMenuFunctionsFinalList.add(appMenuFunction);
3236 } catch (Exception e) {
3237 logger.error(EELFLoggerDelegate.errorLogger, "getMenuFunctionsList: Failed", e);
3238 return appMenuFunctionsFinalList;
3240 return appMenuFunctionsFinalList;
3243 @SuppressWarnings({ "unchecked"})
3245 public List<EcompUser> getAllAppUsers(String uebkey) throws Exception {
3246 List<String> usersList = new ArrayList<>();
3247 List<EcompUser> usersfinalList = new ArrayList<>();
3249 EPApp app = getApp(uebkey).get(0);
3250 final Map<String, Long> appParams = new HashMap<>();
3251 appParams.put("appId", app.getId());
3252 List<EcompUserRoles> userList = (List<EcompUserRoles>) dataAccessService
3253 .executeNamedQuery("ApplicationUserRoles", appParams, null);
3254 for (EcompUserRoles ecompUserRole : userList) {
3255 boolean found = false;
3256 Set<EcompRole> roles = null;
3257 for (EcompUser user : usersfinalList) {
3258 if (user.getOrgUserId().equals(ecompUserRole.getOrgUserId())) {
3259 EcompRole ecompRole = new EcompRole();
3260 ecompRole.setId(ecompUserRole.getRoleId());
3261 ecompRole.setName(ecompUserRole.getRoleName());
3262 roles = user.getRoles();
3263 EcompRole role = roles.stream().filter(x -> x.getName().equals(ecompUserRole.getRoleName())).findAny()
3265 SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
3268 roleFunctionSet = (SortedSet<EcompRoleFunction>) role.getRoleFunctions();
3271 String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
3272 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
3273 EcompRoleFunction epRoleFunction = new EcompRoleFunction();
3274 epRoleFunction.setName(ecompUserRole.getFunctionName());
3275 epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
3276 epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
3277 epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
3278 roleFunctionSet.add(epRoleFunction);
3279 ecompRole.setRoleFunctions(roleFunctionSet);
3280 roles.add(ecompRole);
3281 user.setRoles(roles);
3288 EcompUser epUser = new EcompUser();
3289 epUser.setOrgId(ecompUserRole.getOrgId());
3290 epUser.setManagerId(ecompUserRole.getManagerId());
3291 epUser.setFirstName(ecompUserRole.getFirstName());
3292 epUser.setLastName(ecompUserRole.getLastName());
3293 epUser.setPhone(ecompUserRole.getPhone());
3294 epUser.setEmail(ecompUserRole.getEmail());
3295 epUser.setOrgUserId(ecompUserRole.getOrgUserId());
3296 epUser.setOrgCode(ecompUserRole.getOrgCode());
3297 epUser.setOrgManagerUserId(ecompUserRole.getOrgManagerUserId());
3298 epUser.setJobTitle(ecompUserRole.getJobTitle());
3299 epUser.setLoginId(ecompUserRole.getLoginId());
3300 epUser.setActive(true);
3301 roles = new HashSet<>();
3302 EcompRole ecompRole = new EcompRole();
3303 ecompRole.setId(ecompUserRole.getRoleId());
3304 ecompRole.setName(ecompUserRole.getRoleName());
3305 SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
3307 String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
3308 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
3309 EcompRoleFunction epRoleFunction = new EcompRoleFunction();
3310 epRoleFunction.setName(ecompUserRole.getFunctionName());
3311 epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
3312 epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
3313 epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
3314 roleFunctionSet.add(epRoleFunction);
3315 ecompRole.setRoleFunctions(roleFunctionSet);
3316 roles.add(ecompRole);
3317 epUser.setRoles(roles);
3318 usersfinalList.add(epUser);
3321 ObjectMapper mapper = new ObjectMapper();
3323 for (EcompUser u1 : usersfinalList) {
3324 String str = mapper.writeValueAsString(u1);
3327 } catch (Exception e) {
3328 logger.error(EELFLoggerDelegate.errorLogger, "getAllUsers failed", e);
3331 return usersfinalList;
3337 public Role ConvertCentralRoleToRole(String result) {
3338 ObjectMapper mapper = new ObjectMapper();
3339 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
3340 Role newRole = new Role();
3342 newRole = mapper.readValue(result, Role.class);
3343 } catch (IOException e) {
3344 logger.error(EELFLoggerDelegate.errorLogger, "Failed to convert the result to Role Object", e);
3346 if (newRole.getRoleFunctions() != null) {
3347 @SuppressWarnings("unchecked")
3348 Set<RoleFunction> roleFunctionList = newRole.getRoleFunctions();
3349 Set<RoleFunction> roleFunctionListNew = new HashSet<>();
3350 Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
3351 while (itetaror.hasNext()) {
3352 Object nextValue = itetaror.next();
3353 RoleFunction roleFun = mapper.convertValue(nextValue, RoleFunction.class);
3354 roleFunctionListNew.add(roleFun);
3356 newRole.setRoleFunctions(roleFunctionListNew);
3362 @SuppressWarnings("unchecked")
3363 public List<CentralizedApp> getCentralizedAppsOfUser(String userId) {
3364 Map<String, String> params = new HashMap<>();
3365 params.put("userId", userId);
3366 List<CentralizedApp> centralizedAppsList = new ArrayList<>();
3368 centralizedAppsList = dataAccessService
3369 .executeNamedQuery("getCentralizedAppsOfUser", params, null);
3370 }catch (Exception e) {
3371 logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
3373 return centralizedAppsList;
3376 @SuppressWarnings("unchecked")
3377 public List<CentralV2Role> getGlobalRolesOfApplication(Long appId) {
3378 Map<String, Long> params = new HashMap<>();
3379 params.put("appId", appId);
3380 List<GlobalRoleWithApplicationRoleFunction> globalRoles = new ArrayList<>();
3382 globalRoles = dataAccessService.executeNamedQuery("getGlobalRoleWithApplicationRoleFunctions", params,
3384 } catch (Exception e) {
3385 logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
3387 List<CentralV2Role> rolesfinalList = new ArrayList<>();
3388 if (globalRoles.size() > 0)
3389 rolesfinalList = finalListOfCentralRoles(globalRoles);
3390 return rolesfinalList;
3393 @SuppressWarnings("unchecked")
3394 private CentralV2Role getGlobalRoleForRequestedApp(long requestedAppId, long roleId) {
3395 CentralV2Role finalGlobalrole = null;
3396 List<GlobalRoleWithApplicationRoleFunction> roleWithApplicationRoleFucntions = new ArrayList<>();
3397 Map<String, Long> params = new HashMap<>();
3398 params.put("roleId", roleId);
3399 params.put("requestedAppId", requestedAppId);
3401 roleWithApplicationRoleFucntions = dataAccessService.executeNamedQuery("getGlobalRoleForRequestedApp",
3403 } catch (Exception e) {
3404 logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRoleForRequestedApp failed", e);
3406 if (roleWithApplicationRoleFucntions.size() > 0) {
3407 List<CentralV2Role> rolesfinalList = finalListOfCentralRoles(roleWithApplicationRoleFucntions);
3408 finalGlobalrole = rolesfinalList.get(0);
3410 List<EPRole> roleList = getPortalAppRoleInfo(roleId);
3411 finalGlobalrole = convertRoleToCentralV2Role(roleList.get(0));
3413 return finalGlobalrole;
3416 private List<CentralV2Role> finalListOfCentralRoles(List<GlobalRoleWithApplicationRoleFunction> globalRoles) {
3417 List<CentralV2Role> rolesfinalList = new ArrayList<>();
3418 for (GlobalRoleWithApplicationRoleFunction role : globalRoles) {
3419 boolean found = false;
3420 for (CentralV2Role cenRole : rolesfinalList) {
3421 if (role.getRoleId().equals(cenRole.getId())) {
3422 SortedSet<CentralV2RoleFunction> roleFunctions = cenRole.getRoleFunctions();
3423 CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
3424 roleFunctions.add(cenRoleFun);
3425 cenRole.setRoleFunctions(roleFunctions);
3431 CentralV2Role cenrole = new CentralV2Role();
3432 cenrole.setName(role.getRoleName());
3433 cenrole.setId(role.getRoleId());
3434 cenrole.setActive(role.isActive());
3435 cenrole.setPriority(role.getPriority());
3436 SortedSet<CentralV2RoleFunction> roleFunctions = new TreeSet<>();
3437 CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
3438 roleFunctions.add(cenRoleFun);
3439 cenrole.setRoleFunctions(roleFunctions);
3440 rolesfinalList.add(cenrole);
3443 return rolesfinalList;
3446 private CentralV2RoleFunction createCentralRoleFunctionForGlobalRole(GlobalRoleWithApplicationRoleFunction role) {
3450 CentralV2RoleFunction cenRoleFun;
3451 if(role.getFunctionCd().contains(FUNCTION_PIPE)){
3452 instance = EcompPortalUtils.getFunctionCode(role.getFunctionCd());
3453 type = EcompPortalUtils.getFunctionType(role.getFunctionCd());
3454 action = EcompPortalUtils.getFunctionAction(role.getFunctionCd());
3455 cenRoleFun = new CentralV2RoleFunction(null, instance, role.getFunctionName(), null, type, action, null);
3457 type = getFunctionCodeType(role.getFunctionCd());
3458 action = getFunctionCodeAction(role.getFunctionCd());
3459 cenRoleFun = new CentralV2RoleFunction(null, role.getFunctionCd(), role.getFunctionName(), null, type, action, null);
3464 @SuppressWarnings("unchecked")
3466 public List<EPRole> getGlobalRolesOfPortal() {
3467 List<EPRole> globalRoles = new ArrayList<>();
3469 globalRoles = dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null);
3470 } catch (Exception e) {
3471 logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRolesOfPortal failed", e);
3476 private CentralV2Role convertRoleToCentralV2Role(EPRole role) {
3477 return new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
3478 role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
3479 new TreeSet<>(), new TreeSet<>(), new TreeSet<>());
3484 public List<CentralRoleFunction> convertCentralRoleFunctionToRoleFunctionObject(List<CentralV2RoleFunction> answer) {
3485 List<CentralRoleFunction> addRoleFuncList = new ArrayList<>();
3486 for(CentralV2RoleFunction cenRoleFunc : answer){
3487 CentralRoleFunction setRoleFunc = new CentralRoleFunction();
3488 setRoleFunc.setCode(cenRoleFunc.getCode());
3489 setRoleFunc.setName(cenRoleFunc.getName());
3490 addRoleFuncList.add(setRoleFunc);
3492 return addRoleFuncList;
3496 public CentralUser getUserRoles(String loginId, String uebkey) throws Exception {
3497 CentralUser sendUserRoles = null;
3500 CentralV2User cenV2User = getV2UserAppRoles(loginId, uebkey);
3501 sendUserRoles = convertV2UserRolesToOlderVersion(cenV2User);
3502 } catch (Exception e) {
3503 logger.error(EELFLoggerDelegate.errorLogger, "getUserRoles: failed", e);
3506 return sendUserRoles;
3511 * It returns V2 CentralUser object if user has any roles and permissions
3515 * @return CentralUser object
3518 private CentralV2User getV2UserAppRoles(String loginId, String uebkey) throws Exception {
3520 List<EPUser> epUserList;
3521 List<EPApp> appList = getApp(uebkey);
3522 app = appList.get(0);
3523 epUserList = getUser(loginId);
3524 EPUser user = epUserList.get(0);
3525 Set<EPUserApp> userAppSet = user.getEPUserApps();
3526 return createEPUser(user, userAppSet, app);
3530 * It converts V2 CentralUser object to old version CentralUser object
3533 * @return EPUser object
3535 private CentralUser convertV2UserRolesToOlderVersion(CentralV2User cenV2User) {
3536 Set<CentralV2UserApp> userV2Apps = cenV2User.getUserApps();
3537 Set<CentralUserApp> userApps = new TreeSet<>();
3538 for(CentralV2UserApp userApp : userV2Apps){
3539 CentralApp app = userApp.getApp();
3540 CentralUserApp cua = new CentralUserApp();
3541 cua.setUserId(null);
3543 SortedSet<CentralRoleFunction> cenRoleFunction = new TreeSet<>();
3544 for(CentralV2RoleFunction cenV2RoleFunc : userApp.getRole().getRoleFunctions() ){
3545 CentralRoleFunction cenRoleFunc = new CentralRoleFunction(cenV2RoleFunc.getCode(), cenV2RoleFunc.getName());
3546 cenRoleFunction.add(cenRoleFunc);
3548 CentralRole role = new CentralRole(userApp.getRole().getId(), userApp.getRole().getName(), userApp.getRole().getActive(), userApp.getRole().getPriority(),
3553 return new CentralUser(cenV2User.getId(), cenV2User.getCreated(), cenV2User.getModified(),
3554 cenV2User.getCreatedId(),cenV2User.getModifiedId(),
3555 cenV2User.getRowNum(), cenV2User.getOrgId(), cenV2User.getManagerId(), cenV2User.getFirstName(),
3556 cenV2User.getMiddleInitial(), cenV2User.getLastName(), cenV2User.getPhone(), cenV2User.getFax(),
3557 cenV2User.getCellular(),cenV2User.getEmail(),cenV2User.getAddressId(),cenV2User.getAlertMethodCd(),
3558 cenV2User.getHrid(),cenV2User.getOrgUserId(),cenV2User.getOrgCode(),cenV2User.getAddress1(),
3559 cenV2User.getAddress2(),cenV2User.getCity(),cenV2User.getState(),cenV2User.getZipCode(),cenV2User.getCountry(),
3560 cenV2User.getOrgManagerUserId(),cenV2User.getLocationClli(),cenV2User.getBusinessCountryCode(),
3561 cenV2User.getBusinessCountryName(),cenV2User.getBusinessUnit(),cenV2User.getBusinessUnitName(),
3562 cenV2User.getDepartment(),cenV2User.getDepartmentName(),cenV2User.getCompanyCode(),
3563 cenV2User.getCompany(),cenV2User.getZipCodeSuffix(),cenV2User.getJobTitle(),
3564 cenV2User.getCommandChain(),cenV2User.getSiloStatus(),cenV2User.getCostCenter(),
3565 cenV2User.getFinancialLocCode(),cenV2User.getLoginId(),cenV2User.getLoginPwd(),
3566 cenV2User.getLastLoginDate(),cenV2User.isActive(),cenV2User.isInternal(),cenV2User.getSelectedProfileId(),cenV2User.getTimeZoneId(),
3567 cenV2User.isOnline(),cenV2User.getChatId(),
3572 public List<CentralRole> convertV2CentralRoleListToOldVerisonCentralRoleList(List<CentralV2Role> v2CenRoleList) {
3573 List<CentralRole> cenRoleList = new ArrayList<>();
3574 for(CentralV2Role v2CenRole : v2CenRoleList){
3575 SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
3576 for(CentralV2RoleFunction v2CenRoleFunc: v2CenRole.getRoleFunctions()){
3577 CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName());
3578 cenRoleFuncList.add(roleFunc);
3580 CentralRole role = new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.getActive(), v2CenRole.getPriority(), cenRoleFuncList);
3581 cenRoleList.add(role);
3587 public ResponseEntity<String> getNameSpaceIfExists(EPApp app) throws Exception {
3588 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3589 HttpEntity<String> entity = new HttpEntity<>(headers);
3590 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Connecting to External Auth system");
3591 ResponseEntity<String> response = null;
3594 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
3595 + "nss/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
3596 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Finished ",
3597 response.getStatusCode().value());
3598 } catch (HttpClientErrorException e) {
3599 logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e);
3600 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3601 if (e.getStatusCode() == HttpStatus.NOT_FOUND)
3602 throw new InvalidApplicationException("Invalid NameSpace");
3610 public CentralRole convertV2CentralRoleToOldVerisonCentralRole(CentralV2Role v2CenRole) {
3611 SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
3612 for (CentralV2RoleFunction v2CenRoleFunc : v2CenRole.getRoleFunctions()) {
3613 CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName());
3614 cenRoleFuncList.add(roleFunc);
3616 return new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.getActive(), v2CenRole.getPriority(),
3620 @SuppressWarnings("unchecked")
3622 public Integer bulkUploadUsersSingleRole(String uebkey, Long roleId, String modifiedRoleName) throws Exception {
3623 EPApp app = getApp(uebkey).get(0);
3624 final Map<String, String> params = new HashMap<>();
3625 params.put("uebKey", app.getUebKey());
3626 params.put("roleId", String.valueOf(roleId));
3627 List<BulkUploadUserRoles> userRolesList = null;
3628 Integer userRolesAdded = 0;
3629 if (app.getCentralAuth()) {
3630 userRolesList = dataAccessService.executeNamedQuery("getBulkUsersForSingleRole", params, null);
3631 for (BulkUploadUserRoles userRolesUpload : userRolesList) {
3632 userRolesUpload.setRoleName(modifiedRoleName);
3633 if(!userRolesUpload.getOrgUserId().equals("su1234")){
3634 addUserRoleInExternalSystem(userRolesUpload);
3639 return userRolesAdded;
3643 public String encodeFunctionCode(String funCode){
3644 String encodedString = funCode;
3645 List<Pattern> encodingList = new ArrayList<>();
3646 encodingList.add(Pattern.compile("/"));
3647 encodingList.add(Pattern.compile("-"));
3648 for (Pattern xssInputPattern : encodingList) {
3649 encodedString = xssInputPattern.matcher(encodedString)
3650 .replaceAll("%" + Hex.encodeHexString(xssInputPattern.toString().getBytes()));
3652 encodedString = encodedString.replaceAll("\\*", "%"+ Hex.encodeHexString("*".getBytes()));
3653 return encodedString;
3657 public void bulkUploadRoleFunc(UploadRoleFunctionExtSystem data, EPApp app) throws Exception {
3658 ObjectMapper mapper = new ObjectMapper();
3659 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3661 ExternalAccessRolePerms extRolePerms;
3662 ExternalAccessPerms extPerms;
3663 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + data.getType(), encodeFunctionCode(data.getInstance()), data.getAction());
3664 String appNameSpace = "";
3665 if(data.getIsGlobalRolePartnerFunc()) {
3666 appNameSpace = epAppService.getApp(1l).getNameSpace();
3668 appNameSpace = app.getNameSpace();
3670 extRolePerms = new ExternalAccessRolePerms(extPerms,
3672 + data.getRoleName().replaceAll(
3673 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
3675 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
3676 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
3677 updateRoleFunctionInExternalSystem(updateRolePerms, entity);
3678 } catch (HttpClientErrorException e) {
3679 logger.error(EELFLoggerDelegate.errorLogger,
3680 "HttpClientErrorException - Failed to add role function in external central auth system", e);
3681 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3683 } catch (Exception e) {
3684 logger.error(EELFLoggerDelegate.errorLogger,
3685 "addFunctionInExternalSystem: Failed to add role fucntion in external central auth system", e);
3691 private void updateRoleFunctionInExternalSystem(String updateRolePerms, HttpEntity<String> entity) {
3692 logger.debug(EELFLoggerDelegate.debugLogger, "bulkUploadRoleFunc: {} for POST: {}",
3693 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
3694 ResponseEntity<String> addPermResponse = template.exchange(
3695 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
3696 HttpMethod.POST, entity, String.class);
3697 logger.debug(EELFLoggerDelegate.debugLogger,
3698 "bulkUploadRoleFunc: Finished adding permission for POST: {} and status code: {} ",
3699 addPermResponse.getStatusCode().value(), updateRolePerms);
3703 public void syncApplicationUserRolesFromExtAuthSystem(String loginId) throws Exception {
3705 if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
3706 name = loginId + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
3708 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3709 HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
3710 ResponseEntity<String> getResponse = getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
3711 List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
3712 String res = getResponse.getBody();
3713 JSONObject jsonObj = null;
3714 JSONArray extRoles = null;
3715 if (!res.equals("{}")) {
3716 jsonObj = new JSONObject(res);
3717 extRoles = jsonObj.getJSONArray("role");
3719 updateUserRolesInLocal(userRoleDetailList, extRoles, loginId);
3722 @SuppressWarnings("unchecked")
3723 private void updateUserRolesInLocal(List<ExternalAccessUserRoleDetail> userRoleDetailList, JSONArray extRoles,
3724 String loginId) throws InvalidUserException {
3725 HashMap<String, String> userParams = new HashMap<>();
3726 userParams.put("orgUserId", loginId);
3727 // Get all centralized applications existing user roles from local
3728 List<CentralizedAppRoles> currentUserAppRoles = dataAccessService
3729 .executeNamedQuery("getUserCentralizedAppRoles", userParams, null);
3730 EPUser user = getUser(loginId).get(0);
3731 // Get all centralized applications roles from local
3732 HashMap<String, CentralizedAppRoles> cenAppRolesMap = getCentralizedAppRoleList();
3733 HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap = getCurrentUserCentralizedAppRoles(
3734 currentUserAppRoles);
3735 // Get all centralized applications + admin role from local
3736 HashMap<String, EPApp> centralisedAppsMap = getCentralizedAdminAppsInfo();
3737 if (extRoles != null) {
3738 ExternalAccessUserRoleDetail userRoleDetail = null;
3739 for (int i = 0; i < extRoles.length(); i++) {
3740 if (!extRoles.getJSONObject(i).getString("name").endsWith(ADMIN)
3741 && !extRoles.getJSONObject(i).getString("name").endsWith(OWNER)) {
3742 userRoleDetail = new ExternalAccessUserRoleDetail(extRoles.getJSONObject(i).getString("name"),
3744 userRoleDetailList.add(userRoleDetail);
3747 addUserRolesInLocal(userRoleDetailList, user, cenAppRolesMap, currentCentralizedUserAppRolesMap,
3748 centralisedAppsMap);
3752 private void addUserRolesInLocal(List<ExternalAccessUserRoleDetail> userRoleDetailList, EPUser user,
3753 HashMap<String, CentralizedAppRoles> cenAppRolesMap,
3754 HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap,
3755 HashMap<String, EPApp> centralisedAppsMap) {
3756 for (ExternalAccessUserRoleDetail extUserRoleDetail : userRoleDetailList) {
3758 // check if user already has role in local
3759 if (!currentCentralizedUserAppRolesMap.containsKey(extUserRoleDetail.getName())) {
3760 CentralizedAppRoles getCenAppRole = cenAppRolesMap.get(extUserRoleDetail.getName());
3761 if (getCenAppRole != null) {
3762 logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Adding user role from external auth system {}",
3763 extUserRoleDetail.toString());
3764 EPUserApp userApp = new EPUserApp();
3765 EPApp app = new EPApp();
3766 app.setId(getCenAppRole.getAppId());
3767 EPRole epRole = new EPRole();
3768 epRole.setId(getCenAppRole.getRoleId());
3769 userApp.setApp(app);
3770 userApp.setUserId(user.getId());
3771 userApp.setRole(epRole);
3772 dataAccessService.saveDomainObject(userApp, null);
3773 logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Finished user role from external auth system {}",
3774 extUserRoleDetail.toString());
3775 } else if (getCenAppRole == null // check if user has app account admin role
3776 && extUserRoleDetail.getName().endsWith(PortalConstants.ADMIN_ROLE.replaceAll(
3777 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
3778 EPApp app = centralisedAppsMap.get(extUserRoleDetail.getName());
3780 logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Adding user role from external auth system {}",
3781 extUserRoleDetail.toString());
3782 EPUserApp userApp = new EPUserApp();
3783 EPRole epRole = new EPRole();
3784 epRole.setId(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
3785 userApp.setApp(app);
3786 userApp.setUserId(user.getId());
3787 userApp.setRole(epRole);
3788 dataAccessService.saveDomainObject(userApp, null);
3789 logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Finished user role from external auth system {}",
3790 extUserRoleDetail.toString());
3794 } catch (Exception e) {
3795 logger.error(EELFLoggerDelegate.errorLogger,
3796 "addUserRolesInLocal - Failed to update user role in local from external auth system {} ",
3797 extUserRoleDetail.toString(), e);
3802 @SuppressWarnings("unchecked")
3803 private HashMap<String, EPApp> getCentralizedAdminAppsInfo() {
3804 List<EPApp> centralizedApps = dataAccessService
3805 .executeNamedQuery("getCentralizedApps", null, null);
3806 HashMap<String, EPApp> centralisedAppsMap = new HashMap<>();
3807 for (EPApp cenApp : centralizedApps) {
3808 centralisedAppsMap.put(cenApp.getNameSpace()+ "." +
3809 PortalConstants.ADMIN_ROLE.replaceAll(
3810 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), cenApp);
3812 return centralisedAppsMap;
3815 private HashMap<String, CentralizedAppRoles> getCurrentUserCentralizedAppRoles(
3816 List<CentralizedAppRoles> currentUserAppRoles) {
3817 HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap = new HashMap<>();
3818 for (CentralizedAppRoles cenAppUserRole : currentUserAppRoles) {
3819 currentCentralizedUserAppRolesMap.put(
3820 cenAppUserRole.getAppNameSpace() + "." + cenAppUserRole.getRoleName()
3821 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
3824 return currentCentralizedUserAppRolesMap;
3827 @SuppressWarnings("unchecked")
3828 private HashMap<String, CentralizedAppRoles> getCentralizedAppRoleList() {
3829 List<CentralizedAppRoles> centralizedAppRoles = dataAccessService
3830 .executeNamedQuery("getAllCentralizedAppsRoles", null, null);
3831 HashMap<String, CentralizedAppRoles> cenAppRolesMap = new HashMap<>();
3832 for (CentralizedAppRoles CentralizedAppRole : centralizedAppRoles) {
3834 CentralizedAppRole.getAppNameSpace() + "." + CentralizedAppRole.getRoleName()
3835 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
3836 CentralizedAppRole);
3838 return cenAppRolesMap;
3842 public ResponseEntity<String> getUserRolesFromExtAuthSystem(String name, HttpEntity<String> getUserRolesEntity) {
3843 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles");
3844 ResponseEntity<String> getResponse = template
3845 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
3846 + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class);
3847 if (getResponse.getStatusCode().value() == 200) {
3848 logger.debug(EELFLoggerDelegate.debugLogger, "getAllUserRoleFromExtAuthSystem: Finished GET user roles from external system and received user roles {}",
3849 getResponse.getBody());
3852 logger.error(EELFLoggerDelegate.errorLogger, "getAllUserRoleFromExtAuthSystem: Failed GET user roles from external system and received user roles {}",getResponse.getBody() );
3853 EPLogUtil.logExternalAuthAccessAlarm(logger, getResponse.getStatusCode());