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 extRole.setName(app.getNameSpace() + "." + addRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
871 extRole.setDescription(String.valueOf(addRole.getName()));
872 addNewRole = mapper.writeValueAsString(extRole);
877 * It create a role in the external auth system and then in our local
881 * @return true else false
884 @SuppressWarnings("unchecked")
885 @Transactional(rollbackFor = Exception.class)
886 public boolean addRoleInEcompDB(Role addRoleInDB, EPApp app) throws Exception {
887 boolean result = false;
888 EPRole epRole = null;
889 Set<RoleFunction> roleFunctionList = addRoleInDB.getRoleFunctions();
890 List<RoleFunction> roleFunctionListNew = new ArrayList<>();
891 ObjectMapper mapper = new ObjectMapper();
892 Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
893 while (itetaror.hasNext()) {
894 Object nextValue = itetaror.next();
895 RoleFunction roleFunction = mapper.convertValue(nextValue, RoleFunction.class);
896 roleFunctionListNew.add(roleFunction);
898 List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct().collect(Collectors.toList());
900 if (addRoleInDB.getId() == null) { // check if it is new role
901 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
902 checkIfRoleExitsInExternalSystem(addRoleInDB, app);
904 EPRole epRoleNew = new EPRole();
905 epRoleNew.setActive(addRoleInDB.getActive());
906 epRoleNew.setName(addRoleInDB.getName());
907 epRoleNew.setPriority(addRoleInDB.getPriority());
908 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
909 epRoleNew.setAppId(null);
911 epRoleNew.setAppId(app.getId());
913 dataAccessService.saveDomainObject(epRoleNew, null);
914 List<EPRole> getRoleCreated = null;
915 final Map<String, String> epAppRoleParams = new HashMap<>();
916 final Map<String, String> epAppPortalRoleParams = new HashMap<>();
917 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
918 epAppRoleParams.put("appId", String.valueOf(app.getId()));
919 epAppRoleParams.put(APP_ROLE_NAME_PARAM, addRoleInDB.getName());
920 List<EPRole> roleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, epAppRoleParams, null);
921 EPRole epUpdateRole = roleCreated.get(0);
922 epUpdateRole.setAppRoleId(epUpdateRole.getId());
923 dataAccessService.saveDomainObject(epUpdateRole, null);
924 getRoleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, epAppRoleParams, null);
926 epAppPortalRoleParams.put(APP_ROLE_NAME_PARAM, addRoleInDB.getName());
927 getRoleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, epAppPortalRoleParams, null);
929 // Add role in External Auth system
930 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
931 addNewRoleInExternalSystem(getRoleCreated, app);
933 } else { // if role already exists then update it
934 EPRole globalRole = null;
935 List<EPRole> applicationRoles;
936 List<EPRole> globalRoleList = getGlobalRolesOfPortal();
937 boolean isGlobalRole = false;
938 if (!globalRoleList.isEmpty()) {
939 EPRole role = globalRoleList.stream().filter(x -> addRoleInDB.getId().equals(x.getId())).findAny()
946 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)
947 || (globalRole != null && app.getId() != globalRole.getAppId())) {
948 applicationRoles = getPortalAppRoleInfo(addRoleInDB.getId());
950 applicationRoles = getPartnerAppRoleInfo(addRoleInDB.getId(), app);
952 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
953 updateRoleInExternalSystem(addRoleInDB, app, isGlobalRole);
954 // Add all user to the re-named role in external auth system
955 if (!applicationRoles.isEmpty()
956 && !addRoleInDB.getName().equals(applicationRoles.get(0).getName())) {
957 bulkUploadUsersSingleRole(app.getUebKey(), applicationRoles.get(0).getId(),
958 addRoleInDB.getName());
961 deleteRoleFunction(app, applicationRoles);
962 if (!applicationRoles.isEmpty()) {
963 epRole = applicationRoles.get(0);
964 epRole.setName(addRoleInDB.getName());
965 epRole.setPriority(addRoleInDB.getPriority());
966 epRole.setActive(addRoleInDB.getActive());
967 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
968 epRole.setAppId(null);
969 epRole.setAppRoleId(null);
970 } else if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)
971 && applicationRoles.get(0).getAppRoleId() == null) {
972 epRole.setAppRoleId(epRole.getId());
974 dataAccessService.saveDomainObject(epRole, null);
976 Long roleAppId = null;
977 if (globalRole != null && !app.getId().equals(globalRole.getAppId()))
978 roleAppId = PortalConstants.PORTAL_APP_ID;
979 saveRoleFunction(listWithoutDuplicates, app, applicationRoles, roleAppId);
982 } catch (Exception e) {
983 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInEcompDB is failed", e);
991 * It validates whether role exists in external auth system
998 private void checkIfRoleExitsInExternalSystem(Role checkRole, EPApp app) throws Exception {
999 getNameSpaceIfExists(app);
1000 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1001 String roleName = app.getNameSpace() + "." + checkRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_");
1002 HttpEntity<String> checkRoleEntity = new HttpEntity<>(headers);
1003 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRoleExitsInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1004 ResponseEntity<String> checkRoleInExternalSystem = template
1005 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
1006 + roleName, HttpMethod.GET, checkRoleEntity, String.class);
1007 if (!checkRoleInExternalSystem.getBody().equals(IS_EMPTY_JSON_STRING)) {
1008 logger.debug("checkIfRoleExitsInExternalSystem: Role already exists in external system {} and status code: {} ", checkRoleInExternalSystem.getBody(), checkRoleInExternalSystem.getStatusCode().value());
1009 throw new ExternalAuthSystemException(" Role already exists in external system");
1014 * It saves list of functions to the role in portal
1016 * @param roleFunctionListNew
1018 * @param applicationRoles
1021 @SuppressWarnings("unchecked")
1022 private void saveRoleFunction(List<RoleFunction> roleFunctionListNew, EPApp app, List<EPRole> applicationRoles ,Long roleAppId)
1024 final Map<String, String> getAppFunctionParams = new HashMap<>();
1026 for (RoleFunction roleFunc : roleFunctionListNew) {
1027 String code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1028 EPAppRoleFunction appRoleFunc = new EPAppRoleFunction();
1029 appRoleFunc.setAppId(app.getId());
1030 appRoleFunc.setRoleId(applicationRoles.get(0).getId());
1031 appRoleFunc.setRoleAppId(String.valueOf(roleAppId));
1032 getAppFunctionParams.put("appId", String.valueOf(app.getId()));
1033 getAppFunctionParams.put(FUNCTION_CODE_PARAMS, roleFunc.getCode());
1034 // query to check if function code has pipes
1035 List<CentralV2RoleFunction> roleFunction = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null);
1036 if(roleFunction.isEmpty()){
1037 getAppFunctionParams.put(FUNCTION_CODE_PARAMS, code);
1038 roleFunction = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null);
1040 if(roleFunction.size() > 1){
1041 CentralV2RoleFunction getExactFunctionCode = appFunctionListFilter(code, roleFunction);
1042 appRoleFunc.setCode(getExactFunctionCode.getCode());
1044 appRoleFunc.setCode(roleFunction.get(0).getCode());
1047 dataAccessService.saveDomainObject(appRoleFunc, null);
1053 * It filters the app functions which starts with similar name in the result set
1056 * @param roleFunction
1057 * @return CentralRoleFunction
1059 private CentralV2RoleFunction appFunctionListFilter(String roleFuncCode, List<CentralV2RoleFunction> roleFunction) {
1060 final Map<String, CentralV2RoleFunction> appFunctionsFilter = new HashMap<>();
1061 final Map<String, CentralV2RoleFunction> appFunctionsFilterPipes = new HashMap<>();
1062 CentralV2RoleFunction getExactFunctionCode = null;
1063 for(CentralV2RoleFunction cenRoleFunction : roleFunction){
1064 appFunctionsFilter.put(cenRoleFunction.getCode(), cenRoleFunction);
1065 appFunctionsFilterPipes.put(EcompPortalUtils.getFunctionCode(cenRoleFunction.getCode()), cenRoleFunction);
1067 getExactFunctionCode = appFunctionsFilter.get(roleFuncCode);
1068 if(getExactFunctionCode == null){
1069 getExactFunctionCode = appFunctionsFilterPipes.get(roleFuncCode);
1071 return getExactFunctionCode;
1075 * It deletes all EPAppRoleFunction records in the portal
1080 @SuppressWarnings("unchecked")
1081 private void deleteRoleFunction(EPApp app, List<EPRole> role) {
1082 final Map<String, Long> appRoleFuncsParams = new HashMap<>();
1083 appRoleFuncsParams.put("appId", app.getId());
1084 appRoleFuncsParams.put("roleId", role.get(0).getId());
1085 List<EPAppRoleFunction> appRoleFunctionList = dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null);
1086 if (!appRoleFunctionList.isEmpty()) {
1087 for (EPAppRoleFunction approleFunction : appRoleFunctionList) {
1088 dataAccessService.deleteDomainObject(approleFunction, null);
1094 @SuppressWarnings("unchecked")
1095 public List<EPUser> getUser(String loginId) throws InvalidUserException{
1096 final Map<String, String> userParams = new HashMap<>();
1097 userParams.put("org_user_id", loginId);
1098 List<EPUser> userList = dataAccessService.executeNamedQuery("getEPUserByOrgUserId", userParams, null);
1099 if (userList.isEmpty()) {
1100 throw new InvalidUserException("User not found");
1106 public String getV2UserWithRoles(String loginId, String uebkey) throws Exception {
1107 final Map<String, String> params = new HashMap<>();
1108 List<EPUser> userList = null;
1109 CentralV2User cenV2User = null;
1110 String result = null;
1112 params.put("orgUserIdValue", loginId);
1113 List<EPApp> appList = getApp(uebkey);
1114 if (!appList.isEmpty()) {
1115 userList = getUser(loginId);
1116 if (!userList.isEmpty()) {
1117 ObjectMapper mapper = new ObjectMapper();
1118 cenV2User = getV2UserAppRoles(loginId, uebkey);
1119 result = mapper.writeValueAsString(cenV2User);
1120 } else if (userList.isEmpty()) {
1121 throw new InvalidUserException("User not found");
1124 throw new InactiveApplicationException("Application not found");
1126 } catch (Exception e) {
1127 logger.error(EELFLoggerDelegate.errorLogger, "getUser: failed", e);
1134 public List<CentralV2Role> getRolesForApp(String uebkey) throws Exception {
1135 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Entering into getRolesForApp");
1136 List<CentralV2Role> roleList = new ArrayList<>();
1137 final Map<String, Long> params = new HashMap<>();
1139 List<EPApp> app = getApp(uebkey);
1140 List<EPRole> appRolesList = getAppRoles(app.get(0).getId());
1141 roleList = createCentralRoleObject(app, appRolesList, roleList, params);
1142 if(app.get(0).getId() != PortalConstants.PORTAL_APP_ID){
1143 List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
1144 List<EPRole> globalRolesList = getGlobalRolesOfPortal();
1145 List<CentralV2Role> portalsGlobalRolesFinlaList = new ArrayList<>();
1146 if (!globalRolesList.isEmpty()) {
1147 for (EPRole eprole : globalRolesList) {
1148 CentralV2Role cenRole = convertRoleToCentralV2Role(eprole);
1149 portalsGlobalRolesFinlaList.add(cenRole);
1151 roleList.addAll(globalRoleList);
1152 for (CentralV2Role role : portalsGlobalRolesFinlaList) {
1153 CentralV2Role result = roleList.stream()
1154 .filter(x -> role.getId().equals(x.getId())).findAny().orElse(null);
1159 for (EPRole role : globalRolesList) {
1160 CentralV2Role cenRole = convertRoleToCentralV2Role(role);
1161 roleList.add(cenRole);
1165 } catch (Exception e) {
1166 logger.error(EELFLoggerDelegate.errorLogger, "getRolesForApp: Failed!", e);
1169 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Finished!");
1170 return roleList.stream().distinct().collect(Collectors.toList());
1173 @SuppressWarnings("unchecked")
1175 public List<CentralV2RoleFunction> getRoleFuncList(String uebkey) throws Exception {
1176 EPApp app = getApp(uebkey).get(0);
1177 List<CentralV2RoleFunction> finalRoleList = new ArrayList<>();
1178 final Map<String, Long> params = new HashMap<>();
1179 params.put(APP_ID, app.getId());
1180 List<CentralV2RoleFunction> getRoleFuncList = dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null);
1181 for (CentralV2RoleFunction roleFuncItem : getRoleFuncList) {
1182 String code = EcompPortalUtils.getFunctionCode(roleFuncItem.getCode());
1183 String type = getFunctionCodeType(roleFuncItem.getCode());
1184 String action = getFunctionCodeAction(roleFuncItem.getCode());
1185 roleFuncItem.setCode(EPUserUtils.decodeFunctionCode(code));
1186 roleFuncItem.setType(type);
1187 roleFuncItem.setAction(action);
1188 finalRoleList.add(roleFuncItem);
1190 return finalRoleList;
1195 public String getFunctionCodeAction(String roleFuncItem) {
1196 return (!roleFuncItem.contains(FUNCTION_PIPE)) ? "*"
1197 : EcompPortalUtils.getFunctionAction(roleFuncItem);
1201 public String getFunctionCodeType(String roleFuncItem) {
1203 if ((roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))
1204 || (!roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))) {
1206 } else if (checkIfCodeHasNoPipesAndHasTypeUrl(roleFuncItem)
1207 ||checkIfCodeHasPipesAndHasTypeUrl(roleFuncItem)
1208 ||checkIfCodeHasNoPipesAndHasNoTypeUrl(roleFuncItem)) {
1210 } else if (roleFuncItem.contains(FUNCTION_PIPE)
1211 && (!roleFuncItem.contains("menu") || roleFuncItem.contains("url"))) {
1212 type = EcompPortalUtils.getFunctionType(roleFuncItem);
1219 * It check whether function code has no pipes and no url string in it
1221 * @param roleFuncItem
1222 * @return true or false
1224 private boolean checkIfCodeHasNoPipesAndHasNoTypeUrl(String roleFuncItem) {
1225 return !roleFuncItem.contains(FUNCTION_PIPE) && !roleFuncItem.contains("url");
1230 * It check whether function code has pipes and url string in it
1232 * @param roleFuncItem
1233 * @return true or false
1235 private boolean checkIfCodeHasPipesAndHasTypeUrl(String roleFuncItem) {
1236 return roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
1241 * It check whether function code has no pipes and has url string in it
1243 * @param roleFuncItem
1244 * @return true or false
1246 private boolean checkIfCodeHasNoPipesAndHasTypeUrl(String roleFuncItem) {
1247 return !roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
1251 * It returns user detail information which is deep copy of EPUser.class object
1259 @SuppressWarnings("unchecked")
1260 private CentralV2User createEPUser(EPUser userInfo, Set<EPUserApp> userAppSet, EPApp app) throws Exception {
1262 final Map<String, Long> params = new HashMap<>();
1263 CentralV2User userAppList = new CentralV2User();
1264 CentralV2User user1 = null;
1265 final Map<String, Long> params1 = new HashMap<>();
1266 List<EPRole> globalRoleList = new ArrayList<>();
1269 if (app.getId() != PortalConstants.PORTAL_APP_ID) {
1270 params1.put("userId", userInfo.getId());
1271 params1.put("appId", app.getId());
1272 globalRoleList = dataAccessService.executeNamedQuery("userAppGlobalRoles", params1, null);
1274 userAppList.setUserApps(new TreeSet<CentralV2UserApp>());
1275 for (EPUserApp userApp : userAppSet) {
1276 if (userApp.getRole().getActive()) {
1277 EPApp epApp = userApp.getApp();
1278 String globalRole = userApp.getRole().getName().toLowerCase();
1279 if (((epApp.getId().equals(app.getId()))
1280 && (!userApp.getRole().getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)))
1281 || ((epApp.getId().equals(PortalConstants.PORTAL_APP_ID))
1282 && (globalRole.toLowerCase().startsWith("global_")))) {
1283 CentralV2UserApp cua = new CentralV2UserApp();
1284 cua.setUserId(null);
1285 CentralApp cenApp = new CentralApp(1L, epApp.getCreated(), epApp.getModified(),
1286 epApp.getCreatedId(), epApp.getModifiedId(), epApp.getRowNum(), epApp.getName(),
1287 epApp.getImageUrl(), epApp.getDescription(), epApp.getNotes(), epApp.getUrl(),
1288 epApp.getAlternateUrl(), epApp.getAppRestEndpoint(), epApp.getMlAppName(),
1289 epApp.getMlAppAdminId(), String.valueOf(epApp.getMotsId()), epApp.getAppPassword(),
1290 String.valueOf(epApp.getOpen()), String.valueOf(epApp.getEnabled()),
1291 epApp.getThumbnail(), epApp.getUsername(), epApp.getUebKey(), epApp.getUebSecret(),
1292 epApp.getUebTopicName());
1295 if (globalRole.toLowerCase().startsWith("global_")
1296 && epApp.getId().equals(PortalConstants.PORTAL_APP_ID)
1297 && !epApp.getId().equals(app.getId())) {
1298 appId = app.getId();
1299 EPRole result = null;
1300 if (globalRoleList.size() > 0)
1301 result = globalRoleList.stream()
1302 .filter(x -> userApp.getRole().getId().equals(x.getId())).findAny()
1307 appId = userApp.getApp().getId();
1309 params.put("roleId", userApp.getRole().getId());
1310 params.put(APP_ID, appId);
1311 List<CentralV2RoleFunction> appRoleFunctionList = dataAccessService
1312 .executeNamedQuery("getAppRoleFunctionList", params, null);
1313 SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>();
1314 for (CentralV2RoleFunction roleFunc : appRoleFunctionList) {
1315 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1316 String type = getFunctionCodeType(roleFunc.getCode());
1317 String action = getFunctionCodeAction(roleFunc.getCode());
1318 CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(roleFunc.getId(),
1319 functionCode, roleFunc.getName(), null, type, action, null);
1320 roleFunctionSet.add(cenRoleFunc);
1322 Long userRoleId = null;
1323 if (globalRole.toLowerCase().startsWith("global_")
1324 || epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1325 userRoleId = userApp.getRole().getId();
1327 userRoleId = userApp.getRole().getAppRoleId();
1329 CentralV2Role cenRole = new CentralV2Role(userRoleId, userApp.getRole().getCreated(),
1330 userApp.getRole().getModified(), userApp.getRole().getCreatedId(),
1331 userApp.getRole().getModifiedId(), userApp.getRole().getRowNum(),
1332 userApp.getRole().getName(), userApp.getRole().getActive(),
1333 userApp.getRole().getPriority(), roleFunctionSet, null, null);
1334 cua.setRole(cenRole);
1336 userAppList.getUserApps().add(cua);
1341 user1 = new CentralV2User(null, userInfo.getCreated(), userInfo.getModified(), userInfo.getCreatedId(),
1342 userInfo.getModifiedId(), userInfo.getRowNum(), userInfo.getOrgId(), userInfo.getManagerId(),
1343 userInfo.getFirstName(), userInfo.getMiddleInitial(), userInfo.getLastName(), userInfo.getPhone(),
1344 userInfo.getFax(), userInfo.getCellular(), userInfo.getEmail(), userInfo.getAddressId(),
1345 userInfo.getAlertMethodCd(), userInfo.getHrid(), userInfo.getOrgUserId(), userInfo.getOrgCode(),
1346 userInfo.getAddress1(), userInfo.getAddress2(), userInfo.getCity(), userInfo.getState(),
1347 userInfo.getZipCode(), userInfo.getCountry(), userInfo.getOrgManagerUserId(),
1348 userInfo.getLocationClli(), userInfo.getBusinessCountryCode(), userInfo.getBusinessCountryName(),
1349 userInfo.getBusinessUnit(), userInfo.getBusinessUnitName(), userInfo.getDepartment(),
1350 userInfo.getDepartmentName(), userInfo.getCompanyCode(), userInfo.getCompany(),
1351 userInfo.getZipCodeSuffix(), userInfo.getJobTitle(), userInfo.getCommandChain(),
1352 userInfo.getSiloStatus(), userInfo.getCostCenter(), userInfo.getFinancialLocCode(),
1353 userInfo.getLoginId(), userInfo.getLoginPwd(), userInfo.getLastLoginDate(), userInfo.getActive(),
1354 userInfo.getInternal(), userInfo.getSelectedProfileId(), userInfo.getTimeZoneId(),
1355 userInfo.isOnline(), userInfo.getChatId(), userAppList.getUserApps(), null);
1356 } catch (Exception e) {
1357 logger.error(EELFLoggerDelegate.errorLogger, "createEPUser: createEPUser failed", e);
1364 public CentralV2Role getRoleInfo(Long roleId, String uebkey) throws Exception {
1365 final Map<String, Long> params = new HashMap<>();
1366 List<CentralV2Role> roleList = new ArrayList<>();
1367 CentralV2Role cenRole = new CentralV2Role();
1368 List<EPRole> roleInfo = null;
1369 List<EPApp> app = null;
1371 app = getApp(uebkey);
1372 if (app.isEmpty()) {
1373 throw new InactiveApplicationException("Application not found");
1375 if (app.get(0).getId() != PortalConstants.PORTAL_APP_ID) {
1376 List<EPRole> globalRoleList = new ArrayList<>();
1377 globalRoleList = getGlobalRolesOfPortal();
1378 if (globalRoleList.size() > 0) {
1379 EPRole result = globalRoleList.stream().filter(x -> roleId.equals(x.getId())).findAny()
1382 return getGlobalRoleForRequestedApp(app.get(0).getId(), roleId);
1385 if (app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
1386 roleInfo = getPortalAppRoleInfo(roleId);
1388 roleInfo = getPartnerAppRoleInfo(roleId, app.get(0));
1390 roleList = createCentralRoleObject(app, roleInfo, roleList, params);
1391 if (roleList.isEmpty()) {
1395 } catch (Exception e) {
1396 logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo: failed", e);
1400 return roleList.get(0);
1403 @SuppressWarnings("unchecked")
1404 private List<EPRole> getPartnerAppRoleInfo(Long roleId, EPApp app) {
1405 List<EPRole> roleInfo;
1406 final Map<String, Long> getPartnerAppRoleParams = new HashMap<>();
1407 getPartnerAppRoleParams.put("appRoleId", roleId);
1408 getPartnerAppRoleParams.put("appId", app.getId());
1409 roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams, null);
1410 if(roleInfo.isEmpty()) {
1411 getPartnerAppRoleParams.put("appRoleId", roleId);
1412 roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleById", getPartnerAppRoleParams, null);
1417 @SuppressWarnings("unchecked")
1418 private List<EPRole> getPortalAppRoleInfo(Long roleId) {
1419 List<EPRole> roleInfo;
1420 final Map<String, Long> getPortalAppRoleParams = new HashMap<>();
1421 getPortalAppRoleParams.put("roleId", roleId);
1422 roleInfo = dataAccessService.executeNamedQuery("getPortalAppRoleByRoleId", getPortalAppRoleParams, null);
1428 * It returns list of app roles along with role functions and which went through deep copy
1435 * @throws DecoderException
1437 @SuppressWarnings("unchecked")
1438 private List<CentralV2Role> createCentralRoleObject(List<EPApp> app, List<EPRole> roleInfo,
1439 List<CentralV2Role> roleList, Map<String, Long> params) throws RoleFunctionException {
1440 for (EPRole role : roleInfo) {
1441 params.put("roleId", role.getId());
1442 params.put(APP_ID, app.get(0).getId());
1443 List<CentralV2RoleFunction> cenRoleFuncList = dataAccessService.executeNamedQuery("getAppRoleFunctionList",
1445 SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>();
1446 for (CentralV2RoleFunction roleFunc : cenRoleFuncList) {
1447 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1448 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
1449 String type = getFunctionCodeType(roleFunc.getCode());
1450 String action = getFunctionCodeAction(roleFunc.getCode());
1451 CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(role.getId(), functionCode,
1452 roleFunc.getName(), null, type, action, null);
1453 roleFunctionSet.add(cenRoleFunc);
1455 SortedSet<CentralV2Role> childRoles = new TreeSet<>();
1456 SortedSet<CentralV2Role> parentRoles = new TreeSet<>();
1457 CentralV2Role cenRole = null;
1458 if (role.getAppRoleId() == null) {
1459 cenRole = new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
1460 role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
1461 roleFunctionSet, childRoles, parentRoles);
1463 cenRole = new CentralV2Role(role.getAppRoleId(), role.getCreated(), role.getModified(),
1464 role.getCreatedId(), role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(),
1465 role.getPriority(), roleFunctionSet, childRoles, parentRoles);
1467 roleList.add(cenRole);
1472 @SuppressWarnings("unchecked")
1474 public CentralV2RoleFunction getRoleFunction(String functionCode, String uebkey) throws Exception {
1475 String code = EcompPortalUtils.getFunctionCode(functionCode);
1476 String encodedCode = encodeFunctionCode(code);
1477 CentralV2RoleFunction roleFunc = null;
1478 EPApp app = getApp(uebkey).get(0);
1479 List<CentralV2RoleFunction> getRoleFuncList = null;
1480 final Map<String, String> params = new HashMap<>();
1482 params.put(FUNCTION_CODE_PARAMS, functionCode);
1483 params.put(APP_ID, String.valueOf(app.getId()));
1484 getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
1485 if (getRoleFuncList.isEmpty()) {
1486 params.put(FUNCTION_CODE_PARAMS, encodedCode);
1487 getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
1488 if (getRoleFuncList.isEmpty()) {
1492 if (getRoleFuncList.size() > 1) {
1493 CentralV2RoleFunction cenV2RoleFunction = appFunctionListFilter(encodedCode, getRoleFuncList);
1494 if (cenV2RoleFunction == null)
1496 roleFunc = checkIfPipesExitsInFunctionCode(cenV2RoleFunction);
1498 // Check even if single record have pipes
1499 if (!getRoleFuncList.isEmpty() && getRoleFuncList.get(0).getCode().contains(FUNCTION_PIPE)) {
1500 roleFunc = checkIfPipesExitsInFunctionCode(getRoleFuncList.get(0));
1502 roleFunc = getRoleFuncList.get(0);
1505 } catch (Exception e) {
1506 logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction: failed", e);
1512 private CentralV2RoleFunction checkIfPipesExitsInFunctionCode(CentralV2RoleFunction getRoleFuncList) {
1513 CentralV2RoleFunction roleFunc;
1514 String functionCodeFormat = getRoleFuncList.getCode();
1515 if (functionCodeFormat.contains(FUNCTION_PIPE)) {
1516 String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(functionCodeFormat);
1517 String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(functionCodeFormat);
1518 String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(functionCodeFormat);
1519 roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), newfunctionCodeFormat,
1520 getRoleFuncList.getName(), getRoleFuncList.getAppId(), newfunctionTypeFormat, newfunctionActionFormat,
1521 getRoleFuncList.getEditUrl());
1523 roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), functionCodeFormat,
1524 getRoleFuncList.getName(), getRoleFuncList.getAppId(),
1525 getRoleFuncList.getEditUrl());
1531 public boolean saveCentralRoleFunction(CentralV2RoleFunction domainCentralRoleFunction, EPApp app) throws Exception {
1532 boolean saveOrUpdateFunction = false;
1534 domainCentralRoleFunction.setCode(encodeFunctionCode(domainCentralRoleFunction.getCode()));
1535 final Map<String, String> functionParams = new HashMap<>();
1536 functionParams.put("appId", String.valueOf(app.getId()));
1537 if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1538 addRoleFunctionInExternalSystem(domainCentralRoleFunction, app);
1540 if(domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null){
1541 domainCentralRoleFunction.setCode(domainCentralRoleFunction.getType()+
1542 FUNCTION_PIPE+domainCentralRoleFunction.getCode()+FUNCTION_PIPE+domainCentralRoleFunction.getAction());
1544 domainCentralRoleFunction.setAppId(app.getId());
1545 dataAccessService.saveDomainObject(domainCentralRoleFunction, null);
1546 saveOrUpdateFunction = true;
1547 } catch (Exception e) {
1548 logger.error(EELFLoggerDelegate.errorLogger, "saveCentralRoleFunction: failed", e);
1551 return saveOrUpdateFunction;
1555 * It creates application permission in external auth system
1557 * @param domainCentralRoleFunction
1561 private void addRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
1563 ObjectMapper mapper = new ObjectMapper();
1564 ExternalAccessPerms extPerms = new ExternalAccessPerms();
1565 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1567 String instance = "";
1569 if((domainCentralRoleFunction.getType()!=null && domainCentralRoleFunction.getAction()!=null) || domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)){
1570 type = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) ? EcompPortalUtils.getFunctionType(domainCentralRoleFunction.getCode()) : domainCentralRoleFunction.getType();
1571 instance = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) ? EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode()) : domainCentralRoleFunction.getCode();
1572 action = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) ? EcompPortalUtils.getFunctionAction(domainCentralRoleFunction.getCode()) : domainCentralRoleFunction.getAction();
1574 type = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url";
1575 instance = domainCentralRoleFunction.getCode();
1578 // get Permissions from External Auth System
1579 JSONArray extPermsList = getExtAuthPermissions(app);
1580 List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPermsList);
1581 String requestedPerm = type+FUNCTION_PIPE+instance+FUNCTION_PIPE+action;
1582 boolean checkIfFunctionsExits = permsDetailList.stream().anyMatch(permsDetail -> permsDetail.getInstance().equals(requestedPerm));
1583 if (!checkIfFunctionsExits) {
1585 extPerms.setAction(action);
1586 extPerms.setInstance(instance);
1587 extPerms.setType(app.getNameSpace() + "." + type);
1588 extPerms.setDescription(domainCentralRoleFunction.getName());
1589 String addFunction = mapper.writeValueAsString(extPerms);
1590 HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
1591 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for POST: {}" , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
1592 ResponseEntity<String> addPermResponse= template.exchange(
1593 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
1594 HttpMethod.POST, entity, String.class);
1595 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ", addPermResponse.getStatusCode().value(), addFunction);
1596 } catch(HttpClientErrorException e){
1597 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to add function in external central auth system", e);
1598 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1600 }catch (Exception e) {
1601 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionInExternalSystem: Failed to add fucntion in external central auth system",
1607 extPerms.setAction(action);
1608 extPerms.setInstance(instance);
1609 extPerms.setType(app.getNameSpace() + "." + type);
1610 extPerms.setDescription(domainCentralRoleFunction.getName());
1611 String updateRoleFunction = mapper.writeValueAsString(extPerms);
1612 HttpEntity<String> entity = new HttpEntity<>(updateRoleFunction, headers);
1613 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for PUT: {}" , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRoleFunction);
1614 ResponseEntity<String> updatePermResponse = template.exchange(
1615 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
1616 HttpMethod.PUT, entity, String.class);
1617 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished updating permission in External Auth system {} and response: {} ", updateRoleFunction, updatePermResponse.getStatusCode().value());
1618 } catch(HttpClientErrorException e){
1619 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to add function in external central auth system", e);
1620 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1622 } catch (Exception e) {
1623 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionInExternalSystem: Failed to update function in external central auth system",e);
1629 @SuppressWarnings("unchecked")
1631 @Transactional(rollbackFor = Exception.class)
1632 public boolean deleteCentralRoleFunction(String code, EPApp app) {
1633 boolean deleteFunctionResponse = false;
1635 final Map<String, String> params = new HashMap<>();
1636 params.put(FUNCTION_CODE_PARAMS, code);
1637 params.put(APP_ID, String.valueOf(app.getId()));
1638 List<CentralV2RoleFunction> domainCentralRoleFunction = dataAccessService
1639 .executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
1640 CentralV2RoleFunction appFunctionCode = appFunctionListFilter(code, domainCentralRoleFunction);
1641 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1642 deleteRoleFunctionInExternalSystem(appFunctionCode, app);
1643 // Delete role function dependency records
1644 deleteAppRoleFunctions(appFunctionCode.getCode(), app);
1646 dataAccessService.deleteDomainObject(appFunctionCode, null);
1647 deleteFunctionResponse = true;
1648 } catch (Exception e) {
1649 logger.error(EELFLoggerDelegate.errorLogger, "deleteCentralRoleFunction: failed", e);
1651 return deleteFunctionResponse;
1655 * It deletes app function record in portal
1660 private void deleteAppRoleFunctions(String code, EPApp app) {
1661 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
1662 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + code + "'", null);
1667 * It deletes permission in the external auth system
1669 * @param domainCentralRoleFunction
1673 private void deleteRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
1676 ObjectMapper mapper = new ObjectMapper();
1677 ExternalAccessPerms extPerms = new ExternalAccessPerms();
1678 String instanceValue = EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode());
1679 String checkType = getFunctionCodeType(domainCentralRoleFunction.getCode());
1680 String actionValue = getFunctionCodeAction(domainCentralRoleFunction.getCode());
1681 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1682 extPerms.setAction(actionValue);
1683 extPerms.setInstance(instanceValue);
1684 extPerms.setType(app.getNameSpace() + "." + checkType);
1685 extPerms.setDescription(domainCentralRoleFunction.getName());
1686 String deleteRoleFunction = mapper.writeValueAsString(extPerms);
1687 HttpEntity<String> entity = new HttpEntity<>(deleteRoleFunction, headers);
1688 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleFunctionInExternalSystem: {} for DELETE: {} ",
1689 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, deleteRoleFunction);
1690 ResponseEntity<String> delPermResponse = template
1691 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1692 + "perm?force=true", HttpMethod.DELETE, entity, String.class);
1693 logger.debug(EELFLoggerDelegate.debugLogger,
1694 "deleteRoleFunctionInExternalSystem: Finished deleting permission in External Auth system {} and status code: {} ",
1695 deleteRoleFunction, delPermResponse.getStatusCode().value());
1696 } catch(HttpClientErrorException e){
1697 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to delete functions in External System", e);
1698 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1699 } catch (Exception e) {
1700 if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
1701 logger.debug(EELFLoggerDelegate.debugLogger,
1702 " deleteRoleFunctionInExternalSystem: It seems like function is already deleted in external central auth system but exists in local DB",
1705 logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleFunctionInExternalSystem: Failed to delete functions in External System", e);
1711 public ExternalRequestFieldsValidator saveRoleForApplication(Role saveRole, String uebkey) throws Exception {
1712 boolean response = false;
1713 String message = "";
1715 EPApp app = getApp(uebkey).get(0);
1716 addRoleInEcompDB(saveRole, app);
1718 } catch (Exception e) {
1719 message = e.getMessage();
1720 logger.error(EELFLoggerDelegate.errorLogger, "saveRoleForApplication failed", e);
1722 return new ExternalRequestFieldsValidator(response,message);
1725 @SuppressWarnings("unchecked")
1727 public boolean deleteRoleForApplication(String deleteRole, String uebkey) throws Exception {
1728 Session localSession = sessionFactory.openSession();
1729 Transaction transaction = null;
1730 boolean result = false;
1732 List<EPRole> epRoleList = null;
1733 EPApp app = getApp(uebkey).get(0);
1734 final Map<String, String> deleteRoleParams = new HashMap<>();
1735 deleteRoleParams.put(APP_ROLE_NAME_PARAM, deleteRole);
1736 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1737 epRoleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, deleteRoleParams, null);
1739 deleteRoleParams.put(APP_ID, String.valueOf(app.getId()));
1740 epRoleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, deleteRoleParams, null);
1742 if (!epRoleList.isEmpty()) {
1743 transaction = localSession.beginTransaction();
1744 // Delete app role functions before deleting role
1745 deleteRoleFunction(app, epRoleList);
1746 if (app.getId() == 1) {
1747 // Delete fn_user_ role
1748 dataAccessService.deleteDomainObjects(EPUserApp.class,
1749 APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
1750 boolean isPortalRequest = false;
1751 deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest);
1753 deleteRoleInExternalAuthSystem(epRoleList, app);
1754 transaction.commit();
1755 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: committed the transaction");
1756 dataAccessService.deleteDomainObject(epRoleList.get(0), null);
1759 } catch (Exception e) {
1760 logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleForApplication: failed", e);
1763 localSession.close();
1770 * It deletes role for application in external auth system
1772 * @param epRoleList contains role information
1773 * @param app contains application information
1776 private void deleteRoleInExternalAuthSystem(List<EPRole> epRoleList, EPApp app) throws Exception {
1777 ResponseEntity<String> deleteResponse;
1778 ResponseEntity<String> res = getNameSpaceIfExists(app);
1779 if (res.getStatusCode() == HttpStatus.OK) {
1780 // Delete Role in External System
1781 String deleteRoleKey = "{\"name\":\"" + app.getNameSpace() + "." + epRoleList.get(0).getName()
1782 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_") + "\"}";
1783 deleteResponse = deleteRoleInExternalSystem(deleteRoleKey);
1784 if (deleteResponse.getStatusCode().value() != 200 || deleteResponse.getStatusCode().value() != 404) {
1785 EPLogUtil.logExternalAuthAccessAlarm(logger, deleteResponse.getStatusCode());
1786 logger.error(EELFLoggerDelegate.errorLogger,
1787 "deleteRoleForApplication: Failed to delete role in external auth system! due to {} ",
1788 deleteResponse.getBody());
1790 logger.debug(EELFLoggerDelegate.debugLogger,
1791 "deleteRoleForApplication: about to commit the transaction");
1797 * It deletes application user role in external auth system
1804 private void deleteUserRoleInExternalSystem(EPRole role, EPApp app, String LoginId) throws Exception {
1805 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1806 HttpEntity<String> entity = new HttpEntity<>(headers);
1807 getNameSpaceIfExists(app);
1808 logger.debug(EELFLoggerDelegate.debugLogger,"deleteUserRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1809 ResponseEntity<String> getResponse = template
1811 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
1814 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
1815 + "/" + app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
1816 HttpMethod.GET, entity, String.class);
1817 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: Finished GET user roles from External Auth system and response: {} ", getResponse.getBody());
1818 if (getResponse.getStatusCode().value() != 200) {
1819 throw new ExternalAuthSystemException(getResponse.getBody());
1821 String res = getResponse.getBody();
1822 if (!res.equals(IS_EMPTY_JSON_STRING)) {
1823 HttpEntity<String> userRoleentity = new HttpEntity<>(headers);
1824 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1825 ResponseEntity<String> deleteResponse = template
1827 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1828 + "userRole/" + LoginId
1830 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
1831 + "/" + app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
1832 HttpMethod.DELETE, userRoleentity, String.class);
1833 if (deleteResponse.getStatusCode().value() != 200) {
1834 throw new ExternalAuthSystemException("Failed to delete user role");
1836 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: Finished deleting user role in External Auth system and status code: {} ", deleteResponse.getStatusCode().value());
1840 @SuppressWarnings("unchecked")
1842 public List<CentralV2Role> getActiveRoles(String uebkey) throws Exception {
1843 List<CentralV2Role> roleList = new ArrayList<>();
1845 List<EPApp> app = getApp(uebkey);
1846 final Map<String, Long> params = new HashMap<>();
1849 if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
1850 appId = app.get(0).getId();
1852 List<Criterion> restrictionsList = new ArrayList<Criterion>();
1853 Criterion active_ynCrt = Restrictions.eq("active", Boolean.TRUE);
1856 appIdCrt = Restrictions.isNull("appId");
1858 appIdCrt = Restrictions.eq("appId", appId);
1859 Criterion andCrit = Restrictions.and(active_ynCrt, appIdCrt);
1860 restrictionsList.add(andCrit);
1861 List<EPRole> epRole = (List<EPRole>) dataAccessService.getList(EPRole.class, null, restrictionsList, null);
1862 roleList = createCentralRoleObject(app, epRole, roleList, params);
1863 List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
1864 if (globalRoleList.size() > 0)
1865 roleList.addAll(globalRoleList);
1866 } catch (Exception e) {
1867 logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles: failed", e);
1875 @Transactional(rollbackFor = Exception.class)
1876 public ExternalRequestFieldsValidator deleteDependencyRoleRecord(Long roleId, String uebkey, String LoginId) throws Exception {
1877 Session localSession = sessionFactory.openSession();
1878 String message = "";
1879 Transaction transaction = null;
1880 boolean response = false;
1883 transaction = localSession.beginTransaction();
1884 List<EPRole> epRoleList = null;
1885 app = getApp(uebkey).get(0);
1886 if(app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1887 epRoleList = getPortalAppRoleInfo(roleId);
1889 epRoleList = getPartnerAppRoleInfo(roleId, app);
1891 if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1892 // Delete User Role in External System before deleting role
1893 deleteUserRoleInExternalSystem(epRoleList.get(0), app, LoginId);
1895 // Delete user app roles
1896 dataAccessService.deleteDomainObjects(EPUserApp.class,
1897 APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
1898 boolean isPortalRequest = false;
1899 deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest);
1900 transaction.commit();
1901 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1902 // Final call to delete role once all dependencies has been deleted
1903 deleteRoleInExternalAuthSystem(epRoleList, app);
1905 dataAccessService.deleteDomainObjects(EPRole.class, " role_id = "+ epRoleList.get(0).getId(), null);
1906 logger.debug(EELFLoggerDelegate.debugLogger, "deleteDependencyRoleRecord: committed the transaction");
1908 } catch(HttpClientErrorException e){
1909 logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord: HttpClientErrorException", e);
1910 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1911 message = e.getMessage();
1912 } catch (Exception e) {
1913 logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord failed", e);
1914 EcompPortalUtils.rollbackTransaction(transaction,
1915 "deleteDependencyRoleRecord rollback, exception = " + e.toString());
1916 message = e.getMessage();
1918 localSession.close();
1920 return new ExternalRequestFieldsValidator(response,message);
1924 @SuppressWarnings("unchecked")
1926 public void syncRoleFunctionFromExternalAccessSystem(EPApp app) {
1929 // get Permissions from External Auth System
1930 JSONArray extPerms = getExtAuthPermissions(app);
1931 List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);
1933 // get functions in DB
1934 final Map<String, Long> params = new HashMap<>();
1935 final Map<String, CentralV2RoleFunction> roleFuncMap = new HashMap<>();
1936 params.put(APP_ID, app.getId());
1937 List<CentralV2RoleFunction> appFunctions = dataAccessService.executeNamedQuery("getAllRoleFunctions", params,
1939 if (!appFunctions.isEmpty()) {
1940 for (CentralV2RoleFunction roleFunc : appFunctions) {
1941 roleFuncMap.put(roleFunc.getCode(), roleFunc);
1945 // get Roles for portal in DB
1946 List<EPRole> portalRoleList = getGlobalRolesOfPortal();
1947 final Map<String, EPRole> existingPortalRolesMap = new HashMap<>();
1948 for(EPRole epRole : portalRoleList){
1949 existingPortalRolesMap.put(epRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), epRole);
1953 final Map<String, EPRole> currentRolesInDB = getCurrentRolesInDB(app);
1955 // store External Permissions with Pipe and without Pipe (just instance)
1956 final Map<String, ExternalAccessPermsDetail> extAccessPermsContainsPipeMap = new HashMap<>();
1957 final Map<String, ExternalAccessPermsDetail> extAccessPermsMap = new HashMap<>();
1958 for (ExternalAccessPermsDetail permsDetailInfoWithPipe : permsDetailList) {
1959 extAccessPermsContainsPipeMap.put(permsDetailInfoWithPipe.getInstance(), permsDetailInfoWithPipe);
1960 String finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetailInfoWithPipe.getInstance());
1961 extAccessPermsMap.put(finalFunctionCodeVal, permsDetailInfoWithPipe);
1964 // Add if new functions and app role functions were added in
1965 // external auth system
1966 for (ExternalAccessPermsDetail permsDetail : permsDetailList) {
1967 String code = permsDetail.getInstance();
1968 CentralV2RoleFunction getFunctionCodeKey = roleFuncMap.get(permsDetail.getInstance());
1969 List<CentralV2RoleFunction> roleFunctionList = addGetLocalFunction(app, roleFuncMap, permsDetail, code,
1970 getFunctionCodeKey);
1971 List<String> roles = permsDetail.getRoles();
1972 if (roles != null) {
1973 // Check if function has any roles and which does not exist
1974 // in External Auth System. If exists delete in local
1975 addRemoveIfFunctionsRolesIsSyncWithExternalAuth(app, currentRolesInDB, roleFunctionList, roles, existingPortalRolesMap);
1979 // Check if function does exits in External Auth System but exits in
1980 // local then delete function and its dependencies
1981 for (CentralV2RoleFunction roleFunc : appFunctions) {
1983 ExternalAccessPermsDetail getFunctionCodeContainsPipeKey = extAccessPermsContainsPipeMap
1984 .get(roleFunc.getCode());
1985 if (null == getFunctionCodeContainsPipeKey) {
1986 ExternalAccessPermsDetail getFunctionCodeKey = extAccessPermsMap.get(roleFunc.getCode());
1987 if (null == getFunctionCodeKey) {
1988 deleteAppRoleFuncDoesNotExitsInExtSystem(app, roleFunc);
1991 } catch (Exception e) {
1992 logger.error(EELFLoggerDelegate.errorLogger,
1993 "syncRoleFunctionFromExternalAccessSystem: Failed to delete function", e);
1998 logger.debug(EELFLoggerDelegate.debugLogger,
1999 "syncRoleFunctionFromExternalAccessSystem: Finished syncRoleFunctionFromExternalAccessSystem");
2000 } catch (Exception e) {
2001 logger.error(EELFLoggerDelegate.errorLogger,
2002 "syncRoleFunctionFromExternalAccessSystem: Failed syncRoleFunctionFromExternalAccessSystem", e);
2007 @SuppressWarnings("unchecked")
2008 private void addRemoveIfFunctionsRolesIsSyncWithExternalAuth(EPApp app, final Map<String, EPRole> currentRolesInDB,
2009 List<CentralV2RoleFunction> roleFunctionList, List<String> roles, Map<String, EPRole> existingPortalRolesMap)
2011 if (!roleFunctionList.isEmpty()) {
2012 final Map<String, String> appRoleFuncParams = new HashMap<>();
2013 final Map<String, LocalRole> currentAppRoleFunctionsMap = new HashMap<>();
2014 final Map<String, String> currentRolesInExtSystem = new HashMap<>();
2015 appRoleFuncParams.put("functionCd", roleFunctionList.get(0).getCode());
2016 appRoleFuncParams.put("appId", String.valueOf(app.getId()));
2017 List<LocalRole> localRoleList = dataAccessService.executeNamedQuery("getCurrentAppRoleFunctions",
2018 appRoleFuncParams, null);
2019 for (LocalRole localRole : localRoleList) {
2020 currentAppRoleFunctionsMap.put(localRole.getRolename().replaceAll(
2021 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), localRole);
2023 for (String addRole : roles) {
2024 currentRolesInExtSystem.put(addRole.substring(addRole.indexOf(FUNCTION_PIPE)+1), addRole);
2026 for (String extAuthrole : roles) {
2027 String roleNameSpace = extAuthrole.substring(0, extAuthrole.indexOf(FUNCTION_PIPE));
2028 boolean isNameSpaceMatching = EcompPortalUtils.checkNameSpaceMatching(roleNameSpace, app.getNameSpace());
2029 if (isNameSpaceMatching) {
2030 if (!currentAppRoleFunctionsMap
2031 .containsKey(extAuthrole.substring(app.getNameSpace().length() + 1))) {
2032 EPRole localAddFuntionRole = currentRolesInDB
2033 .get(extAuthrole.substring(app.getNameSpace().length() + 1));
2034 if (localAddFuntionRole == null) {
2035 checkAndAddRoleInDB(app, currentRolesInDB, roleFunctionList, extAuthrole);
2037 EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
2038 addAppRoleFunc.setAppId(app.getId());
2039 addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
2040 addAppRoleFunc.setRoleId(localAddFuntionRole.getId());
2041 dataAccessService.saveDomainObject(addAppRoleFunc, null);
2044 // This block is to save global role function if exists
2046 String extAuthAppRoleName = extAuthrole.substring(extAuthrole.indexOf(FUNCTION_PIPE) + 1);
2047 boolean checkIfGlobalRoleExists = existingPortalRolesMap.containsKey(extAuthAppRoleName);
2048 if (checkIfGlobalRoleExists) {
2049 final Map<String, Long> params = new HashMap<>();
2050 EPRole role = existingPortalRolesMap.get(extAuthAppRoleName);
2051 EPAppRoleFunction addGlobalRoleFunctions = new EPAppRoleFunction();
2052 params.put("appId", app.getId());
2053 params.put("roleId", role.getId());
2054 List<EPAppRoleFunction> currentGlobalRoleFunctionsList = dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", params, null);
2055 boolean checkIfRoleFunctionExists = currentGlobalRoleFunctionsList.stream().anyMatch(currentGlobalRoleFunction -> currentGlobalRoleFunction.getCode().equals(roleFunctionList.get(0).getCode()));
2056 if (role != null && !checkIfRoleFunctionExists) {
2057 addGlobalRoleFunctions.setAppId(app.getId());
2058 addGlobalRoleFunctions.setRoleId(role.getId());
2059 if (!app.getId().equals(role.getAppRoleId())) {
2060 addGlobalRoleFunctions.setRoleAppId((PortalConstants.PORTAL_APP_ID).toString());
2062 addGlobalRoleFunctions.setRoleAppId(null);
2064 addGlobalRoleFunctions.setCode(roleFunctionList.get(0).getCode());
2065 dataAccessService.saveDomainObject(addGlobalRoleFunctions, null);
2070 for (LocalRole localRoleDelete : localRoleList) {
2071 if (!currentRolesInExtSystem.containsKey(localRoleDelete.getRolename()
2072 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
2073 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
2074 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunctionList.get(0).getCode()
2075 + "'" + " and role_id = " + localRoleDelete.getRoleId().longValue(),
2082 private void deleteAppRoleFuncDoesNotExitsInExtSystem(EPApp app, CentralV2RoleFunction roleFunc) {
2083 logger.debug(EELFLoggerDelegate.debugLogger,
2084 "syncRoleFunctionFromExternalAccessSystem: Deleting app role function {}",
2085 roleFunc.getCode());
2086 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
2087 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() +"'", null);
2088 logger.debug(EELFLoggerDelegate.debugLogger,
2089 "syncRoleFunctionFromExternalAccessSystem: Deleted app role function {}",
2090 roleFunc.getCode());
2092 logger.debug(EELFLoggerDelegate.debugLogger,
2093 "syncRoleFunctionFromExternalAccessSystem: Deleting app function {}",
2094 roleFunc.getCode());
2095 dataAccessService.deleteDomainObjects(CentralV2RoleFunction.class,
2096 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() +"'", null);
2097 logger.debug(EELFLoggerDelegate.debugLogger,
2098 "syncRoleFunctionFromExternalAccessSystem: Deleted app function {}",
2099 roleFunc.getCode());
2102 private void checkAndAddRoleInDB(EPApp app, final Map<String, EPRole> currentRolesInDB,
2103 List<CentralV2RoleFunction> roleFunctionList, String roleList) throws Exception {
2104 if (!currentRolesInDB.containsKey(
2105 roleList.substring(app.getNameSpace().length() + 1))) {
2106 Role role = addRoleInDBIfDoesNotExists(app,
2107 roleList.substring(app.getNameSpace().length() + 1));
2108 addIfRoleDescriptionNotExitsInExtSystem(role, app);
2109 if (!roleFunctionList.isEmpty()) {
2111 if (!roleFunctionList.isEmpty()) {
2112 EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
2113 addAppRoleFunc.setAppId(app.getId());
2114 addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
2115 addAppRoleFunc.setRoleId(role.getId());
2116 dataAccessService.saveDomainObject(addAppRoleFunc, null);
2118 } catch (Exception e) {
2119 logger.error(EELFLoggerDelegate.errorLogger,
2120 "syncRoleFunctionFromExternalAccessSystem: Failed to save app role function ",
2127 @SuppressWarnings("unchecked")
2128 private List<CentralV2RoleFunction> addGetLocalFunction(EPApp app, final Map<String, CentralV2RoleFunction> roleFuncMap,
2129 ExternalAccessPermsDetail permsDetail, String code, CentralV2RoleFunction getFunctionCodeKey) {
2130 String finalFunctionCodeVal = addToLocalIfFunctionNotExists(app, roleFuncMap, permsDetail, code,
2131 getFunctionCodeKey);
2132 final Map<String, String> appSyncFuncsParams = new HashMap<>();
2133 appSyncFuncsParams.put("appId", String.valueOf(app.getId()));
2134 appSyncFuncsParams.put("functionCd", finalFunctionCodeVal);
2135 List<CentralV2RoleFunction> roleFunctionList = null;
2136 roleFunctionList = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams,
2138 if (roleFunctionList.isEmpty()) {
2139 appSyncFuncsParams.put("functionCd", code);
2140 roleFunctionList = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams,
2143 return roleFunctionList;
2146 private String addToLocalIfFunctionNotExists(EPApp app, final Map<String, CentralV2RoleFunction> roleFuncMap,
2147 ExternalAccessPermsDetail permsDetail, String code, CentralV2RoleFunction getFunctionCodeKey
2149 String finalFunctionCodeVal = "";
2150 if (null == getFunctionCodeKey) {
2151 finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetail.getInstance());
2152 CentralV2RoleFunction checkIfCodeStillExits = roleFuncMap.get(finalFunctionCodeVal);
2153 // If function does not exist in local then add!
2154 if (null == checkIfCodeStillExits) {
2155 logger.debug(EELFLoggerDelegate.debugLogger,
2156 "syncRoleFunctionFromExternalAccessSystem: Adding function: {} ", code);
2157 addFunctionInEcompDB(app, permsDetail, code);
2158 logger.debug(EELFLoggerDelegate.debugLogger,
2159 "syncRoleFunctionFromExternalAccessSystem: Finished adding function: {} ", code);
2162 return finalFunctionCodeVal;
2165 @SuppressWarnings("unchecked")
2167 public Map<String, EPRole> getCurrentRolesInDB(EPApp app) {
2168 final Map<String, EPRole> currentRolesInDB = new HashMap<>();
2169 List<EPRole> getCurrentRoleList = null;
2170 final Map<String, Long> appParams = new HashMap<>();
2171 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2172 getCurrentRoleList = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
2174 appParams.put("appId", app.getId());
2175 getCurrentRoleList = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
2177 for (EPRole role : getCurrentRoleList) {
2178 currentRolesInDB.put(role.getName()
2179 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), role);
2181 return currentRolesInDB;
2184 private List<ExternalAccessPermsDetail> getExtAuthPerrmissonList(EPApp app, JSONArray extPerms)
2186 ExternalAccessPermsDetail permDetails = null;
2187 List<ExternalAccessPermsDetail> permsDetailList = new ArrayList<>();
2188 for (int i = 0; i < extPerms.length(); i++) {
2189 String description = null;
2190 if (extPerms.getJSONObject(i).has("description")) {
2191 description = extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
2193 description = extPerms.getJSONObject(i).getString("instance");
2195 if (extPerms.getJSONObject(i).has("roles")) {
2196 ObjectMapper rolesListMapper = new ObjectMapper();
2197 JSONArray resRoles = extPerms.getJSONObject(i).getJSONArray("roles");
2198 List<String> list = rolesListMapper.readValue(resRoles.toString(),
2199 TypeFactory.defaultInstance().constructCollectionType(List.class, String.class));
2200 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
2201 extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
2202 + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
2203 + extPerms.getJSONObject(i).getString("action"),
2204 extPerms.getJSONObject(i).getString("action"), list, description);
2205 permsDetailList.add(permDetails);
2207 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
2208 extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
2209 + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
2210 + extPerms.getJSONObject(i).getString("action"),
2211 extPerms.getJSONObject(i).getString("action"), description);
2212 permsDetailList.add(permDetails);
2215 return permsDetailList;
2218 private JSONArray getExtAuthPermissions(EPApp app) throws Exception {
2219 ResponseEntity<String> response = null;
2220 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2221 HttpEntity<String> entity = new HttpEntity<>(headers);
2222 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: {} ",
2223 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2225 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
2226 + "perms/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
2228 String res = response.getBody();
2229 logger.debug(EELFLoggerDelegate.debugLogger,
2230 "syncRoleFunctionFromExternalAccessSystem: Finished GET permissions from External Auth system and response: {} ",
2231 response.getBody());
2232 JSONObject jsonObj = new JSONObject(res);
2233 JSONArray extPerms = jsonObj.getJSONArray("perm");
2234 for (int i = 0; i < extPerms.length(); i++) {
2235 if (extPerms.getJSONObject(i).getString("type").equals(app.getNameSpace() + ".access")) {
2245 * Add function into local DB
2248 * @param permsDetail
2251 private void addFunctionInEcompDB(EPApp app, ExternalAccessPermsDetail permsDetail, String code) {
2253 CentralV2RoleFunction addFunction = new CentralV2RoleFunction();
2254 addFunction.setAppId(app.getId());
2255 addFunction.setCode(code);
2256 addFunction.setName(permsDetail.getDescription());
2257 dataAccessService.saveDomainObject(addFunction, null);
2258 } catch(Exception e){
2259 logger.error(EELFLoggerDelegate.errorLogger, "addFunctionInEcompDB: Failed to add function", e);
2265 * It updates description of a role in external auth system
2271 private void addIfRoleDescriptionNotExitsInExtSystem(Role role, EPApp app) throws Exception {
2272 String addRoleNew = updateExistingRoleInExternalSystem(role, app);
2273 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2275 HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
2277 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
2278 HttpMethod.PUT, entity, String.class);
2279 } catch (HttpClientErrorException e) {
2280 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addIfRoleDescriptionNotExitsInExtSystem",
2282 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2283 } catch (Exception e) {
2284 logger.error(EELFLoggerDelegate.errorLogger, "addIfRoleDescriptionNotExitsInExtSystem: Failed",
2291 * While sync functions form external auth system if new role found we should add in local and return Role.class object
2297 @SuppressWarnings("unchecked")
2298 private Role addRoleInDBIfDoesNotExists(EPApp app, String role) {
2299 Role setNewRole = new Role();
2301 // functions can have new role created in External Auth System prevent
2303 boolean isCreated = checkIfRoleExitsElseCreateInSyncFunctions(role, app);
2304 final Map<String, String> getRoleByNameParams = new HashMap<>();
2305 List<EPRole> getRoleCreated = null;
2306 getRoleByNameParams.put(APP_ROLE_NAME_PARAM, role);
2307 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2308 getRoleByNameParams.put("appId", String.valueOf(app.getId()));
2309 List<EPRole> roleCreated = dataAccessService
2310 .executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, getRoleByNameParams, null);
2312 EPRole epUpdateRole = roleCreated.get(0);
2313 epUpdateRole.setAppRoleId(epUpdateRole.getId());
2314 dataAccessService.saveDomainObject(epUpdateRole, null);
2315 getRoleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
2316 getRoleByNameParams, null);
2318 getRoleCreated = roleCreated;
2321 getRoleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, getRoleByNameParams,
2324 if (getRoleCreated != null && !getRoleCreated.isEmpty()) {
2325 EPRole roleObject = getRoleCreated.get(0);
2326 setNewRole.setId(roleObject.getId());
2327 setNewRole.setName(roleObject.getName());
2328 setNewRole.setActive(roleObject.getActive());
2329 setNewRole.setPriority(roleObject.getPriority());
2331 } catch (Exception e) {
2332 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInDBIfDoesNotExists: Failed", e);
2337 @SuppressWarnings("unchecked")
2338 private boolean checkIfRoleExitsElseCreateInSyncFunctions(String role, EPApp app) {
2339 boolean isCreated = false;
2340 final Map<String, String> roleParams = new HashMap<>();
2341 roleParams.put(APP_ROLE_NAME_PARAM, role);
2342 List<EPRole> roleCreated = null;
2343 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2344 roleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams,
2347 roleParams.put("appId", String.valueOf(app.getId()));
2348 roleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams,
2351 if (roleCreated == null || roleCreated.isEmpty()) {
2352 roleParams.put("appId", String.valueOf(app.getId()));
2353 EPRole epRoleNew = new EPRole();
2354 epRoleNew.setActive(true);
2355 epRoleNew.setName(role);
2356 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2357 epRoleNew.setAppId(null);
2359 epRoleNew.setAppId(app.getId());
2361 dataAccessService.saveDomainObject(epRoleNew, null);
2370 @SuppressWarnings("unchecked")
2371 public Integer bulkUploadFunctions(String uebkey) throws Exception {
2372 EPApp app = getApp(uebkey).get(0);
2373 List<RoleFunction> roleFuncList = dataAccessService.executeNamedQuery("getAllFunctions", null, null);
2374 CentralV2RoleFunction cenRoleFunc = null;
2375 Integer functionsAdded = 0;
2377 for (RoleFunction roleFunc : roleFuncList) {
2378 cenRoleFunc = new CentralV2RoleFunction(roleFunc.getCode(), roleFunc.getName());
2379 addRoleFunctionInExternalSystem(cenRoleFunc, app);
2382 } catch(HttpClientErrorException e){
2383 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadFunctions failed", e);
2384 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2385 } catch (Exception e) {
2386 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions: failed", e.getMessage(), e);
2388 return functionsAdded;
2392 public Integer bulkUploadRoles(String uebkey) throws Exception {
2393 List<EPApp> app = getApp(uebkey);
2394 List<EPRole> roles = getAppRoles(app.get(0).getId());
2395 List<CentralV2Role> cenRoleList = new ArrayList<>();
2396 final Map<String, Long> params = new HashMap<>();
2397 Integer rolesListAdded = 0;
2399 cenRoleList = createCentralRoleObject(app, roles, cenRoleList, params);
2400 ObjectMapper mapper = new ObjectMapper();
2401 mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
2402 String roleList = mapper.writeValueAsString(cenRoleList);
2403 List<Role> roleObjectList = mapper.readValue(roleList,
2404 TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
2405 for (Role role : roleObjectList) {
2406 addRoleInExternalSystem(role, app.get(0));
2409 if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
2410 // Add Account Admin role in External AUTH System
2412 String addAccountAdminRole = "";
2413 ExternalAccessRole extRole = new ExternalAccessRole();
2414 extRole.setName(app.get(0).getNameSpace() + "." + PortalConstants.ADMIN_ROLE
2415 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2416 addAccountAdminRole = mapper.writeValueAsString(extRole);
2417 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2418 HttpEntity<String> entity = new HttpEntity<>(addAccountAdminRole, headers);
2420 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
2421 HttpMethod.POST, entity, String.class);
2423 } catch (HttpClientErrorException e) {
2424 logger.error(EELFLoggerDelegate.errorLogger,
2425 "HttpClientErrorException - Failed to create Account Admin role", e);
2426 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2427 } catch (Exception e) {
2428 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2429 logger.error(EELFLoggerDelegate.errorLogger,
2430 "bulkUploadRoles: Account Admin Role already exits but does not break functionality",
2433 logger.error(EELFLoggerDelegate.errorLogger,
2434 "bulkUploadRoles: Failed to create Account Admin role", e.getMessage());
2438 } catch (Exception e) {
2439 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles: failed", e);
2442 return rolesListAdded;
2446 * It creating new role in external auth system while doing bulk upload
2452 private void addRoleInExternalSystem(Role role, EPApp app) throws Exception {
2453 String addRoleNew = updateExistingRoleInExternalSystem(role, app);
2454 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2456 HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
2458 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
2459 HttpMethod.POST, entity, String.class);
2460 } catch(HttpClientErrorException e){
2461 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addRoleInExternalSystem", e);
2462 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2463 } catch (Exception e) {
2464 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2465 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInExternalSystem: Role already exits but does not break functionality", e);
2467 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInExternalSystem: Failed to addRoleInExternalSystem", e.getMessage());
2473 @SuppressWarnings("unchecked")
2474 public Integer bulkUploadRolesFunctions(String uebkey) throws Exception {
2475 EPApp app = getApp(uebkey).get(0);
2476 List<EPRole> roles = getAppRoles(app.getId());
2477 final Map<String, Long> params = new HashMap<>();
2478 Integer roleFunctions = 0;
2480 for (EPRole role : roles) {
2481 params.put("roleId", role.getId());
2482 List<BulkUploadRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("uploadAllRoleFunctions",
2484 if (!appRoleFunc.isEmpty()) {
2485 for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
2486 addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
2491 } catch(HttpClientErrorException e){
2492 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
2493 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2494 } catch (Exception e) {
2495 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
2497 return roleFunctions;
2501 * Its adding a role function while doing bulk upload
2503 * @param addRoleFunc
2507 private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, EPRole role, EPApp app) {
2509 String instance = "";
2511 if(addRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)){
2512 type = EcompPortalUtils.getFunctionType(addRoleFunc.getFunctionCd());
2513 instance = EcompPortalUtils.getFunctionCode(addRoleFunc.getFunctionCd());
2514 action = EcompPortalUtils.getFunctionAction(addRoleFunc.getFunctionCd());
2516 type = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
2517 instance = addRoleFunc.getFunctionCd();
2520 ExternalAccessRolePerms extRolePerms = null;
2521 ExternalAccessPerms extPerms = null;
2522 ObjectMapper mapper = new ObjectMapper();
2524 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2525 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, instance, action,
2526 addRoleFunc.getFunctionName());
2527 extRolePerms = new ExternalAccessRolePerms(extPerms,
2528 app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2529 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
2530 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
2532 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
2533 HttpMethod.POST, entity, String.class);
2534 } catch (Exception e) {
2535 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2536 logger.error(EELFLoggerDelegate.errorLogger,
2537 "addRoleFunctionsInExternalSystem: RoleFunction already exits but does not break functionality", e);
2539 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionsInExternalSystem: Failed to addRoleFunctionsInExternalSystem",
2545 @SuppressWarnings("unchecked")
2547 public Integer bulkUploadPartnerFunctions(String uebkey) throws Exception {
2548 EPApp app = getApp(uebkey).get(0);
2549 final Map<String, Long> params = new HashMap<>();
2550 params.put("appId", app.getId());
2551 List<CentralV2RoleFunction> roleFuncList = dataAccessService.executeNamedQuery("getPartnerAppFunctions", params,
2553 Integer functionsAdded = 0;
2555 for (CentralV2RoleFunction roleFunc : roleFuncList) {
2556 addFunctionInExternalSystem(roleFunc, app);
2559 } catch (HttpClientErrorException e) {
2560 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadPartnerFunctions failed", e);
2561 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2562 } catch (Exception e) {
2563 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerFunctions: failed", e.getMessage(), e);
2565 return functionsAdded;
2568 private void addFunctionInExternalSystem(CentralV2RoleFunction roleFunc, EPApp app) throws Exception {
2569 ObjectMapper mapper = new ObjectMapper();
2570 ExternalAccessPerms extPerms = new ExternalAccessPerms();
2571 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2573 String instance = "";
2575 if ((roleFunc.getCode().contains(FUNCTION_PIPE))
2576 || (roleFunc.getType() != null && roleFunc.getAction() != null)) {
2577 type = EcompPortalUtils.getFunctionType(roleFunc.getCode());
2578 instance = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
2579 action = EcompPortalUtils.getFunctionAction(roleFunc.getCode());
2581 type = roleFunc.getCode().contains("menu") ? "menu" : "url";
2582 instance = roleFunc.getCode();
2586 extPerms.setAction(action);
2587 extPerms.setInstance(instance);
2588 extPerms.setType(app.getNameSpace() + "." + type);
2589 extPerms.setDescription(roleFunc.getName());
2590 String addFunction = mapper.writeValueAsString(extPerms);
2591 HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
2592 logger.debug(EELFLoggerDelegate.debugLogger, "addFunctionInExternalSystem: {} for POST: {}",
2593 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
2594 ResponseEntity<String> addPermResponse = template.exchange(
2595 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
2596 HttpMethod.POST, entity, String.class);
2597 logger.debug(EELFLoggerDelegate.debugLogger,
2598 "addFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ",
2599 addPermResponse.getStatusCode().value(), addFunction);
2600 } catch (HttpClientErrorException e) {
2601 logger.error(EELFLoggerDelegate.errorLogger,
2602 "HttpClientErrorException - Failed to add function in external central auth system", e);
2603 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2605 } catch (Exception e) {
2606 logger.error(EELFLoggerDelegate.errorLogger,
2607 "addFunctionInExternalSystem: Failed to add fucntion in external central auth system", e);
2613 public void bulkUploadPartnerRoles(String uebkey, List<Role> roleList) throws Exception {
2614 EPApp app = getApp(uebkey).get(0);
2615 for (Role role : roleList) {
2616 addRoleInExternalSystem(role, app);
2620 @SuppressWarnings("unchecked")
2622 public Integer bulkUploadPartnerRoleFunctions(String uebkey) throws Exception {
2623 EPApp app = getApp(uebkey).get(0);
2624 List<EPRole> roles = getAppRoles(app.getId());
2625 final Map<String, Long> params = new HashMap<>();
2626 Integer roleFunctions = 0;
2628 for (EPRole role : roles) {
2629 params.put("roleId", role.getId());
2630 List<BulkUploadRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("uploadPartnerRoleFunctions",
2632 if (!appRoleFunc.isEmpty()) {
2633 for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
2634 addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
2639 // upload global role functions to ext auth system
2640 if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2641 roleFunctions = bulkUploadGlobalRoleFunctions(app, roleFunctions);
2643 } catch(HttpClientErrorException e){
2644 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
2645 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2646 } catch (Exception e) {
2647 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
2649 return roleFunctions;
2652 @SuppressWarnings("unchecked")
2653 private Integer bulkUploadGlobalRoleFunctions(EPApp app, Integer roleFunctions) throws Exception {
2655 EPApp portalApp = epAppService.getApp(1l);
2656 final Map<String, Long> params = new HashMap<>();
2657 params.put("appId", app.getId());
2658 List<GlobalRoleWithApplicationRoleFunction> globalRoleFuncs = dataAccessService
2659 .executeNamedQuery("getBulkUploadPartnerGlobalRoleFunctions", params, null);
2660 ObjectMapper mapper = new ObjectMapper();
2661 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2662 for (GlobalRoleWithApplicationRoleFunction globalRoleFunc : globalRoleFuncs) {
2663 ExternalAccessRolePerms extRolePerms;
2664 ExternalAccessPerms extPerms;
2666 String instance = "";
2668 if (globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
2669 type = EcompPortalUtils.getFunctionType(globalRoleFunc.getFunctionCd());
2670 instance = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd());
2671 action = EcompPortalUtils.getFunctionAction(globalRoleFunc.getFunctionCd());
2673 type = globalRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
2674 instance = globalRoleFunc.getFunctionCd();
2677 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, instance, action);
2678 extRolePerms = new ExternalAccessRolePerms(extPerms, portalApp.getNameSpace() + "." + globalRoleFunc.getRoleName()
2679 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2680 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
2681 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
2682 updateRoleFunctionInExternalSystem(updateRolePerms, entity);
2685 } catch (HttpClientErrorException e) {
2686 logger.error(EELFLoggerDelegate.errorLogger,
2687 "HttpClientErrorException - Failed to add role function in external central auth system", e);
2688 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2690 } catch (Exception e) {
2691 logger.error(EELFLoggerDelegate.errorLogger,
2692 "bulkUploadGlobalRoleFunctions: Failed to add role fucntion in external central auth system", e);
2695 return roleFunctions;
2700 public void syncApplicationRolesWithEcompDB(EPApp app) {
2702 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Started");
2703 //Sync functions and roles assigned to it which also creates new roles if does not exits in portal
2704 syncRoleFunctionFromExternalAccessSystem(app);
2705 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Finished");
2707 ObjectMapper mapper = new ObjectMapper();
2708 logger.debug(EELFLoggerDelegate.debugLogger, "Entering to getAppRolesJSONFromExtAuthSystem");
2709 // Get Permissions from External Auth System
2710 JSONArray extRole = getAppRolesJSONFromExtAuthSystem(app);
2712 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into getExternalRoleDetailsList");
2713 List<ExternalRoleDetails> externalRoleDetailsList = getExternalRoleDetailsList(app,
2716 List<EPRole> finalRoleList = new ArrayList<>();
2717 for (ExternalRoleDetails externalRole : externalRoleDetailsList) {
2718 EPRole ecompRole = convertExternalRoleDetailstoEpRole(externalRole);
2719 finalRoleList.add(ecompRole);
2722 List<EPRole> applicationRolesList;
2723 applicationRolesList = getAppRoles(app.getId());
2724 List<String> applicationRoleIdList = new ArrayList<>();
2725 for (EPRole applicationRole : applicationRolesList) {
2726 applicationRoleIdList.add(applicationRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2729 List<EPRole> roleListToBeAddInEcompDB = new ArrayList<>();
2730 for (EPRole aafRole : finalRoleList) {
2731 if (!applicationRoleIdList.contains(aafRole.getName())) {
2732 roleListToBeAddInEcompDB.add(aafRole);
2736 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into inactiveRolesNotInExternalAuthSystem");
2737 // Check if roles exits in external Access system and if not make inactive in DB
2738 inactiveRolesNotInExternalAuthSystem(app, finalRoleList, applicationRolesList);
2740 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into checkAndUpdateRoleInDB");
2741 // It checks properties in the external auth system app role description and updates role in local
2742 checkAndUpdateRoleInDB(app, finalRoleList);
2744 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addNewRoleInEcompDBUpdateDescInExtAuthSystem");
2745 // Add new roles in DB and updates role description in External Auth System
2746 addNewRoleInEcompDBUpdateDescInExtAuthSystem(app, roleListToBeAddInEcompDB);
2747 logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: Finished");
2748 } catch (HttpClientErrorException e) {
2749 logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed due to the External Auth System", e);
2750 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2751 } catch (Exception e) {
2752 logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed ", e);
2758 * It adds new roles in DB and updates description in External Auth System
2761 * @param roleListToBeAddInEcompDB
2763 @SuppressWarnings("unchecked")
2764 private void addNewRoleInEcompDBUpdateDescInExtAuthSystem(EPApp app, List<EPRole> roleListToBeAddInEcompDB) {
2765 EPRole roleToBeAddedInEcompDB;
2766 for (int i = 0; i < roleListToBeAddInEcompDB.size(); i++) {
2768 roleToBeAddedInEcompDB = roleListToBeAddInEcompDB.get(i);
2769 if (app.getId() == 1) {
2770 roleToBeAddedInEcompDB.setAppRoleId(null);
2772 dataAccessService.saveDomainObject(roleToBeAddedInEcompDB, null);
2773 List<EPRole> getRoleCreatedInSync = null;
2774 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2775 final Map<String, String> globalRoleParams = new HashMap<>();
2776 globalRoleParams.put("appId", String.valueOf(app.getId()));
2777 globalRoleParams.put("appRoleName", roleToBeAddedInEcompDB.getName());
2778 getRoleCreatedInSync = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, globalRoleParams, null);
2779 EPRole epUpdateRole = getRoleCreatedInSync.get(0);
2780 epUpdateRole.setAppRoleId(epUpdateRole.getId());
2781 dataAccessService.saveDomainObject(epUpdateRole, null);
2783 List<EPRole> roleList = new ArrayList<>();
2784 final Map<String, String> params = new HashMap<>();
2786 params.put(APP_ROLE_NAME_PARAM, roleToBeAddedInEcompDB.getName());
2787 boolean isPortalRole = false;
2788 if (app.getId() == 1) {
2789 isPortalRole = true;
2790 roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, params, null);
2792 isPortalRole = false;
2793 params.put(APP_ID, app.getId().toString());
2794 roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, params, null);
2796 EPRole role = roleList.get(0);
2797 Role aaFrole = new Role();
2798 aaFrole.setId(role.getId());
2799 aaFrole.setActive(role.getActive());
2800 aaFrole.setPriority(role.getPriority());
2801 aaFrole.setName(role.getName());
2802 updateRoleInExternalSystem(aaFrole, app, isPortalRole);
2803 } catch (Exception e) {
2804 logger.error(EELFLoggerDelegate.errorLogger,
2805 "SyncApplicationRolesWithEcompDB: Failed to add or update role in external auth system", e);
2812 * It checks description in External Auth System if found any changes updates in DB
2815 * @param finalRoleList contains list of External Auth System roles list which is converted to EPRole
2817 @SuppressWarnings("unchecked")
2818 private void checkAndUpdateRoleInDB(EPApp app, List<EPRole> finalRoleList) {
2819 for (EPRole roleItem : finalRoleList) {
2820 final Map<String, String> roleParams = new HashMap<>();
2821 List<EPRole> currentList = null;
2822 roleParams.put(APP_ROLE_NAME_PARAM, roleItem.getName());
2823 if (app.getId() == 1) {
2824 currentList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, roleParams, null);
2826 roleParams.put(APP_ID, app.getId().toString());
2827 currentList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams, null);
2830 if (!currentList.isEmpty()) {
2832 Boolean aafRoleActive;
2833 Boolean localRoleActive;
2835 aafRoleActive = Boolean.valueOf(roleItem.getActive());
2836 localRoleActive = Boolean.valueOf(currentList.get(0).getActive());
2837 result = aafRoleActive.equals(localRoleActive);
2838 EPRole updateRole = currentList.get(0);
2841 updateRole.setActive(roleItem.getActive());
2842 dataAccessService.saveDomainObject(updateRole, null);
2844 if (roleItem.getPriority() != null
2845 && !currentList.get(0).getPriority().equals(roleItem.getPriority())) {
2846 updateRole.setPriority(roleItem.getPriority());
2847 dataAccessService.saveDomainObject(updateRole, null);
2849 } catch (Exception e) {
2850 logger.error(EELFLoggerDelegate.errorLogger,
2851 "syncApplicationRolesWithEcompDB: Failed to update role ", e);
2858 * It de-activates application roles in DB if not present in External Auth system
2861 * @param finalRoleList contains list of current roles present in External Auth System
2862 * @param applicationRolesList contains list of current roles present in DB
2864 @SuppressWarnings("unchecked")
2865 private void inactiveRolesNotInExternalAuthSystem(EPApp app, List<EPRole> finalRoleList,
2866 List<EPRole> applicationRolesList) {
2867 final Map<String, EPRole> checkRolesInactive = new HashMap<>();
2868 for (EPRole extrole : finalRoleList) {
2869 checkRolesInactive.put(extrole.getName(), extrole);
2871 for (EPRole role : applicationRolesList) {
2873 final Map<String, String> extRoleParams = new HashMap<>();
2874 List<EPRole> roleList = null;
2875 extRoleParams.put(APP_ROLE_NAME_PARAM, role.getName());
2876 if (!checkRolesInactive.containsKey(role.getName())) {
2877 if (app.getId() == 1) {
2878 roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, extRoleParams, null);
2880 extRoleParams.put(APP_ID, app.getId().toString());
2881 roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, extRoleParams, null);
2883 if(!roleList.isEmpty()) {
2884 EPRole updateRoleInactive = roleList.get(0);
2885 updateRoleInactive.setActive(false);
2886 dataAccessService.saveDomainObject(updateRoleInactive, null);
2889 } catch (Exception e) {
2890 logger.error(EELFLoggerDelegate.errorLogger,
2891 "syncApplicationRolesWithEcompDB: Failed to de-activate role ", e);
2897 @SuppressWarnings("unchecked")
2898 public List<ExternalRoleDetails> getExternalRoleDetailsList(EPApp app,
2899 ObjectMapper mapper, JSONArray extRole)
2900 throws IOException {
2901 List<ExternalRoleDetails> externalRoleDetailsList = new ArrayList<>();
2902 ExternalRoleDescription ApplicationRole = new ExternalRoleDescription();
2903 ExternalAccessPerms externalAccessPerms = new ExternalAccessPerms();
2904 List<String> functionCodelist = new ArrayList<>();
2905 Map<String, EPRole> curRolesMap = getCurrentRolesInDB(app);
2907 for (int i = 0; i < extRole.length(); i++) {
2908 ExternalRoleDetails externalRoleDetail = new ExternalRoleDetails();
2909 EPAppRoleFunction ePAppRoleFunction = new EPAppRoleFunction();
2910 JSONObject Role = (JSONObject) extRole.get(i);
2911 String roleName = extRole.getJSONObject(i).getString(ROLE_NAME);
2912 ApplicationRole.setName(roleName.substring(app.getNameSpace().length() + 1));
2913 if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
2914 String desc = extRole.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
2915 ApplicationRole.setName(desc);
2917 SortedSet<ExternalAccessPerms> externalAccessPermsOfRole = new TreeSet<>();
2918 if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_PERMS)) {
2919 JSONArray extPerm = (JSONArray) Role.get(EXTERNAL_AUTH_PERMS);
2920 for (int j = 0; j < extPerm.length(); j++) {
2921 JSONObject perms = extPerm.getJSONObject(j);
2922 boolean isNamespaceMatching = EcompPortalUtils.checkNameSpaceMatching(perms.getString("type"),
2923 app.getNameSpace());
2924 if (isNamespaceMatching) {
2925 externalAccessPerms = new ExternalAccessPerms(perms.getString("type"),
2926 perms.getString("instance"), perms.getString("action"));
2927 ePAppRoleFunction.setCode(externalAccessPerms.getInstance());
2928 functionCodelist.add(ePAppRoleFunction.getCode());
2929 externalAccessPermsOfRole.add(externalAccessPerms);
2934 externalRoleDetail.setActive(true);
2935 externalRoleDetail.setName(ApplicationRole.getName());
2936 if (app.getId() == 1) {
2937 externalRoleDetail.setAppId(null);
2939 externalRoleDetail.setAppId(app.getId());
2941 // get role functions from DB
2942 EPRole currRole = curRolesMap.get(ApplicationRole.getName()
2943 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2945 if (currRole != null)
2946 roleId = currRole.getId();
2947 // get role functions from DB
2948 final Map<String, EPAppRoleFunction> roleFunctionsMap = new HashMap<>();
2949 final Map<String, Long> appRoleFuncsParams = new HashMap<>();
2950 if (roleId != null) {
2951 appRoleFuncsParams.put("appId", app.getId());
2952 appRoleFuncsParams.put("roleId", roleId);
2953 List<EPAppRoleFunction> appRoleFunctions = dataAccessService
2954 .executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null);
2955 if (!appRoleFunctions.isEmpty()) {
2956 for (EPAppRoleFunction roleFunc : appRoleFunctions) {
2957 roleFunctionsMap.put(roleFunc.getCode(), roleFunc);
2961 if (!externalAccessPermsOfRole.isEmpty()) {
2962 // Adding functions to role
2963 for (ExternalAccessPerms externalpermission : externalAccessPermsOfRole) {
2964 EPAppRoleFunction checkRoleFunctionExits = roleFunctionsMap.get(externalpermission.getInstance());
2965 if (checkRoleFunctionExits == null) {
2966 String funcCode = externalpermission.getType().substring(app.getNameSpace().length() + 1)
2967 + FUNCTION_PIPE + externalpermission.getInstance() + FUNCTION_PIPE
2968 + externalpermission.getAction();
2969 EPAppRoleFunction checkRoleFunctionPipeExits = roleFunctionsMap.get(funcCode);
2970 if (checkRoleFunctionPipeExits == null) {
2972 final Map<String, String> appFuncsParams = new HashMap<>();
2973 appFuncsParams.put("appId", String.valueOf(app.getId()));
2974 appFuncsParams.put("functionCd", externalpermission.getInstance());
2975 logger.debug(EELFLoggerDelegate.debugLogger,
2976 "SyncApplicationRolesWithEcompDB: Adding function to the role: {}",
2977 externalpermission.getInstance());
2978 List<CentralV2RoleFunction> roleFunction = null;
2979 roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId",
2980 appFuncsParams, null);
2981 if (roleFunction.isEmpty()) {
2982 appFuncsParams.put("functionCd", funcCode);
2983 roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId",
2984 appFuncsParams, null);
2986 if (!roleFunction.isEmpty()) {
2987 EPAppRoleFunction apRoleFunction = new EPAppRoleFunction();
2988 apRoleFunction.setAppId(app.getId());
2989 apRoleFunction.setRoleId(roleId);
2990 apRoleFunction.setCode(roleFunction.get(0).getCode());
2991 dataAccessService.saveDomainObject(apRoleFunction, null);
2993 } catch (Exception e) {
2994 logger.error(EELFLoggerDelegate.errorLogger,
2995 "SyncApplicationRolesWithEcompDB: Failed to add role function", e);
3001 externalRoleDetailsList.add(externalRoleDetail);
3003 return externalRoleDetailsList;
3007 public JSONArray getAppRolesJSONFromExtAuthSystem(EPApp app) throws Exception {
3008 ResponseEntity<String> response = null;
3009 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3010 HttpEntity<String> entity = new HttpEntity<>(headers);
3011 logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: {} ",
3012 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
3014 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
3015 + "roles/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
3016 String res = response.getBody();
3017 logger.debug(EELFLoggerDelegate.debugLogger,
3018 "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
3020 JSONObject jsonObj = new JSONObject(res);
3021 JSONArray extRole = jsonObj.getJSONArray("role");
3022 for (int i = 0; i < extRole.length(); i++) {
3023 if (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ADMIN)
3024 || extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + OWNER)
3025 || (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ACCOUNT_ADMINISTRATOR)
3026 && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
3035 public JSONArray getAllUsersByRole(String roleName) throws Exception{
3036 ResponseEntity<String> response = null;
3037 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3038 HttpEntity<String> entity = new HttpEntity<>(headers);
3039 logger.debug(EELFLoggerDelegate.debugLogger, "getAllUsersByRole: {} ",
3040 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
3042 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
3043 + "userRoles/role/" + roleName, HttpMethod.GET, entity, String.class);
3044 String res = response.getBody();
3045 logger.debug(EELFLoggerDelegate.debugLogger,
3046 "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
3048 JSONObject jsonObj = new JSONObject(res);
3049 JSONArray extRole = jsonObj.getJSONArray("userRole");
3056 * It converts from ExternalRoleDetails.class object to EPRole.class object
3058 * @param externalRoleDetails
3059 * @return EPRole object
3061 private EPRole convertExternalRoleDetailstoEpRole(ExternalRoleDetails externalRoleDetails) {
3062 EPRole role = new EPRole();
3063 role.setActive(true);
3064 role.setAppId(externalRoleDetails.getAppId());
3065 role.setAppRoleId(externalRoleDetails.getAppRoleId());
3066 role.setName(externalRoleDetails.getName());
3067 role.setPriority(externalRoleDetails.getPriority());
3071 @SuppressWarnings("unchecked")
3073 public Integer bulkUploadUserRoles(String uebkey) throws Exception {
3074 EPApp app = getApp(uebkey).get(0);
3075 final Map<String, String> params = new HashMap<>();
3076 params.put("uebKey", app.getUebKey());
3077 List<BulkUploadUserRoles> userRolesList = null;
3078 Integer userRolesAdded = 0;
3079 if (app.getCentralAuth()) {
3080 userRolesList = dataAccessService.executeNamedQuery("getBulkUserRoles", params, null);
3081 for (BulkUploadUserRoles userRolesUpload : userRolesList) {
3082 if(!userRolesUpload.getOrgUserId().equals("su1234")){
3083 addUserRoleInExternalSystem(userRolesUpload);
3088 return userRolesAdded;
3092 * Its adding a user role in external auth system while doing bulk upload
3094 * @param userRolesUpload
3096 private void addUserRoleInExternalSystem(BulkUploadUserRoles userRolesUpload) {
3099 ObjectMapper mapper = new ObjectMapper();
3100 if (EPCommonSystemProperties
3101 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
3102 name = userRolesUpload.getOrgUserId()
3103 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
3105 ExternalAccessUser extUser = new ExternalAccessUser(name,
3106 userRolesUpload.getAppNameSpace() + "." + userRolesUpload.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
3107 String userRole = mapper.writeValueAsString(extUser);
3108 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3109 HttpEntity<String> entity = new HttpEntity<>(userRole, headers);
3111 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
3112 HttpMethod.POST, entity, String.class);
3113 } catch(HttpClientErrorException e){
3114 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addUserRoleInExternalSystem", e);
3115 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3116 } catch (Exception e) {
3117 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
3118 logger.error(EELFLoggerDelegate.errorLogger, "addUserRoleInExternalSystem: UserRole already exits but does not break functionality");
3120 logger.error(EELFLoggerDelegate.errorLogger, "addUserRoleInExternalSystem: Failed to addUserRoleInExternalSystem", e);
3126 public void deleteRoleDependencyRecords(Session localSession, Long roleId, Long appId, boolean isPortalRequest) throws Exception {
3131 //It should delete only when it portal's roleId
3132 if(appId.equals(PortalConstants.PORTAL_APP_ID)){
3133 // Delete from fn_role_function
3134 sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
3135 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3136 query = localSession.createSQLQuery(sql);
3137 query.executeUpdate();
3139 // Delete from fn_role_composite
3140 sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId;
3141 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3142 query = localSession.createSQLQuery(sql);
3143 query.executeUpdate();
3146 // Delete from ep_app_role_function
3147 sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId;
3148 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3149 query = localSession.createSQLQuery(sql);
3150 query.executeUpdate();
3152 // Delete from ep_role_notification
3153 sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
3154 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3155 query = localSession.createSQLQuery(sql);
3156 query.executeUpdate();
3158 // Delete from fn_user_pseudo_role
3159 sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
3160 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3161 query = localSession.createSQLQuery(sql);
3162 query.executeUpdate();
3164 // Delete form EP_WIDGET_CATALOG_ROLE
3165 sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId;
3166 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3167 query = localSession.createSQLQuery(sql);
3168 query.executeUpdate();
3170 // Delete form EP_WIDGET_CATALOG_ROLE
3171 sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId;
3172 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3173 query = localSession.createSQLQuery(sql);
3174 query.executeUpdate();
3176 if(!isPortalRequest) {
3177 // Delete form fn_menu_functional_roles
3178 sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
3179 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3180 query = localSession.createSQLQuery(sql);
3181 query.executeUpdate();
3183 } catch (Exception e) {
3184 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e);
3185 throw new DeleteDomainObjectFailedException("delete Failed" + e.getMessage());
3190 @SuppressWarnings("unchecked")
3192 public List<String> getMenuFunctionsList(String uebkey) throws Exception {
3193 List<String> appMenuFunctionsList = null;
3194 List<String> appMenuFunctionsFinalList = new ArrayList<>();
3196 EPApp app = getApp(uebkey).get(0);
3197 final Map<String, Long> appParams = new HashMap<>();
3198 appParams.put(APP_ID, app.getId());
3199 appMenuFunctionsList = dataAccessService.executeNamedQuery("getMenuFunctions", appParams, null);
3200 for(String appMenuFunction : appMenuFunctionsList) {
3201 if(appMenuFunction.contains(FUNCTION_PIPE)) {
3202 appMenuFunctionsFinalList.add(EcompPortalUtils.getFunctionCode(appMenuFunction));
3204 appMenuFunctionsFinalList.add(appMenuFunction);
3207 } catch (Exception e) {
3208 logger.error(EELFLoggerDelegate.errorLogger, "getMenuFunctionsList: Failed", e);
3209 return appMenuFunctionsFinalList;
3211 return appMenuFunctionsFinalList;
3214 @SuppressWarnings({ "unchecked"})
3216 public List<EcompUser> getAllAppUsers(String uebkey) throws Exception {
3217 List<String> usersList = new ArrayList<>();
3218 List<EcompUser> usersfinalList = new ArrayList<>();
3220 EPApp app = getApp(uebkey).get(0);
3221 final Map<String, Long> appParams = new HashMap<>();
3222 appParams.put("appId", app.getId());
3223 List<EcompUserRoles> userList = (List<EcompUserRoles>) dataAccessService
3224 .executeNamedQuery("ApplicationUserRoles", appParams, null);
3225 for (EcompUserRoles ecompUserRole : userList) {
3226 boolean found = false;
3227 Set<EcompRole> roles = null;
3228 for (EcompUser user : usersfinalList) {
3229 if (user.getOrgUserId().equals(ecompUserRole.getOrgUserId())) {
3230 EcompRole ecompRole = new EcompRole();
3231 ecompRole.setId(ecompUserRole.getRoleId());
3232 ecompRole.setName(ecompUserRole.getRoleName());
3233 roles = user.getRoles();
3234 EcompRole role = roles.stream().filter(x -> x.getName().equals(ecompUserRole.getRoleName())).findAny()
3236 SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
3239 roleFunctionSet = (SortedSet<EcompRoleFunction>) role.getRoleFunctions();
3242 String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
3243 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
3244 EcompRoleFunction epRoleFunction = new EcompRoleFunction();
3245 epRoleFunction.setName(ecompUserRole.getFunctionName());
3246 epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
3247 epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
3248 epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
3249 roleFunctionSet.add(epRoleFunction);
3250 ecompRole.setRoleFunctions(roleFunctionSet);
3251 roles.add(ecompRole);
3252 user.setRoles(roles);
3259 EcompUser epUser = new EcompUser();
3260 epUser.setOrgId(ecompUserRole.getOrgId());
3261 epUser.setManagerId(ecompUserRole.getManagerId());
3262 epUser.setFirstName(ecompUserRole.getFirstName());
3263 epUser.setLastName(ecompUserRole.getLastName());
3264 epUser.setPhone(ecompUserRole.getPhone());
3265 epUser.setEmail(ecompUserRole.getEmail());
3266 epUser.setOrgUserId(ecompUserRole.getOrgUserId());
3267 epUser.setOrgCode(ecompUserRole.getOrgCode());
3268 epUser.setOrgManagerUserId(ecompUserRole.getOrgManagerUserId());
3269 epUser.setJobTitle(ecompUserRole.getJobTitle());
3270 epUser.setLoginId(ecompUserRole.getLoginId());
3271 epUser.setActive(true);
3272 roles = new HashSet<>();
3273 EcompRole ecompRole = new EcompRole();
3274 ecompRole.setId(ecompUserRole.getRoleId());
3275 ecompRole.setName(ecompUserRole.getRoleName());
3276 SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
3278 String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
3279 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
3280 EcompRoleFunction epRoleFunction = new EcompRoleFunction();
3281 epRoleFunction.setName(ecompUserRole.getFunctionName());
3282 epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
3283 epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
3284 epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
3285 roleFunctionSet.add(epRoleFunction);
3286 ecompRole.setRoleFunctions(roleFunctionSet);
3287 roles.add(ecompRole);
3288 epUser.setRoles(roles);
3289 usersfinalList.add(epUser);
3292 ObjectMapper mapper = new ObjectMapper();
3294 for (EcompUser u1 : usersfinalList) {
3295 String str = mapper.writeValueAsString(u1);
3298 } catch (Exception e) {
3299 logger.error(EELFLoggerDelegate.errorLogger, "getAllUsers failed", e);
3302 return usersfinalList;
3308 public Role ConvertCentralRoleToRole(String result) {
3309 ObjectMapper mapper = new ObjectMapper();
3310 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
3311 Role newRole = new Role();
3313 newRole = mapper.readValue(result, Role.class);
3314 } catch (IOException e) {
3315 logger.error(EELFLoggerDelegate.errorLogger, "Failed to convert the result to Role Object", e);
3317 if (newRole.getRoleFunctions() != null) {
3318 @SuppressWarnings("unchecked")
3319 Set<RoleFunction> roleFunctionList = newRole.getRoleFunctions();
3320 Set<RoleFunction> roleFunctionListNew = new HashSet<>();
3321 Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
3322 while (itetaror.hasNext()) {
3323 Object nextValue = itetaror.next();
3324 RoleFunction roleFun = mapper.convertValue(nextValue, RoleFunction.class);
3325 roleFunctionListNew.add(roleFun);
3327 newRole.setRoleFunctions(roleFunctionListNew);
3333 @SuppressWarnings("unchecked")
3334 public List<CentralizedApp> getCentralizedAppsOfUser(String userId) {
3335 Map<String, String> params = new HashMap<>();
3336 params.put("userId", userId);
3337 List<CentralizedApp> centralizedAppsList = new ArrayList<>();
3339 centralizedAppsList = dataAccessService
3340 .executeNamedQuery("getCentralizedAppsOfUser", params, null);
3341 }catch (Exception e) {
3342 logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
3344 return centralizedAppsList;
3347 @SuppressWarnings("unchecked")
3348 public List<CentralV2Role> getGlobalRolesOfApplication(Long appId) {
3349 Map<String, Long> params = new HashMap<>();
3350 params.put("appId", appId);
3351 List<GlobalRoleWithApplicationRoleFunction> globalRoles = new ArrayList<>();
3353 globalRoles = dataAccessService.executeNamedQuery("getGlobalRoleWithApplicationRoleFunctions", params,
3355 } catch (Exception e) {
3356 logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
3358 List<CentralV2Role> rolesfinalList = new ArrayList<>();
3359 if (globalRoles.size() > 0)
3360 rolesfinalList = finalListOfCentralRoles(globalRoles);
3361 return rolesfinalList;
3364 @SuppressWarnings("unchecked")
3365 private CentralV2Role getGlobalRoleForRequestedApp(long requestedAppId, long roleId) {
3366 CentralV2Role finalGlobalrole = null;
3367 List<GlobalRoleWithApplicationRoleFunction> roleWithApplicationRoleFucntions = new ArrayList<>();
3368 Map<String, Long> params = new HashMap<>();
3369 params.put("roleId", roleId);
3370 params.put("requestedAppId", requestedAppId);
3372 roleWithApplicationRoleFucntions = dataAccessService.executeNamedQuery("getGlobalRoleForRequestedApp",
3374 } catch (Exception e) {
3375 logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRoleForRequestedApp failed", e);
3377 if (roleWithApplicationRoleFucntions.size() > 0) {
3378 List<CentralV2Role> rolesfinalList = finalListOfCentralRoles(roleWithApplicationRoleFucntions);
3379 finalGlobalrole = rolesfinalList.get(0);
3381 List<EPRole> roleList = getPortalAppRoleInfo(roleId);
3382 finalGlobalrole = convertRoleToCentralV2Role(roleList.get(0));
3384 return finalGlobalrole;
3387 private List<CentralV2Role> finalListOfCentralRoles(List<GlobalRoleWithApplicationRoleFunction> globalRoles) {
3388 List<CentralV2Role> rolesfinalList = new ArrayList<>();
3389 for (GlobalRoleWithApplicationRoleFunction role : globalRoles) {
3390 boolean found = false;
3391 for (CentralV2Role cenRole : rolesfinalList) {
3392 if (role.getRoleId().equals(cenRole.getId())) {
3393 SortedSet<CentralV2RoleFunction> roleFunctions = cenRole.getRoleFunctions();
3394 CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
3395 roleFunctions.add(cenRoleFun);
3396 cenRole.setRoleFunctions(roleFunctions);
3402 CentralV2Role cenrole = new CentralV2Role();
3403 cenrole.setName(role.getRoleName());
3404 cenrole.setId(role.getRoleId());
3405 cenrole.setActive(role.isActive());
3406 cenrole.setPriority(role.getPriority());
3407 SortedSet<CentralV2RoleFunction> roleFunctions = new TreeSet<>();
3408 CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
3409 roleFunctions.add(cenRoleFun);
3410 cenrole.setRoleFunctions(roleFunctions);
3411 rolesfinalList.add(cenrole);
3414 return rolesfinalList;
3417 private CentralV2RoleFunction createCentralRoleFunctionForGlobalRole(GlobalRoleWithApplicationRoleFunction role) {
3421 CentralV2RoleFunction cenRoleFun;
3422 if(role.getFunctionCd().contains(FUNCTION_PIPE)){
3423 instance = EcompPortalUtils.getFunctionCode(role.getFunctionCd());
3424 type = EcompPortalUtils.getFunctionType(role.getFunctionCd());
3425 action = EcompPortalUtils.getFunctionAction(role.getFunctionCd());
3426 cenRoleFun = new CentralV2RoleFunction(null, instance, role.getFunctionName(), null, type, action, null);
3428 type = getFunctionCodeType(role.getFunctionCd());
3429 action = getFunctionCodeAction(role.getFunctionCd());
3430 cenRoleFun = new CentralV2RoleFunction(null, role.getFunctionCd(), role.getFunctionName(), null, type, action, null);
3435 @SuppressWarnings("unchecked")
3437 public List<EPRole> getGlobalRolesOfPortal() {
3438 List<EPRole> globalRoles = new ArrayList<>();
3440 globalRoles = dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null);
3441 } catch (Exception e) {
3442 logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRolesOfPortal failed", e);
3447 private CentralV2Role convertRoleToCentralV2Role(EPRole role) {
3448 return new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
3449 role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
3450 new TreeSet<>(), new TreeSet<>(), new TreeSet<>());
3455 public List<CentralRoleFunction> convertCentralRoleFunctionToRoleFunctionObject(List<CentralV2RoleFunction> answer) {
3456 List<CentralRoleFunction> addRoleFuncList = new ArrayList<>();
3457 for(CentralV2RoleFunction cenRoleFunc : answer){
3458 CentralRoleFunction setRoleFunc = new CentralRoleFunction();
3459 setRoleFunc.setCode(cenRoleFunc.getCode());
3460 setRoleFunc.setName(cenRoleFunc.getName());
3461 addRoleFuncList.add(setRoleFunc);
3463 return addRoleFuncList;
3467 public CentralUser getUserRoles(String loginId, String uebkey) throws Exception {
3468 CentralUser sendUserRoles = null;
3471 CentralV2User cenV2User = getV2UserAppRoles(loginId, uebkey);
3472 sendUserRoles = convertV2UserRolesToOlderVersion(cenV2User);
3473 } catch (Exception e) {
3474 logger.error(EELFLoggerDelegate.errorLogger, "getUserRoles: failed", e);
3477 return sendUserRoles;
3482 * It returns V2 CentralUser object if user has any roles and permissions
3486 * @return CentralUser object
3489 private CentralV2User getV2UserAppRoles(String loginId, String uebkey) throws Exception {
3491 List<EPUser> epUserList;
3492 List<EPApp> appList = getApp(uebkey);
3493 app = appList.get(0);
3494 epUserList = getUser(loginId);
3495 EPUser user = epUserList.get(0);
3496 Set<EPUserApp> userAppSet = user.getEPUserApps();
3497 return createEPUser(user, userAppSet, app);
3501 * It converts V2 CentralUser object to old version CentralUser object
3504 * @return EPUser object
3506 private CentralUser convertV2UserRolesToOlderVersion(CentralV2User cenV2User) {
3507 Set<CentralV2UserApp> userV2Apps = cenV2User.getUserApps();
3508 Set<CentralUserApp> userApps = new TreeSet<>();
3509 for(CentralV2UserApp userApp : userV2Apps){
3510 CentralApp app = userApp.getApp();
3511 CentralUserApp cua = new CentralUserApp();
3512 cua.setUserId(null);
3514 SortedSet<CentralRoleFunction> cenRoleFunction = new TreeSet<>();
3515 for(CentralV2RoleFunction cenV2RoleFunc : userApp.getRole().getRoleFunctions() ){
3516 CentralRoleFunction cenRoleFunc = new CentralRoleFunction(cenV2RoleFunc.getCode(), cenV2RoleFunc.getName());
3517 cenRoleFunction.add(cenRoleFunc);
3519 CentralRole role = new CentralRole(userApp.getRole().getId(), userApp.getRole().getName(), userApp.getRole().getActive(), userApp.getRole().getPriority(),
3524 return new CentralUser(cenV2User.getId(), cenV2User.getCreated(), cenV2User.getModified(),
3525 cenV2User.getCreatedId(),cenV2User.getModifiedId(),
3526 cenV2User.getRowNum(), cenV2User.getOrgId(), cenV2User.getManagerId(), cenV2User.getFirstName(),
3527 cenV2User.getMiddleInitial(), cenV2User.getLastName(), cenV2User.getPhone(), cenV2User.getFax(),
3528 cenV2User.getCellular(),cenV2User.getEmail(),cenV2User.getAddressId(),cenV2User.getAlertMethodCd(),
3529 cenV2User.getHrid(),cenV2User.getOrgUserId(),cenV2User.getOrgCode(),cenV2User.getAddress1(),
3530 cenV2User.getAddress2(),cenV2User.getCity(),cenV2User.getState(),cenV2User.getZipCode(),cenV2User.getCountry(),
3531 cenV2User.getOrgManagerUserId(),cenV2User.getLocationClli(),cenV2User.getBusinessCountryCode(),
3532 cenV2User.getBusinessCountryName(),cenV2User.getBusinessUnit(),cenV2User.getBusinessUnitName(),
3533 cenV2User.getDepartment(),cenV2User.getDepartmentName(),cenV2User.getCompanyCode(),
3534 cenV2User.getCompany(),cenV2User.getZipCodeSuffix(),cenV2User.getJobTitle(),
3535 cenV2User.getCommandChain(),cenV2User.getSiloStatus(),cenV2User.getCostCenter(),
3536 cenV2User.getFinancialLocCode(),cenV2User.getLoginId(),cenV2User.getLoginPwd(),
3537 cenV2User.getLastLoginDate(),cenV2User.isActive(),cenV2User.isInternal(),cenV2User.getSelectedProfileId(),cenV2User.getTimeZoneId(),
3538 cenV2User.isOnline(),cenV2User.getChatId(),
3543 public List<CentralRole> convertV2CentralRoleListToOldVerisonCentralRoleList(List<CentralV2Role> v2CenRoleList) {
3544 List<CentralRole> cenRoleList = new ArrayList<>();
3545 for(CentralV2Role v2CenRole : v2CenRoleList){
3546 SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
3547 for(CentralV2RoleFunction v2CenRoleFunc: v2CenRole.getRoleFunctions()){
3548 CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName());
3549 cenRoleFuncList.add(roleFunc);
3551 CentralRole role = new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.getActive(), v2CenRole.getPriority(), cenRoleFuncList);
3552 cenRoleList.add(role);
3558 public ResponseEntity<String> getNameSpaceIfExists(EPApp app) throws Exception {
3559 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3560 HttpEntity<String> entity = new HttpEntity<>(headers);
3561 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Connecting to External Auth system");
3562 ResponseEntity<String> response = null;
3565 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
3566 + "nss/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
3567 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Finished ",
3568 response.getStatusCode().value());
3569 } catch (HttpClientErrorException e) {
3570 logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e);
3571 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3572 if (e.getStatusCode() == HttpStatus.NOT_FOUND)
3573 throw new InvalidApplicationException("Invalid NameSpace");
3581 public CentralRole convertV2CentralRoleToOldVerisonCentralRole(CentralV2Role v2CenRole) {
3582 SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
3583 for (CentralV2RoleFunction v2CenRoleFunc : v2CenRole.getRoleFunctions()) {
3584 CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName());
3585 cenRoleFuncList.add(roleFunc);
3587 return new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.getActive(), v2CenRole.getPriority(),
3591 @SuppressWarnings("unchecked")
3593 public Integer bulkUploadUsersSingleRole(String uebkey, Long roleId, String modifiedRoleName) throws Exception {
3594 EPApp app = getApp(uebkey).get(0);
3595 final Map<String, String> params = new HashMap<>();
3596 params.put("uebKey", app.getUebKey());
3597 params.put("roleId", String.valueOf(roleId));
3598 List<BulkUploadUserRoles> userRolesList = null;
3599 Integer userRolesAdded = 0;
3600 if (app.getCentralAuth()) {
3601 userRolesList = dataAccessService.executeNamedQuery("getBulkUsersForSingleRole", params, null);
3602 for (BulkUploadUserRoles userRolesUpload : userRolesList) {
3603 userRolesUpload.setRoleName(modifiedRoleName);
3604 if(!userRolesUpload.getOrgUserId().equals("su1234")){
3605 addUserRoleInExternalSystem(userRolesUpload);
3610 return userRolesAdded;
3614 public String encodeFunctionCode(String funCode){
3615 String encodedString = funCode;
3616 List<Pattern> encodingList = new ArrayList<>();
3617 encodingList.add(Pattern.compile("/"));
3618 encodingList.add(Pattern.compile("-"));
3619 for (Pattern xssInputPattern : encodingList) {
3620 encodedString = xssInputPattern.matcher(encodedString)
3621 .replaceAll("%" + Hex.encodeHexString(xssInputPattern.toString().getBytes()));
3623 encodedString = encodedString.replaceAll("\\*", "%"+ Hex.encodeHexString("*".getBytes()));
3624 return encodedString;
3628 public void bulkUploadRoleFunc(UploadRoleFunctionExtSystem data, EPApp app) throws Exception {
3629 ObjectMapper mapper = new ObjectMapper();
3630 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3632 ExternalAccessRolePerms extRolePerms;
3633 ExternalAccessPerms extPerms;
3634 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + data.getType(), encodeFunctionCode(data.getInstance()), data.getAction());
3635 String appNameSpace = "";
3636 if(data.getIsGlobalRolePartnerFunc()) {
3637 appNameSpace = epAppService.getApp(1l).getNameSpace();
3639 appNameSpace = app.getNameSpace();
3641 extRolePerms = new ExternalAccessRolePerms(extPerms,
3643 + data.getRoleName().replaceAll(
3644 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
3646 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
3647 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
3648 updateRoleFunctionInExternalSystem(updateRolePerms, entity);
3649 } catch (HttpClientErrorException e) {
3650 logger.error(EELFLoggerDelegate.errorLogger,
3651 "HttpClientErrorException - Failed to add role function in external central auth system", e);
3652 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3654 } catch (Exception e) {
3655 logger.error(EELFLoggerDelegate.errorLogger,
3656 "addFunctionInExternalSystem: Failed to add role fucntion in external central auth system", e);
3662 private void updateRoleFunctionInExternalSystem(String updateRolePerms, HttpEntity<String> entity) {
3663 logger.debug(EELFLoggerDelegate.debugLogger, "bulkUploadRoleFunc: {} for POST: {}",
3664 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
3665 ResponseEntity<String> addPermResponse = template.exchange(
3666 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
3667 HttpMethod.POST, entity, String.class);
3668 logger.debug(EELFLoggerDelegate.debugLogger,
3669 "bulkUploadRoleFunc: Finished adding permission for POST: {} and status code: {} ",
3670 addPermResponse.getStatusCode().value(), updateRolePerms);
3674 public void syncApplicationUserRolesFromExtAuthSystem(String loginId) throws Exception {
3676 if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
3677 name = loginId + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
3679 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3680 HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
3681 ResponseEntity<String> getResponse = getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
3682 List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
3683 String res = getResponse.getBody();
3684 JSONObject jsonObj = null;
3685 JSONArray extRoles = null;
3686 if (!res.equals("{}")) {
3687 jsonObj = new JSONObject(res);
3688 extRoles = jsonObj.getJSONArray("role");
3690 updateUserRolesInLocal(userRoleDetailList, extRoles, loginId);
3693 @SuppressWarnings("unchecked")
3694 private void updateUserRolesInLocal(List<ExternalAccessUserRoleDetail> userRoleDetailList, JSONArray extRoles,
3695 String loginId) throws InvalidUserException {
3696 HashMap<String, String> userParams = new HashMap<>();
3697 userParams.put("orgUserId", loginId);
3698 // Get all centralized applications existing user roles from local
3699 List<CentralizedAppRoles> currentUserAppRoles = dataAccessService
3700 .executeNamedQuery("getUserCentralizedAppRoles", userParams, null);
3701 EPUser user = getUser(loginId).get(0);
3702 // Get all centralized applications roles from local
3703 HashMap<String, CentralizedAppRoles> cenAppRolesMap = getCentralizedAppRoleList();
3704 HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap = getCurrentUserCentralizedAppRoles(
3705 currentUserAppRoles);
3706 // Get all centralized applications + admin role from local
3707 HashMap<String, EPApp> centralisedAppsMap = getCentralizedAdminAppsInfo();
3708 if (extRoles != null) {
3709 ExternalAccessUserRoleDetail userRoleDetail = null;
3710 for (int i = 0; i < extRoles.length(); i++) {
3711 if (!extRoles.getJSONObject(i).getString("name").endsWith(ADMIN)
3712 && !extRoles.getJSONObject(i).getString("name").endsWith(OWNER)) {
3713 userRoleDetail = new ExternalAccessUserRoleDetail(extRoles.getJSONObject(i).getString("name"),
3715 userRoleDetailList.add(userRoleDetail);
3718 addUserRolesInLocal(userRoleDetailList, user, cenAppRolesMap, currentCentralizedUserAppRolesMap,
3719 centralisedAppsMap);
3723 private void addUserRolesInLocal(List<ExternalAccessUserRoleDetail> userRoleDetailList, EPUser user,
3724 HashMap<String, CentralizedAppRoles> cenAppRolesMap,
3725 HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap,
3726 HashMap<String, EPApp> centralisedAppsMap) {
3727 for (ExternalAccessUserRoleDetail extUserRoleDetail : userRoleDetailList) {
3729 // check if user already has role in local
3730 if (!currentCentralizedUserAppRolesMap.containsKey(extUserRoleDetail.getName())) {
3731 CentralizedAppRoles getCenAppRole = cenAppRolesMap.get(extUserRoleDetail.getName());
3732 if (getCenAppRole != null) {
3733 logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Adding user role from external auth system {}",
3734 extUserRoleDetail.toString());
3735 EPUserApp userApp = new EPUserApp();
3736 EPApp app = new EPApp();
3737 app.setId(getCenAppRole.getAppId());
3738 EPRole epRole = new EPRole();
3739 epRole.setId(getCenAppRole.getRoleId());
3740 userApp.setApp(app);
3741 userApp.setUserId(user.getId());
3742 userApp.setRole(epRole);
3743 dataAccessService.saveDomainObject(userApp, null);
3744 logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Finished user role from external auth system {}",
3745 extUserRoleDetail.toString());
3746 } else if (getCenAppRole == null // check if user has app account admin role
3747 && extUserRoleDetail.getName().endsWith(PortalConstants.ADMIN_ROLE.replaceAll(
3748 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
3749 EPApp app = centralisedAppsMap.get(extUserRoleDetail.getName());
3751 logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Adding user role from external auth system {}",
3752 extUserRoleDetail.toString());
3753 EPUserApp userApp = new EPUserApp();
3754 EPRole epRole = new EPRole();
3755 epRole.setId(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
3756 userApp.setApp(app);
3757 userApp.setUserId(user.getId());
3758 userApp.setRole(epRole);
3759 dataAccessService.saveDomainObject(userApp, null);
3760 logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Finished user role from external auth system {}",
3761 extUserRoleDetail.toString());
3765 } catch (Exception e) {
3766 logger.error(EELFLoggerDelegate.errorLogger,
3767 "addUserRolesInLocal - Failed to update user role in local from external auth system {} ",
3768 extUserRoleDetail.toString(), e);
3773 @SuppressWarnings("unchecked")
3774 private HashMap<String, EPApp> getCentralizedAdminAppsInfo() {
3775 List<EPApp> centralizedApps = dataAccessService
3776 .executeNamedQuery("getCentralizedApps", null, null);
3777 HashMap<String, EPApp> centralisedAppsMap = new HashMap<>();
3778 for (EPApp cenApp : centralizedApps) {
3779 centralisedAppsMap.put(cenApp.getNameSpace()+ "." +
3780 PortalConstants.ADMIN_ROLE.replaceAll(
3781 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), cenApp);
3783 return centralisedAppsMap;
3786 private HashMap<String, CentralizedAppRoles> getCurrentUserCentralizedAppRoles(
3787 List<CentralizedAppRoles> currentUserAppRoles) {
3788 HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap = new HashMap<>();
3789 for (CentralizedAppRoles cenAppUserRole : currentUserAppRoles) {
3790 currentCentralizedUserAppRolesMap.put(
3791 cenAppUserRole.getAppNameSpace() + "." + cenAppUserRole.getRoleName()
3792 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
3795 return currentCentralizedUserAppRolesMap;
3798 @SuppressWarnings("unchecked")
3799 private HashMap<String, CentralizedAppRoles> getCentralizedAppRoleList() {
3800 List<CentralizedAppRoles> centralizedAppRoles = dataAccessService
3801 .executeNamedQuery("getAllCentralizedAppsRoles", null, null);
3802 HashMap<String, CentralizedAppRoles> cenAppRolesMap = new HashMap<>();
3803 for (CentralizedAppRoles CentralizedAppRole : centralizedAppRoles) {
3805 CentralizedAppRole.getAppNameSpace() + "." + CentralizedAppRole.getRoleName()
3806 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
3807 CentralizedAppRole);
3809 return cenAppRolesMap;
3813 public ResponseEntity<String> getUserRolesFromExtAuthSystem(String name, HttpEntity<String> getUserRolesEntity) {
3814 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles");
3815 ResponseEntity<String> getResponse = template
3816 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
3817 + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class);
3818 if (getResponse.getStatusCode().value() == 200) {
3819 logger.debug(EELFLoggerDelegate.debugLogger, "getAllUserRoleFromExtAuthSystem: Finished GET user roles from external system and received user roles {}",
3820 getResponse.getBody());
3823 logger.error(EELFLoggerDelegate.errorLogger, "getAllUserRoleFromExtAuthSystem: Failed GET user roles from external system and received user roles {}",getResponse.getBody() );
3824 EPLogUtil.logExternalAuthAccessAlarm(logger, getResponse.getStatusCode());