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============================================
36 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
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.exceptions.DeleteDomainObjectFailedException;
74 import org.onap.portalapp.portal.exceptions.ExternalAuthSystemException;
75 import org.onap.portalapp.portal.exceptions.InactiveApplicationException;
76 import org.onap.portalapp.portal.exceptions.InvalidApplicationException;
77 import org.onap.portalapp.portal.exceptions.InvalidUserException;
78 import org.onap.portalapp.portal.exceptions.RoleFunctionException;
79 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
80 import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
81 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
82 import org.onap.portalapp.portal.transport.BulkUploadRoleFunction;
83 import org.onap.portalapp.portal.transport.BulkUploadUserRoles;
84 import org.onap.portalapp.portal.transport.CentralApp;
85 import org.onap.portalapp.portal.transport.CentralRole;
86 import org.onap.portalapp.portal.transport.CentralRoleFunction;
87 import org.onap.portalapp.portal.transport.CentralUser;
88 import org.onap.portalapp.portal.transport.CentralUserApp;
89 import org.onap.portalapp.portal.transport.CentralV2Role;
90 import org.onap.portalapp.portal.transport.CentralV2User;
91 import org.onap.portalapp.portal.transport.CentralV2UserApp;
92 import org.onap.portalapp.portal.transport.EcompUserRoles;
93 import org.onap.portalapp.portal.transport.ExternalAccessPerms;
94 import org.onap.portalapp.portal.transport.ExternalAccessPermsDetail;
95 import org.onap.portalapp.portal.transport.ExternalAccessRole;
96 import org.onap.portalapp.portal.transport.ExternalAccessRolePerms;
97 import org.onap.portalapp.portal.transport.ExternalAccessUser;
98 import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator;
99 import org.onap.portalapp.portal.transport.ExternalRoleDescription;
100 import org.onap.portalapp.portal.transport.GlobalRoleWithApplicationRoleFunction;
101 import org.onap.portalapp.portal.transport.LocalRole;
102 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
103 import org.onap.portalapp.portal.utils.EcompPortalUtils;
104 import org.onap.portalapp.portal.utils.PortalConstants;
105 import org.onap.portalapp.util.EPUserUtils;
106 import org.onap.portalsdk.core.domain.Role;
107 import org.onap.portalsdk.core.domain.RoleFunction;
108 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
109 import org.onap.portalsdk.core.restful.domain.EcompRole;
110 import org.onap.portalsdk.core.restful.domain.EcompUser;
111 import org.onap.portalsdk.core.service.DataAccessService;
112 import org.onap.portalsdk.core.util.SystemProperties;
113 import org.springframework.beans.factory.annotation.Autowired;
114 import org.springframework.context.annotation.EnableAspectJAutoProxy;
115 import org.springframework.http.HttpEntity;
116 import org.springframework.http.HttpHeaders;
117 import org.springframework.http.HttpMethod;
118 import org.springframework.http.HttpStatus;
119 import org.springframework.http.ResponseEntity;
120 import org.springframework.stereotype.Service;
121 import org.springframework.transaction.annotation.Transactional;
122 import org.springframework.web.client.HttpClientErrorException;
123 import org.springframework.web.client.RestTemplate;
125 import com.fasterxml.jackson.core.JsonProcessingException;
126 import com.fasterxml.jackson.databind.DeserializationFeature;
127 import com.fasterxml.jackson.databind.ObjectMapper;
128 import com.fasterxml.jackson.databind.type.TypeFactory;
130 @Service("externalAccessRolesService")
131 @EnableAspectJAutoProxy
134 public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesService {
136 private static final String APP_ROLE_NAME_PARAM = "appRoleName";
138 private static final String GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM = "getRoletoUpdateInExternalAuthSystem";
140 private static final String GET_PORTAL_APP_ROLES_QUERY = "getPortalAppRoles";
142 private static final String GET_ROLE_FUNCTION_QUERY = "getRoleFunction";
144 private static final String FUNCTION_CODE_PARAMS = "functionCode";
146 private static final String AND_FUNCTION_CD_EQUALS = " and function_cd = '";
148 private static final String OWNER = ".owner";
150 private static final String ADMIN = ".admin";
152 private static final String ACCOUNT_ADMINISTRATOR = ".Account_Administrator";
154 private static final String FUNCTION_PIPE = "|";
156 private static final String IS_NULL_STRING = "null";
158 private static final String EXTERNAL_AUTH_PERMS = "perms";
160 private static final String EXTERNAL_AUTH_ROLE_DESCRIPTION = "description";
162 private static final String IS_EMPTY_JSON_STRING = "{}";
164 private static final String CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE = "Connecting to External Auth system";
166 private static final String APP_ROLE_ID = "appRoleId";
168 private static final String APP_ID = "appId";
170 private static final String PRIORITY = "priority";
172 private static final String ACTIVE = "active";
174 private static final String ROLE_NAME = "name";
176 private static final String ID = "id";
178 private static final String APP_ID_EQUALS = " app_id = ";
180 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesServiceImpl.class);
183 private DataAccessService dataAccessService;
186 private EPAppService epAppService;
189 private SessionFactory sessionFactory;
192 EPRoleService ePRoleService;
194 RestTemplate template = new RestTemplate();
197 // These decode values are based on HexDecoder
198 static final String decodeValueOfForwardSlash = "2f";
199 static final String decodeValueOfHiphen = "2d";
200 static final String decodeValueOfStar = "2a";
202 @SuppressWarnings("unchecked")
203 public List<EPRole> getAppRoles(Long appId) throws Exception {
204 List<EPRole> applicationRoles = null;
205 final Map<String, Long> appParams = new HashMap<>();
208 applicationRoles = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
210 appParams.put("appId", appId);
211 applicationRoles = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
213 } catch (Exception e) {
214 logger.error(EELFLoggerDelegate.errorLogger, "getAppRoles: failed", e);
217 return applicationRoles;
220 @SuppressWarnings("unchecked")
222 public List<EPApp> getApp(String uebkey) throws Exception {
223 List<EPApp> app = null;
225 final Map<String, String> appUebkeyParams = new HashMap<>();
226 appUebkeyParams.put("appKey", uebkey);
227 app = dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null);
228 if(!app.isEmpty() && !app.get(0).getEnabled() && !app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)){
229 throw new InactiveApplicationException("Application:"+app.get(0).getName()+" is Unavailable");
231 } catch (Exception e) {
232 logger.error(EELFLoggerDelegate.errorLogger, "getApp: failed", e);
239 * It returns single application role from external auth system
242 * @return JSON string which contains application role details
245 private String getSingleAppRole(String addRole, EPApp app) throws Exception {
246 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
247 HttpEntity<String> entity = new HttpEntity<>(headers);
248 ResponseEntity<String> response = null;
249 logger.debug(EELFLoggerDelegate.debugLogger, "getSingleAppRole: Connecting to External Auth system");
250 response = template.exchange(
251 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
254 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
255 HttpMethod.GET, entity, String.class);
256 logger.debug(EELFLoggerDelegate.debugLogger,
257 "getSingleAppRole: Finished GET app role from External Auth system and status code: {} ",
258 response.getStatusCode().value());
259 return response.getBody();
263 public boolean addRole(Role addRole, String uebkey) throws Exception {
264 boolean response = false;
265 ResponseEntity<String> addResponse = null;
266 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
267 EPApp app = getApp(uebkey).get(0);
268 String newRole = updateExistingRoleInExternalSystem(addRole, app);
269 HttpEntity<String> entity = new HttpEntity<>(newRole, headers);
270 logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Connecting to External Auth system");
271 addResponse = template.exchange(
272 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
273 HttpMethod.POST, entity, String.class);
274 if (addResponse.getStatusCode().value() == 201) {
276 logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Finished adding role in the External Auth system and response code: {} ", addResponse.getStatusCode().value());
278 if (addResponse.getStatusCode().value() == 406) {
279 logger.error(EELFLoggerDelegate.errorLogger,
280 "addRole: Failed to add in the External Auth system due to {} and status code: {}", addResponse.getBody(), addResponse.getStatusCode().value());
287 * It deletes record in external auth system
290 * @return JSON String which has status code and response body
293 private ResponseEntity<String> deleteRoleInExternalSystem(String delRole) throws Exception {
294 ResponseEntity<String> delResponse = null;
295 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
296 HttpEntity<String> entity = new HttpEntity<>(delRole, headers);
297 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: {} for DELETE: {}" , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, delRole);
298 delResponse = template.exchange(
299 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role?force=true",
300 HttpMethod.DELETE, entity, String.class);
301 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: Finished DELETE operation in the External Auth system {} and status code: {} ", delRole, delResponse.getStatusCode().value());
306 * It updates role in external auth system
308 * @param updateExtRole
310 * @return true if success else false
312 * If updateRoleInExternalSystem fails we catch it in logger for detail message
314 @SuppressWarnings("unchecked")
315 private boolean updateRoleInExternalSystem(Role updateExtRole, EPApp app, boolean isGlobalRole) throws Exception {
316 boolean response = false;
317 ObjectMapper mapper = new ObjectMapper();
318 ResponseEntity<String> deleteResponse = null;
319 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
320 List<EPRole> epRoleList = null;
321 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)
322 || (isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
323 epRoleList = getPortalAppRoleInfo(updateExtRole.getId());
325 epRoleList = getPartnerAppRoleInfo(updateExtRole.getId(), app);
328 // Assigning functions to global role
329 if ((isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
330 List<RoleFunction> globalRoleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole);
331 EPApp portalAppInfo = epAppService.getApp(PortalConstants.PORTAL_APP_ID);
332 addFunctionsTOGlobalRole(epRoleList, updateExtRole, globalRoleFunctionListNew, mapper, app, portalAppInfo);
335 String appRole = getSingleAppRole(epRoleList.get(0).getName(), app);
336 List<RoleFunction> roleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole);
337 if (!appRole.equals(IS_EMPTY_JSON_STRING)) {
338 JSONObject jsonObj = new JSONObject(appRole);
339 JSONArray extRole = jsonObj.getJSONArray("role");
340 if (!extRole.getJSONObject(0).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
341 String roleName = extRole.getJSONObject(0).getString(ROLE_NAME);
342 Map<String, String> delRoleKeyMapper = new HashMap<>();
343 delRoleKeyMapper.put(ROLE_NAME, roleName);
344 String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
345 deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
346 if (deleteResponse.getStatusCode().value() != 200) {
347 throw new ExternalAuthSystemException(deleteResponse.getBody());
349 addRole(updateExtRole, app.getUebKey());
351 String desc = extRole.getJSONObject(0).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
352 String name = extRole.getJSONObject(0).getString(ROLE_NAME);
353 List<ExternalAccessPerms> list = new ArrayList<>();
354 if (extRole.getJSONObject(0).has(EXTERNAL_AUTH_PERMS)) {
355 JSONArray perms = extRole.getJSONObject(0).getJSONArray(EXTERNAL_AUTH_PERMS);
356 list = mapper.readValue(perms.toString(), TypeFactory.defaultInstance()
357 .constructCollectionType(List.class, ExternalAccessPerms.class));
359 ExternalRoleDescription sysRoleList = mapper.readValue(desc, ExternalRoleDescription.class);
360 // If role name or role functions are updated then delete
361 // record in External System and add new record to avoid
363 Boolean existingRoleActive;
364 boolean isActiveValueChanged;
365 // check role active status
366 existingRoleActive = new Boolean(sysRoleList.getActive());
367 isActiveValueChanged = existingRoleActive.equals(updateExtRole.getActive());
368 boolean isRoleNameChanged = false;
369 if (!sysRoleList.getName().equals(updateExtRole.getName())) {
370 isRoleNameChanged = true;
371 Map<String, String> delRoleKeyMapper = new HashMap<>();
372 delRoleKeyMapper.put(ROLE_NAME, name);
373 String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
374 deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
375 if (deleteResponse.getStatusCode().value() != 200) {
376 logger.error(EELFLoggerDelegate.errorLogger,
377 "updateRoleInExternalSystem: Failed to delete role in external system due to {} ",
378 deleteResponse.getBody());
379 throw new ExternalAuthSystemException(deleteResponse.getBody());
381 addRole(updateExtRole, app.getUebKey());
382 // add partner functions to the global role in External Auth System
383 if(!list.isEmpty() && isGlobalRole){
384 addPartnerHasRoleFunctionsToGlobalRole(list, mapper, app, updateExtRole);
386 list.removeIf(perm -> EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace()));
387 // if role name is changes please ignore the previous functions in External Auth and update with user requested functions
388 addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name,
391 boolean checkPriorityStatus = StringUtils.equals(String.valueOf(sysRoleList.getPriority()),
392 String.valueOf(updateExtRole.getPriority()));
393 ExternalAccessRole updateRole = new ExternalAccessRole();
394 if (!isActiveValueChanged || !checkPriorityStatus || sysRoleList.getId().equals(IS_NULL_STRING)
395 || !sysRoleList.getId().equals(String.valueOf(epRoleList.get(0).getId()))) {
396 String updateDesc = "";
397 List<EPRole> getRole;
398 final Map<String, String> getAppRoleByName = new HashMap<>();
399 getAppRoleByName.put(APP_ROLE_NAME_PARAM, updateExtRole.getName());
400 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
401 getRole = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, getAppRoleByName,
404 getAppRoleByName.put("appId", String.valueOf(app.getId()));
405 getRole = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
406 getAppRoleByName, null);
408 Map<String, String> extSystemUpdateRoleJsonMapper = new LinkedHashMap<>();
409 extSystemUpdateRoleJsonMapper.put(ID, String.valueOf(getRole.get(0).getId()));
410 extSystemUpdateRoleJsonMapper.put(ROLE_NAME, String.valueOf(updateExtRole.getName()));
411 extSystemUpdateRoleJsonMapper.put(ACTIVE, String.valueOf(updateExtRole.getActive()));
412 extSystemUpdateRoleJsonMapper.put(PRIORITY, String.valueOf(updateExtRole.getPriority()));
413 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
414 extSystemUpdateRoleJsonMapper.put(APP_ID, "null");
415 extSystemUpdateRoleJsonMapper.put(APP_ROLE_ID, "null");
417 extSystemUpdateRoleJsonMapper.put(APP_ID, String.valueOf(app.getId()));
418 extSystemUpdateRoleJsonMapper.put(APP_ROLE_ID,
419 String.valueOf(getRole.get(0).getAppRoleId()));
422 updateDesc = mapper.writeValueAsString(extSystemUpdateRoleJsonMapper);
423 updateRole.setName(app.getNameSpace() + "." + updateExtRole.getName().replaceAll(
424 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
425 updateRole.setDescription(updateDesc);
426 String updateRoleDesc = mapper.writeValueAsString(updateRole);
427 HttpEntity<String> entity = new HttpEntity<>(updateRoleDesc, headers);
428 logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: {} for PUT: {}",
429 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRoleDesc);
430 ResponseEntity<String> updatePermsResponse = template.exchange(
431 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
433 HttpMethod.PUT, entity, String.class);
434 logger.debug(EELFLoggerDelegate.debugLogger,
435 "updateRoleInExternalSystem: Finished updating in External Auth system {} and status code: {} ",
436 updateRoleDesc, updatePermsResponse.getStatusCode().value());
438 if(!isRoleNameChanged) {
439 response = addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name,
444 // It seems like role exists in local DB but not in External
446 addRole(updateExtRole, app.getUebKey());
447 List<RoleFunction> roleFunctionListUpdate = convertSetToListOfRoleFunctions(updateExtRole);
449 if (!roleFunctionListUpdate.isEmpty()) {
450 addRoleFunctionsInExternalSystem(updateExtRole, mapper, app);
457 private boolean addRemoveFunctionsToRole(Role updateExtRole, EPApp app, ObjectMapper mapper,
458 List<RoleFunction> roleFunctionListNew, String name, List<ExternalAccessPerms> list) throws Exception {
460 Map<String, RoleFunction> updateRoleFunc = new HashMap<>();
461 for (RoleFunction addPerm : roleFunctionListNew) {
462 updateRoleFunc.put(addPerm.getCode(), addPerm);
464 final Map<String, ExternalAccessPerms> extRolePermMap = new HashMap<>();
465 final Map<String, ExternalAccessPerms> extRolePermMapPipes = new HashMap<>();
466 list.removeIf(perm -> !EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace()));
467 // Update permissions in the ExternalAccess System
468 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
469 if (!list.isEmpty()) {
470 for (ExternalAccessPerms perm : list) {
471 RoleFunction roleFunc = updateRoleFunc.get(perm.getType().substring(app.getNameSpace().length()+1) + FUNCTION_PIPE + perm.getInstance() + FUNCTION_PIPE + perm.getAction());
472 if (roleFunc==null) {
473 RoleFunction roleFuncPipeFilter = updateRoleFunc.get(perm.getInstance());
474 if(roleFuncPipeFilter == null)
475 removePermForRole(perm, mapper, name, headers);
477 extRolePermMap.put(perm.getInstance(), perm);
478 extRolePermMapPipes.put(
479 perm.getType().substring(app.getNameSpace().length()+1) + FUNCTION_PIPE + perm.getInstance() + FUNCTION_PIPE + perm.getAction(), perm);
483 if (!roleFunctionListNew.isEmpty()) {
484 for (RoleFunction roleFunc : roleFunctionListNew) {
485 if(roleFunc.getCode().contains(FUNCTION_PIPE)) {
486 ExternalAccessPerms perm = extRolePermMapPipes.get(roleFunc.getCode());
488 response = addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers,
492 if (!extRolePermMap.containsKey(EcompPortalUtils.getFunctionCode(roleFunc.getCode()))) {
493 response = addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers,
503 * Adds function to the role in the external auth system while editing a role or updating new functions to a role
506 private boolean addFunctionsToRoleInExternalAuthSystem(Role updateExtRole, EPApp app, ObjectMapper mapper,
507 HttpHeaders headers, RoleFunction roleFunc) throws JsonProcessingException {
509 ExternalAccessRolePerms extRolePerms;
510 ExternalAccessPerms extPerms;
514 if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
515 code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
516 type = getFunctionCodeType(roleFunc.getCode());
517 action = getFunctionCodeAction(roleFunc.getCode());
519 code = roleFunc.getCode();
520 type = roleFunc.getCode().contains("menu") ? "menu" : "url";
523 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, code, action);
524 extRolePerms = new ExternalAccessRolePerms(extPerms,
525 app.getNameSpace() + "."
526 + updateExtRole.getName().replaceAll(
527 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
529 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
530 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
531 logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: {} for POST: {}",
532 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
533 ResponseEntity<String> addResponse = template.exchange(
534 SystemProperties.getProperty(
535 EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
536 HttpMethod.POST, entity, String.class);
537 if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value()!= 409) {
539 logger.debug(EELFLoggerDelegate.debugLogger,
540 "updateRoleInExternalSystem: Connected to External Auth system but something went wrong! due to {} and statuscode: {}",
541 addResponse.getStatusCode().getReasonPhrase(),
542 addResponse.getStatusCode().value());
545 logger.debug(EELFLoggerDelegate.debugLogger,
546 "updateRoleInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ",
547 updateRolePerms, addResponse.getStatusCode().value());
552 private void addPartnerHasRoleFunctionsToGlobalRole(List<ExternalAccessPerms> permslist, ObjectMapper mapper,
553 EPApp app, Role updateExtRole) throws Exception {
554 for (ExternalAccessPerms perm : permslist) {
555 if (!EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace())) {
556 ExternalAccessRolePerms extAddGlobalRolePerms = null;
557 ExternalAccessPerms extAddPerms = null;
558 extAddPerms = new ExternalAccessPerms(perm.getType(), perm.getInstance(), perm.getAction());
559 extAddGlobalRolePerms = new ExternalAccessRolePerms(extAddPerms,
560 app.getNameSpace() + "." + updateExtRole.getName().replaceAll(
561 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
562 String addPerms = mapper.writeValueAsString(extAddGlobalRolePerms);
563 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
564 HttpEntity<String> entity = new HttpEntity<>(addPerms, headers);
565 logger.debug(EELFLoggerDelegate.debugLogger, "addPartnerHasRoleFunctionsToGlobalRole: {} ",
566 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
568 ResponseEntity<String> addResponse = template
569 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
570 + "role/perm", HttpMethod.POST, entity, String.class);
571 if (addResponse.getStatusCode().value() != 201) {
572 logger.debug(EELFLoggerDelegate.debugLogger,
573 "addPartnerHasRoleFunctionsToGlobalRole: While adding permission to the role in External Auth system something went wrong! due to {} and statuscode: {}",
574 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
576 logger.debug(EELFLoggerDelegate.debugLogger,
577 "addPartnerHasRoleFunctionsToGlobalRole: Finished adding permissions to roles in External Auth system and status code: {} ",
578 addResponse.getStatusCode().value());
580 } catch (Exception e) {
581 logger.error(EELFLoggerDelegate.errorLogger, "addPartnerHasRoleFunctionsToGlobalRole: Failed for POST request: {} due to ",
588 @SuppressWarnings("unchecked")
589 private void addFunctionsTOGlobalRole(List<EPRole> epRoleList, Role updateExtRole, List<RoleFunction> roleFunctionListNew, ObjectMapper mapper, EPApp app, EPApp portalAppInfo)
592 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addFunctionsTOGlobalRole");
593 //GET Permissions from External Auth System
594 JSONArray extPerms = getExtAuthPermissions(app);
595 List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);
596 final Map<String, ExternalAccessPermsDetail> existingPermsWithRoles = new HashMap<>();
597 final Map<String, ExternalAccessPermsDetail> existingPermsWithRolesWithPipes = new HashMap<>();
598 final Map<String, RoleFunction> userRquestedFunctionsMap = new HashMap<>();
599 final Map<String, RoleFunction> userRquestedFunctionsMapPipesFilter = new HashMap<>();
600 for (ExternalAccessPermsDetail permDetail : permsDetailList) {
601 existingPermsWithRoles.put(EcompPortalUtils.getFunctionCode(permDetail.getInstance()), permDetail);
602 existingPermsWithRolesWithPipes.put(permDetail.getInstance(), permDetail);
605 // Add If function does not exists for role in External Auth System
606 for (RoleFunction roleFunc : roleFunctionListNew) {
607 String roleFuncCode = "";
608 ExternalAccessPermsDetail permsDetail;
609 if(roleFunc.getCode().contains(FUNCTION_PIPE)) {
610 roleFuncCode = roleFunc.getCode();
611 permsDetail = existingPermsWithRolesWithPipes.get(roleFunc.getCode());
613 roleFuncCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
614 permsDetail = existingPermsWithRoles.get(roleFuncCode);
616 if (null == permsDetail.getRoles() || !permsDetail.getRoles()
617 .contains(portalAppInfo.getNameSpace() + FUNCTION_PIPE + epRoleList.get(0).getName().replaceAll(
618 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
619 addRoleFunctionsToGlobalRoleInExternalSystem(roleFunc, updateExtRole, mapper, app, portalAppInfo);
621 userRquestedFunctionsMap.put(roleFuncCode, roleFunc);
622 userRquestedFunctionsMapPipesFilter.put(EcompPortalUtils.getFunctionCode(roleFuncCode), roleFunc);
624 // Delete functions if exists in External Auth System but not in incoming request
625 final Map<String, Long> epAppRoleFuncParams = new HashMap<>();
626 epAppRoleFuncParams.put("requestedAppId", app.getId());
627 epAppRoleFuncParams.put("roleId",updateExtRole.getId());
628 List<GlobalRoleWithApplicationRoleFunction> globalRoleFunctionList = dataAccessService.executeNamedQuery("getGlobalRoleForRequestedApp", epAppRoleFuncParams, null);
629 for(GlobalRoleWithApplicationRoleFunction globalRoleFunc: globalRoleFunctionList){
630 String globalRoleFuncWithoutPipes = "";
631 RoleFunction roleFunc = null;
632 if(globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
633 globalRoleFuncWithoutPipes = globalRoleFunc.getFunctionCd();
634 roleFunc = userRquestedFunctionsMap.get(globalRoleFuncWithoutPipes);
636 globalRoleFuncWithoutPipes = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd());
637 roleFunc = userRquestedFunctionsMapPipesFilter.get(globalRoleFuncWithoutPipes);
639 if(roleFunc == null){
640 ExternalAccessPermsDetail permDetailFromMap = globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE) ? existingPermsWithRolesWithPipes.get(globalRoleFuncWithoutPipes) : existingPermsWithRoles.get(globalRoleFuncWithoutPipes);
641 ExternalAccessPerms perm = new ExternalAccessPerms(permDetailFromMap.getType(), EcompPortalUtils.getFunctionCode(permDetailFromMap.getInstance()), permDetailFromMap.getAction());
642 String roleName = portalAppInfo.getNameSpace()+"."+globalRoleFunc.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_");
643 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
644 removePermForRole(perm, mapper, roleName, headers);
647 logger.debug(EELFLoggerDelegate.debugLogger, "Finished addFunctionsTOGlobalRole");
648 } catch (Exception e) {
649 logger.error(EELFLoggerDelegate.errorLogger, "addFunctionsTOGlobalRole: Failed",e);
654 private void addRoleFunctionsToGlobalRoleInExternalSystem(RoleFunction addFunction, Role globalRole, ObjectMapper mapper, EPApp app,
655 EPApp portalAppInfo) throws Exception {
657 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addRoleFunctionsToGlobalRoleInExternalSystem");
658 ExternalAccessRolePerms extAddRolePerms = null;
659 ExternalAccessPerms extAddPerms = null;
660 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
664 if (addFunction.getCode().contains(FUNCTION_PIPE)) {
665 code = EcompPortalUtils.getFunctionCode(addFunction.getCode());
666 type = getFunctionCodeType(addFunction.getCode());
667 action = getFunctionCodeAction(addFunction.getCode());
669 code = addFunction.getCode();
670 type = addFunction.getCode().contains("menu") ? "menu" : "url";
673 extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, code, action);
674 extAddRolePerms = new ExternalAccessRolePerms(extAddPerms,
675 portalAppInfo.getNameSpace() + "." + globalRole.getName().replaceAll(
676 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
677 String updateRolePerms = mapper.writeValueAsString(extAddRolePerms);
678 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
679 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} ",
680 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
681 ResponseEntity<String> addResponse = template
682 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
683 + "role/perm", HttpMethod.POST, entity, String.class);
684 if (addResponse.getStatusCode().value() != 201) {
685 logger.debug(EELFLoggerDelegate.debugLogger,
686 "addRoleFunctionsInExternalSystem: While adding permission to the role in External Auth system something went wrong! due to {} and statuscode: {}",
687 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
689 logger.debug(EELFLoggerDelegate.debugLogger,
690 "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system and status code: {} ",
691 addResponse.getStatusCode().value());
693 logger.debug(EELFLoggerDelegate.debugLogger, "Finished addRoleFunctionsToGlobalRoleInExternalSystem");
695 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionsToGlobalRoleInExternalSystem: Failed",e);
702 * It adds functions to the role in external auth system
704 * @param updateExtRole
705 * @param addPermsMapper
707 * @return true if success else false
710 private boolean addRoleFunctionsInExternalSystem(Role updateExtRole, ObjectMapper addPermsMapper, EPApp app)
712 boolean response = false;
713 ExternalAccessRolePerms extAddRolePerms = null;
714 ExternalAccessPerms extAddPerms = null;
715 List<RoleFunction> roleFunctionListAdd = convertSetToListOfRoleFunctions(updateExtRole);
716 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
717 for (RoleFunction roleFunc : roleFunctionListAdd) {
721 if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
722 code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
723 type = getFunctionCodeType(roleFunc.getCode());
724 action = getFunctionCodeAction(roleFunc.getCode());
726 code = roleFunc.getCode();
727 type = roleFunc.getCode().contains("menu") ? "menu" : "url";
730 extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, code, action);
731 extAddRolePerms = new ExternalAccessRolePerms(extAddPerms,
732 app.getNameSpace() + "." + updateExtRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
733 String updateRolePerms = addPermsMapper.writeValueAsString(extAddRolePerms);
734 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
735 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} for POST: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
736 ResponseEntity<String> addResponse = template.exchange(
737 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
738 HttpMethod.POST, entity, String.class);
739 if (addResponse.getStatusCode().value() != 201) {
741 logger.debug(EELFLoggerDelegate.debugLogger,
742 "addRoleFunctionsInExternalSystem: While adding permission to the role in External Auth system something went wrong! due to {} and statuscode: {}",
743 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
746 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ", updateRolePerms, addResponse.getStatusCode().value());
754 * It converts list of functions in updateExtRole parameter to the RoleFunction object
756 * @param updateExtRole
757 * @return list of functions
759 @SuppressWarnings("unchecked")
760 private List<RoleFunction> convertSetToListOfRoleFunctions(Role updateExtRole) {
761 Set<RoleFunction> roleFunctionSetList = updateExtRole.getRoleFunctions();
762 List<RoleFunction> roleFunctionList = new ArrayList<>();
763 ObjectMapper roleFuncMapper = new ObjectMapper();
764 Iterator<RoleFunction> itetaror = roleFunctionSetList.iterator();
765 while (itetaror.hasNext()) {
766 Object nextValue = itetaror.next();
767 RoleFunction roleFunction = roleFuncMapper.convertValue(nextValue, RoleFunction.class);
768 roleFunctionList.add(roleFunction);
770 return roleFunctionList.stream().distinct().collect(Collectors.toList());
774 * It delete permissions/functions in the external auth system
780 * @throws JsonProcessingException
783 private void removePermForRole(ExternalAccessPerms perm, ObjectMapper permMapper, String name, HttpHeaders headers)
784 throws ExternalAuthSystemException, JsonProcessingException {
785 ExternalAccessRolePerms extAccessRolePerms = new ExternalAccessRolePerms(perm, name);
786 String permDetails = permMapper.writeValueAsString(extAccessRolePerms);
788 HttpEntity<String> deleteEntity = new HttpEntity<>(permDetails, headers);
789 logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: {} for DELETE: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, permDetails);
790 ResponseEntity<String> deletePermResponse = template
791 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/"
792 + name + "/perm", HttpMethod.DELETE, deleteEntity, String.class);
793 if (deletePermResponse.getStatusCode().value() != 200) {
794 throw new ExternalAuthSystemException(deletePermResponse.getBody());
796 logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: Finished deleting permission to role in External Auth system: {} and status code: {}",
797 permDetails, deletePermResponse.getStatusCode().value());
798 } catch(Exception e){
799 if(e.getMessage().contains("404")){
800 logger.error(EELFLoggerDelegate.errorLogger, "Failed to add role for DELETE request: {} due to {}", permDetails, e.getMessage());
808 * It will create new role in the External Auth System
812 * @return true if successfully added in the system else false
814 * If fails to add role in the system
816 private void addNewRoleInExternalSystem(List<EPRole> newRole, EPApp app) throws Exception, HttpClientErrorException {
818 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
819 ObjectMapper mapper = new ObjectMapper();
820 String addNewRole = "";
821 ExternalAccessRole extRole = new ExternalAccessRole();
822 String addDesc = null;
823 Map<String, String> extSystemJsonMapper = new LinkedHashMap<>();
824 extSystemJsonMapper.put(ID, String.valueOf(newRole.get(0).getId()));
825 extSystemJsonMapper.put(ROLE_NAME, String.valueOf(newRole.get(0).getName()));
826 extSystemJsonMapper.put(ACTIVE, String.valueOf(newRole.get(0).getActive()));
827 extSystemJsonMapper.put(PRIORITY, String.valueOf(newRole.get(0).getPriority()));
828 extSystemJsonMapper.put(APP_ID, String.valueOf(newRole.get(0).getAppId()));
829 extSystemJsonMapper.put(APP_ROLE_ID, String.valueOf(newRole.get(0).getAppRoleId()));
830 addDesc = mapper.writeValueAsString(extSystemJsonMapper);
831 extRole.setName(app.getNameSpace() + "." + newRole.get(0).getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
832 extRole.setDescription(addDesc);
833 addNewRole = mapper.writeValueAsString(extRole);
834 HttpEntity<String> postEntity = new HttpEntity<>(addNewRole, headers);
835 logger.debug(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: {} for POST: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addNewRole);
836 ResponseEntity<String> addNewRoleInExternalSystem = template.exchange(
837 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
838 HttpMethod.POST, postEntity, String.class);
839 if (addNewRoleInExternalSystem.getStatusCode().value() == 201) {
840 logger.debug(EELFLoggerDelegate.debugLogger,
841 "addNewRoleInExternalSystem: Finished adding into External Auth system for POST: {} and status code: {}",
842 addNewRole, addNewRoleInExternalSystem.getStatusCode().value());
844 }catch(HttpClientErrorException ht){
845 dataAccessService.deleteDomainObjects(EPRole.class, " role_id = "+ newRole.get(0).getId(), null);
846 logger.error(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: Failed to add in External Auth system and status code: {}",
848 throw new HttpClientErrorException(ht.getStatusCode());
854 * It updates existing role in the External Auth System
857 * It Contains role information
859 * @return string which is formatted to match with the external auth system
860 * @throws JsonProcessingException
862 private String updateExistingRoleInExternalSystem(Role addRole, EPApp app) throws JsonProcessingException {
863 ObjectMapper mapper = new ObjectMapper();
864 String addNewRole = "";
865 ExternalAccessRole extRole = new ExternalAccessRole();
866 List<EPRole> role = null;
867 String addDesc = null;
868 Map<String, String> extSystemUpdateRole = new LinkedHashMap<>();
869 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
870 role = getPortalAppRoleInfo(addRole.getId());
872 role = getPartnerAppRoleInfo(addRole.getId(), app);
874 extSystemUpdateRole.put(ID, String.valueOf(role.get(0).getId()));
875 extSystemUpdateRole.put(ROLE_NAME, String.valueOf(addRole.getName()));
876 extSystemUpdateRole.put(ACTIVE, String.valueOf(role.get(0).getActive()));
877 extSystemUpdateRole.put(PRIORITY, String.valueOf(role.get(0).getPriority()));
878 extSystemUpdateRole.put(APP_ID, String.valueOf(role.get(0).getAppId()));
879 extSystemUpdateRole.put(APP_ROLE_ID, String.valueOf(role.get(0).getAppRoleId()));
880 addDesc = mapper.writeValueAsString(extSystemUpdateRole);
881 extRole.setName(app.getNameSpace() + "." + addRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
882 extRole.setDescription(addDesc);
883 addNewRole = mapper.writeValueAsString(extRole);
888 * It create a role in the external auth system and then in our local
892 * @return true else false
895 @SuppressWarnings("unchecked")
896 @Transactional(rollbackFor = Exception.class)
897 private boolean addRoleInEcompDB(Role addRoleInDB, EPApp app) throws Exception {
898 boolean result = false;
899 EPRole epRole = null;
900 Set<RoleFunction> roleFunctionList = addRoleInDB.getRoleFunctions();
901 List<RoleFunction> roleFunctionListNew = new ArrayList<>();
902 ObjectMapper mapper = new ObjectMapper();
903 Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
904 while (itetaror.hasNext()) {
905 Object nextValue = itetaror.next();
906 RoleFunction roleFunction = mapper.convertValue(nextValue, RoleFunction.class);
907 roleFunctionListNew.add(roleFunction);
909 List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct().collect(Collectors.toList());
911 if (addRoleInDB.getId() == null) { // check if it is new role
912 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
913 checkIfRoleExitsInExternalSystem(addRoleInDB, app);
915 EPRole epRoleNew = new EPRole();
916 epRoleNew.setActive(addRoleInDB.getActive());
917 epRoleNew.setName(addRoleInDB.getName());
918 epRoleNew.setPriority(addRoleInDB.getPriority());
919 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
920 epRoleNew.setAppId(null);
922 epRoleNew.setAppId(app.getId());
924 dataAccessService.saveDomainObject(epRoleNew, null);
925 List<EPRole> getRoleCreated = null;
926 final Map<String, String> epAppRoleParams = new HashMap<>();
927 final Map<String, String> epAppPortalRoleParams = new HashMap<>();
928 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
929 epAppRoleParams.put("appId", String.valueOf(app.getId()));
930 epAppRoleParams.put(APP_ROLE_NAME_PARAM, addRoleInDB.getName());
931 List<EPRole> roleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, epAppRoleParams, null);
932 EPRole epUpdateRole = roleCreated.get(0);
933 epUpdateRole.setAppRoleId(epUpdateRole.getId());
934 dataAccessService.saveDomainObject(epUpdateRole, null);
935 getRoleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, epAppRoleParams, null);
937 epAppPortalRoleParams.put(APP_ROLE_NAME_PARAM, addRoleInDB.getName());
938 getRoleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, epAppPortalRoleParams, null);
940 // Add role in External Auth system
941 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
942 addNewRoleInExternalSystem(getRoleCreated, app);
944 } else { // if role already exists then update it
945 EPRole globalRole = null;
946 List<EPRole> applicationRoles;
947 List<EPRole> globalRoleList = getGlobalRolesOfPortal();
948 boolean isGlobalRole = false;
949 if (!globalRoleList.isEmpty()) {
950 EPRole role = globalRoleList.stream().filter(x -> addRoleInDB.getId().equals(x.getId())).findAny()
957 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)
958 || (globalRole != null && app.getId() != globalRole.getAppId())) {
959 applicationRoles = getPortalAppRoleInfo(addRoleInDB.getId());
961 applicationRoles = getPartnerAppRoleInfo(addRoleInDB.getId(), app);
963 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
964 updateRoleInExternalSystem(addRoleInDB, app, isGlobalRole);
965 // Add all user to the re-named role in external auth system
966 if (!applicationRoles.isEmpty()
967 && !addRoleInDB.getName().equals(applicationRoles.get(0).getName())) {
968 bulkUploadUsersSingleRole(app.getUebKey(), applicationRoles.get(0).getId(),
969 addRoleInDB.getName());
972 deleteRoleFunction(app, applicationRoles);
973 if (!applicationRoles.isEmpty()) {
974 epRole = applicationRoles.get(0);
975 epRole.setName(addRoleInDB.getName());
976 epRole.setPriority(addRoleInDB.getPriority());
977 epRole.setActive(addRoleInDB.getActive());
978 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
979 epRole.setAppId(null);
980 epRole.setAppRoleId(null);
981 } else if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)
982 && applicationRoles.get(0).getAppRoleId() == null) {
983 epRole.setAppRoleId(epRole.getId());
985 dataAccessService.saveDomainObject(epRole, null);
987 Long roleAppId = null;
988 if (globalRole != null && !app.getId().equals(globalRole.getAppId()))
989 roleAppId = PortalConstants.PORTAL_APP_ID;
990 saveRoleFunction(listWithoutDuplicates, app, applicationRoles, roleAppId);
993 } catch (Exception e) {
994 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInEcompDB is failed", e);
1002 * It validates whether role exists in external auth system
1009 private void checkIfRoleExitsInExternalSystem(Role checkRole, EPApp app) throws Exception {
1010 getNameSpaceIfExists(app);
1011 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1012 String roleName = app.getNameSpace() + "." + checkRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_");
1013 HttpEntity<String> checkRoleEntity = new HttpEntity<>(headers);
1014 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRoleExitsInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1015 ResponseEntity<String> checkRoleInExternalSystem = template
1016 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
1017 + roleName, HttpMethod.GET, checkRoleEntity, String.class);
1018 if (!checkRoleInExternalSystem.getBody().equals(IS_EMPTY_JSON_STRING)) {
1019 logger.debug("checkIfRoleExitsInExternalSystem: Role already exists in external system {} and status code: {} ", checkRoleInExternalSystem.getBody(), checkRoleInExternalSystem.getStatusCode().value());
1020 throw new ExternalAuthSystemException(" Role already exists in external system");
1025 * It saves list of functions to the role in portal
1027 * @param roleFunctionListNew
1029 * @param applicationRoles
1032 @SuppressWarnings("unchecked")
1033 private void saveRoleFunction(List<RoleFunction> roleFunctionListNew, EPApp app, List<EPRole> applicationRoles ,Long roleAppId)
1035 final Map<String, String> getAppFunctionParams = new HashMap<>();
1037 for (RoleFunction roleFunc : roleFunctionListNew) {
1038 String code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1039 EPAppRoleFunction appRoleFunc = new EPAppRoleFunction();
1040 appRoleFunc.setAppId(app.getId());
1041 appRoleFunc.setRoleId(applicationRoles.get(0).getId());
1042 appRoleFunc.setRoleAppId(String.valueOf(roleAppId));
1043 getAppFunctionParams.put("appId", String.valueOf(app.getId()));
1044 getAppFunctionParams.put(FUNCTION_CODE_PARAMS, roleFunc.getCode());
1045 // query to check if function code has pipes
1046 List<CentralV2RoleFunction> roleFunction = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null);
1047 if(roleFunction.isEmpty()){
1048 getAppFunctionParams.put(FUNCTION_CODE_PARAMS, code);
1049 roleFunction = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null);
1051 if(roleFunction.size() > 1){
1052 CentralV2RoleFunction getExactFunctionCode = appFunctionListFilter(code, roleFunction);
1053 appRoleFunc.setCode(getExactFunctionCode.getCode());
1055 appRoleFunc.setCode(roleFunction.get(0).getCode());
1058 dataAccessService.saveDomainObject(appRoleFunc, null);
1064 * It filters the app functions which starts with similar name in the result set
1067 * @param roleFunction
1068 * @return CentralRoleFunction
1070 private CentralV2RoleFunction appFunctionListFilter(String roleFuncCode, List<CentralV2RoleFunction> roleFunction) {
1071 final Map<String, CentralV2RoleFunction> appFunctionsFilter = new HashMap<>();
1072 final Map<String, CentralV2RoleFunction> appFunctionsFilterPipes = new HashMap<>();
1073 CentralV2RoleFunction getExactFunctionCode = null;
1074 for(CentralV2RoleFunction cenRoleFunction : roleFunction){
1075 appFunctionsFilter.put(cenRoleFunction.getCode(), cenRoleFunction);
1076 appFunctionsFilterPipes.put(EcompPortalUtils.getFunctionCode(cenRoleFunction.getCode()), cenRoleFunction);
1078 getExactFunctionCode = appFunctionsFilter.get(roleFuncCode);
1079 if(getExactFunctionCode == null){
1080 getExactFunctionCode = appFunctionsFilterPipes.get(roleFuncCode);
1082 return getExactFunctionCode;
1086 * It deletes all EPAppRoleFunction records in the portal
1091 @SuppressWarnings("unchecked")
1092 private void deleteRoleFunction(EPApp app, List<EPRole> role) {
1093 final Map<String, Long> appRoleFuncsParams = new HashMap<>();
1094 appRoleFuncsParams.put("appId", app.getId());
1095 appRoleFuncsParams.put("roleId", role.get(0).getId());
1096 List<EPAppRoleFunction> appRoleFunctionList = dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null);
1097 if (!appRoleFunctionList.isEmpty()) {
1098 for (EPAppRoleFunction approleFunction : appRoleFunctionList) {
1099 dataAccessService.deleteDomainObject(approleFunction, null);
1105 @SuppressWarnings("unchecked")
1106 public List<EPUser> getUser(String loginId) throws InvalidUserException{
1107 final Map<String, String> userParams = new HashMap<>();
1108 userParams.put("org_user_id", loginId);
1109 List<EPUser> userList = dataAccessService.executeNamedQuery("getEPUserByOrgUserId", userParams, null);
1110 if (userList.isEmpty()) {
1111 throw new InvalidUserException("User not found");
1117 public String getV2UserWithRoles(String loginId, String uebkey) throws Exception {
1118 final Map<String, String> params = new HashMap<>();
1119 List<EPUser> userList = null;
1120 CentralV2User cenV2User = null;
1121 String result = null;
1123 params.put("orgUserIdValue", loginId);
1124 List<EPApp> appList = getApp(uebkey);
1125 if (!appList.isEmpty()) {
1126 userList = getUser(loginId);
1127 if (!userList.isEmpty()) {
1128 ObjectMapper mapper = new ObjectMapper();
1129 cenV2User = getV2UserAppRoles(loginId, uebkey);
1130 result = mapper.writeValueAsString(cenV2User);
1131 } else if (userList.isEmpty()) {
1132 throw new InvalidUserException("User not found");
1135 throw new InactiveApplicationException("Application not found");
1137 } catch (Exception e) {
1138 logger.error(EELFLoggerDelegate.errorLogger, "getUser: failed", e);
1145 public List<CentralV2Role> getRolesForApp(String uebkey) throws Exception {
1146 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Entering into getRolesForApp");
1147 List<CentralV2Role> roleList = new ArrayList<>();
1148 final Map<String, Long> params = new HashMap<>();
1150 List<EPApp> app = getApp(uebkey);
1151 List<EPRole> appRolesList = getAppRoles(app.get(0).getId());
1152 roleList = createCentralRoleObject(app, appRolesList, roleList, params);
1153 if(app.get(0).getId() != PortalConstants.PORTAL_APP_ID){
1154 List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
1155 List<EPRole> globalRolesList = getGlobalRolesOfPortal();
1156 List<CentralV2Role> portalsGlobalRolesFinlaList = new ArrayList<>();
1157 if (!globalRolesList.isEmpty()) {
1158 for (EPRole eprole : globalRolesList) {
1159 CentralV2Role cenRole = convertRoleToCentralV2Role(eprole);
1160 portalsGlobalRolesFinlaList.add(cenRole);
1162 roleList.addAll(globalRoleList);
1163 for (CentralV2Role role : portalsGlobalRolesFinlaList) {
1164 CentralV2Role result = roleList.stream()
1165 .filter(x -> role.getId().equals(x.getId())).findAny().orElse(null);
1170 for (EPRole role : globalRolesList) {
1171 CentralV2Role cenRole = convertRoleToCentralV2Role(role);
1172 roleList.add(cenRole);
1176 } catch (Exception e) {
1177 logger.error(EELFLoggerDelegate.errorLogger, "getRolesForApp: Failed!", e);
1180 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Finished!");
1181 return roleList.stream().distinct().collect(Collectors.toList());
1184 @SuppressWarnings("unchecked")
1186 public List<CentralV2RoleFunction> getRoleFuncList(String uebkey) throws Exception {
1187 EPApp app = getApp(uebkey).get(0);
1188 List<CentralV2RoleFunction> finalRoleList = new ArrayList<>();
1189 final Map<String, Long> params = new HashMap<>();
1190 params.put(APP_ID, app.getId());
1191 List<CentralV2RoleFunction> getRoleFuncList = dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null);
1192 for (CentralV2RoleFunction roleFuncItem : getRoleFuncList) {
1193 String code = EcompPortalUtils.getFunctionCode(roleFuncItem.getCode());
1194 String type = getFunctionCodeType(roleFuncItem.getCode());
1195 String action = getFunctionCodeAction(roleFuncItem.getCode());
1196 roleFuncItem.setCode(EPUserUtils.decodeFunctionCode(code));
1197 roleFuncItem.setType(type);
1198 roleFuncItem.setAction(action);
1199 finalRoleList.add(roleFuncItem);
1201 return finalRoleList;
1206 public String getFunctionCodeAction(String roleFuncItem) {
1207 return (!roleFuncItem.contains(FUNCTION_PIPE)) ? "*"
1208 : EcompPortalUtils.getFunctionAction(roleFuncItem);
1212 public String getFunctionCodeType(String roleFuncItem) {
1214 if ((roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))
1215 || (!roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))) {
1217 } else if (checkIfCodeHasNoPipesAndHasTypeUrl(roleFuncItem)
1218 ||checkIfCodeHasPipesAndHasTypeUrl(roleFuncItem)
1219 ||checkIfCodeHasNoPipesAndHasNoTypeUrl(roleFuncItem)) {
1221 } else if (roleFuncItem.contains(FUNCTION_PIPE)
1222 && (!roleFuncItem.contains("menu") || roleFuncItem.contains("url"))) {
1223 type = EcompPortalUtils.getFunctionType(roleFuncItem);
1230 * It check whether function code has no pipes and no url string in it
1232 * @param roleFuncItem
1233 * @return true or false
1235 private boolean checkIfCodeHasNoPipesAndHasNoTypeUrl(String roleFuncItem) {
1236 return !roleFuncItem.contains(FUNCTION_PIPE) && !roleFuncItem.contains("url");
1241 * It check whether function code has pipes and url string in it
1243 * @param roleFuncItem
1244 * @return true or false
1246 private boolean checkIfCodeHasPipesAndHasTypeUrl(String roleFuncItem) {
1247 return roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
1252 * It check whether function code has no pipes and has url string in it
1254 * @param roleFuncItem
1255 * @return true or false
1257 private boolean checkIfCodeHasNoPipesAndHasTypeUrl(String roleFuncItem) {
1258 return !roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
1262 * It returns user detail information which is deep copy of EPUser.class object
1270 @SuppressWarnings("unchecked")
1271 private CentralV2User createEPUser(EPUser userInfo, Set<EPUserApp> userAppSet, EPApp app) throws Exception {
1273 final Map<String, Long> params = new HashMap<>();
1274 CentralV2User userAppList = new CentralV2User();
1275 CentralV2User user1 = null;
1276 final Map<String, Long> params1 = new HashMap<>();
1277 List<EPRole> globalRoleList = new ArrayList<>();
1280 if (app.getId() != PortalConstants.PORTAL_APP_ID) {
1281 params1.put("userId", userInfo.getId());
1282 params1.put("appId", app.getId());
1283 globalRoleList = dataAccessService.executeNamedQuery("userAppGlobalRoles", params1, null);
1285 userAppList.setUserApps(new TreeSet<CentralV2UserApp>());
1286 for (EPUserApp userApp : userAppSet) {
1287 if (userApp.getRole().getActive()) {
1288 EPApp epApp = userApp.getApp();
1289 String globalRole = userApp.getRole().getName().toLowerCase();
1290 if (((epApp.getId().equals(app.getId()))
1291 && (!userApp.getRole().getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)))
1292 || ((epApp.getId().equals(PortalConstants.PORTAL_APP_ID))
1293 && (globalRole.toLowerCase().startsWith("global_")))) {
1294 CentralV2UserApp cua = new CentralV2UserApp();
1295 cua.setUserId(null);
1296 CentralApp cenApp = new CentralApp(1L, epApp.getCreated(), epApp.getModified(),
1297 epApp.getCreatedId(), epApp.getModifiedId(), epApp.getRowNum(), epApp.getName(),
1298 epApp.getImageUrl(), epApp.getDescription(), epApp.getNotes(), epApp.getUrl(),
1299 epApp.getAlternateUrl(), epApp.getAppRestEndpoint(), epApp.getMlAppName(),
1300 epApp.getMlAppAdminId(), String.valueOf(epApp.getMotsId()), epApp.getAppPassword(),
1301 String.valueOf(epApp.getOpen()), String.valueOf(epApp.getEnabled()),
1302 epApp.getThumbnail(), epApp.getUsername(), epApp.getUebKey(), epApp.getUebSecret(),
1303 epApp.getUebTopicName());
1306 if (globalRole.toLowerCase().startsWith("global_")
1307 && epApp.getId().equals(PortalConstants.PORTAL_APP_ID)
1308 && !epApp.getId().equals(app.getId())) {
1309 appId = app.getId();
1310 EPRole result = null;
1311 if (globalRoleList.size() > 0)
1312 result = globalRoleList.stream()
1313 .filter(x -> userApp.getRole().getId().equals(x.getId())).findAny()
1318 appId = userApp.getApp().getId();
1320 params.put("roleId", userApp.getRole().getId());
1321 params.put(APP_ID, appId);
1322 List<CentralV2RoleFunction> appRoleFunctionList = dataAccessService
1323 .executeNamedQuery("getAppRoleFunctionList", params, null);
1324 SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>();
1325 for (CentralV2RoleFunction roleFunc : appRoleFunctionList) {
1326 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1327 CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(roleFunc.getId(),
1328 functionCode, roleFunc.getName(), null, null);
1329 roleFunctionSet.add(cenRoleFunc);
1331 Long userRoleId = null;
1332 if (globalRole.toLowerCase().startsWith("global_")
1333 || epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1334 userRoleId = userApp.getRole().getId();
1336 userRoleId = userApp.getRole().getAppRoleId();
1338 CentralV2Role cenRole = new CentralV2Role(userRoleId, userApp.getRole().getCreated(),
1339 userApp.getRole().getModified(), userApp.getRole().getCreatedId(),
1340 userApp.getRole().getModifiedId(), userApp.getRole().getRowNum(),
1341 userApp.getRole().getName(), userApp.getRole().getActive(),
1342 userApp.getRole().getPriority(), roleFunctionSet, null, null);
1343 cua.setRole(cenRole);
1345 userAppList.getUserApps().add(cua);
1350 user1 = new CentralV2User(null, userInfo.getCreated(), userInfo.getModified(), userInfo.getCreatedId(),
1351 userInfo.getModifiedId(), userInfo.getRowNum(), userInfo.getOrgId(), userInfo.getManagerId(),
1352 userInfo.getFirstName(), userInfo.getMiddleInitial(), userInfo.getLastName(), userInfo.getPhone(),
1353 userInfo.getFax(), userInfo.getCellular(), userInfo.getEmail(), userInfo.getAddressId(),
1354 userInfo.getAlertMethodCd(), userInfo.getHrid(), userInfo.getOrgUserId(), userInfo.getOrgCode(),
1355 userInfo.getAddress1(), userInfo.getAddress2(), userInfo.getCity(), userInfo.getState(),
1356 userInfo.getZipCode(), userInfo.getCountry(), userInfo.getOrgManagerUserId(),
1357 userInfo.getLocationClli(), userInfo.getBusinessCountryCode(), userInfo.getBusinessCountryName(),
1358 userInfo.getBusinessUnit(), userInfo.getBusinessUnitName(), userInfo.getDepartment(),
1359 userInfo.getDepartmentName(), userInfo.getCompanyCode(), userInfo.getCompany(),
1360 userInfo.getZipCodeSuffix(), userInfo.getJobTitle(), userInfo.getCommandChain(),
1361 userInfo.getSiloStatus(), userInfo.getCostCenter(), userInfo.getFinancialLocCode(),
1362 userInfo.getLoginId(), userInfo.getLoginPwd(), userInfo.getLastLoginDate(), userInfo.getActive(),
1363 userInfo.getInternal(), userInfo.getSelectedProfileId(), userInfo.getTimeZoneId(),
1364 userInfo.isOnline(), userInfo.getChatId(), userAppList.getUserApps(), null);
1365 } catch (Exception e) {
1366 logger.error(EELFLoggerDelegate.errorLogger, "createEPUser: createEPUser failed", e);
1373 public CentralV2Role getRoleInfo(Long roleId, String uebkey) throws Exception {
1374 final Map<String, Long> params = new HashMap<>();
1375 List<CentralV2Role> roleList = new ArrayList<>();
1376 CentralV2Role cenRole = new CentralV2Role();
1377 List<EPRole> roleInfo = null;
1378 List<EPApp> app = null;
1380 app = getApp(uebkey);
1381 if (app.isEmpty()) {
1382 throw new InactiveApplicationException("Application not found");
1384 if (app.get(0).getId() != PortalConstants.PORTAL_APP_ID) {
1385 List<EPRole> globalRoleList = new ArrayList<>();
1386 globalRoleList = getGlobalRolesOfPortal();
1387 if (globalRoleList.size() > 0) {
1388 EPRole result = globalRoleList.stream().filter(x -> roleId.equals(x.getId())).findAny()
1391 return getGlobalRoleForRequestedApp(app.get(0).getId(), roleId);
1394 if (app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
1395 roleInfo = getPortalAppRoleInfo(roleId);
1397 roleInfo = getPartnerAppRoleInfo(roleId, app.get(0));
1399 roleList = createCentralRoleObject(app, roleInfo, roleList, params);
1400 if (roleList.isEmpty()) {
1404 } catch (Exception e) {
1405 logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo: failed", e);
1409 return roleList.get(0);
1412 @SuppressWarnings("unchecked")
1413 private List<EPRole> getPartnerAppRoleInfo(Long roleId, EPApp app) {
1414 List<EPRole> roleInfo;
1415 final Map<String, Long> getPartnerAppRoleParams = new HashMap<>();
1416 getPartnerAppRoleParams.put("appRoleId", roleId);
1417 getPartnerAppRoleParams.put("appId", app.getId());
1418 roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams, null);
1419 if(roleInfo.isEmpty()) {
1420 getPartnerAppRoleParams.put("appRoleId", roleId);
1421 roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleById", getPartnerAppRoleParams, null);
1426 @SuppressWarnings("unchecked")
1427 private List<EPRole> getPortalAppRoleInfo(Long roleId) {
1428 List<EPRole> roleInfo;
1429 final Map<String, Long> getPortalAppRoleParams = new HashMap<>();
1430 getPortalAppRoleParams.put("roleId", roleId);
1431 roleInfo = dataAccessService.executeNamedQuery("getPortalAppRoleByRoleId", getPortalAppRoleParams, null);
1437 * It returns list of app roles along with role functions and which went through deep copy
1444 * @throws DecoderException
1446 @SuppressWarnings("unchecked")
1447 private List<CentralV2Role> createCentralRoleObject(List<EPApp> app, List<EPRole> roleInfo,
1448 List<CentralV2Role> roleList, Map<String, Long> params) throws RoleFunctionException {
1449 for (EPRole role : roleInfo) {
1450 params.put("roleId", role.getId());
1451 params.put(APP_ID, app.get(0).getId());
1452 List<CentralV2RoleFunction> cenRoleFuncList = dataAccessService.executeNamedQuery("getAppRoleFunctionList",
1454 SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>();
1455 for (CentralV2RoleFunction roleFunc : cenRoleFuncList) {
1456 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1457 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
1458 String type = getFunctionCodeType(roleFunc.getCode());
1459 String action = getFunctionCodeAction(roleFunc.getCode());
1460 CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(role.getId(), functionCode,
1461 roleFunc.getName(), null, type, action, null);
1462 roleFunctionSet.add(cenRoleFunc);
1464 SortedSet<CentralV2Role> childRoles = new TreeSet<>();
1465 SortedSet<CentralV2Role> parentRoles = new TreeSet<>();
1466 CentralV2Role cenRole = null;
1467 if (role.getAppRoleId() == null) {
1468 cenRole = new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
1469 role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
1470 roleFunctionSet, childRoles, parentRoles);
1472 cenRole = new CentralV2Role(role.getAppRoleId(), role.getCreated(), role.getModified(),
1473 role.getCreatedId(), role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(),
1474 role.getPriority(), roleFunctionSet, childRoles, parentRoles);
1476 roleList.add(cenRole);
1481 @SuppressWarnings("unchecked")
1483 public CentralV2RoleFunction getRoleFunction(String functionCode, String uebkey) throws Exception {
1484 String code = EcompPortalUtils.getFunctionCode(functionCode);
1485 String encodedCode = encodeFunctionCode(code);
1486 CentralV2RoleFunction roleFunc = null;
1487 EPApp app = getApp(uebkey).get(0);
1488 List<CentralV2RoleFunction> getRoleFuncList = null;
1489 final Map<String, String> params = new HashMap<>();
1491 params.put(FUNCTION_CODE_PARAMS, functionCode);
1492 params.put(APP_ID, String.valueOf(app.getId()));
1493 getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
1494 if (getRoleFuncList.isEmpty()) {
1495 params.put(FUNCTION_CODE_PARAMS, encodedCode);
1496 getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
1497 if (getRoleFuncList.isEmpty()) {
1501 if (getRoleFuncList.size() > 1) {
1502 CentralV2RoleFunction cenV2RoleFunction = appFunctionListFilter(encodedCode, getRoleFuncList);
1503 if (cenV2RoleFunction == null)
1505 roleFunc = checkIfPipesExitsInFunctionCode(cenV2RoleFunction);
1507 roleFunc = getRoleFuncList.get(0);
1509 } catch (Exception e) {
1510 logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction: failed", e);
1516 private CentralV2RoleFunction checkIfPipesExitsInFunctionCode(CentralV2RoleFunction getRoleFuncList) {
1517 CentralV2RoleFunction roleFunc;
1518 String functionCodeFormat = getRoleFuncList.getCode();
1519 if (functionCodeFormat.contains(FUNCTION_PIPE)) {
1520 String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(functionCodeFormat);
1521 String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(functionCodeFormat);
1522 String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(functionCodeFormat);
1523 roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), newfunctionCodeFormat,
1524 getRoleFuncList.getName(), getRoleFuncList.getAppId(), newfunctionTypeFormat, newfunctionActionFormat,
1525 getRoleFuncList.getEditUrl());
1527 roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), functionCodeFormat,
1528 getRoleFuncList.getName(), getRoleFuncList.getAppId(),
1529 getRoleFuncList.getEditUrl());
1535 public boolean saveCentralRoleFunction(CentralV2RoleFunction domainCentralRoleFunction, EPApp app) throws Exception {
1536 boolean saveOrUpdateFunction = false;
1538 domainCentralRoleFunction.setCode(encodeFunctionCode(domainCentralRoleFunction.getCode()));
1539 final Map<String, String> functionParams = new HashMap<>();
1540 functionParams.put("appId", String.valueOf(app.getId()));
1541 if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1542 addRoleFunctionInExternalSystem(domainCentralRoleFunction, app);
1544 if(domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null){
1545 domainCentralRoleFunction.setCode(domainCentralRoleFunction.getType()+
1546 FUNCTION_PIPE+domainCentralRoleFunction.getCode()+FUNCTION_PIPE+domainCentralRoleFunction.getAction());
1548 domainCentralRoleFunction.setAppId(app.getId());
1549 dataAccessService.saveDomainObject(domainCentralRoleFunction, null);
1550 saveOrUpdateFunction = true;
1551 } catch (Exception e) {
1552 logger.error(EELFLoggerDelegate.errorLogger, "saveCentralRoleFunction: failed", e);
1555 return saveOrUpdateFunction;
1559 * It creates application permission in external auth system
1561 * @param domainCentralRoleFunction
1565 private void addRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
1567 ObjectMapper mapper = new ObjectMapper();
1568 ExternalAccessPerms extPerms = new ExternalAccessPerms();
1569 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1571 String instance = "";
1573 if((domainCentralRoleFunction.getType()!=null && domainCentralRoleFunction.getAction()!=null) || domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)){
1574 type = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) ? EcompPortalUtils.getFunctionType(domainCentralRoleFunction.getCode()) : domainCentralRoleFunction.getType();
1575 instance = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) ? EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode()) : domainCentralRoleFunction.getCode();
1576 action = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) ? EcompPortalUtils.getFunctionAction(domainCentralRoleFunction.getCode()) : domainCentralRoleFunction.getAction();
1578 type = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url";
1579 instance = domainCentralRoleFunction.getCode();
1582 // get Permissions from External Auth System
1583 JSONArray extPermsList = getExtAuthPermissions(app);
1584 List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPermsList);
1585 String requestedPerm = type+FUNCTION_PIPE+instance+FUNCTION_PIPE+action;
1586 boolean checkIfFunctionsExits = permsDetailList.stream().anyMatch(permsDetail -> permsDetail.getInstance().equals(requestedPerm));
1587 if (!checkIfFunctionsExits) {
1589 extPerms.setAction(action);
1590 extPerms.setInstance(instance);
1591 extPerms.setType(app.getNameSpace() + "." + type);
1592 extPerms.setDescription(domainCentralRoleFunction.getName());
1593 String addFunction = mapper.writeValueAsString(extPerms);
1594 HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
1595 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for POST: {}" , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
1596 ResponseEntity<String> addPermResponse= template.exchange(
1597 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
1598 HttpMethod.POST, entity, String.class);
1599 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ", addPermResponse.getStatusCode().value(), addFunction);
1600 } catch(HttpClientErrorException e){
1601 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to add function in external central auth system", e);
1602 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1604 }catch (Exception e) {
1605 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionInExternalSystem: Failed to add fucntion in external central auth system",
1611 extPerms.setAction(action);
1612 extPerms.setInstance(instance);
1613 extPerms.setType(app.getNameSpace() + "." + type);
1614 extPerms.setDescription(domainCentralRoleFunction.getName());
1615 String updateRoleFunction = mapper.writeValueAsString(extPerms);
1616 HttpEntity<String> entity = new HttpEntity<>(updateRoleFunction, headers);
1617 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for PUT: {}" , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRoleFunction);
1618 ResponseEntity<String> updatePermResponse = template.exchange(
1619 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
1620 HttpMethod.PUT, entity, String.class);
1621 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished updating permission in External Auth system {} and response: {} ", updateRoleFunction, updatePermResponse.getStatusCode().value());
1622 } catch(HttpClientErrorException e){
1623 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to add function in external central auth system", e);
1624 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1626 } catch (Exception e) {
1627 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionInExternalSystem: Failed to update function in external central auth system",e);
1633 @SuppressWarnings("unchecked")
1635 @Transactional(rollbackFor = Exception.class)
1636 public boolean deleteCentralRoleFunction(String code, EPApp app) {
1637 boolean deleteFunctionResponse = false;
1639 final Map<String, String> params = new HashMap<>();
1640 params.put(FUNCTION_CODE_PARAMS, code);
1641 params.put(APP_ID, String.valueOf(app.getId()));
1642 List<CentralV2RoleFunction> domainCentralRoleFunction = dataAccessService
1643 .executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
1644 CentralV2RoleFunction appFunctionCode = appFunctionListFilter(code, domainCentralRoleFunction);
1645 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1646 deleteRoleFunctionInExternalSystem(appFunctionCode, app);
1647 // Delete role function dependency records
1648 deleteAppRoleFunctions(appFunctionCode.getCode(), app);
1650 dataAccessService.deleteDomainObject(appFunctionCode, null);
1651 deleteFunctionResponse = true;
1652 } catch (Exception e) {
1653 logger.error(EELFLoggerDelegate.errorLogger, "deleteCentralRoleFunction: failed", e);
1655 return deleteFunctionResponse;
1659 * It deletes app function record in portal
1664 private void deleteAppRoleFunctions(String code, EPApp app) {
1665 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
1666 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + code + "'", null);
1671 * It deletes permission in the external auth system
1673 * @param domainCentralRoleFunction
1677 private void deleteRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
1680 ObjectMapper mapper = new ObjectMapper();
1681 ExternalAccessPerms extPerms = new ExternalAccessPerms();
1682 String instanceValue = EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode());
1683 String checkType = getFunctionCodeType(domainCentralRoleFunction.getCode());
1684 String actionValue = getFunctionCodeAction(domainCentralRoleFunction.getCode());
1685 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1686 extPerms.setAction(actionValue);
1687 extPerms.setInstance(instanceValue);
1688 extPerms.setType(app.getNameSpace() + "." + checkType);
1689 extPerms.setDescription(domainCentralRoleFunction.getName());
1690 String deleteRoleFunction = mapper.writeValueAsString(extPerms);
1691 HttpEntity<String> entity = new HttpEntity<>(deleteRoleFunction, headers);
1692 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleFunctionInExternalSystem: {} for DELETE: {} ",
1693 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, deleteRoleFunction);
1694 ResponseEntity<String> delPermResponse = template
1695 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1696 + "perm?force=true", HttpMethod.DELETE, entity, String.class);
1697 logger.debug(EELFLoggerDelegate.debugLogger,
1698 "deleteRoleFunctionInExternalSystem: Finished deleting permission in External Auth system {} and status code: {} ",
1699 deleteRoleFunction, delPermResponse.getStatusCode().value());
1700 } catch(HttpClientErrorException e){
1701 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to delete functions in External System", e);
1702 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1703 } catch (Exception e) {
1704 if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
1705 logger.debug(EELFLoggerDelegate.debugLogger,
1706 " deleteRoleFunctionInExternalSystem: It seems like function is already deleted in external central auth system but exists in local DB",
1709 logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleFunctionInExternalSystem: Failed to delete functions in External System", e);
1715 public ExternalRequestFieldsValidator saveRoleForApplication(Role saveRole, String uebkey) throws Exception {
1716 boolean response = false;
1717 String message = "";
1719 EPApp app = getApp(uebkey).get(0);
1720 addRoleInEcompDB(saveRole, app);
1722 } catch (Exception e) {
1723 message = e.getMessage();
1724 logger.error(EELFLoggerDelegate.errorLogger, "saveRoleForApplication failed", e);
1726 return new ExternalRequestFieldsValidator(response,message);
1729 @SuppressWarnings("unchecked")
1731 public boolean deleteRoleForApplication(String deleteRole, String uebkey) throws Exception {
1732 Session localSession = sessionFactory.openSession();
1733 Transaction transaction = null;
1734 boolean result = false;
1736 List<EPRole> epRoleList = null;
1737 EPApp app = getApp(uebkey).get(0);
1738 final Map<String, String> deleteRoleParams = new HashMap<>();
1739 deleteRoleParams.put(APP_ROLE_NAME_PARAM, deleteRole);
1740 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1741 epRoleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, deleteRoleParams, null);
1743 deleteRoleParams.put(APP_ID, String.valueOf(app.getId()));
1744 epRoleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, deleteRoleParams, null);
1746 if (!epRoleList.isEmpty()) {
1747 transaction = localSession.beginTransaction();
1748 // Delete app role functions before deleting role
1749 deleteRoleFunction(app, epRoleList);
1750 if (app.getId() == 1) {
1751 // Delete fn_user_ role
1752 dataAccessService.deleteDomainObjects(EPUserApp.class,
1753 APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
1754 boolean isPortalRequest = false;
1755 deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest);
1757 deleteRoleInExternalAuthSystem(epRoleList, app);
1758 transaction.commit();
1759 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: committed the transaction");
1760 dataAccessService.deleteDomainObject(epRoleList.get(0), null);
1763 } catch (Exception e) {
1764 logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleForApplication: failed", e);
1767 localSession.close();
1774 * It deletes role for application in external auth system
1776 * @param epRoleList contains role information
1777 * @param app contains application information
1780 private void deleteRoleInExternalAuthSystem(List<EPRole> epRoleList, EPApp app) throws Exception {
1781 ResponseEntity<String> deleteResponse;
1782 ResponseEntity<String> res = getNameSpaceIfExists(app);
1783 if (res.getStatusCode() == HttpStatus.OK) {
1784 // Delete Role in External System
1785 String deleteRoleKey = "{\"name\":\"" + app.getNameSpace() + "." + epRoleList.get(0).getName()
1786 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_") + "\"}";
1787 deleteResponse = deleteRoleInExternalSystem(deleteRoleKey);
1788 if (deleteResponse.getStatusCode().value() != 200 || deleteResponse.getStatusCode().value() != 404) {
1789 EPLogUtil.logExternalAuthAccessAlarm(logger, deleteResponse.getStatusCode());
1790 logger.error(EELFLoggerDelegate.errorLogger,
1791 "deleteRoleForApplication: Failed to delete role in external auth system! due to {} ",
1792 deleteResponse.getBody());
1794 logger.debug(EELFLoggerDelegate.debugLogger,
1795 "deleteRoleForApplication: about to commit the transaction");
1801 * It deletes application user role in external auth system
1808 private void deleteUserRoleInExternalSystem(EPRole role, EPApp app, String LoginId) throws Exception {
1809 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1810 HttpEntity<String> entity = new HttpEntity<>(headers);
1811 getNameSpaceIfExists(app);
1812 logger.debug(EELFLoggerDelegate.debugLogger,"deleteUserRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1813 ResponseEntity<String> getResponse = template
1815 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
1818 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
1819 + "/" + app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
1820 HttpMethod.GET, entity, String.class);
1821 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: Finished GET user roles from External Auth system and response: {} ", getResponse.getBody());
1822 if (getResponse.getStatusCode().value() != 200) {
1823 throw new ExternalAuthSystemException(getResponse.getBody());
1825 String res = getResponse.getBody();
1826 if (!res.equals(IS_EMPTY_JSON_STRING)) {
1827 HttpEntity<String> userRoleentity = new HttpEntity<>(headers);
1828 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1829 ResponseEntity<String> deleteResponse = template
1831 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1832 + "userRole/" + LoginId
1834 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
1835 + "/" + app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
1836 HttpMethod.DELETE, userRoleentity, String.class);
1837 if (deleteResponse.getStatusCode().value() != 200) {
1838 throw new ExternalAuthSystemException("Failed to delete user role");
1840 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: Finished deleting user role in External Auth system and status code: {} ", deleteResponse.getStatusCode().value());
1844 @SuppressWarnings("unchecked")
1846 public List<CentralV2Role> getActiveRoles(String uebkey) throws Exception {
1847 List<CentralV2Role> roleList = new ArrayList<>();
1849 List<EPApp> app = getApp(uebkey);
1850 final Map<String, Long> params = new HashMap<>();
1853 if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
1854 appId = app.get(0).getId();
1856 List<Criterion> restrictionsList = new ArrayList<Criterion>();
1857 Criterion active_ynCrt = Restrictions.eq("active", Boolean.TRUE);
1860 appIdCrt = Restrictions.isNull("appId");
1862 appIdCrt = Restrictions.eq("appId", appId);
1863 Criterion andCrit = Restrictions.and(active_ynCrt, appIdCrt);
1864 restrictionsList.add(andCrit);
1865 List<EPRole> epRole = (List<EPRole>) dataAccessService.getList(EPRole.class, null, restrictionsList, null);
1866 roleList = createCentralRoleObject(app, epRole, roleList, params);
1867 List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
1868 if (globalRoleList.size() > 0)
1869 roleList.addAll(globalRoleList);
1870 } catch (Exception e) {
1871 logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles: failed", e);
1879 @Transactional(rollbackFor = Exception.class)
1880 public ExternalRequestFieldsValidator deleteDependencyRoleRecord(Long roleId, String uebkey, String LoginId) throws Exception {
1881 Session localSession = sessionFactory.openSession();
1882 String message = "";
1883 Transaction transaction = null;
1884 boolean response = false;
1887 transaction = localSession.beginTransaction();
1888 List<EPRole> epRoleList = null;
1889 app = getApp(uebkey).get(0);
1890 if(app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1891 epRoleList = getPortalAppRoleInfo(roleId);
1893 epRoleList = getPartnerAppRoleInfo(roleId, app);
1895 if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1896 // Delete User Role in External System before deleting role
1897 deleteUserRoleInExternalSystem(epRoleList.get(0), app, LoginId);
1899 // Delete user app roles
1900 dataAccessService.deleteDomainObjects(EPUserApp.class,
1901 APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
1902 boolean isPortalRequest = false;
1903 deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest);
1904 transaction.commit();
1905 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1906 // Final call to delete role once all dependencies has been deleted
1907 deleteRoleInExternalAuthSystem(epRoleList, app);
1909 dataAccessService.deleteDomainObjects(EPRole.class, " role_id = "+ epRoleList.get(0).getId(), null);
1910 logger.debug(EELFLoggerDelegate.debugLogger, "deleteDependencyRoleRecord: committed the transaction");
1912 } catch(HttpClientErrorException e){
1913 logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord: HttpClientErrorException", e);
1914 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1915 message = e.getMessage();
1916 } catch (Exception e) {
1917 logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord failed", e);
1918 EcompPortalUtils.rollbackTransaction(transaction,
1919 "deleteDependencyRoleRecord rollback, exception = " + e.toString());
1920 message = e.getMessage();
1922 localSession.close();
1924 return new ExternalRequestFieldsValidator(response,message);
1928 @SuppressWarnings("unchecked")
1930 public void syncRoleFunctionFromExternalAccessSystem(EPApp app) {
1933 // get Permissions from External Auth System
1934 JSONArray extPerms = getExtAuthPermissions(app);
1935 List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);
1937 // get functions in DB
1938 final Map<String, Long> params = new HashMap<>();
1939 final Map<String, CentralV2RoleFunction> roleFuncMap = new HashMap<>();
1940 params.put(APP_ID, app.getId());
1941 List<CentralV2RoleFunction> appFunctions = dataAccessService.executeNamedQuery("getAllRoleFunctions", params,
1943 if (!appFunctions.isEmpty()) {
1944 for (CentralV2RoleFunction roleFunc : appFunctions) {
1945 roleFuncMap.put(roleFunc.getCode(), roleFunc);
1949 // get Roles for portal in DB
1950 List<EPRole> portalRoleList = getGlobalRolesOfPortal();
1951 final Map<String, EPRole> existingPortalRolesMap = new HashMap<>();
1952 for(EPRole epRole : portalRoleList){
1953 existingPortalRolesMap.put(epRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), epRole);
1957 final Map<String, EPRole> currentRolesInDB = getCurrentRolesInDB(app);
1959 // store External Permissions with Pipe and without Pipe (just instance)
1960 final Map<String, ExternalAccessPermsDetail> extAccessPermsContainsPipeMap = new HashMap<>();
1961 final Map<String, ExternalAccessPermsDetail> extAccessPermsMap = new HashMap<>();
1962 for (ExternalAccessPermsDetail permsDetailInfoWithPipe : permsDetailList) {
1963 extAccessPermsContainsPipeMap.put(permsDetailInfoWithPipe.getInstance(), permsDetailInfoWithPipe);
1964 String finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetailInfoWithPipe.getInstance());
1965 extAccessPermsMap.put(finalFunctionCodeVal, permsDetailInfoWithPipe);
1968 // Add if new functions and app role functions were added in
1969 // external auth system
1970 for (ExternalAccessPermsDetail permsDetail : permsDetailList) {
1971 String code = permsDetail.getInstance();
1972 CentralV2RoleFunction getFunctionCodeKey = roleFuncMap.get(permsDetail.getInstance());
1973 List<CentralV2RoleFunction> roleFunctionList = addGetLocalFunction(app, roleFuncMap, permsDetail, code,
1974 getFunctionCodeKey);
1975 List<String> roles = permsDetail.getRoles();
1976 if (roles != null) {
1977 // Check if function has any roles and which does not exist
1978 // in External Auth System. If exists delete in local
1979 addRemoveIfFunctionsRolesIsSyncWithExternalAuth(app, currentRolesInDB, roleFunctionList, roles, existingPortalRolesMap);
1983 // Check if function does exits in External Auth System but exits in
1984 // local then delete function and its dependencies
1985 for (CentralV2RoleFunction roleFunc : appFunctions) {
1987 ExternalAccessPermsDetail getFunctionCodeContainsPipeKey = extAccessPermsContainsPipeMap
1988 .get(roleFunc.getCode());
1989 if (null == getFunctionCodeContainsPipeKey) {
1990 ExternalAccessPermsDetail getFunctionCodeKey = extAccessPermsMap.get(roleFunc.getCode());
1991 if (null == getFunctionCodeKey) {
1992 deleteAppRoleFuncDoesNotExitsInExtSystem(app, roleFunc);
1995 } catch (Exception e) {
1996 logger.error(EELFLoggerDelegate.errorLogger,
1997 "syncRoleFunctionFromExternalAccessSystem: Failed to delete function", e);
2002 logger.debug(EELFLoggerDelegate.debugLogger,
2003 "syncRoleFunctionFromExternalAccessSystem: Finished syncRoleFunctionFromExternalAccessSystem");
2004 } catch (Exception e) {
2005 logger.error(EELFLoggerDelegate.errorLogger,
2006 "syncRoleFunctionFromExternalAccessSystem: Failed syncRoleFunctionFromExternalAccessSystem", e);
2011 @SuppressWarnings("unchecked")
2012 private void addRemoveIfFunctionsRolesIsSyncWithExternalAuth(EPApp app, final Map<String, EPRole> currentRolesInDB,
2013 List<CentralV2RoleFunction> roleFunctionList, List<String> roles, Map<String, EPRole> existingPortalRolesMap)
2015 if (!roleFunctionList.isEmpty()) {
2016 final Map<String, String> appRoleFuncParams = new HashMap<>();
2017 final Map<String, LocalRole> currentAppRoleFunctionsMap = new HashMap<>();
2018 final Map<String, String> currentRolesInExtSystem = new HashMap<>();
2019 appRoleFuncParams.put("functionCd", roleFunctionList.get(0).getCode());
2020 appRoleFuncParams.put("appId", String.valueOf(app.getId()));
2021 List<LocalRole> localRoleList = dataAccessService.executeNamedQuery("getCurrentAppRoleFunctions",
2022 appRoleFuncParams, null);
2023 for (LocalRole localRole : localRoleList) {
2024 currentAppRoleFunctionsMap.put(localRole.getRolename().replaceAll(
2025 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), localRole);
2027 for (String addRole : roles) {
2028 currentRolesInExtSystem.put(addRole.substring(addRole.indexOf(FUNCTION_PIPE)+1), addRole);
2030 for (String extAuthrole : roles) {
2031 String roleNameSpace = extAuthrole.substring(0, extAuthrole.indexOf(FUNCTION_PIPE));
2032 boolean isNameSpaceMatching = EcompPortalUtils.checkNameSpaceMatching(roleNameSpace, app.getNameSpace());
2033 if (isNameSpaceMatching) {
2034 if (!currentAppRoleFunctionsMap
2035 .containsKey(extAuthrole.substring(app.getNameSpace().length() + 1))) {
2036 EPRole localAddFuntionRole = currentRolesInDB
2037 .get(extAuthrole.substring(app.getNameSpace().length() + 1));
2038 if (localAddFuntionRole == null) {
2039 checkAndAddRoleInDB(app, currentRolesInDB, roleFunctionList, extAuthrole);
2041 EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
2042 addAppRoleFunc.setAppId(app.getId());
2043 addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
2044 addAppRoleFunc.setRoleId(localAddFuntionRole.getId());
2045 dataAccessService.saveDomainObject(addAppRoleFunc, null);
2048 // This block is to save global role function if exists
2050 String extAuthAppRoleName = extAuthrole.substring(extAuthrole.indexOf(FUNCTION_PIPE) + 1);
2051 boolean checkIfGlobalRoleExists = existingPortalRolesMap.containsKey(extAuthAppRoleName);
2052 if (checkIfGlobalRoleExists) {
2053 final Map<String, Long> params = new HashMap<>();
2054 EPRole role = existingPortalRolesMap.get(extAuthAppRoleName);
2055 EPAppRoleFunction addGlobalRoleFunctions = new EPAppRoleFunction();
2056 params.put("appId", app.getId());
2057 params.put("roleId", role.getId());
2058 List<EPAppRoleFunction> currentGlobalRoleFunctionsList = dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", params, null);
2059 boolean checkIfRoleFunctionExists = currentGlobalRoleFunctionsList.stream().anyMatch(currentGlobalRoleFunction -> currentGlobalRoleFunction.getCode().equals(roleFunctionList.get(0).getCode()));
2060 if (role != null && !checkIfRoleFunctionExists) {
2061 addGlobalRoleFunctions.setAppId(app.getId());
2062 addGlobalRoleFunctions.setRoleId(role.getId());
2063 if (!app.getId().equals(role.getAppRoleId())) {
2064 addGlobalRoleFunctions.setRoleAppId((PortalConstants.PORTAL_APP_ID).toString());
2066 addGlobalRoleFunctions.setRoleAppId(null);
2068 addGlobalRoleFunctions.setCode(roleFunctionList.get(0).getCode());
2069 dataAccessService.saveDomainObject(addGlobalRoleFunctions, null);
2074 for (LocalRole localRoleDelete : localRoleList) {
2075 if (!currentRolesInExtSystem.containsKey(localRoleDelete.getRolename()
2076 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
2077 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
2078 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunctionList.get(0).getCode()
2079 + "'" + " and role_id = " + localRoleDelete.getRoleId().longValue(),
2086 private void deleteAppRoleFuncDoesNotExitsInExtSystem(EPApp app, CentralV2RoleFunction roleFunc) {
2087 logger.debug(EELFLoggerDelegate.debugLogger,
2088 "syncRoleFunctionFromExternalAccessSystem: Deleting app role function {}",
2089 roleFunc.getCode());
2090 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
2091 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() +"'", null);
2092 logger.debug(EELFLoggerDelegate.debugLogger,
2093 "syncRoleFunctionFromExternalAccessSystem: Deleted app role function {}",
2094 roleFunc.getCode());
2096 logger.debug(EELFLoggerDelegate.debugLogger,
2097 "syncRoleFunctionFromExternalAccessSystem: Deleting app function {}",
2098 roleFunc.getCode());
2099 dataAccessService.deleteDomainObjects(CentralV2RoleFunction.class,
2100 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() +"'", null);
2101 logger.debug(EELFLoggerDelegate.debugLogger,
2102 "syncRoleFunctionFromExternalAccessSystem: Deleted app function {}",
2103 roleFunc.getCode());
2106 private void checkAndAddRoleInDB(EPApp app, final Map<String, EPRole> currentRolesInDB,
2107 List<CentralV2RoleFunction> roleFunctionList, String roleList) throws Exception {
2108 if (!currentRolesInDB.containsKey(
2109 roleList.substring(app.getNameSpace().length() + 1))) {
2110 Role role = addRoleInDBIfDoesNotExists(app,
2111 roleList.substring(app.getNameSpace().length() + 1));
2112 addIfRoleDescriptionNotExitsInExtSystem(role, app);
2113 if (!roleFunctionList.isEmpty()) {
2115 if (!roleFunctionList.isEmpty()) {
2116 EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
2117 addAppRoleFunc.setAppId(app.getId());
2118 addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
2119 addAppRoleFunc.setRoleId(role.getId());
2120 dataAccessService.saveDomainObject(addAppRoleFunc, null);
2122 } catch (Exception e) {
2123 logger.error(EELFLoggerDelegate.errorLogger,
2124 "syncRoleFunctionFromExternalAccessSystem: Failed to save app role function ",
2131 @SuppressWarnings("unchecked")
2132 private List<CentralV2RoleFunction> addGetLocalFunction(EPApp app, final Map<String, CentralV2RoleFunction> roleFuncMap,
2133 ExternalAccessPermsDetail permsDetail, String code, CentralV2RoleFunction getFunctionCodeKey) {
2134 String finalFunctionCodeVal = addToLocalIfFunctionNotExists(app, roleFuncMap, permsDetail, code,
2135 getFunctionCodeKey);
2136 final Map<String, String> appSyncFuncsParams = new HashMap<>();
2137 appSyncFuncsParams.put("appId", String.valueOf(app.getId()));
2138 appSyncFuncsParams.put("functionCd", finalFunctionCodeVal);
2139 List<CentralV2RoleFunction> roleFunctionList = null;
2140 roleFunctionList = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams,
2142 if (roleFunctionList.isEmpty()) {
2143 appSyncFuncsParams.put("functionCd", code);
2144 roleFunctionList = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams,
2147 return roleFunctionList;
2150 private String addToLocalIfFunctionNotExists(EPApp app, final Map<String, CentralV2RoleFunction> roleFuncMap,
2151 ExternalAccessPermsDetail permsDetail, String code, CentralV2RoleFunction getFunctionCodeKey
2153 String finalFunctionCodeVal = "";
2154 if (null == getFunctionCodeKey) {
2155 finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetail.getInstance());
2156 CentralV2RoleFunction checkIfCodeStillExits = roleFuncMap.get(finalFunctionCodeVal);
2157 // If function does not exist in local then add!
2158 if (null == checkIfCodeStillExits) {
2159 logger.debug(EELFLoggerDelegate.debugLogger,
2160 "syncRoleFunctionFromExternalAccessSystem: Adding function: {} ", code);
2161 addFunctionInEcompDB(app, permsDetail, code);
2162 logger.debug(EELFLoggerDelegate.debugLogger,
2163 "syncRoleFunctionFromExternalAccessSystem: Finished adding function: {} ", code);
2166 return finalFunctionCodeVal;
2169 @SuppressWarnings("unchecked")
2171 public Map<String, EPRole> getCurrentRolesInDB(EPApp app) {
2172 final Map<String, EPRole> currentRolesInDB = new HashMap<>();
2173 List<EPRole> getCurrentRoleList = null;
2174 final Map<String, Long> appParams = new HashMap<>();
2175 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2176 getCurrentRoleList = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
2178 appParams.put("appId", app.getId());
2179 getCurrentRoleList = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
2181 for (EPRole role : getCurrentRoleList) {
2182 currentRolesInDB.put(role.getName()
2183 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), role);
2185 return currentRolesInDB;
2188 private List<ExternalAccessPermsDetail> getExtAuthPerrmissonList(EPApp app, JSONArray extPerms)
2190 ExternalAccessPermsDetail permDetails = null;
2191 List<ExternalAccessPermsDetail> permsDetailList = new ArrayList<>();
2192 for (int i = 0; i < extPerms.length(); i++) {
2193 String description = null;
2194 if (extPerms.getJSONObject(i).has("description")) {
2195 description = extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
2197 description = extPerms.getJSONObject(i).getString("instance");
2199 if (extPerms.getJSONObject(i).has("roles")) {
2200 ObjectMapper rolesListMapper = new ObjectMapper();
2201 JSONArray resRoles = extPerms.getJSONObject(i).getJSONArray("roles");
2202 List<String> list = rolesListMapper.readValue(resRoles.toString(),
2203 TypeFactory.defaultInstance().constructCollectionType(List.class, String.class));
2204 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
2205 extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
2206 + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
2207 + extPerms.getJSONObject(i).getString("action"),
2208 extPerms.getJSONObject(i).getString("action"), list, description);
2209 permsDetailList.add(permDetails);
2211 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
2212 extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
2213 + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
2214 + extPerms.getJSONObject(i).getString("action"),
2215 extPerms.getJSONObject(i).getString("action"), description);
2216 permsDetailList.add(permDetails);
2219 return permsDetailList;
2222 private JSONArray getExtAuthPermissions(EPApp app) throws Exception {
2223 ResponseEntity<String> response = null;
2224 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2225 HttpEntity<String> entity = new HttpEntity<>(headers);
2226 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: {} ",
2227 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2229 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
2230 + "perms/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
2232 String res = response.getBody();
2233 logger.debug(EELFLoggerDelegate.debugLogger,
2234 "syncRoleFunctionFromExternalAccessSystem: Finished GET permissions from External Auth system and response: {} ",
2235 response.getBody());
2236 JSONObject jsonObj = new JSONObject(res);
2237 JSONArray extPerms = jsonObj.getJSONArray("perm");
2238 for (int i = 0; i < extPerms.length(); i++) {
2239 if (extPerms.getJSONObject(i).getString("type").equals(app.getNameSpace() + ".access")) {
2249 * Add function into local DB
2252 * @param permsDetail
2255 private void addFunctionInEcompDB(EPApp app, ExternalAccessPermsDetail permsDetail, String code) {
2257 CentralV2RoleFunction addFunction = new CentralV2RoleFunction();
2258 addFunction.setAppId(app.getId());
2259 addFunction.setCode(code);
2260 addFunction.setName(permsDetail.getDescription());
2261 dataAccessService.saveDomainObject(addFunction, null);
2262 } catch(Exception e){
2263 logger.error(EELFLoggerDelegate.errorLogger, "addFunctionInEcompDB: Failed to add function", e);
2269 * It updates description of a role in external auth system
2275 private void addIfRoleDescriptionNotExitsInExtSystem(Role role, EPApp app) throws Exception {
2276 String addRoleNew = updateExistingRoleInExternalSystem(role, app);
2277 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2279 HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
2281 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
2282 HttpMethod.PUT, entity, String.class);
2283 } catch (HttpClientErrorException e) {
2284 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addIfRoleDescriptionNotExitsInExtSystem",
2286 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2287 } catch (Exception e) {
2288 logger.error(EELFLoggerDelegate.errorLogger, "addIfRoleDescriptionNotExitsInExtSystem: Failed",
2295 * While sync functions form external auth system if new role found we should add in local and return Role.class object
2301 @SuppressWarnings("unchecked")
2302 private Role addRoleInDBIfDoesNotExists(EPApp app, String role) {
2303 Role setNewRole = new Role();
2305 // functions can have new role created in External Auth System prevent
2307 boolean isCreated = checkIfRoleExitsElseCreateInSyncFunctions(role, app);
2308 final Map<String, String> getRoleByNameParams = new HashMap<>();
2309 List<EPRole> getRoleCreated = null;
2310 getRoleByNameParams.put(APP_ROLE_NAME_PARAM, role);
2311 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2312 getRoleByNameParams.put("appId", String.valueOf(app.getId()));
2313 List<EPRole> roleCreated = dataAccessService
2314 .executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, getRoleByNameParams, null);
2316 EPRole epUpdateRole = roleCreated.get(0);
2317 epUpdateRole.setAppRoleId(epUpdateRole.getId());
2318 dataAccessService.saveDomainObject(epUpdateRole, null);
2319 getRoleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
2320 getRoleByNameParams, null);
2322 getRoleCreated = roleCreated;
2325 getRoleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, getRoleByNameParams,
2328 if (getRoleCreated != null && !getRoleCreated.isEmpty()) {
2329 EPRole roleObject = getRoleCreated.get(0);
2330 setNewRole.setId(roleObject.getId());
2331 setNewRole.setName(roleObject.getName());
2332 setNewRole.setActive(roleObject.getActive());
2333 setNewRole.setPriority(roleObject.getPriority());
2335 } catch (Exception e) {
2336 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInDBIfDoesNotExists: Failed", e);
2341 @SuppressWarnings("unchecked")
2342 private boolean checkIfRoleExitsElseCreateInSyncFunctions(String role, EPApp app) {
2343 boolean isCreated = false;
2344 final Map<String, String> roleParams = new HashMap<>();
2345 roleParams.put(APP_ROLE_NAME_PARAM, role);
2346 List<EPRole> roleCreated = null;
2347 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2348 roleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams,
2351 roleParams.put("appId", String.valueOf(app.getId()));
2352 roleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams,
2355 if (roleCreated == null || roleCreated.isEmpty()) {
2356 roleParams.put("appId", String.valueOf(app.getId()));
2357 EPRole epRoleNew = new EPRole();
2358 epRoleNew.setActive(true);
2359 epRoleNew.setName(role);
2360 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2361 epRoleNew.setAppId(null);
2363 epRoleNew.setAppId(app.getId());
2365 dataAccessService.saveDomainObject(epRoleNew, null);
2374 @SuppressWarnings("unchecked")
2375 public Integer bulkUploadFunctions(String uebkey) throws Exception {
2376 EPApp app = getApp(uebkey).get(0);
2377 List<RoleFunction> roleFuncList = dataAccessService.executeNamedQuery("getAllFunctions", null, null);
2378 CentralV2RoleFunction cenRoleFunc = null;
2379 Integer functionsAdded = 0;
2381 for (RoleFunction roleFunc : roleFuncList) {
2382 cenRoleFunc = new CentralV2RoleFunction(roleFunc.getCode(), roleFunc.getName());
2383 addRoleFunctionInExternalSystem(cenRoleFunc, app);
2386 } catch(HttpClientErrorException e){
2387 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadFunctions failed", e);
2388 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2389 } catch (Exception e) {
2390 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions: failed", e.getMessage(), e);
2392 return functionsAdded;
2396 public Integer bulkUploadRoles(String uebkey) throws Exception {
2397 List<EPApp> app = getApp(uebkey);
2398 List<EPRole> roles = getAppRoles(app.get(0).getId());
2399 List<CentralV2Role> cenRoleList = new ArrayList<>();
2400 final Map<String, Long> params = new HashMap<>();
2401 Integer rolesListAdded = 0;
2403 cenRoleList = createCentralRoleObject(app, roles, cenRoleList, params);
2404 ObjectMapper mapper = new ObjectMapper();
2405 mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
2406 String roleList = mapper.writeValueAsString(cenRoleList);
2407 List<Role> roleObjectList = mapper.readValue(roleList,
2408 TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
2409 for (Role role : roleObjectList) {
2410 addRoleInExternalSystem(role, app.get(0));
2413 } catch (Exception e) {
2414 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles: failed", e);
2417 return rolesListAdded;
2421 * It creating new role in external auth system while doing bulk upload
2427 private void addRoleInExternalSystem(Role role, EPApp app) throws Exception {
2428 String addRoleNew = updateExistingRoleInExternalSystem(role, app);
2429 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2431 HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
2433 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
2434 HttpMethod.POST, entity, String.class);
2435 } catch(HttpClientErrorException e){
2436 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addRoleInExternalSystem", e);
2437 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2438 } catch (Exception e) {
2439 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2440 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInExternalSystem: Role already exits but does not break functionality", e);
2442 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInExternalSystem: Failed to addRoleInExternalSystem", e.getMessage());
2448 @SuppressWarnings("unchecked")
2449 public Integer bulkUploadRolesFunctions(String uebkey) throws Exception {
2450 EPApp app = getApp(uebkey).get(0);
2451 List<EPRole> roles = getAppRoles(app.getId());
2452 final Map<String, Long> params = new HashMap<>();
2453 Integer roleFunctions = 0;
2455 for (EPRole role : roles) {
2456 params.put("roleId", role.getId());
2457 List<BulkUploadRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("uploadAllRoleFunctions",
2459 if (!appRoleFunc.isEmpty()) {
2460 for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
2461 addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
2466 } catch(HttpClientErrorException e){
2467 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
2468 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2469 } catch (Exception e) {
2470 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
2472 return roleFunctions;
2476 * Its adding a role function while doing bulk upload
2478 * @param addRoleFunc
2482 private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, EPRole role, EPApp app) {
2483 String checkType = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
2484 ExternalAccessRolePerms extRolePerms = null;
2485 ExternalAccessPerms extPerms = null;
2486 ObjectMapper mapper = new ObjectMapper();
2488 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2490 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, addRoleFunc.getFunctionCd(), "*",
2491 addRoleFunc.getFunctionName());
2492 extRolePerms = new ExternalAccessRolePerms(extPerms,
2493 app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2494 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
2495 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
2497 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
2498 HttpMethod.POST, entity, String.class);
2499 } catch (Exception e) {
2500 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2501 logger.error(EELFLoggerDelegate.errorLogger,
2502 "addRoleFunctionsInExternalSystem: RoleFunction already exits but does not break functionality", e);
2504 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionsInExternalSystem: Failed to addRoleFunctionsInExternalSystem",
2511 public void bulkUploadPartnerFunctions(String uebkey, List<RoleFunction> roleFunctionsList) throws Exception {
2512 EPApp app = getApp(uebkey).get(0);
2513 CentralV2RoleFunction cenRoleFunc = null;
2514 for (RoleFunction roleFunction : roleFunctionsList) {
2515 cenRoleFunc = new CentralV2RoleFunction(roleFunction.getCode(), roleFunction.getName());
2516 addRoleFunctionInExternalSystem(cenRoleFunc, app);
2521 public void bulkUploadPartnerRoles(String uebkey, List<Role> roleList) throws Exception {
2522 EPApp app = getApp(uebkey).get(0);
2523 for (Role role : roleList) {
2524 addRoleInExternalSystem(role, app);
2528 @SuppressWarnings("unchecked")
2530 public void bulkUploadPartnerRoleFunctions(String uebkey, List<Role> roleList) throws Exception {
2531 EPApp app = getApp(uebkey).get(0);
2532 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2533 for (Role role : roleList) {
2535 Set<RoleFunction> roleFunctionList = role.getRoleFunctions();
2536 List<RoleFunction> roleFunctionListNew = new ArrayList<>();
2537 ObjectMapper roleFunctionsMapper = new ObjectMapper();
2538 Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
2539 while (itetaror.hasNext()) {
2540 Object nextValue = itetaror.next();
2541 RoleFunction roleFunction = roleFunctionsMapper.convertValue(nextValue, RoleFunction.class);
2542 roleFunctionListNew.add(roleFunction);
2544 List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct()
2545 .collect(Collectors.toList());
2546 for (RoleFunction roleFunction : listWithoutDuplicates) {
2547 String checkType = roleFunction.getCode().contains("menu") ? "menu" : "url";
2548 ExternalAccessRolePerms extRolePerms = null;
2549 ExternalAccessPerms extPerms = null;
2550 ObjectMapper mapper = new ObjectMapper();
2551 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, roleFunction.getCode(),
2553 extRolePerms = new ExternalAccessRolePerms(extPerms,
2554 app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2555 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
2556 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
2557 template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
2558 + "role/perm", HttpMethod.PUT, entity, String.class);
2560 } catch (Exception e) {
2561 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2562 logger.error(EELFLoggerDelegate.errorLogger,
2563 "bulkUploadPartnerRoleFunctions: RoleFunction already exits but does not break functionality");
2565 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerRoleFunctions: Failed to addRoleFunctionsInExternalSystem",
2575 public void syncApplicationRolesWithEcompDB(EPApp app) {
2577 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Started");
2578 //Sync functions and roles assigned to it which also creates new roles if does not exits in portal
2579 syncRoleFunctionFromExternalAccessSystem(app);
2580 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Finished");
2582 ObjectMapper mapper = new ObjectMapper();
2583 logger.debug(EELFLoggerDelegate.debugLogger, "Entering to getAppRolesJSONFromExtAuthSystem");
2584 // Get Permissions from External Auth System
2585 JSONArray extRole = getAppRolesJSONFromExtAuthSystem(app);
2587 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into getExternalRoleDetailsList");
2588 List<ExternalRoleDetails> externalRoleDetailsList = getExternalRoleDetailsList(app,
2591 List<EPRole> finalRoleList = new ArrayList<>();
2592 for (ExternalRoleDetails externalRole : externalRoleDetailsList) {
2593 EPRole ecompRole = convertExternalRoleDetailstoEpRole(externalRole);
2594 finalRoleList.add(ecompRole);
2597 List<EPRole> applicationRolesList;
2598 applicationRolesList = getAppRoles(app.getId());
2599 List<String> applicationRoleIdList = new ArrayList<>();
2600 for (EPRole applicationRole : applicationRolesList) {
2601 applicationRoleIdList.add(applicationRole.getName());
2604 List<EPRole> roleListToBeAddInEcompDB = new ArrayList<>();
2605 for (EPRole aafRole : finalRoleList) {
2606 if (!applicationRoleIdList.contains(aafRole.getName())) {
2607 roleListToBeAddInEcompDB.add(aafRole);
2611 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into inactiveRolesNotInExternalAuthSystem");
2612 // Check if roles exits in external Access system and if not make inactive in DB
2613 inactiveRolesNotInExternalAuthSystem(app, finalRoleList, applicationRolesList);
2615 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into checkAndUpdateRoleInDB");
2616 // It checks properties in the external auth system app role description and updates role in local
2617 checkAndUpdateRoleInDB(app, finalRoleList);
2619 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addNewRoleInEcompDBUpdateDescInExtAuthSystem");
2620 // Add new roles in DB and updates role description in External Auth System
2621 addNewRoleInEcompDBUpdateDescInExtAuthSystem(app, roleListToBeAddInEcompDB);
2622 logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: Finished");
2623 } catch (HttpClientErrorException e) {
2624 logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed due to the External Auth System", e);
2625 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2626 } catch (Exception e) {
2627 logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed ", e);
2633 * It adds new roles in DB and updates description in External Auth System
2636 * @param roleListToBeAddInEcompDB
2638 @SuppressWarnings("unchecked")
2639 private void addNewRoleInEcompDBUpdateDescInExtAuthSystem(EPApp app, List<EPRole> roleListToBeAddInEcompDB) {
2640 EPRole roleToBeAddedInEcompDB;
2641 for (int i = 0; i < roleListToBeAddInEcompDB.size(); i++) {
2643 roleToBeAddedInEcompDB = roleListToBeAddInEcompDB.get(i);
2644 if (app.getId() == 1) {
2645 roleToBeAddedInEcompDB.setAppRoleId(null);
2647 dataAccessService.saveDomainObject(roleToBeAddedInEcompDB, null);
2648 List<EPRole> getRoleCreatedInSync = null;
2649 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2650 final Map<String, String> globalRoleParams = new HashMap<>();
2651 globalRoleParams.put("appId", String.valueOf(app.getId()));
2652 globalRoleParams.put("appRoleName", roleToBeAddedInEcompDB.getName());
2653 getRoleCreatedInSync = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, globalRoleParams, null);
2654 EPRole epUpdateRole = getRoleCreatedInSync.get(0);
2655 epUpdateRole.setAppRoleId(epUpdateRole.getId());
2656 dataAccessService.saveDomainObject(epUpdateRole, null);
2658 List<EPRole> roleList = new ArrayList<>();
2659 final Map<String, String> params = new HashMap<>();
2661 params.put(APP_ROLE_NAME_PARAM, roleToBeAddedInEcompDB.getName());
2662 boolean isPortalRole = false;
2663 if (app.getId() == 1) {
2664 isPortalRole = true;
2665 roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, params, null);
2667 isPortalRole = false;
2668 params.put(APP_ID, app.getId().toString());
2669 roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, params, null);
2671 EPRole role = roleList.get(0);
2672 Role aaFrole = new Role();
2673 aaFrole.setId(role.getId());
2674 aaFrole.setActive(role.getActive());
2675 aaFrole.setPriority(role.getPriority());
2676 aaFrole.setName(role.getName());
2677 updateRoleInExternalSystem(aaFrole, app, isPortalRole);
2678 } catch (Exception e) {
2679 logger.error(EELFLoggerDelegate.errorLogger,
2680 "SyncApplicationRolesWithEcompDB: Failed to add or update role in external auth system", e);
2687 * It checks description in External Auth System if found any changes updates in DB
2690 * @param finalRoleList contains list of External Auth System roles list which is converted to EPRole
2692 @SuppressWarnings("unchecked")
2693 private void checkAndUpdateRoleInDB(EPApp app, List<EPRole> finalRoleList) {
2694 for (EPRole roleItem : finalRoleList) {
2695 final Map<String, String> roleParams = new HashMap<>();
2696 List<EPRole> currentList = null;
2697 roleParams.put(APP_ROLE_NAME_PARAM, roleItem.getName());
2698 if (app.getId() == 1) {
2699 currentList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, roleParams, null);
2701 roleParams.put(APP_ID, app.getId().toString());
2702 currentList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams, null);
2705 if (!currentList.isEmpty()) {
2707 Boolean aafRoleActive;
2708 Boolean localRoleActive;
2710 aafRoleActive = Boolean.valueOf(roleItem.getActive());
2711 localRoleActive = Boolean.valueOf(currentList.get(0).getActive());
2712 result = aafRoleActive.equals(localRoleActive);
2713 EPRole updateRole = currentList.get(0);
2716 updateRole.setActive(roleItem.getActive());
2717 dataAccessService.saveDomainObject(updateRole, null);
2719 if (roleItem.getPriority() != null
2720 && !currentList.get(0).getPriority().equals(roleItem.getPriority())) {
2721 updateRole.setPriority(roleItem.getPriority());
2722 dataAccessService.saveDomainObject(updateRole, null);
2724 } catch (Exception e) {
2725 logger.error(EELFLoggerDelegate.errorLogger,
2726 "syncApplicationRolesWithEcompDB: Failed to update role ", e);
2733 * It de-activates application roles in DB if not present in External Auth system
2736 * @param finalRoleList contains list of current roles present in External Auth System
2737 * @param applicationRolesList contains list of current roles present in DB
2739 @SuppressWarnings("unchecked")
2740 private void inactiveRolesNotInExternalAuthSystem(EPApp app, List<EPRole> finalRoleList,
2741 List<EPRole> applicationRolesList) {
2742 final Map<String, EPRole> checkRolesInactive = new HashMap<>();
2743 for (EPRole extrole : finalRoleList) {
2744 checkRolesInactive.put(extrole.getName(), extrole);
2746 for (EPRole role : applicationRolesList) {
2748 final Map<String, String> extRoleParams = new HashMap<>();
2749 List<EPRole> roleList = null;
2750 extRoleParams.put(APP_ROLE_NAME_PARAM, role.getName());
2751 if (!checkRolesInactive.containsKey(role.getName())) {
2752 if (app.getId() == 1) {
2753 roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, extRoleParams, null);
2755 extRoleParams.put(APP_ID, app.getId().toString());
2756 roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, extRoleParams, null);
2758 if(!roleList.isEmpty()) {
2759 EPRole updateRoleInactive = roleList.get(0);
2760 updateRoleInactive.setActive(false);
2761 dataAccessService.saveDomainObject(updateRoleInactive, null);
2764 } catch (Exception e) {
2765 logger.error(EELFLoggerDelegate.errorLogger,
2766 "syncApplicationRolesWithEcompDB: Failed to de-activate role ", e);
2772 @SuppressWarnings("unchecked")
2773 public List<ExternalRoleDetails> getExternalRoleDetailsList(EPApp app,
2774 ObjectMapper mapper, JSONArray extRole)
2775 throws IOException {
2776 List<ExternalRoleDetails> externalRoleDetailsList = new ArrayList<>();
2777 ExternalRoleDescription ApplicationRole = new ExternalRoleDescription();
2778 ExternalAccessPerms externalAccessPerms = new ExternalAccessPerms();
2779 List<String> functionCodelist = new ArrayList<>();
2780 for (int i = 0; i < extRole.length(); i++) {
2781 ExternalRoleDetails externalRoleDetail = new ExternalRoleDetails();
2782 EPAppRoleFunction ePAppRoleFunction = new EPAppRoleFunction();
2783 JSONObject Role = (JSONObject) extRole.get(i);
2784 if (!extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
2785 ApplicationRole.setActive("true");
2786 ApplicationRole.setAppId(IS_NULL_STRING);
2787 ApplicationRole.setPriority(IS_NULL_STRING);
2788 ApplicationRole.setAppRoleId(IS_NULL_STRING);
2789 String roleName = extRole.getJSONObject(i).getString(ROLE_NAME);
2790 ApplicationRole.setName(roleName.substring(app.getNameSpace().length() + 1));
2792 String desc = extRole.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
2793 ApplicationRole = mapper.readValue(desc, ExternalRoleDescription.class);
2796 SortedSet<ExternalAccessPerms> externalAccessPermsOfRole = new TreeSet<>();
2797 if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_PERMS)) {
2798 JSONArray extPerm = (JSONArray) Role.get(EXTERNAL_AUTH_PERMS);
2799 for (int j = 0; j < extPerm.length(); j++) {
2800 JSONObject perms = extPerm.getJSONObject(j);
2801 boolean isNamespaceMatching = EcompPortalUtils.checkNameSpaceMatching(perms.getString("type"), app.getNameSpace());
2802 if (isNamespaceMatching) {
2803 externalAccessPerms = new ExternalAccessPerms(perms.getString("type"),
2804 perms.getString("instance"), perms.getString("action"));
2805 ePAppRoleFunction.setCode(externalAccessPerms.getInstance());
2806 functionCodelist.add(ePAppRoleFunction.getCode());
2807 externalAccessPermsOfRole.add(externalAccessPerms);
2813 if (ApplicationRole.getActive().equals(IS_NULL_STRING)) {
2814 externalRoleDetail.setActive(false);
2816 externalRoleDetail.setActive(Boolean.parseBoolean(ApplicationRole.getActive()));
2818 externalRoleDetail.setName(ApplicationRole.getName());
2820 if (ApplicationRole.getAppId().equals(IS_NULL_STRING) && app.getId() == 1) {
2821 externalRoleDetail.setAppId(null);
2822 } else if (ApplicationRole.getAppId().equals(IS_NULL_STRING)) {
2823 externalRoleDetail.setAppId(app.getId());
2825 externalRoleDetail.setAppId(Long.parseLong(ApplicationRole.getAppId()));
2828 if (ApplicationRole.getPriority().equals(IS_NULL_STRING)) {
2829 externalRoleDetail.setPriority(null);
2831 externalRoleDetail.setPriority(Integer.parseInt(ApplicationRole.getPriority()));
2834 if (ApplicationRole.getAppRoleId().equals(IS_NULL_STRING) && app.getId() == 1) {
2835 externalRoleDetail.setAppRoleId(null);
2838 // get role functions from DB
2839 final Map<String, EPAppRoleFunction> roleFunctionsMap = new HashMap<>();
2840 if (!ApplicationRole.getId().equals(IS_NULL_STRING)) {
2841 final Map<String, Long> appRoleFuncsParams = new HashMap<>();
2842 appRoleFuncsParams.put("appId", app.getId());
2843 appRoleFuncsParams.put("roleId", Long.valueOf(ApplicationRole.getId()));
2844 List<EPAppRoleFunction> appRoleFunctions = dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null);
2845 if (!appRoleFunctions.isEmpty()) {
2846 for (EPAppRoleFunction roleFunc : appRoleFunctions) {
2847 roleFunctionsMap.put(roleFunc.getCode(), roleFunc);
2852 if (!externalAccessPermsOfRole.isEmpty()) {
2853 // Adding functions to role
2854 for (ExternalAccessPerms externalpermission : externalAccessPermsOfRole) {
2855 EPAppRoleFunction checkRoleFunctionExits = roleFunctionsMap.get(externalpermission.getInstance());
2856 if (checkRoleFunctionExits == null) {
2857 String funcCode = externalpermission.getType().substring(app.getNameSpace().length() + 1)
2858 + FUNCTION_PIPE + externalpermission.getInstance() + FUNCTION_PIPE
2859 + externalpermission.getAction();
2860 EPAppRoleFunction checkRoleFunctionPipeExits = roleFunctionsMap.get(funcCode);
2861 if (checkRoleFunctionPipeExits == null) {
2863 final Map<String, String> appFuncsParams = new HashMap<>();
2864 appFuncsParams.put("appId", String.valueOf(app.getId()));
2865 appFuncsParams.put("functionCd", externalpermission.getInstance());
2866 logger.debug(EELFLoggerDelegate.debugLogger,
2867 "SyncApplicationRolesWithEcompDB: Adding function to the role: {}",
2868 externalpermission.getInstance());
2869 List<CentralV2RoleFunction> roleFunction = null;
2870 roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appFuncsParams, null);
2871 if (roleFunction.isEmpty()) {
2872 appFuncsParams.put("functionCd", funcCode);
2873 roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appFuncsParams, null);
2875 if (!roleFunction.isEmpty()) {
2876 EPAppRoleFunction apRoleFunction = new EPAppRoleFunction();
2877 apRoleFunction.setAppId(app.getId());
2878 apRoleFunction.setRoleId(Long.parseLong(ApplicationRole.getId()));
2879 apRoleFunction.setCode(roleFunction.get(0).getCode());
2880 dataAccessService.saveDomainObject(apRoleFunction, null);
2882 } catch (Exception e) {
2883 logger.error(EELFLoggerDelegate.errorLogger,
2884 "SyncApplicationRolesWithEcompDB: Failed to add role function", e);
2890 externalRoleDetailsList.add(externalRoleDetail);
2892 return externalRoleDetailsList;
2896 public JSONArray getAppRolesJSONFromExtAuthSystem(EPApp app) throws Exception {
2897 ResponseEntity<String> response = null;
2898 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2899 HttpEntity<String> entity = new HttpEntity<>(headers);
2900 logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: {} ",
2901 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2903 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
2904 + "roles/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
2905 String res = response.getBody();
2906 logger.debug(EELFLoggerDelegate.debugLogger,
2907 "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
2909 JSONObject jsonObj = new JSONObject(res);
2910 JSONArray extRole = jsonObj.getJSONArray("role");
2911 for (int i = 0; i < extRole.length(); i++) {
2912 if (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ADMIN)
2913 || extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + OWNER)
2914 || (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ACCOUNT_ADMINISTRATOR)
2915 && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
2924 public JSONArray getAllUsersByRole(String roleName) throws Exception{
2925 ResponseEntity<String> response = null;
2926 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2927 HttpEntity<String> entity = new HttpEntity<>(headers);
2928 logger.debug(EELFLoggerDelegate.debugLogger, "getAllUsersByRole: {} ",
2929 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2931 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
2932 + "userRoles/role/" + roleName, HttpMethod.GET, entity, String.class);
2933 String res = response.getBody();
2934 logger.debug(EELFLoggerDelegate.debugLogger,
2935 "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
2937 JSONObject jsonObj = new JSONObject(res);
2938 JSONArray extRole = jsonObj.getJSONArray("userRole");
2945 * It converts from ExternalRoleDetails.class object to EPRole.class object
2947 * @param externalRoleDetails
2948 * @return EPRole object
2950 private EPRole convertExternalRoleDetailstoEpRole(ExternalRoleDetails externalRoleDetails) {
2951 EPRole role = new EPRole();
2952 role.setActive(externalRoleDetails.isActive());
2953 role.setAppId(externalRoleDetails.getAppId());
2954 role.setAppRoleId(externalRoleDetails.getAppRoleId());
2955 role.setName(externalRoleDetails.getName());
2956 role.setPriority(externalRoleDetails.getPriority());
2960 @SuppressWarnings("unchecked")
2962 public Integer bulkUploadUserRoles(String uebkey) throws Exception {
2963 EPApp app = getApp(uebkey).get(0);
2964 final Map<String, String> params = new HashMap<>();
2965 params.put("uebKey", app.getUebKey());
2966 List<BulkUploadUserRoles> userRolesList = null;
2967 Integer userRolesAdded = 0;
2968 if (app.getCentralAuth()) {
2969 userRolesList = dataAccessService.executeNamedQuery("getBulkUserRoles", params, null);
2970 for (BulkUploadUserRoles userRolesUpload : userRolesList) {
2971 if(!userRolesUpload.getOrgUserId().equals("su1234")){
2972 addUserRoleInExternalSystem(userRolesUpload);
2977 return userRolesAdded;
2981 * Its adding a user role in external auth system while doing bulk upload
2983 * @param userRolesUpload
2985 private void addUserRoleInExternalSystem(BulkUploadUserRoles userRolesUpload) {
2988 ObjectMapper mapper = new ObjectMapper();
2989 if (EPCommonSystemProperties
2990 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
2991 name = userRolesUpload.getOrgUserId()
2992 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
2994 ExternalAccessUser extUser = new ExternalAccessUser(name,
2995 userRolesUpload.getAppNameSpace() + "." + userRolesUpload.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2996 String userRole = mapper.writeValueAsString(extUser);
2997 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2998 HttpEntity<String> entity = new HttpEntity<>(userRole, headers);
3000 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
3001 HttpMethod.POST, entity, String.class);
3002 } catch(HttpClientErrorException e){
3003 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addUserRoleInExternalSystem", e);
3004 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3005 } catch (Exception e) {
3006 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
3007 logger.error(EELFLoggerDelegate.errorLogger, "addUserRoleInExternalSystem: UserRole already exits but does not break functionality");
3009 logger.error(EELFLoggerDelegate.errorLogger, "addUserRoleInExternalSystem: Failed to addUserRoleInExternalSystem", e);
3015 public void deleteRoleDependencyRecords(Session localSession, Long roleId, Long appId, boolean isPortalRequest) throws Exception {
3020 //It should delete only when it portal's roleId
3021 if(appId.equals(PortalConstants.PORTAL_APP_ID)){
3022 // Delete from fn_role_function
3023 sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
3024 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3025 query = localSession.createSQLQuery(sql);
3026 query.executeUpdate();
3028 // Delete from fn_role_composite
3029 sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId;
3030 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3031 query = localSession.createSQLQuery(sql);
3032 query.executeUpdate();
3035 // Delete from ep_app_role_function
3036 sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId;
3037 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3038 query = localSession.createSQLQuery(sql);
3039 query.executeUpdate();
3041 // Delete from ep_role_notification
3042 sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
3043 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3044 query = localSession.createSQLQuery(sql);
3045 query.executeUpdate();
3047 // Delete from fn_user_pseudo_role
3048 sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
3049 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3050 query = localSession.createSQLQuery(sql);
3051 query.executeUpdate();
3053 // Delete form EP_WIDGET_CATALOG_ROLE
3054 sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId;
3055 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3056 query = localSession.createSQLQuery(sql);
3057 query.executeUpdate();
3059 // Delete form EP_WIDGET_CATALOG_ROLE
3060 sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId;
3061 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3062 query = localSession.createSQLQuery(sql);
3063 query.executeUpdate();
3065 if(!isPortalRequest) {
3066 // Delete form fn_menu_functional_roles
3067 sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
3068 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3069 query = localSession.createSQLQuery(sql);
3070 query.executeUpdate();
3072 } catch (Exception e) {
3073 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e);
3074 throw new DeleteDomainObjectFailedException("delete Failed" + e.getMessage());
3079 @SuppressWarnings("unchecked")
3081 public List<String> getMenuFunctionsList(String uebkey) throws Exception {
3082 List<String> appMenuFunctionsList = null;
3084 EPApp app = getApp(uebkey).get(0);
3085 final Map<String, Long> appParams = new HashMap<>();
3086 appParams.put(APP_ID, app.getId());
3087 appMenuFunctionsList = dataAccessService.executeNamedQuery("getMenuFunctions", appParams, null);
3088 } catch (Exception e) {
3089 logger.error(EELFLoggerDelegate.errorLogger, "getMenuFunctionsList: Failed", e);
3090 return appMenuFunctionsList;
3092 return appMenuFunctionsList;
3095 @SuppressWarnings({ "unchecked"})
3097 public List<EcompUser> getAllAppUsers(String uebkey) throws Exception {
3098 List<String> usersList = new ArrayList<>();
3099 List<EcompUser> usersfinalList = new ArrayList<>();
3101 EPApp app = getApp(uebkey).get(0);
3102 final Map<String, Long> appParams = new HashMap<>();
3103 appParams.put("appId", app.getId());
3104 List<EcompUserRoles> userList = (List<EcompUserRoles>) dataAccessService
3105 .executeNamedQuery("ApplicationUserRoles", appParams, null);
3106 for (EcompUserRoles ecompUserRole : userList) {
3107 boolean found = false;
3108 Set<EcompRole> roles = null;
3109 for (EcompUser user : usersfinalList) {
3110 if (user.getOrgUserId().equals(ecompUserRole.getOrgUserId())) {
3111 EcompRole ecompRole = new EcompRole();
3112 ecompRole.setId(ecompUserRole.getRoleId());
3113 ecompRole.setName(ecompUserRole.getRoleName());
3114 roles = user.getRoles();
3115 roles.add(ecompRole);
3116 user.setRoles(roles);
3123 EcompUser epUser = new EcompUser();
3124 epUser.setOrgId(ecompUserRole.getOrgId());
3125 epUser.setManagerId(ecompUserRole.getManagerId());
3126 epUser.setFirstName(ecompUserRole.getFirstName());
3127 epUser.setLastName(ecompUserRole.getLastName());
3128 epUser.setPhone(ecompUserRole.getPhone());
3129 epUser.setEmail(ecompUserRole.getEmail());
3130 epUser.setOrgUserId(ecompUserRole.getOrgUserId());
3131 epUser.setOrgCode(ecompUserRole.getOrgCode());
3132 epUser.setOrgManagerUserId(ecompUserRole.getOrgManagerUserId());
3133 epUser.setJobTitle(ecompUserRole.getJobTitle());
3134 epUser.setLoginId(ecompUserRole.getLoginId());
3135 epUser.setActive(true);
3136 roles = new HashSet<>();
3137 EcompRole ecompRole = new EcompRole();
3138 ecompRole.setId(ecompUserRole.getRoleId());
3139 ecompRole.setName(ecompUserRole.getRoleName());
3140 roles.add(ecompRole);
3141 epUser.setRoles(roles);
3142 usersfinalList.add(epUser);
3145 ObjectMapper mapper = new ObjectMapper();
3147 for (EcompUser u1 : usersfinalList) {
3148 String str = mapper.writeValueAsString(u1);
3151 } catch (Exception e) {
3152 logger.error(EELFLoggerDelegate.errorLogger, "getAllUsers failed", e);
3155 return usersfinalList;
3160 public Role ConvertCentralRoleToRole(String result) {
3161 ObjectMapper mapper = new ObjectMapper();
3162 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
3163 Role newRole = new Role();
3165 newRole = mapper.readValue(result, Role.class);
3166 } catch (IOException e) {
3167 logger.error(EELFLoggerDelegate.errorLogger, "Failed to convert the result to Role Object", e);
3169 if (newRole.getRoleFunctions() != null) {
3170 @SuppressWarnings("unchecked")
3171 Set<RoleFunction> roleFunctionList = newRole.getRoleFunctions();
3172 Set<RoleFunction> roleFunctionListNew = new HashSet<>();
3173 Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
3174 while (itetaror.hasNext()) {
3175 Object nextValue = itetaror.next();
3176 RoleFunction roleFun = mapper.convertValue(nextValue, RoleFunction.class);
3177 roleFunctionListNew.add(roleFun);
3179 newRole.setRoleFunctions(roleFunctionListNew);
3185 @SuppressWarnings("unchecked")
3186 public List<CentralizedApp> getCentralizedAppsOfUser(String userId) {
3187 Map<String, String> params = new HashMap<>();
3188 params.put("userId", userId);
3189 List<CentralizedApp> centralizedAppsList = new ArrayList<>();
3191 centralizedAppsList = dataAccessService
3192 .executeNamedQuery("getCentralizedAppsOfUser", params, null);
3193 }catch (Exception e) {
3194 logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
3196 return centralizedAppsList;
3199 @SuppressWarnings("unchecked")
3200 public List<CentralV2Role> getGlobalRolesOfApplication(Long appId) {
3201 Map<String, Long> params = new HashMap<>();
3202 params.put("appId", appId);
3203 List<GlobalRoleWithApplicationRoleFunction> globalRoles = new ArrayList<>();
3205 globalRoles = dataAccessService.executeNamedQuery("getGlobalRoleWithApplicationRoleFunctions", params,
3207 } catch (Exception e) {
3208 logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
3210 List<CentralV2Role> rolesfinalList = new ArrayList<>();
3211 if (globalRoles.size() > 0)
3212 rolesfinalList = finalListOfCentralRoles(globalRoles);
3213 return rolesfinalList;
3216 @SuppressWarnings("unchecked")
3217 private CentralV2Role getGlobalRoleForRequestedApp(long requestedAppId, long roleId) {
3218 CentralV2Role finalGlobalrole = null;
3219 List<GlobalRoleWithApplicationRoleFunction> roleWithApplicationRoleFucntions = new ArrayList<>();
3220 Map<String, Long> params = new HashMap<>();
3221 params.put("roleId", roleId);
3222 params.put("requestedAppId", requestedAppId);
3224 roleWithApplicationRoleFucntions = dataAccessService.executeNamedQuery("getGlobalRoleForRequestedApp",
3226 } catch (Exception e) {
3227 logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRoleForRequestedApp failed", e);
3229 if (roleWithApplicationRoleFucntions.size() > 0) {
3230 List<CentralV2Role> rolesfinalList = finalListOfCentralRoles(roleWithApplicationRoleFucntions);
3231 finalGlobalrole = rolesfinalList.get(0);
3233 List<EPRole> roleList = getPortalAppRoleInfo(roleId);
3234 finalGlobalrole = convertRoleToCentralV2Role(roleList.get(0));
3236 return finalGlobalrole;
3239 private List<CentralV2Role> finalListOfCentralRoles(List<GlobalRoleWithApplicationRoleFunction> globalRoles) {
3240 List<CentralV2Role> rolesfinalList = new ArrayList<>();
3241 for (GlobalRoleWithApplicationRoleFunction role : globalRoles) {
3242 boolean found = false;
3243 for (CentralV2Role cenRole : rolesfinalList) {
3244 if (role.getRoleId().equals(cenRole.getId())) {
3245 SortedSet<CentralV2RoleFunction> roleFunctions = cenRole.getRoleFunctions();
3246 CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
3247 roleFunctions.add(cenRoleFun);
3248 cenRole.setRoleFunctions(roleFunctions);
3254 CentralV2Role cenrole = new CentralV2Role();
3255 cenrole.setName(role.getRoleName());
3256 cenrole.setId(role.getRoleId());
3257 cenrole.setActive(role.isActive());
3258 cenrole.setPriority(role.getPriority());
3259 SortedSet<CentralV2RoleFunction> roleFunctions = new TreeSet<>();
3260 CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
3261 roleFunctions.add(cenRoleFun);
3262 cenrole.setRoleFunctions(roleFunctions);
3263 rolesfinalList.add(cenrole);
3266 return rolesfinalList;
3269 private CentralV2RoleFunction createCentralRoleFunctionForGlobalRole(GlobalRoleWithApplicationRoleFunction role) {
3273 CentralV2RoleFunction cenRoleFun;
3274 if(role.getFunctionCd().contains(FUNCTION_PIPE)){
3275 instance = EcompPortalUtils.getFunctionCode(role.getFunctionCd());
3276 type = EcompPortalUtils.getFunctionType(role.getFunctionCd());
3277 action = EcompPortalUtils.getFunctionAction(role.getFunctionCd());
3278 cenRoleFun = new CentralV2RoleFunction(null, instance, role.getFunctionName(), null, type, action, null);
3280 type = getFunctionCodeType(role.getFunctionCd());
3281 action = getFunctionCodeAction(role.getFunctionCd());
3282 cenRoleFun = new CentralV2RoleFunction(null, role.getFunctionCd(), role.getFunctionName(), null, type, action, null);
3287 @SuppressWarnings("unchecked")
3289 public List<EPRole> getGlobalRolesOfPortal() {
3290 List<EPRole> globalRoles = new ArrayList<>();
3292 globalRoles = dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null);
3293 } catch (Exception e) {
3294 logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRolesOfPortal failed", e);
3299 private CentralV2Role convertRoleToCentralV2Role(EPRole role) {
3300 return new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
3301 role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
3302 new TreeSet<>(), new TreeSet<>(), new TreeSet<>());
3307 public List<RoleFunction> convertCentralRoleFunctionToRoleFunctionObject(List<CentralV2RoleFunction> answer) {
3308 List<RoleFunction> addRoleFuncList = new ArrayList<>();
3309 for(CentralV2RoleFunction cenRoleFunc : answer){
3310 RoleFunction setRoleFunc = new RoleFunction();
3311 setRoleFunc.setCode(cenRoleFunc.getCode());
3312 setRoleFunc.setName(cenRoleFunc.getName());
3313 addRoleFuncList.add(setRoleFunc);
3315 return addRoleFuncList;
3319 public CentralUser getUserRoles(String loginId, String uebkey) throws Exception {
3320 CentralUser sendUserRoles = null;
3323 CentralV2User cenV2User = getV2UserAppRoles(loginId, uebkey);
3324 sendUserRoles = convertV2UserRolesToOlderVersion(cenV2User);
3325 } catch (Exception e) {
3326 logger.error(EELFLoggerDelegate.errorLogger, "getUserRoles: failed", e);
3328 return sendUserRoles;
3333 * It returns V2 CentralUser object if user has any roles and permissions
3337 * @return CentralUser object
3340 private CentralV2User getV2UserAppRoles(String loginId, String uebkey) throws Exception {
3342 List<EPUser> epUserList;
3343 List<EPApp> appList = getApp(uebkey);
3344 app = appList.get(0);
3345 epUserList = getUser(loginId);
3346 EPUser user = epUserList.get(0);
3347 Set<EPUserApp> userAppSet = user.getEPUserApps();
3348 return createEPUser(user, userAppSet, app);
3352 * It converts V2 CentralUser object to old version CentralUser object
3355 * @return EPUser object
3357 private CentralUser convertV2UserRolesToOlderVersion(CentralV2User cenV2User) {
3358 Set<CentralV2UserApp> userV2Apps = cenV2User.getUserApps();
3359 Set<CentralUserApp> userApps = new TreeSet<>();
3360 for(CentralV2UserApp userApp : userV2Apps){
3361 CentralApp app = userApp.getApp();
3362 CentralUserApp cua = new CentralUserApp();
3363 cua.setUserId(null);
3365 SortedSet<CentralRoleFunction> cenRoleFunction = new TreeSet<>();
3366 for(CentralV2RoleFunction cenV2RoleFunc : userApp.getRole().getRoleFunctions() ){
3367 CentralRoleFunction cenRoleFunc = new CentralRoleFunction(cenV2RoleFunc.getCode(), cenV2RoleFunc.getName());
3368 cenRoleFunction.add(cenRoleFunc);
3370 CentralRole role = new CentralRole(userApp.getRole().getId(), userApp.getRole().getName(), userApp.getRole().isActive(), userApp.getRole().getPriority(),
3375 return new CentralUser(cenV2User.getId(), cenV2User.getCreated(), cenV2User.getModified(),
3376 cenV2User.getCreatedId(),cenV2User.getModifiedId(),
3377 cenV2User.getRowNum(), cenV2User.getOrgId(), cenV2User.getManagerId(), cenV2User.getFirstName(),
3378 cenV2User.getMiddleInitial(), cenV2User.getLastName(), cenV2User.getPhone(), cenV2User.getFax(),
3379 cenV2User.getCellular(),cenV2User.getEmail(),cenV2User.getAddressId(),cenV2User.getAlertMethodCd(),
3380 cenV2User.getHrid(),cenV2User.getOrgUserId(),cenV2User.getOrgCode(),cenV2User.getAddress1(),
3381 cenV2User.getAddress2(),cenV2User.getCity(),cenV2User.getState(),cenV2User.getZipCode(),cenV2User.getCountry(),
3382 cenV2User.getOrgManagerUserId(),cenV2User.getLocationClli(),cenV2User.getBusinessCountryCode(),
3383 cenV2User.getBusinessCountryName(),cenV2User.getBusinessUnit(),cenV2User.getBusinessUnitName(),
3384 cenV2User.getDepartment(),cenV2User.getDepartmentName(),cenV2User.getCompanyCode(),
3385 cenV2User.getCompany(),cenV2User.getZipCodeSuffix(),cenV2User.getJobTitle(),
3386 cenV2User.getCommandChain(),cenV2User.getSiloStatus(),cenV2User.getCostCenter(),
3387 cenV2User.getFinancialLocCode(),cenV2User.getLoginId(),cenV2User.getLoginPwd(),
3388 cenV2User.getLastLoginDate(),cenV2User.isActive(),cenV2User.isInternal(),cenV2User.getSelectedProfileId(),cenV2User.getTimeZoneId(),
3389 cenV2User.isOnline(),cenV2User.getChatId(),
3394 public List<CentralRole> convertV2CentralRoleListToOldVerisonCentralRoleList(List<CentralV2Role> v2CenRoleList) {
3395 List<CentralRole> cenRoleList = new ArrayList<>();
3396 SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
3397 for(CentralV2Role v2CenRole : v2CenRoleList){
3398 for(CentralV2RoleFunction v2CenRoleFunc: v2CenRole.getRoleFunctions()){
3399 CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName());
3400 cenRoleFuncList.add(roleFunc);
3402 CentralRole role = new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.isActive(), v2CenRole.getPriority(), cenRoleFuncList);
3403 cenRoleList.add(role);
3409 public ResponseEntity<String> getNameSpaceIfExists(EPApp app) throws Exception {
3410 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3411 HttpEntity<String> entity = new HttpEntity<>(headers);
3412 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Connecting to External Auth system");
3413 ResponseEntity<String> response = null;
3416 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
3417 + "nss/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
3418 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Finished ",
3419 response.getStatusCode().value());
3420 } catch (HttpClientErrorException e) {
3421 logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e);
3422 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3423 if (e.getStatusCode() == HttpStatus.NOT_FOUND)
3424 throw new InvalidApplicationException("Invalid NameSpace");
3432 public CentralRole convertV2CentralRoleToOldVerisonCentralRole(CentralV2Role v2CenRole) {
3433 SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
3434 for (CentralV2RoleFunction v2CenRoleFunc : v2CenRole.getRoleFunctions()) {
3435 CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName());
3436 cenRoleFuncList.add(roleFunc);
3438 return new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.isActive(), v2CenRole.getPriority(),
3442 @SuppressWarnings("unchecked")
3444 public Integer bulkUploadUsersSingleRole(String uebkey, Long roleId, String modifiedRoleName) throws Exception {
3445 EPApp app = getApp(uebkey).get(0);
3446 final Map<String, String> params = new HashMap<>();
3447 params.put("uebKey", app.getUebKey());
3448 params.put("roleId", String.valueOf(roleId));
3449 List<BulkUploadUserRoles> userRolesList = null;
3450 Integer userRolesAdded = 0;
3451 if (app.getCentralAuth()) {
3452 userRolesList = dataAccessService.executeNamedQuery("getBulkUsersForSingleRole", params, null);
3453 for (BulkUploadUserRoles userRolesUpload : userRolesList) {
3454 userRolesUpload.setRoleName(modifiedRoleName);
3455 if(!userRolesUpload.getOrgUserId().equals("su1234")){
3456 addUserRoleInExternalSystem(userRolesUpload);
3461 return userRolesAdded;
3465 public String encodeFunctionCode(String funCode){
3466 String encodedString = funCode;
3467 List<Pattern> encodingList = new ArrayList<>();
3468 encodingList.add(Pattern.compile("/"));
3469 encodingList.add(Pattern.compile("-"));
3470 for (Pattern xssInputPattern : encodingList) {
3471 encodedString = xssInputPattern.matcher(encodedString)
3472 .replaceAll("%" + Hex.encodeHexString(xssInputPattern.toString().getBytes()));
3474 encodedString = encodedString.replaceAll("\\*", "%"+ Hex.encodeHexString("*".getBytes()));
3475 return encodedString;