2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
8 * Unless otherwise specified, all software contained herein is licensed
9 * under the Apache License, Version 2.0 (the "License");
10 * you may not use this software except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * Unless otherwise specified, all documentation contained herein is licensed
22 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23 * you may not use this documentation except in compliance with the License.
24 * You may obtain a copy of the License at
26 * https://creativecommons.org/licenses/by/4.0/
28 * Unless required by applicable law or agreed to in writing, documentation
29 * distributed under the License is distributed on an "AS IS" BASIS,
30 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31 * See the License for the specific language governing permissions and
32 * limitations under the License.
34 * ============LICENSE_END============================================
38 package org.onap.portalapp.portal.service;
40 import java.io.IOException;
41 import java.util.ArrayList;
42 import java.util.HashMap;
43 import java.util.HashSet;
44 import java.util.Iterator;
45 import java.util.List;
48 import java.util.SortedSet;
49 import java.util.TreeSet;
50 import java.util.regex.Pattern;
51 import java.util.stream.Collectors;
53 import org.apache.commons.codec.DecoderException;
54 import org.apache.commons.codec.binary.Hex;
55 import org.hibernate.Query;
56 import org.hibernate.Session;
57 import org.hibernate.SessionFactory;
58 import org.hibernate.Transaction;
59 import org.hibernate.criterion.Criterion;
60 import org.hibernate.criterion.Restrictions;
61 import org.json.JSONArray;
62 import org.json.JSONObject;
63 import org.onap.portalapp.portal.domain.CentralV2RoleFunction;
64 import org.onap.portalapp.portal.domain.CentralizedApp;
65 import org.onap.portalapp.portal.domain.EPApp;
66 import org.onap.portalapp.portal.domain.EPAppRoleFunction;
67 import org.onap.portalapp.portal.domain.EPRole;
68 import org.onap.portalapp.portal.domain.EPUser;
69 import org.onap.portalapp.portal.domain.EPUserApp;
70 import org.onap.portalapp.portal.domain.ExternalRoleDetails;
71 import org.onap.portalapp.portal.ecomp.model.UploadRoleFunctionExtSystem;
72 import org.onap.portalapp.portal.exceptions.DeleteDomainObjectFailedException;
73 import org.onap.portalapp.portal.exceptions.ExternalAuthSystemException;
74 import org.onap.portalapp.portal.exceptions.InactiveApplicationException;
75 import org.onap.portalapp.portal.exceptions.InvalidApplicationException;
76 import org.onap.portalapp.portal.exceptions.InvalidUserException;
77 import org.onap.portalapp.portal.exceptions.RoleFunctionException;
78 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
79 import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
80 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
81 import org.onap.portalapp.portal.transport.BulkUploadRoleFunction;
82 import org.onap.portalapp.portal.transport.BulkUploadUserRoles;
83 import org.onap.portalapp.portal.transport.CentralApp;
84 import org.onap.portalapp.portal.transport.CentralRole;
85 import org.onap.portalapp.portal.transport.CentralRoleFunction;
86 import org.onap.portalapp.portal.transport.CentralUser;
87 import org.onap.portalapp.portal.transport.CentralUserApp;
88 import org.onap.portalapp.portal.transport.CentralV2Role;
89 import org.onap.portalapp.portal.transport.CentralV2User;
90 import org.onap.portalapp.portal.transport.CentralV2UserApp;
91 import org.onap.portalapp.portal.transport.CentralizedAppRoles;
92 import org.onap.portalapp.portal.transport.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.ExternalAccessUserRoleDetail;
99 import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator;
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.EcompRoleFunction;
111 import org.onap.portalsdk.core.restful.domain.EcompUser;
112 import org.onap.portalsdk.core.service.DataAccessService;
113 import org.onap.portalsdk.core.util.SystemProperties;
114 import org.springframework.beans.factory.annotation.Autowired;
115 import org.springframework.context.annotation.EnableAspectJAutoProxy;
116 import org.springframework.http.HttpEntity;
117 import org.springframework.http.HttpHeaders;
118 import org.springframework.http.HttpMethod;
119 import org.springframework.http.HttpStatus;
120 import org.springframework.http.ResponseEntity;
121 import org.springframework.stereotype.Service;
122 import org.springframework.transaction.annotation.Transactional;
123 import org.springframework.web.client.HttpClientErrorException;
124 import org.springframework.web.client.RestTemplate;
126 import com.fasterxml.jackson.core.JsonProcessingException;
127 import com.fasterxml.jackson.databind.DeserializationFeature;
128 import com.fasterxml.jackson.databind.ObjectMapper;
129 import com.fasterxml.jackson.databind.type.TypeFactory;
131 @Service("externalAccessRolesService")
132 @EnableAspectJAutoProxy
135 public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesService {
137 private static final String APP_ROLE_NAME_PARAM = "appRoleName";
139 private static final String GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM = "getRoletoUpdateInExternalAuthSystem";
141 private static final String GET_PORTAL_APP_ROLES_QUERY = "getPortalAppRoles";
143 private static final String GET_ROLE_FUNCTION_QUERY = "getRoleFunction";
145 private static final String FUNCTION_CODE_PARAMS = "functionCode";
147 private static final String AND_FUNCTION_CD_EQUALS = " and function_cd = '";
149 private static final String OWNER = ".owner";
151 private static final String ADMIN = ".admin";
153 private static final String ACCOUNT_ADMINISTRATOR = ".Account_Administrator";
155 private static final String FUNCTION_PIPE = "|";
157 private static final String EXTERNAL_AUTH_PERMS = "perms";
159 private static final String EXTERNAL_AUTH_ROLE_DESCRIPTION = "description";
161 private static final String IS_EMPTY_JSON_STRING = "{}";
163 private static final String CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE = "Connecting to External Auth system";
165 private static final String APP_ID = "appId";
167 private static final String ROLE_NAME = "name";
169 private static final String APP_ID_EQUALS = " app_id = ";
171 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesServiceImpl.class);
174 private DataAccessService dataAccessService;
177 private EPAppService epAppService;
180 private SessionFactory sessionFactory;
183 EPRoleService ePRoleService;
185 RestTemplate template = new RestTemplate();
188 // These decode values are based on HexDecoder
189 static final String decodeValueOfForwardSlash = "2f";
190 static final String decodeValueOfHiphen = "2d";
191 static final String decodeValueOfStar = "2a";
193 @SuppressWarnings("unchecked")
194 public List<EPRole> getAppRoles(Long appId) throws Exception {
195 List<EPRole> applicationRoles = null;
196 final Map<String, Long> appParams = new HashMap<>();
199 applicationRoles = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
201 appParams.put("appId", appId);
202 applicationRoles = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
204 } catch (Exception e) {
205 logger.error(EELFLoggerDelegate.errorLogger, "getAppRoles: failed", e);
208 return applicationRoles;
211 @SuppressWarnings("unchecked")
213 public List<EPApp> getApp(String uebkey) throws Exception {
214 List<EPApp> app = null;
216 final Map<String, String> appUebkeyParams = new HashMap<>();
217 appUebkeyParams.put("appKey", uebkey);
218 app = dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null);
219 if(!app.isEmpty() && !app.get(0).getEnabled() && !app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)){
220 throw new InactiveApplicationException("Application:"+app.get(0).getName()+" is Unavailable");
222 } catch (Exception e) {
223 logger.error(EELFLoggerDelegate.errorLogger, "getApp: failed", e);
230 * It returns single application role from external auth system
233 * @return JSON string which contains application role details
236 private String getSingleAppRole(String addRole, EPApp app) throws Exception {
237 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
238 HttpEntity<String> entity = new HttpEntity<>(headers);
239 ResponseEntity<String> response = null;
240 logger.debug(EELFLoggerDelegate.debugLogger, "getSingleAppRole: Connecting to External Auth system");
241 response = template.exchange(
242 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
245 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
246 HttpMethod.GET, entity, String.class);
247 logger.debug(EELFLoggerDelegate.debugLogger,
248 "getSingleAppRole: Finished GET app role from External Auth system and status code: {} ",
249 response.getStatusCode().value());
250 return response.getBody();
254 public boolean addRole(Role addRole, String uebkey) throws Exception {
255 boolean response = false;
256 ResponseEntity<String> addResponse = null;
257 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
258 EPApp app = getApp(uebkey).get(0);
259 String newRole = updateExistingRoleInExternalSystem(addRole, app);
260 HttpEntity<String> entity = new HttpEntity<>(newRole, headers);
261 logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Connecting to External Auth system");
262 addResponse = template.exchange(
263 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
264 HttpMethod.POST, entity, String.class);
265 if (addResponse.getStatusCode().value() == 201) {
267 logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Finished adding role in the External Auth system and response code: {} ", addResponse.getStatusCode().value());
269 if (addResponse.getStatusCode().value() == 406) {
270 logger.error(EELFLoggerDelegate.errorLogger,
271 "addRole: Failed to add in the External Auth system due to {} and status code: {}", addResponse.getBody(), addResponse.getStatusCode().value());
278 * It deletes record in external auth system
281 * @return JSON String which has status code and response body
284 private ResponseEntity<String> deleteRoleInExternalSystem(String delRole) throws Exception {
285 ResponseEntity<String> delResponse = null;
286 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
287 HttpEntity<String> entity = new HttpEntity<>(delRole, headers);
288 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: {} for DELETE: {}" , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, delRole);
289 delResponse = template.exchange(
290 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role?force=true",
291 HttpMethod.DELETE, entity, String.class);
292 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: Finished DELETE operation in the External Auth system {} and status code: {} ", delRole, delResponse.getStatusCode().value());
297 * It updates role in external auth system
299 * @param updateExtRole
301 * @return true if success else false
303 * If updateRoleInExternalSystem fails we catch it in logger for detail message
305 private boolean updateRoleInExternalSystem(Role updateExtRole, EPApp app, boolean isGlobalRole) throws Exception {
306 boolean response = false;
307 ObjectMapper mapper = new ObjectMapper();
308 ResponseEntity<String> deleteResponse = null;
309 List<EPRole> epRoleList = null;
310 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)
311 || (isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
312 epRoleList = getPortalAppRoleInfo(updateExtRole.getId());
314 epRoleList = getPartnerAppRoleInfo(updateExtRole.getId(), app);
316 // Assigning functions to global role
317 if ((isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
318 List<RoleFunction> globalRoleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole);
319 EPApp portalAppInfo = epAppService.getApp(PortalConstants.PORTAL_APP_ID);
320 addFunctionsTOGlobalRole(epRoleList, updateExtRole, globalRoleFunctionListNew, mapper, app, portalAppInfo);
323 String appRole = getSingleAppRole(epRoleList.get(0).getName(), app);
324 List<RoleFunction> roleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole);
325 if (!appRole.equals(IS_EMPTY_JSON_STRING)) {
326 JSONObject jsonObj = new JSONObject(appRole);
327 JSONArray extRole = jsonObj.getJSONArray("role");
328 if (!extRole.getJSONObject(0).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
329 String roleName = extRole.getJSONObject(0).getString(ROLE_NAME);
330 Map<String, String> delRoleKeyMapper = new HashMap<>();
331 delRoleKeyMapper.put(ROLE_NAME, roleName);
332 String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
333 deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
334 if (deleteResponse.getStatusCode().value() != 200) {
335 throw new ExternalAuthSystemException(deleteResponse.getBody());
337 addRole(updateExtRole, app.getUebKey());
339 String desc = extRole.getJSONObject(0).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
340 String name = extRole.getJSONObject(0).getString(ROLE_NAME);
341 List<ExternalAccessPerms> list = new ArrayList<>();
342 if (extRole.getJSONObject(0).has(EXTERNAL_AUTH_PERMS)) {
343 JSONArray perms = extRole.getJSONObject(0).getJSONArray(EXTERNAL_AUTH_PERMS);
344 list = mapper.readValue(perms.toString(), TypeFactory.defaultInstance()
345 .constructCollectionType(List.class, ExternalAccessPerms.class));
347 // If role name or role functions are updated then delete
348 // record in External System and add new record to avoid
350 boolean isRoleNameChanged = false;
351 if (!desc.equals(updateExtRole.getName())) {
352 isRoleNameChanged = true;
353 deleteRoleInExtSystem(mapper, name);
354 addRole(updateExtRole, app.getUebKey());
355 // add partner functions to the global role in External Auth System
356 if (!list.isEmpty() && isGlobalRole) {
357 addPartnerHasRoleFunctionsToGlobalRole(list, mapper, app, updateExtRole);
360 perm -> EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace()));
361 // if role name is changes please ignore the previous functions in External Auth
362 // and update with user requested functions
363 addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name, list);
365 // Delete role in External System if role is inactive
366 if (!updateExtRole.getActive()) {
367 deleteRoleInExtSystem(mapper, name);
369 if (!isRoleNameChanged) {
370 response = addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name,
375 // It seems like role exists in local DB but not in External
377 if (updateExtRole.getActive()) {
378 addRole(updateExtRole, app.getUebKey());
379 ExternalAccessRolePerms extAddRolePerms = null;
380 ExternalAccessPerms extAddPerms = null;
381 List<RoleFunction> roleFunctionListAdd = convertSetToListOfRoleFunctions(updateExtRole);
382 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
383 for (RoleFunction roleFunc : roleFunctionListAdd) {
384 extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + roleFunc.getType(),
385 roleFunc.getCode(), roleFunc.getAction());
386 extAddRolePerms = new ExternalAccessRolePerms(extAddPerms,
387 app.getNameSpace() + "." + updateExtRole.getName().replaceAll(
388 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
389 response = addRoleFuncExtSysRestAPI(mapper, extAddRolePerms, headers);
397 private void deleteRoleInExtSystem(ObjectMapper mapper, String name)
398 throws JsonProcessingException, Exception, ExternalAuthSystemException {
399 ResponseEntity<String> deleteResponse;
400 Map<String, String> delRoleKeyMapper = new HashMap<>();
401 delRoleKeyMapper.put(ROLE_NAME, name);
402 String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
403 deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
404 if (deleteResponse.getStatusCode().value() != 200) {
405 logger.error(EELFLoggerDelegate.errorLogger,
406 "updateRoleInExternalSystem: Failed to delete role in external system due to {} ",
407 deleteResponse.getBody());
408 throw new ExternalAuthSystemException(deleteResponse.getBody());
412 private boolean addRemoveFunctionsToRole(Role updateExtRole, EPApp app, ObjectMapper mapper,
413 List<RoleFunction> roleFunctionListNew, String name, List<ExternalAccessPerms> list) throws Exception {
415 Map<String, RoleFunction> updateRoleFunc = new HashMap<>();
416 for (RoleFunction addPerm : roleFunctionListNew) {
417 updateRoleFunc.put(addPerm.getCode(), addPerm);
419 final Map<String, ExternalAccessPerms> extRolePermMap = new HashMap<>();
420 final Map<String, ExternalAccessPerms> extRolePermMapPipes = new HashMap<>();
421 list.removeIf(perm -> !EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace()));
422 // Update permissions in the ExternalAccess System
423 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
424 if (!list.isEmpty()) {
425 for (ExternalAccessPerms perm : list) {
426 RoleFunction roleFunc = updateRoleFunc.get(perm.getType().substring(app.getNameSpace().length()+1) + FUNCTION_PIPE + perm.getInstance() + FUNCTION_PIPE + perm.getAction());
427 if (roleFunc==null) {
428 RoleFunction roleFuncPipeFilter = updateRoleFunc.get(perm.getInstance());
429 if(roleFuncPipeFilter == null)
430 removePermForRole(perm, mapper, name, headers);
432 extRolePermMap.put(perm.getInstance(), perm);
433 extRolePermMapPipes.put(
434 perm.getType().substring(app.getNameSpace().length()+1) + FUNCTION_PIPE + perm.getInstance() + FUNCTION_PIPE + perm.getAction(), perm);
438 if (!roleFunctionListNew.isEmpty()) {
439 for (RoleFunction roleFunc : roleFunctionListNew) {
440 if(roleFunc.getCode().contains(FUNCTION_PIPE)) {
441 ExternalAccessPerms perm = extRolePermMapPipes.get(roleFunc.getCode());
443 response = addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers,
447 if (!extRolePermMap.containsKey(EcompPortalUtils.getFunctionCode(roleFunc.getCode()))) {
448 response = addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers,
458 * Adds function to the role in the external auth system while editing a role or updating new functions to a role
461 private boolean addFunctionsToRoleInExternalAuthSystem(Role updateExtRole, EPApp app, ObjectMapper mapper,
462 HttpHeaders headers, RoleFunction roleFunc) throws JsonProcessingException {
464 ExternalAccessRolePerms extRolePerms;
465 ExternalAccessPerms extPerms;
469 if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
470 code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
471 type = getFunctionCodeType(roleFunc.getCode());
472 action = getFunctionCodeAction(roleFunc.getCode());
474 code = roleFunc.getCode();
475 type = roleFunc.getCode().contains("menu") ? "menu" : "url";
478 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, code, action);
479 extRolePerms = new ExternalAccessRolePerms(extPerms,
480 app.getNameSpace() + "."
481 + updateExtRole.getName().replaceAll(
482 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
484 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
485 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
486 logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: {} for POST: {}",
487 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
488 ResponseEntity<String> addResponse = template.exchange(
489 SystemProperties.getProperty(
490 EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
491 HttpMethod.POST, entity, String.class);
492 if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value()!= 409) {
494 logger.debug(EELFLoggerDelegate.debugLogger,
495 "updateRoleInExternalSystem: Connected to External Auth system but something went wrong! due to {} and statuscode: {}",
496 addResponse.getStatusCode().getReasonPhrase(),
497 addResponse.getStatusCode().value());
500 logger.debug(EELFLoggerDelegate.debugLogger,
501 "updateRoleInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ",
502 updateRolePerms, addResponse.getStatusCode().value());
507 private void addPartnerHasRoleFunctionsToGlobalRole(List<ExternalAccessPerms> permslist, ObjectMapper mapper,
508 EPApp app, Role updateExtRole) throws Exception {
509 for (ExternalAccessPerms perm : permslist) {
510 if (!EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace())) {
511 ExternalAccessRolePerms extAddGlobalRolePerms = null;
512 ExternalAccessPerms extAddPerms = null;
513 extAddPerms = new ExternalAccessPerms(perm.getType(), perm.getInstance(), perm.getAction());
514 extAddGlobalRolePerms = new ExternalAccessRolePerms(extAddPerms,
515 app.getNameSpace() + "." + updateExtRole.getName().replaceAll(
516 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
517 String addPerms = mapper.writeValueAsString(extAddGlobalRolePerms);
518 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
519 HttpEntity<String> entity = new HttpEntity<>(addPerms, headers);
520 logger.debug(EELFLoggerDelegate.debugLogger, "addPartnerHasRoleFunctionsToGlobalRole: {} ",
521 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
523 ResponseEntity<String> addResponse = template
524 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
525 + "role/perm", HttpMethod.POST, entity, String.class);
526 if (addResponse.getStatusCode().value() != 201) {
527 logger.debug(EELFLoggerDelegate.debugLogger,
528 "addPartnerHasRoleFunctionsToGlobalRole: While adding permission to the role in External Auth system something went wrong! due to {} and statuscode: {}",
529 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
531 logger.debug(EELFLoggerDelegate.debugLogger,
532 "addPartnerHasRoleFunctionsToGlobalRole: Finished adding permissions to roles in External Auth system and status code: {} ",
533 addResponse.getStatusCode().value());
535 } catch (Exception e) {
536 logger.error(EELFLoggerDelegate.errorLogger, "addPartnerHasRoleFunctionsToGlobalRole: Failed for POST request: {} due to ",
543 @SuppressWarnings("unchecked")
544 private void addFunctionsTOGlobalRole(List<EPRole> epRoleList, Role updateExtRole, List<RoleFunction> roleFunctionListNew, ObjectMapper mapper, EPApp app, EPApp portalAppInfo)
547 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addFunctionsTOGlobalRole");
548 //GET Permissions from External Auth System
549 JSONArray extPerms = getExtAuthPermissions(app);
550 List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);
551 final Map<String, ExternalAccessPermsDetail> existingPermsWithRoles = new HashMap<>();
552 final Map<String, ExternalAccessPermsDetail> existingPermsWithRolesWithPipes = new HashMap<>();
553 final Map<String, RoleFunction> userRquestedFunctionsMap = new HashMap<>();
554 final Map<String, RoleFunction> userRquestedFunctionsMapPipesFilter = new HashMap<>();
555 for (ExternalAccessPermsDetail permDetail : permsDetailList) {
556 existingPermsWithRoles.put(EcompPortalUtils.getFunctionCode(permDetail.getInstance()), permDetail);
557 existingPermsWithRolesWithPipes.put(permDetail.getInstance(), permDetail);
560 // Add If function does not exists for role in External Auth System
561 for (RoleFunction roleFunc : roleFunctionListNew) {
562 String roleFuncCode = "";
563 ExternalAccessPermsDetail permsDetail;
564 if(roleFunc.getCode().contains(FUNCTION_PIPE)) {
565 roleFuncCode = roleFunc.getCode();
566 permsDetail = existingPermsWithRolesWithPipes.get(roleFunc.getCode());
568 roleFuncCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
569 permsDetail = existingPermsWithRoles.get(roleFuncCode);
571 if (null == permsDetail.getRoles() || !permsDetail.getRoles()
572 .contains(portalAppInfo.getNameSpace() + FUNCTION_PIPE + epRoleList.get(0).getName().replaceAll(
573 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
574 addRoleFunctionsToGlobalRoleInExternalSystem(roleFunc, updateExtRole, mapper, app, portalAppInfo);
576 userRquestedFunctionsMap.put(roleFuncCode, roleFunc);
577 userRquestedFunctionsMapPipesFilter.put(EcompPortalUtils.getFunctionCode(roleFuncCode), roleFunc);
579 // Delete functions if exists in External Auth System but not in incoming request
580 final Map<String, Long> epAppRoleFuncParams = new HashMap<>();
581 epAppRoleFuncParams.put("requestedAppId", app.getId());
582 epAppRoleFuncParams.put("roleId",updateExtRole.getId());
583 List<GlobalRoleWithApplicationRoleFunction> globalRoleFunctionList = dataAccessService.executeNamedQuery("getGlobalRoleForRequestedApp", epAppRoleFuncParams, null);
584 for(GlobalRoleWithApplicationRoleFunction globalRoleFunc: globalRoleFunctionList){
585 String globalRoleFuncWithoutPipes = "";
586 RoleFunction roleFunc = null;
587 if(globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
588 globalRoleFuncWithoutPipes = globalRoleFunc.getFunctionCd();
589 roleFunc = userRquestedFunctionsMap.get(globalRoleFuncWithoutPipes);
591 globalRoleFuncWithoutPipes = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd());
592 roleFunc = userRquestedFunctionsMapPipesFilter.get(globalRoleFuncWithoutPipes);
594 if(roleFunc == null){
595 ExternalAccessPermsDetail permDetailFromMap = globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE) ? existingPermsWithRolesWithPipes.get(globalRoleFuncWithoutPipes) : existingPermsWithRoles.get(globalRoleFuncWithoutPipes);
596 ExternalAccessPerms perm = new ExternalAccessPerms(permDetailFromMap.getType(), EcompPortalUtils.getFunctionCode(permDetailFromMap.getInstance()), permDetailFromMap.getAction());
597 String roleName = portalAppInfo.getNameSpace()+"."+globalRoleFunc.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_");
598 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
599 removePermForRole(perm, mapper, roleName, headers);
602 logger.debug(EELFLoggerDelegate.debugLogger, "Finished addFunctionsTOGlobalRole");
603 } catch (Exception e) {
604 logger.error(EELFLoggerDelegate.errorLogger, "addFunctionsTOGlobalRole: Failed",e);
609 private void addRoleFunctionsToGlobalRoleInExternalSystem(RoleFunction addFunction, Role globalRole, ObjectMapper mapper, EPApp app,
610 EPApp portalAppInfo) throws Exception {
612 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addRoleFunctionsToGlobalRoleInExternalSystem");
613 ExternalAccessRolePerms extAddRolePerms = null;
614 ExternalAccessPerms extAddPerms = null;
615 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
619 if (addFunction.getCode().contains(FUNCTION_PIPE)) {
620 code = EcompPortalUtils.getFunctionCode(addFunction.getCode());
621 type = getFunctionCodeType(addFunction.getCode());
622 action = getFunctionCodeAction(addFunction.getCode());
624 code = addFunction.getCode();
625 type = addFunction.getCode().contains("menu") ? "menu" : "url";
628 extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, code, action);
629 extAddRolePerms = new ExternalAccessRolePerms(extAddPerms,
630 portalAppInfo.getNameSpace() + "." + globalRole.getName().replaceAll(
631 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
632 String updateRolePerms = mapper.writeValueAsString(extAddRolePerms);
633 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
634 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} ",
635 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
636 ResponseEntity<String> addResponse = template
637 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
638 + "role/perm", HttpMethod.POST, entity, String.class);
639 if (addResponse.getStatusCode().value() != 201) {
640 logger.debug(EELFLoggerDelegate.debugLogger,
641 "addRoleFunctionsInExternalSystem: While adding permission to the role in External Auth system something went wrong! due to {} and statuscode: {}",
642 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
644 logger.debug(EELFLoggerDelegate.debugLogger,
645 "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system and status code: {} ",
646 addResponse.getStatusCode().value());
648 logger.debug(EELFLoggerDelegate.debugLogger, "Finished addRoleFunctionsToGlobalRoleInExternalSystem");
650 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionsToGlobalRoleInExternalSystem: Failed",e);
655 private boolean addRoleFuncExtSysRestAPI(ObjectMapper addPermsMapper, ExternalAccessRolePerms extAddRolePerms,
656 HttpHeaders headers) throws JsonProcessingException {
658 String updateRolePerms = addPermsMapper.writeValueAsString(extAddRolePerms);
659 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
660 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} for POST: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
661 ResponseEntity<String> addResponse = template.exchange(
662 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
663 HttpMethod.POST, entity, String.class);
664 if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 409) {
666 logger.debug(EELFLoggerDelegate.debugLogger,
667 "addRoleFunctionsInExternalSystem: While adding permission to the role in External Auth system something went wrong! due to {} and statuscode: {}",
668 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
671 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ", updateRolePerms, addResponse.getStatusCode().value());
678 * It converts list of functions in updateExtRole parameter to the RoleFunction object
680 * @param updateExtRole
681 * @return list of functions
683 @SuppressWarnings("unchecked")
684 private List<RoleFunction> convertSetToListOfRoleFunctions(Role updateExtRole) {
685 Set<RoleFunction> roleFunctionSetList = updateExtRole.getRoleFunctions();
686 List<RoleFunction> roleFunctionList = new ArrayList<>();
687 ObjectMapper roleFuncMapper = new ObjectMapper();
688 Iterator<RoleFunction> itetaror = roleFunctionSetList.iterator();
689 while (itetaror.hasNext()) {
690 Object nextValue = itetaror.next();
691 RoleFunction roleFunction = roleFuncMapper.convertValue(nextValue, RoleFunction.class);
692 roleFunctionList.add(roleFunction);
694 return roleFunctionList.stream().distinct().collect(Collectors.toList());
698 * It delete permissions/functions in the external auth system
704 * @throws JsonProcessingException
707 private void removePermForRole(ExternalAccessPerms perm, ObjectMapper permMapper, String name, HttpHeaders headers)
708 throws ExternalAuthSystemException, JsonProcessingException {
709 ExternalAccessRolePerms extAccessRolePerms = new ExternalAccessRolePerms(perm, name);
710 String permDetails = permMapper.writeValueAsString(extAccessRolePerms);
712 HttpEntity<String> deleteEntity = new HttpEntity<>(permDetails, headers);
713 logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: {} for DELETE: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, permDetails);
714 ResponseEntity<String> deletePermResponse = template
715 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/"
716 + name + "/perm", HttpMethod.DELETE, deleteEntity, String.class);
717 if (deletePermResponse.getStatusCode().value() != 200) {
718 throw new ExternalAuthSystemException(deletePermResponse.getBody());
720 logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: Finished deleting permission to role in External Auth system: {} and status code: {}",
721 permDetails, deletePermResponse.getStatusCode().value());
722 } catch(Exception e){
723 if(e.getMessage().contains("404")){
724 logger.error(EELFLoggerDelegate.errorLogger, "Failed to add role for DELETE request: {} due to {}", permDetails, e.getMessage());
732 * It will create new role in the External Auth System
736 * @return true if successfully added in the system else false
738 * If fails to add role in the system
740 private void addNewRoleInExternalSystem(List<EPRole> newRole, EPApp app) throws Exception, HttpClientErrorException {
742 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
743 ObjectMapper mapper = new ObjectMapper();
744 String addNewRole = "";
745 ExternalAccessRole extRole = new ExternalAccessRole();
746 extRole.setName(app.getNameSpace() + "." + newRole.get(0).getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
747 extRole.setDescription(String.valueOf(newRole.get(0).getName()));
748 addNewRole = mapper.writeValueAsString(extRole);
749 HttpEntity<String> postEntity = new HttpEntity<>(addNewRole, headers);
750 logger.debug(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: {} for POST: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addNewRole);
751 ResponseEntity<String> addNewRoleInExternalSystem = template.exchange(
752 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
753 HttpMethod.POST, postEntity, String.class);
754 if (addNewRoleInExternalSystem.getStatusCode().value() == 201) {
755 logger.debug(EELFLoggerDelegate.debugLogger,
756 "addNewRoleInExternalSystem: Finished adding into External Auth system for POST: {} and status code: {}",
757 addNewRole, addNewRoleInExternalSystem.getStatusCode().value());
759 }catch(HttpClientErrorException ht){
760 dataAccessService.deleteDomainObjects(EPRole.class, " role_id = "+ newRole.get(0).getId(), null);
761 logger.error(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: Failed to add in External Auth system and status code: {}",
763 throw new HttpClientErrorException(ht.getStatusCode());
769 * It updates existing role in the External Auth System
772 * It Contains role information
774 * @return string which is formatted to match with the external auth system
775 * @throws JsonProcessingException
777 private String updateExistingRoleInExternalSystem(Role addRole, EPApp app) throws JsonProcessingException {
778 ObjectMapper mapper = new ObjectMapper();
779 String addNewRole = "";
780 ExternalAccessRole extRole = new ExternalAccessRole();
781 extRole.setName(app.getNameSpace() + "." + addRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
782 extRole.setDescription(String.valueOf(addRole.getName()));
783 addNewRole = mapper.writeValueAsString(extRole);
788 * It create a role in the external auth system and then in our local
792 * @return true else false
795 @SuppressWarnings("unchecked")
796 @Transactional(rollbackFor = Exception.class)
797 public boolean addRoleInEcompDB(Role addRoleInDB, EPApp app) throws Exception {
798 boolean result = false;
799 EPRole epRole = null;
800 Set<RoleFunction> roleFunctionList = addRoleInDB.getRoleFunctions();
801 List<RoleFunction> roleFunctionListNew = new ArrayList<>();
802 ObjectMapper mapper = new ObjectMapper();
803 Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
804 while (itetaror.hasNext()) {
805 Object nextValue = itetaror.next();
806 RoleFunction roleFunction = mapper.convertValue(nextValue, RoleFunction.class);
807 roleFunctionListNew.add(roleFunction);
809 List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct().collect(Collectors.toList());
811 if (addRoleInDB.getId() == null) { // check if it is new role
812 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
813 checkIfRoleExitsInExternalSystem(addRoleInDB, app);
815 EPRole epRoleNew = new EPRole();
816 epRoleNew.setActive(addRoleInDB.getActive());
817 epRoleNew.setName(addRoleInDB.getName());
818 epRoleNew.setPriority(addRoleInDB.getPriority());
819 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
820 epRoleNew.setAppId(null);
822 epRoleNew.setAppId(app.getId());
824 dataAccessService.saveDomainObject(epRoleNew, null);
825 List<EPRole> getRoleCreated = null;
826 final Map<String, String> epAppRoleParams = new HashMap<>();
827 final Map<String, String> epAppPortalRoleParams = new HashMap<>();
828 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
829 epAppRoleParams.put("appId", String.valueOf(app.getId()));
830 epAppRoleParams.put(APP_ROLE_NAME_PARAM, addRoleInDB.getName());
831 List<EPRole> roleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, epAppRoleParams, null);
832 EPRole epUpdateRole = roleCreated.get(0);
833 epUpdateRole.setAppRoleId(epUpdateRole.getId());
834 dataAccessService.saveDomainObject(epUpdateRole, null);
835 getRoleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, epAppRoleParams, null);
837 epAppPortalRoleParams.put(APP_ROLE_NAME_PARAM, addRoleInDB.getName());
838 getRoleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, epAppPortalRoleParams, null);
840 // Add role in External Auth system
841 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
842 addNewRoleInExternalSystem(getRoleCreated, app);
844 } else { // if role already exists then update it
845 EPRole globalRole = null;
846 List<EPRole> applicationRoles;
847 List<EPRole> globalRoleList = getGlobalRolesOfPortal();
848 boolean isGlobalRole = false;
849 if (!globalRoleList.isEmpty()) {
850 EPRole role = globalRoleList.stream().filter(x -> addRoleInDB.getId().equals(x.getId())).findAny()
857 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)
858 || (globalRole != null && app.getId() != globalRole.getAppId())) {
859 applicationRoles = getPortalAppRoleInfo(addRoleInDB.getId());
861 applicationRoles = getPartnerAppRoleInfo(addRoleInDB.getId(), app);
863 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
864 updateRoleInExternalSystem(addRoleInDB, app, isGlobalRole);
865 // Add all user to the re-named role in external auth system
866 if (!applicationRoles.isEmpty()
867 && !addRoleInDB.getName().equals(applicationRoles.get(0).getName())) {
868 bulkUploadUsersSingleRole(app.getUebKey(), applicationRoles.get(0).getId(),
869 addRoleInDB.getName());
872 deleteRoleFunction(app, applicationRoles);
873 if (!applicationRoles.isEmpty()) {
874 epRole = applicationRoles.get(0);
875 epRole.setName(addRoleInDB.getName());
876 epRole.setPriority(addRoleInDB.getPriority());
877 epRole.setActive(addRoleInDB.getActive());
878 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
879 epRole.setAppId(null);
880 epRole.setAppRoleId(null);
881 } else if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)
882 && applicationRoles.get(0).getAppRoleId() == null) {
883 epRole.setAppRoleId(epRole.getId());
885 dataAccessService.saveDomainObject(epRole, null);
887 Long roleAppId = null;
888 if (globalRole != null && !app.getId().equals(globalRole.getAppId()))
889 roleAppId = PortalConstants.PORTAL_APP_ID;
890 saveRoleFunction(listWithoutDuplicates, app, applicationRoles, roleAppId);
893 } catch (Exception e) {
894 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInEcompDB is failed", e);
902 * It validates whether role exists in external auth system
909 private void checkIfRoleExitsInExternalSystem(Role checkRole, EPApp app) throws Exception {
910 getNameSpaceIfExists(app);
911 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
912 String roleName = app.getNameSpace() + "." + checkRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_");
913 HttpEntity<String> checkRoleEntity = new HttpEntity<>(headers);
914 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRoleExitsInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
915 ResponseEntity<String> checkRoleInExternalSystem = template
916 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
917 + roleName, HttpMethod.GET, checkRoleEntity, String.class);
918 if (!checkRoleInExternalSystem.getBody().equals(IS_EMPTY_JSON_STRING)) {
919 logger.debug("checkIfRoleExitsInExternalSystem: Role already exists in external system {} and status code: {} ", checkRoleInExternalSystem.getBody(), checkRoleInExternalSystem.getStatusCode().value());
920 throw new ExternalAuthSystemException(" Role already exists in external system");
925 * It saves list of functions to the role in portal
927 * @param roleFunctionListNew
929 * @param applicationRoles
932 @SuppressWarnings("unchecked")
933 private void saveRoleFunction(List<RoleFunction> roleFunctionListNew, EPApp app, List<EPRole> applicationRoles ,Long roleAppId)
935 final Map<String, String> getAppFunctionParams = new HashMap<>();
937 for (RoleFunction roleFunc : roleFunctionListNew) {
938 String code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
939 EPAppRoleFunction appRoleFunc = new EPAppRoleFunction();
940 appRoleFunc.setAppId(app.getId());
941 appRoleFunc.setRoleId(applicationRoles.get(0).getId());
942 appRoleFunc.setRoleAppId(String.valueOf(roleAppId));
943 getAppFunctionParams.put("appId", String.valueOf(app.getId()));
944 getAppFunctionParams.put(FUNCTION_CODE_PARAMS, roleFunc.getCode());
945 // query to check if function code has pipes
946 List<CentralV2RoleFunction> roleFunction = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null);
947 if(roleFunction.isEmpty()){
948 getAppFunctionParams.put(FUNCTION_CODE_PARAMS, code);
949 roleFunction = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null);
951 if(roleFunction.size() > 1){
952 CentralV2RoleFunction getExactFunctionCode = appFunctionListFilter(code, roleFunction);
953 appRoleFunc.setCode(getExactFunctionCode.getCode());
955 appRoleFunc.setCode(roleFunction.get(0).getCode());
958 dataAccessService.saveDomainObject(appRoleFunc, null);
964 * It filters the app functions which starts with similar name in the result set
967 * @param roleFunction
968 * @return CentralRoleFunction
970 private CentralV2RoleFunction appFunctionListFilter(String roleFuncCode, List<CentralV2RoleFunction> roleFunction) {
971 final Map<String, CentralV2RoleFunction> appFunctionsFilter = new HashMap<>();
972 final Map<String, CentralV2RoleFunction> appFunctionsFilterPipes = new HashMap<>();
973 CentralV2RoleFunction getExactFunctionCode = null;
974 for(CentralV2RoleFunction cenRoleFunction : roleFunction){
975 appFunctionsFilter.put(cenRoleFunction.getCode(), cenRoleFunction);
976 appFunctionsFilterPipes.put(EcompPortalUtils.getFunctionCode(cenRoleFunction.getCode()), cenRoleFunction);
978 getExactFunctionCode = appFunctionsFilter.get(roleFuncCode);
979 if(getExactFunctionCode == null){
980 getExactFunctionCode = appFunctionsFilterPipes.get(roleFuncCode);
982 return getExactFunctionCode;
986 * It deletes all EPAppRoleFunction records in the portal
991 @SuppressWarnings("unchecked")
992 private void deleteRoleFunction(EPApp app, List<EPRole> role) {
993 final Map<String, Long> appRoleFuncsParams = new HashMap<>();
994 appRoleFuncsParams.put("appId", app.getId());
995 appRoleFuncsParams.put("roleId", role.get(0).getId());
996 List<EPAppRoleFunction> appRoleFunctionList = dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null);
997 if (!appRoleFunctionList.isEmpty()) {
998 for (EPAppRoleFunction approleFunction : appRoleFunctionList) {
999 dataAccessService.deleteDomainObject(approleFunction, null);
1005 @SuppressWarnings("unchecked")
1006 public List<EPUser> getUser(String loginId) throws InvalidUserException{
1007 final Map<String, String> userParams = new HashMap<>();
1008 userParams.put("org_user_id", loginId);
1009 List<EPUser> userList = dataAccessService.executeNamedQuery("getEPUserByOrgUserId", userParams, null);
1010 if (userList.isEmpty()) {
1011 throw new InvalidUserException("User not found");
1017 public String getV2UserWithRoles(String loginId, String uebkey) throws Exception {
1018 final Map<String, String> params = new HashMap<>();
1019 List<EPUser> userList = null;
1020 CentralV2User cenV2User = null;
1021 String result = null;
1023 params.put("orgUserIdValue", loginId);
1024 List<EPApp> appList = getApp(uebkey);
1025 if (!appList.isEmpty()) {
1026 userList = getUser(loginId);
1027 if (!userList.isEmpty()) {
1028 ObjectMapper mapper = new ObjectMapper();
1029 cenV2User = getV2UserAppRoles(loginId, uebkey);
1030 result = mapper.writeValueAsString(cenV2User);
1031 } else if (userList.isEmpty()) {
1032 throw new InvalidUserException("User not found");
1035 throw new InactiveApplicationException("Application not found");
1037 } catch (Exception e) {
1038 logger.error(EELFLoggerDelegate.errorLogger, "getUser: failed", e);
1045 public List<CentralV2Role> getRolesForApp(String uebkey) throws Exception {
1046 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Entering into getRolesForApp");
1047 List<CentralV2Role> roleList = new ArrayList<>();
1048 final Map<String, Long> params = new HashMap<>();
1050 List<EPApp> app = getApp(uebkey);
1051 List<EPRole> appRolesList = getAppRoles(app.get(0).getId());
1052 roleList = createCentralRoleObject(app, appRolesList, roleList, params);
1053 if(app.get(0).getId() != PortalConstants.PORTAL_APP_ID){
1054 List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
1055 List<EPRole> globalRolesList = getGlobalRolesOfPortal();
1056 List<CentralV2Role> portalsGlobalRolesFinlaList = new ArrayList<>();
1057 if (!globalRolesList.isEmpty()) {
1058 for (EPRole eprole : globalRolesList) {
1059 CentralV2Role cenRole = convertRoleToCentralV2Role(eprole);
1060 portalsGlobalRolesFinlaList.add(cenRole);
1062 roleList.addAll(globalRoleList);
1063 for (CentralV2Role role : portalsGlobalRolesFinlaList) {
1064 CentralV2Role result = roleList.stream()
1065 .filter(x -> role.getId().equals(x.getId())).findAny().orElse(null);
1070 for (EPRole role : globalRolesList) {
1071 CentralV2Role cenRole = convertRoleToCentralV2Role(role);
1072 roleList.add(cenRole);
1076 } catch (Exception e) {
1077 logger.error(EELFLoggerDelegate.errorLogger, "getRolesForApp: Failed!", e);
1080 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Finished!");
1081 return roleList.stream().distinct().collect(Collectors.toList());
1084 @SuppressWarnings("unchecked")
1086 public List<CentralV2RoleFunction> getRoleFuncList(String uebkey) throws Exception {
1087 EPApp app = getApp(uebkey).get(0);
1088 List<CentralV2RoleFunction> finalRoleList = new ArrayList<>();
1089 final Map<String, Long> params = new HashMap<>();
1090 params.put(APP_ID, app.getId());
1091 List<CentralV2RoleFunction> getRoleFuncList = dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null);
1092 for (CentralV2RoleFunction roleFuncItem : getRoleFuncList) {
1093 String code = EcompPortalUtils.getFunctionCode(roleFuncItem.getCode());
1094 String type = getFunctionCodeType(roleFuncItem.getCode());
1095 String action = getFunctionCodeAction(roleFuncItem.getCode());
1096 roleFuncItem.setCode(EPUserUtils.decodeFunctionCode(code));
1097 roleFuncItem.setType(type);
1098 roleFuncItem.setAction(action);
1099 finalRoleList.add(roleFuncItem);
1101 return finalRoleList;
1106 public String getFunctionCodeAction(String roleFuncItem) {
1107 return (!roleFuncItem.contains(FUNCTION_PIPE)) ? "*"
1108 : EcompPortalUtils.getFunctionAction(roleFuncItem);
1112 public String getFunctionCodeType(String roleFuncItem) {
1114 if ((roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))
1115 || (!roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))) {
1117 } else if (checkIfCodeHasNoPipesAndHasTypeUrl(roleFuncItem)
1118 ||checkIfCodeHasPipesAndHasTypeUrl(roleFuncItem)
1119 ||checkIfCodeHasNoPipesAndHasNoTypeUrl(roleFuncItem)) {
1121 } else if (roleFuncItem.contains(FUNCTION_PIPE)
1122 && (!roleFuncItem.contains("menu") || roleFuncItem.contains("url"))) {
1123 type = EcompPortalUtils.getFunctionType(roleFuncItem);
1130 * It check whether function code has no pipes and no url string in it
1132 * @param roleFuncItem
1133 * @return true or false
1135 private boolean checkIfCodeHasNoPipesAndHasNoTypeUrl(String roleFuncItem) {
1136 return !roleFuncItem.contains(FUNCTION_PIPE) && !roleFuncItem.contains("url");
1141 * It check whether function code has pipes and url string in it
1143 * @param roleFuncItem
1144 * @return true or false
1146 private boolean checkIfCodeHasPipesAndHasTypeUrl(String roleFuncItem) {
1147 return roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
1152 * It check whether function code has no pipes and has url string in it
1154 * @param roleFuncItem
1155 * @return true or false
1157 private boolean checkIfCodeHasNoPipesAndHasTypeUrl(String roleFuncItem) {
1158 return !roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
1162 * It returns user detail information which is deep copy of EPUser.class object
1170 @SuppressWarnings("unchecked")
1171 private CentralV2User createEPUser(EPUser userInfo, Set<EPUserApp> userAppSet, EPApp app) throws Exception {
1172 final Map<String, Long> params = new HashMap<>();
1173 CentralV2User userAppList = new CentralV2User();
1174 CentralV2User user1 = null;
1175 final Map<String, Long> params1 = new HashMap<>();
1176 List<EPRole> globalRoleList = new ArrayList<>();
1178 if (app.getId() != PortalConstants.PORTAL_APP_ID) {
1179 params1.put("userId", userInfo.getId());
1180 params1.put("appId", app.getId());
1181 globalRoleList = dataAccessService.executeNamedQuery("userAppGlobalRoles", params1, null);
1183 userAppList.setUserApps(new TreeSet<CentralV2UserApp>());
1184 for (EPUserApp userApp : userAppSet) {
1185 if (userApp.getRole().getActive()) {
1186 EPApp epApp = userApp.getApp();
1187 String globalRole = userApp.getRole().getName().toLowerCase();
1188 if (((epApp.getId().equals(app.getId()))
1189 && (!userApp.getRole().getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)))
1190 || ((epApp.getId().equals(PortalConstants.PORTAL_APP_ID))
1191 && (globalRole.toLowerCase().startsWith("global_")))) {
1192 CentralV2UserApp cua = new CentralV2UserApp();
1193 cua.setUserId(null);
1194 CentralApp cenApp = new CentralApp(1L, epApp.getCreated(), epApp.getModified(),
1195 epApp.getCreatedId(), epApp.getModifiedId(), epApp.getRowNum(), epApp.getName(),
1196 epApp.getImageUrl(), epApp.getDescription(), epApp.getNotes(), epApp.getUrl(),
1197 epApp.getAlternateUrl(), epApp.getAppRestEndpoint(), epApp.getMlAppName(),
1198 epApp.getMlAppAdminId(), String.valueOf(epApp.getMotsId()), epApp.getAppPassword(),
1199 String.valueOf(epApp.getOpen()), String.valueOf(epApp.getEnabled()),
1200 epApp.getThumbnail(), epApp.getUsername(), epApp.getUebKey(), epApp.getUebSecret(),
1201 epApp.getUebTopicName());
1204 if (globalRole.toLowerCase().startsWith("global_")
1205 && epApp.getId().equals(PortalConstants.PORTAL_APP_ID)
1206 && !epApp.getId().equals(app.getId())) {
1207 appId = app.getId();
1208 EPRole result = null;
1209 if (globalRoleList.size() > 0)
1210 result = globalRoleList.stream()
1211 .filter(x -> userApp.getRole().getId().equals(x.getId())).findAny()
1216 appId = userApp.getApp().getId();
1218 params.put("roleId", userApp.getRole().getId());
1219 params.put(APP_ID, appId);
1220 List<CentralV2RoleFunction> appRoleFunctionList = dataAccessService
1221 .executeNamedQuery("getAppRoleFunctionList", params, null);
1222 SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>();
1223 for (CentralV2RoleFunction roleFunc : appRoleFunctionList) {
1224 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1225 String type = getFunctionCodeType(roleFunc.getCode());
1226 String action = getFunctionCodeAction(roleFunc.getCode());
1227 CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(roleFunc.getId(),
1228 functionCode, roleFunc.getName(), null, type, action, null);
1229 roleFunctionSet.add(cenRoleFunc);
1231 Long userRoleId = null;
1232 if (globalRole.toLowerCase().startsWith("global_")
1233 || epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1234 userRoleId = userApp.getRole().getId();
1236 userRoleId = userApp.getRole().getAppRoleId();
1238 CentralV2Role cenRole = new CentralV2Role(userRoleId, userApp.getRole().getCreated(),
1239 userApp.getRole().getModified(), userApp.getRole().getCreatedId(),
1240 userApp.getRole().getModifiedId(), userApp.getRole().getRowNum(),
1241 userApp.getRole().getName(), userApp.getRole().getActive(),
1242 userApp.getRole().getPriority(), roleFunctionSet, null, null);
1243 cua.setRole(cenRole);
1245 userAppList.getUserApps().add(cua);
1250 user1 = new CentralV2User(null, userInfo.getCreated(), userInfo.getModified(), userInfo.getCreatedId(),
1251 userInfo.getModifiedId(), userInfo.getRowNum(), userInfo.getOrgId(), userInfo.getManagerId(),
1252 userInfo.getFirstName(), userInfo.getMiddleInitial(), userInfo.getLastName(), userInfo.getPhone(),
1253 userInfo.getFax(), userInfo.getCellular(), userInfo.getEmail(), userInfo.getAddressId(),
1254 userInfo.getAlertMethodCd(), userInfo.getHrid(), userInfo.getOrgUserId(), userInfo.getOrgCode(),
1255 userInfo.getAddress1(), userInfo.getAddress2(), userInfo.getCity(), userInfo.getState(),
1256 userInfo.getZipCode(), userInfo.getCountry(), userInfo.getOrgManagerUserId(),
1257 userInfo.getLocationClli(), userInfo.getBusinessCountryCode(), userInfo.getBusinessCountryName(),
1258 userInfo.getBusinessUnit(), userInfo.getBusinessUnitName(), userInfo.getDepartment(),
1259 userInfo.getDepartmentName(), userInfo.getCompanyCode(), userInfo.getCompany(),
1260 userInfo.getZipCodeSuffix(), userInfo.getJobTitle(), userInfo.getCommandChain(),
1261 userInfo.getSiloStatus(), userInfo.getCostCenter(), userInfo.getFinancialLocCode(),
1262 userInfo.getLoginId(), userInfo.getLoginPwd(), userInfo.getLastLoginDate(), userInfo.getActive(),
1263 userInfo.getInternal(), userInfo.getSelectedProfileId(), userInfo.getTimeZoneId(),
1264 userInfo.isOnline(), userInfo.getChatId(), userAppList.getUserApps(), null);
1265 } catch (Exception e) {
1266 logger.error(EELFLoggerDelegate.errorLogger, "createEPUser: createEPUser failed", e);
1273 public CentralV2Role getRoleInfo(Long roleId, String uebkey) throws Exception {
1274 final Map<String, Long> params = new HashMap<>();
1275 List<CentralV2Role> roleList = new ArrayList<>();
1276 CentralV2Role cenRole = new CentralV2Role();
1277 List<EPRole> roleInfo = null;
1278 List<EPApp> app = null;
1280 app = getApp(uebkey);
1281 if (app.isEmpty()) {
1282 throw new InactiveApplicationException("Application not found");
1284 if (app.get(0).getId() != PortalConstants.PORTAL_APP_ID) {
1285 List<EPRole> globalRoleList = new ArrayList<>();
1286 globalRoleList = getGlobalRolesOfPortal();
1287 if (globalRoleList.size() > 0) {
1288 EPRole result = globalRoleList.stream().filter(x -> roleId.equals(x.getId())).findAny()
1291 return getGlobalRoleForRequestedApp(app.get(0).getId(), roleId);
1294 if (app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
1295 roleInfo = getPortalAppRoleInfo(roleId);
1297 roleInfo = getPartnerAppRoleInfo(roleId, app.get(0));
1299 roleList = createCentralRoleObject(app, roleInfo, roleList, params);
1300 if (roleList.isEmpty()) {
1304 } catch (Exception e) {
1305 logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo: failed", e);
1309 return roleList.get(0);
1312 @SuppressWarnings("unchecked")
1313 private List<EPRole> getPartnerAppRoleInfo(Long roleId, EPApp app) {
1314 List<EPRole> roleInfo;
1315 final Map<String, Long> getPartnerAppRoleParams = new HashMap<>();
1316 getPartnerAppRoleParams.put("appRoleId", roleId);
1317 getPartnerAppRoleParams.put("appId", app.getId());
1318 roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams, null);
1319 if(roleInfo.isEmpty()) {
1320 getPartnerAppRoleParams.put("appRoleId", roleId);
1321 roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleById", getPartnerAppRoleParams, null);
1326 @SuppressWarnings("unchecked")
1327 private List<EPRole> getPortalAppRoleInfo(Long roleId) {
1328 List<EPRole> roleInfo;
1329 final Map<String, Long> getPortalAppRoleParams = new HashMap<>();
1330 getPortalAppRoleParams.put("roleId", roleId);
1331 roleInfo = dataAccessService.executeNamedQuery("getPortalAppRoleByRoleId", getPortalAppRoleParams, null);
1337 * It returns list of app roles along with role functions and which went through deep copy
1344 * @throws DecoderException
1346 @SuppressWarnings("unchecked")
1347 private List<CentralV2Role> createCentralRoleObject(List<EPApp> app, List<EPRole> roleInfo,
1348 List<CentralV2Role> roleList, Map<String, Long> params) throws RoleFunctionException {
1349 for (EPRole role : roleInfo) {
1350 params.put("roleId", role.getId());
1351 params.put(APP_ID, app.get(0).getId());
1352 List<CentralV2RoleFunction> cenRoleFuncList = dataAccessService.executeNamedQuery("getAppRoleFunctionList",
1354 SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>();
1355 for (CentralV2RoleFunction roleFunc : cenRoleFuncList) {
1356 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1357 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
1358 String type = getFunctionCodeType(roleFunc.getCode());
1359 String action = getFunctionCodeAction(roleFunc.getCode());
1360 CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(role.getId(), functionCode,
1361 roleFunc.getName(), null, type, action, null);
1362 roleFunctionSet.add(cenRoleFunc);
1364 SortedSet<CentralV2Role> childRoles = new TreeSet<>();
1365 SortedSet<CentralV2Role> parentRoles = new TreeSet<>();
1366 CentralV2Role cenRole = null;
1367 if (role.getAppRoleId() == null) {
1368 cenRole = new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
1369 role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
1370 roleFunctionSet, childRoles, parentRoles);
1372 cenRole = new CentralV2Role(role.getAppRoleId(), role.getCreated(), role.getModified(),
1373 role.getCreatedId(), role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(),
1374 role.getPriority(), roleFunctionSet, childRoles, parentRoles);
1376 roleList.add(cenRole);
1381 @SuppressWarnings("unchecked")
1383 public CentralV2RoleFunction getRoleFunction(String functionCode, String uebkey) throws Exception {
1384 String code = EcompPortalUtils.getFunctionCode(functionCode);
1385 String encodedCode = encodeFunctionCode(code);
1386 CentralV2RoleFunction roleFunc = null;
1387 EPApp app = getApp(uebkey).get(0);
1388 List<CentralV2RoleFunction> getRoleFuncList = null;
1389 final Map<String, String> params = new HashMap<>();
1391 params.put(FUNCTION_CODE_PARAMS, functionCode);
1392 params.put(APP_ID, String.valueOf(app.getId()));
1393 getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
1394 if (getRoleFuncList.isEmpty()) {
1395 params.put(FUNCTION_CODE_PARAMS, encodedCode);
1396 getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
1397 if (getRoleFuncList.isEmpty()) {
1401 if (getRoleFuncList.size() > 1) {
1402 CentralV2RoleFunction cenV2RoleFunction = appFunctionListFilter(encodedCode, getRoleFuncList);
1403 if (cenV2RoleFunction == null)
1405 roleFunc = checkIfPipesExitsInFunctionCode(cenV2RoleFunction);
1407 // Check even if single record have pipes
1408 if (!getRoleFuncList.isEmpty() && getRoleFuncList.get(0).getCode().contains(FUNCTION_PIPE)) {
1409 roleFunc = checkIfPipesExitsInFunctionCode(getRoleFuncList.get(0));
1411 roleFunc = getRoleFuncList.get(0);
1414 } catch (Exception e) {
1415 logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction: failed", e);
1421 private CentralV2RoleFunction checkIfPipesExitsInFunctionCode(CentralV2RoleFunction getRoleFuncList) {
1422 CentralV2RoleFunction roleFunc;
1423 String functionCodeFormat = getRoleFuncList.getCode();
1424 if (functionCodeFormat.contains(FUNCTION_PIPE)) {
1425 String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(functionCodeFormat);
1426 String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(functionCodeFormat);
1427 String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(functionCodeFormat);
1428 roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), newfunctionCodeFormat,
1429 getRoleFuncList.getName(), getRoleFuncList.getAppId(), newfunctionTypeFormat, newfunctionActionFormat,
1430 getRoleFuncList.getEditUrl());
1432 roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), functionCodeFormat,
1433 getRoleFuncList.getName(), getRoleFuncList.getAppId(),
1434 getRoleFuncList.getEditUrl());
1440 public boolean saveCentralRoleFunction(CentralV2RoleFunction domainCentralRoleFunction, EPApp app) throws Exception {
1441 boolean saveOrUpdateFunction = false;
1443 domainCentralRoleFunction.setCode(encodeFunctionCode(domainCentralRoleFunction.getCode()));
1444 final Map<String, String> functionParams = new HashMap<>();
1445 functionParams.put("appId", String.valueOf(app.getId()));
1446 if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1447 addRoleFunctionInExternalSystem(domainCentralRoleFunction, app);
1449 if(domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null){
1450 domainCentralRoleFunction.setCode(domainCentralRoleFunction.getType()+
1451 FUNCTION_PIPE+domainCentralRoleFunction.getCode()+FUNCTION_PIPE+domainCentralRoleFunction.getAction());
1453 domainCentralRoleFunction.setAppId(app.getId());
1454 dataAccessService.saveDomainObject(domainCentralRoleFunction, null);
1455 saveOrUpdateFunction = true;
1456 } catch (Exception e) {
1457 logger.error(EELFLoggerDelegate.errorLogger, "saveCentralRoleFunction: failed", e);
1460 return saveOrUpdateFunction;
1464 * It creates application permission in external auth system
1466 * @param domainCentralRoleFunction
1470 private void addRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
1472 ObjectMapper mapper = new ObjectMapper();
1473 ExternalAccessPerms extPerms = new ExternalAccessPerms();
1474 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1476 String instance = "";
1478 if((domainCentralRoleFunction.getType()!=null && domainCentralRoleFunction.getAction()!=null) || domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)){
1479 type = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) ? EcompPortalUtils.getFunctionType(domainCentralRoleFunction.getCode()) : domainCentralRoleFunction.getType();
1480 instance = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) ? EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode()) : domainCentralRoleFunction.getCode();
1481 action = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) ? EcompPortalUtils.getFunctionAction(domainCentralRoleFunction.getCode()) : domainCentralRoleFunction.getAction();
1483 type = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url";
1484 instance = domainCentralRoleFunction.getCode();
1487 // get Permissions from External Auth System
1488 JSONArray extPermsList = getExtAuthPermissions(app);
1489 List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPermsList);
1490 String requestedPerm = type+FUNCTION_PIPE+instance+FUNCTION_PIPE+action;
1491 boolean checkIfFunctionsExits = permsDetailList.stream().anyMatch(permsDetail -> permsDetail.getInstance().equals(requestedPerm));
1492 if (!checkIfFunctionsExits) {
1494 extPerms.setAction(action);
1495 extPerms.setInstance(instance);
1496 extPerms.setType(app.getNameSpace() + "." + type);
1497 extPerms.setDescription(domainCentralRoleFunction.getName());
1498 String addFunction = mapper.writeValueAsString(extPerms);
1499 HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
1500 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for POST: {}" , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
1501 ResponseEntity<String> addPermResponse= template.exchange(
1502 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
1503 HttpMethod.POST, entity, String.class);
1504 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ", addPermResponse.getStatusCode().value(), addFunction);
1505 } catch(HttpClientErrorException e){
1506 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to add function in external central auth system", e);
1507 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1509 }catch (Exception e) {
1510 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionInExternalSystem: Failed to add fucntion in external central auth system",
1516 extPerms.setAction(action);
1517 extPerms.setInstance(instance);
1518 extPerms.setType(app.getNameSpace() + "." + type);
1519 extPerms.setDescription(domainCentralRoleFunction.getName());
1520 String updateRoleFunction = mapper.writeValueAsString(extPerms);
1521 HttpEntity<String> entity = new HttpEntity<>(updateRoleFunction, headers);
1522 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for PUT: {}" , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRoleFunction);
1523 ResponseEntity<String> updatePermResponse = template.exchange(
1524 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
1525 HttpMethod.PUT, entity, String.class);
1526 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished updating permission in External Auth system {} and response: {} ", updateRoleFunction, updatePermResponse.getStatusCode().value());
1527 } catch(HttpClientErrorException e){
1528 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to add function in external central auth system", e);
1529 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1531 } catch (Exception e) {
1532 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionInExternalSystem: Failed to update function in external central auth system",e);
1538 @SuppressWarnings("unchecked")
1540 @Transactional(rollbackFor = Exception.class)
1541 public boolean deleteCentralRoleFunction(String code, EPApp app) {
1542 boolean deleteFunctionResponse = false;
1544 final Map<String, String> params = new HashMap<>();
1545 params.put(FUNCTION_CODE_PARAMS, code);
1546 params.put(APP_ID, String.valueOf(app.getId()));
1547 List<CentralV2RoleFunction> domainCentralRoleFunction = dataAccessService
1548 .executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
1549 CentralV2RoleFunction appFunctionCode = appFunctionListFilter(code, domainCentralRoleFunction);
1550 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1551 deleteRoleFunctionInExternalSystem(appFunctionCode, app);
1552 // Delete role function dependency records
1553 deleteAppRoleFunctions(appFunctionCode.getCode(), app);
1555 dataAccessService.deleteDomainObject(appFunctionCode, null);
1556 deleteFunctionResponse = true;
1557 } catch (Exception e) {
1558 logger.error(EELFLoggerDelegate.errorLogger, "deleteCentralRoleFunction: failed", e);
1560 return deleteFunctionResponse;
1564 * It deletes app function record in portal
1569 private void deleteAppRoleFunctions(String code, EPApp app) {
1570 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
1571 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + code + "'", null);
1576 * It deletes permission in the external auth system
1578 * @param domainCentralRoleFunction
1582 private void deleteRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
1585 ObjectMapper mapper = new ObjectMapper();
1586 ExternalAccessPerms extPerms = new ExternalAccessPerms();
1587 String instanceValue = EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode());
1588 String checkType = getFunctionCodeType(domainCentralRoleFunction.getCode());
1589 String actionValue = getFunctionCodeAction(domainCentralRoleFunction.getCode());
1590 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1591 extPerms.setAction(actionValue);
1592 extPerms.setInstance(instanceValue);
1593 extPerms.setType(app.getNameSpace() + "." + checkType);
1594 extPerms.setDescription(domainCentralRoleFunction.getName());
1595 String deleteRoleFunction = mapper.writeValueAsString(extPerms);
1596 HttpEntity<String> entity = new HttpEntity<>(deleteRoleFunction, headers);
1597 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleFunctionInExternalSystem: {} for DELETE: {} ",
1598 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, deleteRoleFunction);
1599 ResponseEntity<String> delPermResponse = template
1600 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1601 + "perm?force=true", HttpMethod.DELETE, entity, String.class);
1602 logger.debug(EELFLoggerDelegate.debugLogger,
1603 "deleteRoleFunctionInExternalSystem: Finished deleting permission in External Auth system {} and status code: {} ",
1604 deleteRoleFunction, delPermResponse.getStatusCode().value());
1605 } catch(HttpClientErrorException e){
1606 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to delete functions in External System", e);
1607 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1608 } catch (Exception e) {
1609 if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
1610 logger.debug(EELFLoggerDelegate.debugLogger,
1611 " deleteRoleFunctionInExternalSystem: It seems like function is already deleted in external central auth system but exists in local DB",
1614 logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleFunctionInExternalSystem: Failed to delete functions in External System", e);
1620 public ExternalRequestFieldsValidator saveRoleForApplication(Role saveRole, String uebkey) throws Exception {
1621 boolean response = false;
1622 String message = "";
1624 EPApp app = getApp(uebkey).get(0);
1625 addRoleInEcompDB(saveRole, app);
1627 } catch (Exception e) {
1628 message = e.getMessage();
1629 logger.error(EELFLoggerDelegate.errorLogger, "saveRoleForApplication failed", e);
1631 return new ExternalRequestFieldsValidator(response,message);
1634 @SuppressWarnings("unchecked")
1636 public boolean deleteRoleForApplication(String deleteRole, String uebkey) throws Exception {
1637 Session localSession = sessionFactory.openSession();
1638 Transaction transaction = null;
1639 boolean result = false;
1641 List<EPRole> epRoleList = null;
1642 EPApp app = getApp(uebkey).get(0);
1643 final Map<String, String> deleteRoleParams = new HashMap<>();
1644 deleteRoleParams.put(APP_ROLE_NAME_PARAM, deleteRole);
1645 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1646 epRoleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, deleteRoleParams, null);
1648 deleteRoleParams.put(APP_ID, String.valueOf(app.getId()));
1649 epRoleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, deleteRoleParams, null);
1651 if (!epRoleList.isEmpty()) {
1652 transaction = localSession.beginTransaction();
1653 // Delete app role functions before deleting role
1654 deleteRoleFunction(app, epRoleList);
1655 if (app.getId() == 1) {
1656 // Delete fn_user_ role
1657 dataAccessService.deleteDomainObjects(EPUserApp.class,
1658 APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
1659 boolean isPortalRequest = false;
1660 deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest);
1662 deleteRoleInExternalAuthSystem(epRoleList, app);
1663 transaction.commit();
1664 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: committed the transaction");
1665 dataAccessService.deleteDomainObject(epRoleList.get(0), null);
1668 } catch (Exception e) {
1669 logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleForApplication: failed", e);
1672 localSession.close();
1679 * It deletes role for application in external auth system
1681 * @param epRoleList contains role information
1682 * @param app contains application information
1685 private void deleteRoleInExternalAuthSystem(List<EPRole> epRoleList, EPApp app) throws Exception {
1686 ResponseEntity<String> deleteResponse;
1687 ResponseEntity<String> res = getNameSpaceIfExists(app);
1688 if (res.getStatusCode() == HttpStatus.OK) {
1689 // Delete Role in External System
1690 String deleteRoleKey = "{\"name\":\"" + app.getNameSpace() + "." + epRoleList.get(0).getName()
1691 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_") + "\"}";
1692 deleteResponse = deleteRoleInExternalSystem(deleteRoleKey);
1693 if (deleteResponse.getStatusCode().value() != 200 && deleteResponse.getStatusCode().value() != 404) {
1694 EPLogUtil.logExternalAuthAccessAlarm(logger, deleteResponse.getStatusCode());
1695 logger.error(EELFLoggerDelegate.errorLogger,
1696 "deleteRoleForApplication: Failed to delete role in external auth system! due to {} ",
1697 deleteResponse.getBody());
1699 logger.debug(EELFLoggerDelegate.debugLogger,
1700 "deleteRoleForApplication: about to commit the transaction");
1706 * It deletes application user role in external auth system
1713 private void deleteUserRoleInExternalSystem(EPRole role, EPApp app, String LoginId) throws Exception {
1714 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1715 HttpEntity<String> entity = new HttpEntity<>(headers);
1716 getNameSpaceIfExists(app);
1717 logger.debug(EELFLoggerDelegate.debugLogger,"deleteUserRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1718 ResponseEntity<String> getResponse = template
1720 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
1723 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
1724 + "/" + app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
1725 HttpMethod.GET, entity, String.class);
1726 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: Finished GET user roles from External Auth system and response: {} ", getResponse.getBody());
1727 if (getResponse.getStatusCode().value() != 200) {
1728 throw new ExternalAuthSystemException(getResponse.getBody());
1730 String res = getResponse.getBody();
1731 if (!res.equals(IS_EMPTY_JSON_STRING)) {
1732 HttpEntity<String> userRoleentity = new HttpEntity<>(headers);
1733 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1734 ResponseEntity<String> deleteResponse = template
1736 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1737 + "userRole/" + LoginId
1739 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
1740 + "/" + app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
1741 HttpMethod.DELETE, userRoleentity, String.class);
1742 if (deleteResponse.getStatusCode().value() != 200) {
1743 throw new ExternalAuthSystemException("Failed to delete user role");
1745 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: Finished deleting user role in External Auth system and status code: {} ", deleteResponse.getStatusCode().value());
1749 @SuppressWarnings("unchecked")
1751 public List<CentralV2Role> getActiveRoles(String uebkey) throws Exception {
1752 List<CentralV2Role> roleList = new ArrayList<>();
1754 List<EPApp> app = getApp(uebkey);
1755 final Map<String, Long> params = new HashMap<>();
1758 if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
1759 appId = app.get(0).getId();
1761 List<Criterion> restrictionsList = new ArrayList<Criterion>();
1762 Criterion active_ynCrt = Restrictions.eq("active", Boolean.TRUE);
1765 appIdCrt = Restrictions.isNull("appId");
1767 appIdCrt = Restrictions.eq("appId", appId);
1768 Criterion andCrit = Restrictions.and(active_ynCrt, appIdCrt);
1769 restrictionsList.add(andCrit);
1770 List<EPRole> epRole = (List<EPRole>) dataAccessService.getList(EPRole.class, null, restrictionsList, null);
1771 roleList = createCentralRoleObject(app, epRole, roleList, params);
1772 List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
1773 if (globalRoleList.size() > 0)
1774 roleList.addAll(globalRoleList);
1775 } catch (Exception e) {
1776 logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles: failed", e);
1784 @Transactional(rollbackFor = Exception.class)
1785 public ExternalRequestFieldsValidator deleteDependencyRoleRecord(Long roleId, String uebkey, String LoginId) throws Exception {
1786 Session localSession = sessionFactory.openSession();
1787 String message = "";
1788 Transaction transaction = null;
1789 boolean response = false;
1792 transaction = localSession.beginTransaction();
1793 List<EPRole> epRoleList = null;
1794 app = getApp(uebkey).get(0);
1795 if(app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1796 epRoleList = getPortalAppRoleInfo(roleId);
1798 epRoleList = getPartnerAppRoleInfo(roleId, app);
1800 if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1801 // Delete User Role in External System before deleting role
1802 deleteUserRoleInExternalSystem(epRoleList.get(0), app, LoginId);
1804 // Delete user app roles
1805 dataAccessService.deleteDomainObjects(EPUserApp.class,
1806 APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
1807 boolean isPortalRequest = false;
1808 deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest);
1809 transaction.commit();
1810 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1811 // Final call to delete role once all dependencies has been deleted
1812 deleteRoleInExternalAuthSystem(epRoleList, app);
1814 dataAccessService.deleteDomainObjects(EPRole.class, " role_id = "+ epRoleList.get(0).getId(), null);
1815 logger.debug(EELFLoggerDelegate.debugLogger, "deleteDependencyRoleRecord: committed the transaction");
1817 } catch(HttpClientErrorException e){
1818 logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord: HttpClientErrorException", e);
1819 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1820 message = e.getMessage();
1821 } catch (Exception e) {
1822 logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord failed", e);
1823 EcompPortalUtils.rollbackTransaction(transaction,
1824 "deleteDependencyRoleRecord rollback, exception = " + e.toString());
1825 message = e.getMessage();
1827 localSession.close();
1829 return new ExternalRequestFieldsValidator(response,message);
1833 @SuppressWarnings("unchecked")
1835 public void syncRoleFunctionFromExternalAccessSystem(EPApp app) {
1838 // get Permissions from External Auth System
1839 JSONArray extPerms = getExtAuthPermissions(app);
1840 List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);
1842 // get functions in DB
1843 final Map<String, Long> params = new HashMap<>();
1844 final Map<String, CentralV2RoleFunction> roleFuncMap = new HashMap<>();
1845 params.put(APP_ID, app.getId());
1846 List<CentralV2RoleFunction> appFunctions = dataAccessService.executeNamedQuery("getAllRoleFunctions", params,
1848 if (!appFunctions.isEmpty()) {
1849 for (CentralV2RoleFunction roleFunc : appFunctions) {
1850 roleFuncMap.put(roleFunc.getCode(), roleFunc);
1854 // get Roles for portal in DB
1855 List<EPRole> portalRoleList = getGlobalRolesOfPortal();
1856 final Map<String, EPRole> existingPortalRolesMap = new HashMap<>();
1857 for(EPRole epRole : portalRoleList){
1858 existingPortalRolesMap.put(epRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), epRole);
1862 final Map<String, EPRole> currentRolesInDB = getCurrentRolesInDB(app);
1864 // store External Permissions with Pipe and without Pipe (just instance)
1865 final Map<String, ExternalAccessPermsDetail> extAccessPermsContainsPipeMap = new HashMap<>();
1866 final Map<String, ExternalAccessPermsDetail> extAccessPermsMap = new HashMap<>();
1867 for (ExternalAccessPermsDetail permsDetailInfoWithPipe : permsDetailList) {
1868 extAccessPermsContainsPipeMap.put(permsDetailInfoWithPipe.getInstance(), permsDetailInfoWithPipe);
1869 String finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetailInfoWithPipe.getInstance());
1870 extAccessPermsMap.put(finalFunctionCodeVal, permsDetailInfoWithPipe);
1873 // Add if new functions and app role functions were added in
1874 // external auth system
1875 for (ExternalAccessPermsDetail permsDetail : permsDetailList) {
1876 String code = permsDetail.getInstance();
1877 CentralV2RoleFunction getFunctionCodeKey = roleFuncMap.get(permsDetail.getInstance());
1878 List<CentralV2RoleFunction> roleFunctionList = addGetLocalFunction(app, roleFuncMap, permsDetail, code,
1879 getFunctionCodeKey);
1880 List<String> roles = permsDetail.getRoles();
1881 if (roles != null) {
1882 // Check if function has any roles and which does not exist
1883 // in External Auth System. If exists delete in local
1884 addRemoveIfFunctionsRolesIsSyncWithExternalAuth(app, currentRolesInDB, roleFunctionList, roles, existingPortalRolesMap);
1888 // Check if function does exits in External Auth System but exits in
1889 // local then delete function and its dependencies
1890 for (CentralV2RoleFunction roleFunc : appFunctions) {
1892 ExternalAccessPermsDetail getFunctionCodeContainsPipeKey = extAccessPermsContainsPipeMap
1893 .get(roleFunc.getCode());
1894 if (null == getFunctionCodeContainsPipeKey) {
1895 ExternalAccessPermsDetail getFunctionCodeKey = extAccessPermsMap.get(roleFunc.getCode());
1896 if (null == getFunctionCodeKey) {
1897 deleteAppRoleFuncDoesNotExitsInExtSystem(app, roleFunc);
1900 } catch (Exception e) {
1901 logger.error(EELFLoggerDelegate.errorLogger,
1902 "syncRoleFunctionFromExternalAccessSystem: Failed to delete function", e);
1907 logger.debug(EELFLoggerDelegate.debugLogger,
1908 "syncRoleFunctionFromExternalAccessSystem: Finished syncRoleFunctionFromExternalAccessSystem");
1909 } catch (Exception e) {
1910 logger.error(EELFLoggerDelegate.errorLogger,
1911 "syncRoleFunctionFromExternalAccessSystem: Failed syncRoleFunctionFromExternalAccessSystem", e);
1916 @SuppressWarnings("unchecked")
1917 private void addRemoveIfFunctionsRolesIsSyncWithExternalAuth(EPApp app, final Map<String, EPRole> currentRolesInDB,
1918 List<CentralV2RoleFunction> roleFunctionList, List<String> roles, Map<String, EPRole> existingPortalRolesMap)
1920 if (!roleFunctionList.isEmpty()) {
1921 final Map<String, String> appRoleFuncParams = new HashMap<>();
1922 final Map<String, LocalRole> currentAppRoleFunctionsMap = new HashMap<>();
1923 final Map<String, String> currentRolesInExtSystem = new HashMap<>();
1924 appRoleFuncParams.put("functionCd", roleFunctionList.get(0).getCode());
1925 appRoleFuncParams.put("appId", String.valueOf(app.getId()));
1926 List<LocalRole> localRoleList = dataAccessService.executeNamedQuery("getCurrentAppRoleFunctions",
1927 appRoleFuncParams, null);
1928 for (LocalRole localRole : localRoleList) {
1929 currentAppRoleFunctionsMap.put(localRole.getRolename().replaceAll(
1930 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), localRole);
1932 for (String addRole : roles) {
1933 currentRolesInExtSystem.put(addRole.substring(addRole.indexOf(FUNCTION_PIPE)+1), addRole);
1935 for (String extAuthrole : roles) {
1936 String roleNameSpace = extAuthrole.substring(0, extAuthrole.indexOf(FUNCTION_PIPE));
1937 boolean isNameSpaceMatching = EcompPortalUtils.checkNameSpaceMatching(roleNameSpace, app.getNameSpace());
1938 if (isNameSpaceMatching) {
1939 if (!currentAppRoleFunctionsMap
1940 .containsKey(extAuthrole.substring(app.getNameSpace().length() + 1))) {
1941 EPRole localAddFuntionRole = currentRolesInDB
1942 .get(extAuthrole.substring(app.getNameSpace().length() + 1));
1943 if (localAddFuntionRole == null) {
1944 checkAndAddRoleInDB(app, currentRolesInDB, roleFunctionList, extAuthrole);
1946 EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
1947 addAppRoleFunc.setAppId(app.getId());
1948 addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
1949 addAppRoleFunc.setRoleId(localAddFuntionRole.getId());
1950 dataAccessService.saveDomainObject(addAppRoleFunc, null);
1953 // This block is to save global role function if exists
1955 String extAuthAppRoleName = extAuthrole.substring(extAuthrole.indexOf(FUNCTION_PIPE) + 1);
1956 boolean checkIfGlobalRoleExists = existingPortalRolesMap.containsKey(extAuthAppRoleName);
1957 if (checkIfGlobalRoleExists) {
1958 final Map<String, Long> params = new HashMap<>();
1959 EPRole role = existingPortalRolesMap.get(extAuthAppRoleName);
1960 EPAppRoleFunction addGlobalRoleFunctions = new EPAppRoleFunction();
1961 params.put("appId", app.getId());
1962 params.put("roleId", role.getId());
1963 List<EPAppRoleFunction> currentGlobalRoleFunctionsList = dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", params, null);
1964 boolean checkIfRoleFunctionExists = currentGlobalRoleFunctionsList.stream().anyMatch(currentGlobalRoleFunction -> currentGlobalRoleFunction.getCode().equals(roleFunctionList.get(0).getCode()));
1965 if (role != null && !checkIfRoleFunctionExists) {
1966 addGlobalRoleFunctions.setAppId(app.getId());
1967 addGlobalRoleFunctions.setRoleId(role.getId());
1968 if (!app.getId().equals(role.getAppRoleId())) {
1969 addGlobalRoleFunctions.setRoleAppId((PortalConstants.PORTAL_APP_ID).toString());
1971 addGlobalRoleFunctions.setRoleAppId(null);
1973 addGlobalRoleFunctions.setCode(roleFunctionList.get(0).getCode());
1974 dataAccessService.saveDomainObject(addGlobalRoleFunctions, null);
1979 for (LocalRole localRoleDelete : localRoleList) {
1980 if (!currentRolesInExtSystem.containsKey(localRoleDelete.getRolename()
1981 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
1982 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
1983 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunctionList.get(0).getCode()
1984 + "'" + " and role_id = " + localRoleDelete.getRoleId().longValue(),
1991 private void deleteAppRoleFuncDoesNotExitsInExtSystem(EPApp app, CentralV2RoleFunction roleFunc) {
1992 logger.debug(EELFLoggerDelegate.debugLogger,
1993 "syncRoleFunctionFromExternalAccessSystem: Deleting app role function {}",
1994 roleFunc.getCode());
1995 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
1996 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() +"'", null);
1997 logger.debug(EELFLoggerDelegate.debugLogger,
1998 "syncRoleFunctionFromExternalAccessSystem: Deleted app role function {}",
1999 roleFunc.getCode());
2001 logger.debug(EELFLoggerDelegate.debugLogger,
2002 "syncRoleFunctionFromExternalAccessSystem: Deleting app function {}",
2003 roleFunc.getCode());
2004 dataAccessService.deleteDomainObjects(CentralV2RoleFunction.class,
2005 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() +"'", null);
2006 logger.debug(EELFLoggerDelegate.debugLogger,
2007 "syncRoleFunctionFromExternalAccessSystem: Deleted app function {}",
2008 roleFunc.getCode());
2011 private void checkAndAddRoleInDB(EPApp app, final Map<String, EPRole> currentRolesInDB,
2012 List<CentralV2RoleFunction> roleFunctionList, String roleList) throws Exception {
2013 if (!currentRolesInDB.containsKey(
2014 roleList.substring(app.getNameSpace().length() + 1))) {
2015 Role role = addRoleInDBIfDoesNotExists(app,
2016 roleList.substring(app.getNameSpace().length() + 1));
2017 addIfRoleDescriptionNotExitsInExtSystem(role, app);
2018 if (!roleFunctionList.isEmpty()) {
2020 if (!roleFunctionList.isEmpty()) {
2021 EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
2022 addAppRoleFunc.setAppId(app.getId());
2023 addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
2024 addAppRoleFunc.setRoleId(role.getId());
2025 dataAccessService.saveDomainObject(addAppRoleFunc, null);
2027 } catch (Exception e) {
2028 logger.error(EELFLoggerDelegate.errorLogger,
2029 "syncRoleFunctionFromExternalAccessSystem: Failed to save app role function ",
2036 @SuppressWarnings("unchecked")
2037 private List<CentralV2RoleFunction> addGetLocalFunction(EPApp app, final Map<String, CentralV2RoleFunction> roleFuncMap,
2038 ExternalAccessPermsDetail permsDetail, String code, CentralV2RoleFunction getFunctionCodeKey) {
2039 String finalFunctionCodeVal = addToLocalIfFunctionNotExists(app, roleFuncMap, permsDetail, code,
2040 getFunctionCodeKey);
2041 final Map<String, String> appSyncFuncsParams = new HashMap<>();
2042 appSyncFuncsParams.put("appId", String.valueOf(app.getId()));
2043 appSyncFuncsParams.put("functionCd", finalFunctionCodeVal);
2044 List<CentralV2RoleFunction> roleFunctionList = null;
2045 roleFunctionList = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams,
2047 if (roleFunctionList.isEmpty()) {
2048 appSyncFuncsParams.put("functionCd", code);
2049 roleFunctionList = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams,
2052 return roleFunctionList;
2055 private String addToLocalIfFunctionNotExists(EPApp app, final Map<String, CentralV2RoleFunction> roleFuncMap,
2056 ExternalAccessPermsDetail permsDetail, String code, CentralV2RoleFunction getFunctionCodeKey
2058 String finalFunctionCodeVal = "";
2059 if (null == getFunctionCodeKey) {
2060 finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetail.getInstance());
2061 CentralV2RoleFunction checkIfCodeStillExits = roleFuncMap.get(finalFunctionCodeVal);
2062 // If function does not exist in local then add!
2063 if (null == checkIfCodeStillExits) {
2064 logger.debug(EELFLoggerDelegate.debugLogger,
2065 "syncRoleFunctionFromExternalAccessSystem: Adding function: {} ", code);
2066 addFunctionInEcompDB(app, permsDetail, code);
2067 logger.debug(EELFLoggerDelegate.debugLogger,
2068 "syncRoleFunctionFromExternalAccessSystem: Finished adding function: {} ", code);
2071 return finalFunctionCodeVal;
2074 @SuppressWarnings("unchecked")
2076 public Map<String, EPRole> getCurrentRolesInDB(EPApp app) {
2077 final Map<String, EPRole> currentRolesInDB = new HashMap<>();
2078 List<EPRole> getCurrentRoleList = null;
2079 final Map<String, Long> appParams = new HashMap<>();
2080 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2081 getCurrentRoleList = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
2083 appParams.put("appId", app.getId());
2084 getCurrentRoleList = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
2086 for (EPRole role : getCurrentRoleList) {
2087 currentRolesInDB.put(role.getName()
2088 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), role);
2090 return currentRolesInDB;
2093 private List<ExternalAccessPermsDetail> getExtAuthPerrmissonList(EPApp app, JSONArray extPerms)
2095 ExternalAccessPermsDetail permDetails = null;
2096 List<ExternalAccessPermsDetail> permsDetailList = new ArrayList<>();
2097 for (int i = 0; i < extPerms.length(); i++) {
2098 String description = null;
2099 if (extPerms.getJSONObject(i).has("description")) {
2100 description = extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
2102 description = extPerms.getJSONObject(i).getString("type")+"|"+extPerms.getJSONObject(i).getString("instance")
2103 +"|"+extPerms.getJSONObject(i).getString("action");
2105 if (extPerms.getJSONObject(i).has("roles")) {
2106 ObjectMapper rolesListMapper = new ObjectMapper();
2107 JSONArray resRoles = extPerms.getJSONObject(i).getJSONArray("roles");
2108 List<String> list = rolesListMapper.readValue(resRoles.toString(),
2109 TypeFactory.defaultInstance().constructCollectionType(List.class, String.class));
2110 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
2111 extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
2112 + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
2113 + extPerms.getJSONObject(i).getString("action"),
2114 extPerms.getJSONObject(i).getString("action"), list, description);
2115 permsDetailList.add(permDetails);
2117 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
2118 extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
2119 + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
2120 + extPerms.getJSONObject(i).getString("action"),
2121 extPerms.getJSONObject(i).getString("action"), description);
2122 permsDetailList.add(permDetails);
2125 return permsDetailList;
2128 private JSONArray getExtAuthPermissions(EPApp app) throws Exception {
2129 ResponseEntity<String> response = null;
2130 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2131 HttpEntity<String> entity = new HttpEntity<>(headers);
2132 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: {} ",
2133 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2135 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
2136 + "perms/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
2138 String res = response.getBody();
2139 logger.debug(EELFLoggerDelegate.debugLogger,
2140 "syncRoleFunctionFromExternalAccessSystem: Finished GET permissions from External Auth system and response: {} ",
2141 response.getBody());
2142 JSONObject jsonObj = new JSONObject(res);
2143 JSONArray extPerms = jsonObj.getJSONArray("perm");
2144 for (int i = 0; i < extPerms.length(); i++) {
2145 if (extPerms.getJSONObject(i).getString("type").equals(app.getNameSpace() + ".access")) {
2155 * Add function into local DB
2158 * @param permsDetail
2161 private void addFunctionInEcompDB(EPApp app, ExternalAccessPermsDetail permsDetail, String code) {
2163 CentralV2RoleFunction addFunction = new CentralV2RoleFunction();
2164 addFunction.setAppId(app.getId());
2165 addFunction.setCode(code);
2166 addFunction.setName(permsDetail.getDescription());
2167 dataAccessService.saveDomainObject(addFunction, null);
2168 } catch(Exception e){
2169 logger.error(EELFLoggerDelegate.errorLogger, "addFunctionInEcompDB: Failed to add function", e);
2175 * It updates description of a role in external auth system
2181 private void addIfRoleDescriptionNotExitsInExtSystem(Role role, EPApp app) throws Exception {
2182 String addRoleNew = updateExistingRoleInExternalSystem(role, app);
2183 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2185 HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
2187 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
2188 HttpMethod.PUT, entity, String.class);
2189 } catch (HttpClientErrorException e) {
2190 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addIfRoleDescriptionNotExitsInExtSystem",
2192 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2193 } catch (Exception e) {
2194 logger.error(EELFLoggerDelegate.errorLogger, "addIfRoleDescriptionNotExitsInExtSystem: Failed",
2201 * While sync functions form external auth system if new role found we should add in local and return Role.class object
2207 @SuppressWarnings("unchecked")
2208 private Role addRoleInDBIfDoesNotExists(EPApp app, String role) {
2209 Role setNewRole = new Role();
2211 // functions can have new role created in External Auth System prevent
2213 boolean isCreated = checkIfRoleExitsElseCreateInSyncFunctions(role, app);
2214 final Map<String, String> getRoleByNameParams = new HashMap<>();
2215 List<EPRole> getRoleCreated = null;
2216 getRoleByNameParams.put(APP_ROLE_NAME_PARAM, role);
2217 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2218 getRoleByNameParams.put("appId", String.valueOf(app.getId()));
2219 List<EPRole> roleCreated = dataAccessService
2220 .executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, getRoleByNameParams, null);
2222 EPRole epUpdateRole = roleCreated.get(0);
2223 epUpdateRole.setAppRoleId(epUpdateRole.getId());
2224 dataAccessService.saveDomainObject(epUpdateRole, null);
2225 getRoleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
2226 getRoleByNameParams, null);
2228 getRoleCreated = roleCreated;
2231 getRoleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, getRoleByNameParams,
2234 if (getRoleCreated != null && !getRoleCreated.isEmpty()) {
2235 EPRole roleObject = getRoleCreated.get(0);
2236 setNewRole.setId(roleObject.getId());
2237 setNewRole.setName(roleObject.getName());
2238 setNewRole.setActive(roleObject.getActive());
2239 setNewRole.setPriority(roleObject.getPriority());
2241 } catch (Exception e) {
2242 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInDBIfDoesNotExists: Failed", e);
2247 @SuppressWarnings("unchecked")
2248 private boolean checkIfRoleExitsElseCreateInSyncFunctions(String role, EPApp app) {
2249 boolean isCreated = false;
2250 final Map<String, String> roleParams = new HashMap<>();
2251 roleParams.put(APP_ROLE_NAME_PARAM, role);
2252 List<EPRole> roleCreated = null;
2253 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2254 roleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, roleParams,
2257 roleParams.put("appId", String.valueOf(app.getId()));
2258 roleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams,
2261 if (roleCreated == null || roleCreated.isEmpty()) {
2262 roleParams.put("appId", String.valueOf(app.getId()));
2263 EPRole epRoleNew = new EPRole();
2264 epRoleNew.setActive(true);
2265 epRoleNew.setName(role);
2266 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2267 epRoleNew.setAppId(null);
2269 epRoleNew.setAppId(app.getId());
2271 dataAccessService.saveDomainObject(epRoleNew, null);
2280 @SuppressWarnings("unchecked")
2281 public Integer bulkUploadFunctions(String uebkey) throws Exception {
2282 EPApp app = getApp(uebkey).get(0);
2283 List<RoleFunction> roleFuncList = dataAccessService.executeNamedQuery("getAllFunctions", null, null);
2284 CentralV2RoleFunction cenRoleFunc = null;
2285 Integer functionsAdded = 0;
2287 for (RoleFunction roleFunc : roleFuncList) {
2288 cenRoleFunc = new CentralV2RoleFunction(roleFunc.getCode(), roleFunc.getName());
2289 addRoleFunctionInExternalSystem(cenRoleFunc, app);
2292 } catch(HttpClientErrorException e){
2293 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadFunctions failed", e);
2294 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2295 } catch (Exception e) {
2296 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions: failed", e.getMessage(), e);
2298 return functionsAdded;
2302 public Integer bulkUploadRoles(String uebkey) throws Exception {
2303 List<EPApp> app = getApp(uebkey);
2304 List<EPRole> roles = getAppRoles(app.get(0).getId());
2305 List<CentralV2Role> cenRoleList = new ArrayList<>();
2306 final Map<String, Long> params = new HashMap<>();
2307 Integer rolesListAdded = 0;
2309 cenRoleList = createCentralRoleObject(app, roles, cenRoleList, params);
2310 ObjectMapper mapper = new ObjectMapper();
2311 mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
2312 String roleList = mapper.writeValueAsString(cenRoleList);
2313 List<Role> roleObjectList = mapper.readValue(roleList,
2314 TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
2315 for (Role role : roleObjectList) {
2316 addRoleInExternalSystem(role, app.get(0));
2319 if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
2320 // Add Account Admin role in External AUTH System
2322 String addAccountAdminRole = "";
2323 ExternalAccessRole extRole = new ExternalAccessRole();
2324 extRole.setName(app.get(0).getNameSpace() + "." + PortalConstants.ADMIN_ROLE
2325 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2326 addAccountAdminRole = mapper.writeValueAsString(extRole);
2327 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2328 HttpEntity<String> entity = new HttpEntity<>(addAccountAdminRole, headers);
2330 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
2331 HttpMethod.POST, entity, String.class);
2333 } catch (HttpClientErrorException e) {
2334 logger.error(EELFLoggerDelegate.errorLogger,
2335 "HttpClientErrorException - Failed to create Account Admin role", e);
2336 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2337 } catch (Exception e) {
2338 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2339 logger.error(EELFLoggerDelegate.errorLogger,
2340 "bulkUploadRoles: Account Admin Role already exits but does not break functionality",
2343 logger.error(EELFLoggerDelegate.errorLogger,
2344 "bulkUploadRoles: Failed to create Account Admin role", e.getMessage());
2348 } catch (Exception e) {
2349 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles: failed", e);
2352 return rolesListAdded;
2356 * It creating new role in external auth system while doing bulk upload
2362 private void addRoleInExternalSystem(Role role, EPApp app) throws Exception {
2363 String addRoleNew = updateExistingRoleInExternalSystem(role, app);
2364 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2366 HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
2368 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
2369 HttpMethod.POST, entity, String.class);
2370 } catch(HttpClientErrorException e){
2371 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addRoleInExternalSystem", e);
2372 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2373 } catch (Exception e) {
2374 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2375 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInExternalSystem: Role already exits but does not break functionality", e);
2377 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInExternalSystem: Failed to addRoleInExternalSystem", e.getMessage());
2383 @SuppressWarnings("unchecked")
2384 public Integer bulkUploadRolesFunctions(String uebkey) throws Exception {
2385 EPApp app = getApp(uebkey).get(0);
2386 List<EPRole> roles = getAppRoles(app.getId());
2387 final Map<String, Long> params = new HashMap<>();
2388 Integer roleFunctions = 0;
2390 for (EPRole role : roles) {
2391 params.put("roleId", role.getId());
2392 List<BulkUploadRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("uploadAllRoleFunctions",
2394 if (!appRoleFunc.isEmpty()) {
2395 for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
2396 addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
2401 } catch(HttpClientErrorException e){
2402 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
2403 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2404 } catch (Exception e) {
2405 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
2407 return roleFunctions;
2411 * Its adding a role function while doing bulk upload
2413 * @param addRoleFunc
2417 private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, EPRole role, EPApp app) {
2419 String instance = "";
2421 if(addRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)){
2422 type = EcompPortalUtils.getFunctionType(addRoleFunc.getFunctionCd());
2423 instance = EcompPortalUtils.getFunctionCode(addRoleFunc.getFunctionCd());
2424 action = EcompPortalUtils.getFunctionAction(addRoleFunc.getFunctionCd());
2426 type = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
2427 instance = addRoleFunc.getFunctionCd();
2430 ExternalAccessRolePerms extRolePerms = null;
2431 ExternalAccessPerms extPerms = null;
2432 ObjectMapper mapper = new ObjectMapper();
2434 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2435 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, instance, action,
2436 addRoleFunc.getFunctionName());
2437 extRolePerms = new ExternalAccessRolePerms(extPerms,
2438 app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2439 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
2440 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
2442 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
2443 HttpMethod.POST, entity, String.class);
2444 } catch (Exception e) {
2445 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2446 logger.error(EELFLoggerDelegate.errorLogger,
2447 "addRoleFunctionsInExternalSystem: RoleFunction already exits but does not break functionality", e);
2449 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionsInExternalSystem: Failed to addRoleFunctionsInExternalSystem",
2455 @SuppressWarnings("unchecked")
2457 public Integer bulkUploadPartnerFunctions(String uebkey) throws Exception {
2458 EPApp app = getApp(uebkey).get(0);
2459 final Map<String, Long> params = new HashMap<>();
2460 params.put("appId", app.getId());
2461 List<CentralV2RoleFunction> roleFuncList = dataAccessService.executeNamedQuery("getPartnerAppFunctions", params,
2463 Integer functionsAdded = 0;
2465 for (CentralV2RoleFunction roleFunc : roleFuncList) {
2466 addFunctionInExternalSystem(roleFunc, app);
2469 } catch (HttpClientErrorException e) {
2470 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadPartnerFunctions failed", e);
2471 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2472 } catch (Exception e) {
2473 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerFunctions: failed", e.getMessage(), e);
2475 return functionsAdded;
2478 private void addFunctionInExternalSystem(CentralV2RoleFunction roleFunc, EPApp app) throws Exception {
2479 ObjectMapper mapper = new ObjectMapper();
2480 ExternalAccessPerms extPerms = new ExternalAccessPerms();
2481 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2483 String instance = "";
2485 if ((roleFunc.getCode().contains(FUNCTION_PIPE))
2486 || (roleFunc.getType() != null && roleFunc.getAction() != null)) {
2487 type = EcompPortalUtils.getFunctionType(roleFunc.getCode());
2488 instance = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
2489 action = EcompPortalUtils.getFunctionAction(roleFunc.getCode());
2491 type = roleFunc.getCode().contains("menu") ? "menu" : "url";
2492 instance = roleFunc.getCode();
2496 extPerms.setAction(action);
2497 extPerms.setInstance(instance);
2498 extPerms.setType(app.getNameSpace() + "." + type);
2499 extPerms.setDescription(roleFunc.getName());
2500 String addFunction = mapper.writeValueAsString(extPerms);
2501 HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
2502 logger.debug(EELFLoggerDelegate.debugLogger, "addFunctionInExternalSystem: {} for POST: {}",
2503 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
2504 ResponseEntity<String> addPermResponse = template.exchange(
2505 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
2506 HttpMethod.POST, entity, String.class);
2507 logger.debug(EELFLoggerDelegate.debugLogger,
2508 "addFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ",
2509 addPermResponse.getStatusCode().value(), addFunction);
2510 } catch (HttpClientErrorException e) {
2511 logger.error(EELFLoggerDelegate.errorLogger,
2512 "HttpClientErrorException - Failed to add function in external central auth system", e);
2513 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2515 } catch (Exception e) {
2516 logger.error(EELFLoggerDelegate.errorLogger,
2517 "addFunctionInExternalSystem: Failed to add fucntion in external central auth system", e);
2523 public void bulkUploadPartnerRoles(String uebkey, List<Role> roleList) throws Exception {
2524 EPApp app = getApp(uebkey).get(0);
2525 for (Role role : roleList) {
2526 addRoleInExternalSystem(role, app);
2530 @SuppressWarnings("unchecked")
2532 public Integer bulkUploadPartnerRoleFunctions(String uebkey) throws Exception {
2533 EPApp app = getApp(uebkey).get(0);
2534 List<EPRole> roles = getAppRoles(app.getId());
2535 final Map<String, Long> params = new HashMap<>();
2536 Integer roleFunctions = 0;
2538 for (EPRole role : roles) {
2539 params.put("roleId", role.getId());
2540 List<BulkUploadRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("uploadPartnerRoleFunctions",
2542 if (!appRoleFunc.isEmpty()) {
2543 for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
2544 addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
2549 // upload global role functions to ext auth system
2550 if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2551 roleFunctions = bulkUploadGlobalRoleFunctions(app, roleFunctions);
2553 } catch(HttpClientErrorException e){
2554 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
2555 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2556 } catch (Exception e) {
2557 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
2559 return roleFunctions;
2562 @SuppressWarnings("unchecked")
2563 private Integer bulkUploadGlobalRoleFunctions(EPApp app, Integer roleFunctions) throws Exception {
2565 EPApp portalApp = epAppService.getApp(1l);
2566 final Map<String, Long> params = new HashMap<>();
2567 params.put("appId", app.getId());
2568 List<GlobalRoleWithApplicationRoleFunction> globalRoleFuncs = dataAccessService
2569 .executeNamedQuery("getBulkUploadPartnerGlobalRoleFunctions", params, null);
2570 ObjectMapper mapper = new ObjectMapper();
2571 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2572 for (GlobalRoleWithApplicationRoleFunction globalRoleFunc : globalRoleFuncs) {
2573 ExternalAccessRolePerms extRolePerms;
2574 ExternalAccessPerms extPerms;
2576 String instance = "";
2578 if (globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
2579 type = EcompPortalUtils.getFunctionType(globalRoleFunc.getFunctionCd());
2580 instance = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd());
2581 action = EcompPortalUtils.getFunctionAction(globalRoleFunc.getFunctionCd());
2583 type = globalRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
2584 instance = globalRoleFunc.getFunctionCd();
2587 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, instance, action);
2588 extRolePerms = new ExternalAccessRolePerms(extPerms, portalApp.getNameSpace() + "." + globalRoleFunc.getRoleName()
2589 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2590 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
2591 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
2592 updateRoleFunctionInExternalSystem(updateRolePerms, entity);
2595 } catch (HttpClientErrorException e) {
2596 logger.error(EELFLoggerDelegate.errorLogger,
2597 "HttpClientErrorException - Failed to add role function in external central auth system", e);
2598 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2600 } catch (Exception e) {
2601 logger.error(EELFLoggerDelegate.errorLogger,
2602 "bulkUploadGlobalRoleFunctions: Failed to add role fucntion in external central auth system", e);
2605 return roleFunctions;
2610 public void syncApplicationRolesWithEcompDB(EPApp app) {
2612 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Started");
2613 //Sync functions and roles assigned to it which also creates new roles if does not exits in portal
2614 syncRoleFunctionFromExternalAccessSystem(app);
2615 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Finished");
2617 ObjectMapper mapper = new ObjectMapper();
2618 logger.debug(EELFLoggerDelegate.debugLogger, "Entering to getAppRolesJSONFromExtAuthSystem");
2619 // Get Permissions from External Auth System
2620 JSONArray extRole = getAppRolesJSONFromExtAuthSystem(app);
2622 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into getExternalRoleDetailsList");
2624 List<ExternalRoleDetails> externalRoleDetailsList = getExternalRoleDetailsList(app,
2627 List<EPRole> finalRoleList = new ArrayList<>();
2628 for (ExternalRoleDetails externalRole : externalRoleDetailsList) {
2629 EPRole ecompRole = convertExternalRoleDetailstoEpRole(externalRole);
2630 finalRoleList.add(ecompRole);
2633 List<EPRole> applicationRolesList;
2634 applicationRolesList = getAppRoles(app.getId());
2635 List<String> applicationRoleIdList = new ArrayList<>();
2636 for (EPRole applicationRole : applicationRolesList) {
2637 applicationRoleIdList.add(applicationRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2640 List<EPRole> roleListToBeAddInEcompDB = new ArrayList<>();
2641 for (EPRole aafRole : finalRoleList) {
2642 if (!applicationRoleIdList.contains(aafRole.getName())) {
2643 roleListToBeAddInEcompDB.add(aafRole);
2647 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into inactiveRolesNotInExternalAuthSystem");
2648 // Check if roles exits in external Access system and if not make inactive in DB
2649 inactiveRolesNotInExternalAuthSystem(app, finalRoleList, applicationRolesList);
2651 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into checkAndUpdateRoleInDB");
2652 // It checks properties in the external auth system app role description and updates role in local
2653 checkAndUpdateRoleInDB(app, finalRoleList);
2655 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addNewRoleInEcompDBUpdateDescInExtAuthSystem");
2656 // Add new roles in DB and updates role description in External Auth System
2657 addNewRoleInEcompDBUpdateDescInExtAuthSystem(app, roleListToBeAddInEcompDB);
2658 logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: Finished");
2659 } catch (HttpClientErrorException e) {
2660 logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed due to the External Auth System", e);
2661 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2662 } catch (Exception e) {
2663 logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed ", e);
2669 * It adds new roles in DB and updates description in External Auth System
2672 * @param roleListToBeAddInEcompDB
2674 @SuppressWarnings("unchecked")
2675 private void addNewRoleInEcompDBUpdateDescInExtAuthSystem(EPApp app, List<EPRole> roleListToBeAddInEcompDB) {
2676 EPRole roleToBeAddedInEcompDB;
2677 for (int i = 0; i < roleListToBeAddInEcompDB.size(); i++) {
2679 roleToBeAddedInEcompDB = roleListToBeAddInEcompDB.get(i);
2680 if (app.getId() == 1) {
2681 roleToBeAddedInEcompDB.setAppRoleId(null);
2683 dataAccessService.saveDomainObject(roleToBeAddedInEcompDB, null);
2684 List<EPRole> getRoleCreatedInSync = null;
2685 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2686 final Map<String, String> globalRoleParams = new HashMap<>();
2687 globalRoleParams.put("appId", String.valueOf(app.getId()));
2688 globalRoleParams.put("appRoleName", roleToBeAddedInEcompDB.getName());
2689 getRoleCreatedInSync = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, globalRoleParams, null);
2690 EPRole epUpdateRole = getRoleCreatedInSync.get(0);
2691 epUpdateRole.setAppRoleId(epUpdateRole.getId());
2692 dataAccessService.saveDomainObject(epUpdateRole, null);
2694 List<EPRole> roleList = new ArrayList<>();
2695 final Map<String, String> params = new HashMap<>();
2697 params.put(APP_ROLE_NAME_PARAM, roleToBeAddedInEcompDB.getName());
2698 boolean isPortalRole = false;
2699 if (app.getId() == 1) {
2700 isPortalRole = true;
2701 roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, params, null);
2703 isPortalRole = false;
2704 params.put(APP_ID, app.getId().toString());
2705 roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, params, null);
2707 EPRole role = roleList.get(0);
2708 Role aaFrole = new Role();
2709 aaFrole.setId(role.getId());
2710 aaFrole.setActive(role.getActive());
2711 aaFrole.setPriority(role.getPriority());
2712 aaFrole.setName(role.getName());
2713 updateRoleInExternalSystem(aaFrole, app, isPortalRole);
2714 } catch (Exception e) {
2715 logger.error(EELFLoggerDelegate.errorLogger,
2716 "SyncApplicationRolesWithEcompDB: Failed to add or update role in external auth system", e);
2723 * It checks description in External Auth System if found any changes updates in DB
2726 * @param finalRoleList contains list of External Auth System roles list which is converted to EPRole
2728 @SuppressWarnings("unchecked")
2729 private void checkAndUpdateRoleInDB(EPApp app, List<EPRole> finalRoleList) {
2730 for (EPRole roleItem : finalRoleList) {
2731 final Map<String, String> roleParams = new HashMap<>();
2732 List<EPRole> currentList = null;
2733 roleParams.put(APP_ROLE_NAME_PARAM, roleItem.getName());
2734 if (app.getId() == 1) {
2735 currentList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, roleParams, null);
2737 roleParams.put(APP_ID, app.getId().toString());
2738 currentList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams, null);
2741 if (!currentList.isEmpty()) {
2743 Boolean aafRoleActive;
2744 Boolean localRoleActive;
2746 aafRoleActive = Boolean.valueOf(roleItem.getActive());
2747 localRoleActive = Boolean.valueOf(currentList.get(0).getActive());
2748 result = aafRoleActive.equals(localRoleActive);
2749 EPRole updateRole = currentList.get(0);
2752 updateRole.setActive(roleItem.getActive());
2753 dataAccessService.saveDomainObject(updateRole, null);
2755 if (roleItem.getPriority() != null
2756 && !currentList.get(0).getPriority().equals(roleItem.getPriority())) {
2757 updateRole.setPriority(roleItem.getPriority());
2758 dataAccessService.saveDomainObject(updateRole, null);
2760 } catch (Exception e) {
2761 logger.error(EELFLoggerDelegate.errorLogger,
2762 "syncApplicationRolesWithEcompDB: Failed to update role ", e);
2769 * It de-activates application roles in DB if not present in External Auth system
2772 * @param finalRoleList contains list of current roles present in External Auth System
2773 * @param applicationRolesList contains list of current roles present in DB
2775 @SuppressWarnings("unchecked")
2776 private void inactiveRolesNotInExternalAuthSystem(EPApp app, List<EPRole> finalRoleList,
2777 List<EPRole> applicationRolesList) {
2778 final Map<String, EPRole> checkRolesInactive = new HashMap<>();
2779 for (EPRole extrole : finalRoleList) {
2780 checkRolesInactive.put(extrole.getName(), extrole);
2782 for (EPRole role : applicationRolesList) {
2784 final Map<String, String> extRoleParams = new HashMap<>();
2785 List<EPRole> roleList = null;
2786 extRoleParams.put(APP_ROLE_NAME_PARAM, role.getName());
2787 if (!checkRolesInactive.containsKey(role.getName())) {
2788 if (app.getId() == 1) {
2789 roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, extRoleParams, null);
2791 extRoleParams.put(APP_ID, app.getId().toString());
2792 roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, extRoleParams, null);
2794 if(!roleList.isEmpty()) {
2795 EPRole updateRoleInactive = roleList.get(0);
2796 updateRoleInactive.setActive(false);
2797 dataAccessService.saveDomainObject(updateRoleInactive, null);
2800 } catch (Exception e) {
2801 logger.error(EELFLoggerDelegate.errorLogger,
2802 "syncApplicationRolesWithEcompDB: Failed to de-activate role ", e);
2808 @SuppressWarnings("unchecked")
2809 public List<ExternalRoleDetails> getExternalRoleDetailsList(EPApp app,
2810 ObjectMapper mapper, JSONArray extRole)
2811 throws IOException {
2812 List<ExternalRoleDetails> externalRoleDetailsList = new ArrayList<>();
2813 ExternalAccessPerms externalAccessPerms = new ExternalAccessPerms();
2814 List<String> functionCodelist = new ArrayList<>();
2815 Map<String, EPRole> curRolesMap = getCurrentRolesInDB(app);
2816 for (int i = 0; i < extRole.length(); i++) {
2817 ExternalRoleDetails externalRoleDetail = new ExternalRoleDetails();
2818 EPAppRoleFunction ePAppRoleFunction = new EPAppRoleFunction();
2819 JSONObject Role = (JSONObject) extRole.get(i);
2820 String name = extRole.getJSONObject(i).getString(ROLE_NAME);
2821 String actualRoleName = name.substring(app.getNameSpace().length() + 1);
2822 if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
2823 actualRoleName = extRole.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
2825 SortedSet<ExternalAccessPerms> externalAccessPermsOfRole = new TreeSet<>();
2826 if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_PERMS)) {
2827 JSONArray extPerm = (JSONArray) Role.get(EXTERNAL_AUTH_PERMS);
2828 for (int j = 0; j < extPerm.length(); j++) {
2829 JSONObject perms = extPerm.getJSONObject(j);
2830 boolean isNamespaceMatching = EcompPortalUtils.checkNameSpaceMatching(perms.getString("type"),
2831 app.getNameSpace());
2832 if (isNamespaceMatching) {
2833 externalAccessPerms = new ExternalAccessPerms(perms.getString("type"),
2834 perms.getString("instance"), perms.getString("action"));
2835 ePAppRoleFunction.setCode(externalAccessPerms.getInstance());
2836 functionCodelist.add(ePAppRoleFunction.getCode());
2837 externalAccessPermsOfRole.add(externalAccessPerms);
2842 externalRoleDetail.setActive(true);
2843 externalRoleDetail.setName(actualRoleName);
2844 if (app.getId() == 1) {
2845 externalRoleDetail.setAppId(null);
2847 externalRoleDetail.setAppId(app.getId());
2849 // get role functions from DB
2850 EPRole currRole = curRolesMap.get(actualRoleName
2851 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2853 if (currRole != null)
2854 roleId = currRole.getId();
2855 // get role functions from DB
2856 final Map<String, EPAppRoleFunction> roleFunctionsMap = new HashMap<>();
2857 final Map<String, Long> appRoleFuncsParams = new HashMap<>();
2858 if (roleId != null) {
2859 appRoleFuncsParams.put("appId", app.getId());
2860 appRoleFuncsParams.put("roleId", roleId);
2861 List<EPAppRoleFunction> appRoleFunctions = dataAccessService
2862 .executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null);
2863 if (!appRoleFunctions.isEmpty()) {
2864 for (EPAppRoleFunction roleFunc : appRoleFunctions) {
2865 roleFunctionsMap.put(roleFunc.getCode(), roleFunc);
2869 if (!externalAccessPermsOfRole.isEmpty()) {
2870 // Adding functions to role
2871 for (ExternalAccessPerms externalpermission : externalAccessPermsOfRole) {
2872 EPAppRoleFunction checkRoleFunctionExits = roleFunctionsMap.get(externalpermission.getInstance());
2873 if (checkRoleFunctionExits == null) {
2874 String funcCode = externalpermission.getType().substring(app.getNameSpace().length() + 1)
2875 + FUNCTION_PIPE + externalpermission.getInstance() + FUNCTION_PIPE
2876 + externalpermission.getAction();
2877 EPAppRoleFunction checkRoleFunctionPipeExits = roleFunctionsMap.get(funcCode);
2878 if (checkRoleFunctionPipeExits == null) {
2880 final Map<String, String> appFuncsParams = new HashMap<>();
2881 appFuncsParams.put("appId", String.valueOf(app.getId()));
2882 appFuncsParams.put("functionCd", externalpermission.getInstance());
2883 logger.debug(EELFLoggerDelegate.debugLogger,
2884 "SyncApplicationRolesWithEcompDB: Adding function to the role: {}",
2885 externalpermission.getInstance());
2886 List<CentralV2RoleFunction> roleFunction = null;
2887 roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId",
2888 appFuncsParams, null);
2889 if (roleFunction.isEmpty()) {
2890 appFuncsParams.put("functionCd", funcCode);
2891 roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId",
2892 appFuncsParams, null);
2894 if (!roleFunction.isEmpty()) {
2895 EPAppRoleFunction apRoleFunction = new EPAppRoleFunction();
2896 apRoleFunction.setAppId(app.getId());
2897 apRoleFunction.setRoleId(roleId);
2898 apRoleFunction.setCode(roleFunction.get(0).getCode());
2899 dataAccessService.saveDomainObject(apRoleFunction, null);
2901 } catch (Exception e) {
2902 logger.error(EELFLoggerDelegate.errorLogger,
2903 "SyncApplicationRolesWithEcompDB: Failed to add role function", e);
2909 externalRoleDetailsList.add(externalRoleDetail);
2911 return externalRoleDetailsList;
2915 public JSONArray getAppRolesJSONFromExtAuthSystem(EPApp app) throws Exception {
2916 ResponseEntity<String> response = null;
2917 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2918 HttpEntity<String> entity = new HttpEntity<>(headers);
2919 logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: {} ",
2920 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2922 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
2923 + "roles/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
2924 String res = response.getBody();
2925 logger.debug(EELFLoggerDelegate.debugLogger,
2926 "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
2928 JSONObject jsonObj = new JSONObject(res);
2929 JSONArray extRole = jsonObj.getJSONArray("role");
2930 for (int i = 0; i < extRole.length(); i++) {
2931 if (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ADMIN)
2932 || extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + OWNER)
2933 || (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ACCOUNT_ADMINISTRATOR)
2934 && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
2943 public JSONArray getAllUsersByRole(String roleName) throws Exception{
2944 ResponseEntity<String> response = null;
2945 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2946 HttpEntity<String> entity = new HttpEntity<>(headers);
2947 logger.debug(EELFLoggerDelegate.debugLogger, "getAllUsersByRole: {} ",
2948 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2950 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
2951 + "userRoles/role/" + roleName, HttpMethod.GET, entity, String.class);
2952 String res = response.getBody();
2953 logger.debug(EELFLoggerDelegate.debugLogger,
2954 "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
2956 if(res == null || res.trim().isEmpty())
2959 JSONObject jsonObj = new JSONObject(res);
2960 JSONArray extRole = jsonObj.getJSONArray("userRole");
2967 * It converts from ExternalRoleDetails.class object to EPRole.class object
2969 * @param externalRoleDetails
2970 * @return EPRole object
2972 private EPRole convertExternalRoleDetailstoEpRole(ExternalRoleDetails externalRoleDetails) {
2973 EPRole role = new EPRole();
2974 role.setActive(true);
2975 role.setAppId(externalRoleDetails.getAppId());
2976 role.setAppRoleId(externalRoleDetails.getAppRoleId());
2977 role.setName(externalRoleDetails.getName());
2978 role.setPriority(externalRoleDetails.getPriority());
2982 @SuppressWarnings("unchecked")
2984 public Integer bulkUploadUserRoles(String uebkey) throws Exception {
2985 EPApp app = getApp(uebkey).get(0);
2986 final Map<String, String> params = new HashMap<>();
2987 params.put("uebKey", app.getUebKey());
2988 List<BulkUploadUserRoles> userRolesList = null;
2989 Integer userRolesAdded = 0;
2990 if (app.getCentralAuth()) {
2991 userRolesList = dataAccessService.executeNamedQuery("getBulkUserRoles", params, null);
2992 for (BulkUploadUserRoles userRolesUpload : userRolesList) {
2993 if(!userRolesUpload.getOrgUserId().equals("su1234")){
2994 addUserRoleInExternalSystem(userRolesUpload);
2999 return userRolesAdded;
3003 * Its adding a user role in external auth system while doing bulk upload
3005 * @param userRolesUpload
3007 private void addUserRoleInExternalSystem(BulkUploadUserRoles userRolesUpload) {
3010 ObjectMapper mapper = new ObjectMapper();
3011 if (EPCommonSystemProperties
3012 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
3013 name = userRolesUpload.getOrgUserId()
3014 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
3016 ExternalAccessUser extUser = new ExternalAccessUser(name,
3017 userRolesUpload.getAppNameSpace() + "." + userRolesUpload.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
3018 String userRole = mapper.writeValueAsString(extUser);
3019 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3020 HttpEntity<String> entity = new HttpEntity<>(userRole, headers);
3022 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
3023 HttpMethod.POST, entity, String.class);
3024 } catch(HttpClientErrorException e){
3025 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addUserRoleInExternalSystem", e);
3026 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3027 } catch (Exception e) {
3028 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
3029 logger.error(EELFLoggerDelegate.errorLogger, "addUserRoleInExternalSystem: UserRole already exits but does not break functionality");
3031 logger.error(EELFLoggerDelegate.errorLogger, "addUserRoleInExternalSystem: Failed to addUserRoleInExternalSystem", e);
3037 public void deleteRoleDependencyRecords(Session localSession, Long roleId, Long appId, boolean isPortalRequest) throws Exception {
3042 //It should delete only when it portal's roleId
3043 if(appId.equals(PortalConstants.PORTAL_APP_ID)){
3044 // Delete from fn_role_function
3045 sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
3046 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3047 query = localSession.createSQLQuery(sql);
3048 query.executeUpdate();
3050 // Delete from fn_role_composite
3051 sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId;
3052 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3053 query = localSession.createSQLQuery(sql);
3054 query.executeUpdate();
3057 // Delete from ep_app_role_function
3058 sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId;
3059 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3060 query = localSession.createSQLQuery(sql);
3061 query.executeUpdate();
3063 // Delete from ep_role_notification
3064 sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
3065 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3066 query = localSession.createSQLQuery(sql);
3067 query.executeUpdate();
3069 // Delete from fn_user_pseudo_role
3070 sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
3071 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3072 query = localSession.createSQLQuery(sql);
3073 query.executeUpdate();
3075 // Delete form EP_WIDGET_CATALOG_ROLE
3076 sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId;
3077 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3078 query = localSession.createSQLQuery(sql);
3079 query.executeUpdate();
3081 // Delete form EP_WIDGET_CATALOG_ROLE
3082 sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId;
3083 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3084 query = localSession.createSQLQuery(sql);
3085 query.executeUpdate();
3087 if(!isPortalRequest) {
3088 // Delete form fn_menu_functional_roles
3089 sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
3090 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3091 query = localSession.createSQLQuery(sql);
3092 query.executeUpdate();
3094 } catch (Exception e) {
3095 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e);
3096 throw new DeleteDomainObjectFailedException("delete Failed" + e.getMessage());
3101 @SuppressWarnings("unchecked")
3103 public List<String> getMenuFunctionsList(String uebkey) throws Exception {
3104 List<String> appMenuFunctionsList = null;
3105 List<String> appMenuFunctionsFinalList = new ArrayList<>();
3107 EPApp app = getApp(uebkey).get(0);
3108 final Map<String, Long> appParams = new HashMap<>();
3109 appParams.put(APP_ID, app.getId());
3110 appMenuFunctionsList = dataAccessService.executeNamedQuery("getMenuFunctions", appParams, null);
3111 for(String appMenuFunction : appMenuFunctionsList) {
3112 if(appMenuFunction.contains(FUNCTION_PIPE)) {
3113 appMenuFunctionsFinalList.add(EcompPortalUtils.getFunctionCode(appMenuFunction));
3115 appMenuFunctionsFinalList.add(appMenuFunction);
3118 } catch (Exception e) {
3119 logger.error(EELFLoggerDelegate.errorLogger, "getMenuFunctionsList: Failed", e);
3120 return appMenuFunctionsFinalList;
3122 return appMenuFunctionsFinalList;
3125 @SuppressWarnings({ "unchecked"})
3127 public List<EcompUser> getAllAppUsers(String uebkey) throws Exception {
3128 List<String> usersList = new ArrayList<>();
3129 List<EcompUser> usersfinalList = new ArrayList<>();
3131 EPApp app = getApp(uebkey).get(0);
3132 final Map<String, Long> appParams = new HashMap<>();
3133 appParams.put("appId", app.getId());
3134 List<EcompUserRoles> userList = (List<EcompUserRoles>) dataAccessService
3135 .executeNamedQuery("ApplicationUserRoles", appParams, null);
3136 for (EcompUserRoles ecompUserRole : userList) {
3137 boolean found = false;
3138 Set<EcompRole> roles = null;
3139 for (EcompUser user : usersfinalList) {
3140 if (user.getOrgUserId().equals(ecompUserRole.getOrgUserId())) {
3141 EcompRole ecompRole = new EcompRole();
3142 ecompRole.setId(ecompUserRole.getRoleId());
3143 ecompRole.setName(ecompUserRole.getRoleName());
3144 roles = user.getRoles();
3145 EcompRole role = roles.stream().filter(x -> x.getName().equals(ecompUserRole.getRoleName())).findAny()
3147 SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
3150 roleFunctionSet = (SortedSet<EcompRoleFunction>) role.getRoleFunctions();
3153 String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
3154 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
3155 EcompRoleFunction epRoleFunction = new EcompRoleFunction();
3156 epRoleFunction.setName(ecompUserRole.getFunctionName());
3157 epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
3158 epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
3159 epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
3160 roleFunctionSet.add(epRoleFunction);
3161 ecompRole.setRoleFunctions(roleFunctionSet);
3162 roles.add(ecompRole);
3163 user.setRoles(roles);
3170 EcompUser epUser = new EcompUser();
3171 epUser.setOrgId(ecompUserRole.getOrgId());
3172 epUser.setManagerId(ecompUserRole.getManagerId());
3173 epUser.setFirstName(ecompUserRole.getFirstName());
3174 epUser.setLastName(ecompUserRole.getLastName());
3175 epUser.setPhone(ecompUserRole.getPhone());
3176 epUser.setEmail(ecompUserRole.getEmail());
3177 epUser.setOrgUserId(ecompUserRole.getOrgUserId());
3178 epUser.setOrgCode(ecompUserRole.getOrgCode());
3179 epUser.setOrgManagerUserId(ecompUserRole.getOrgManagerUserId());
3180 epUser.setJobTitle(ecompUserRole.getJobTitle());
3181 epUser.setLoginId(ecompUserRole.getLoginId());
3182 epUser.setActive(true);
3183 roles = new HashSet<>();
3184 EcompRole ecompRole = new EcompRole();
3185 ecompRole.setId(ecompUserRole.getRoleId());
3186 ecompRole.setName(ecompUserRole.getRoleName());
3187 SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
3189 String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
3190 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
3191 EcompRoleFunction epRoleFunction = new EcompRoleFunction();
3192 epRoleFunction.setName(ecompUserRole.getFunctionName());
3193 epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
3194 epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
3195 epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
3196 roleFunctionSet.add(epRoleFunction);
3197 ecompRole.setRoleFunctions(roleFunctionSet);
3198 roles.add(ecompRole);
3199 epUser.setRoles(roles);
3200 usersfinalList.add(epUser);
3203 ObjectMapper mapper = new ObjectMapper();
3205 for (EcompUser u1 : usersfinalList) {
3206 String str = mapper.writeValueAsString(u1);
3209 } catch (Exception e) {
3210 logger.error(EELFLoggerDelegate.errorLogger, "getAllUsers failed", e);
3213 return usersfinalList;
3219 public Role ConvertCentralRoleToRole(String result) {
3220 ObjectMapper mapper = new ObjectMapper();
3221 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
3222 Role newRole = new Role();
3224 newRole = mapper.readValue(result, Role.class);
3225 } catch (IOException e) {
3226 logger.error(EELFLoggerDelegate.errorLogger, "Failed to convert the result to Role Object", e);
3228 if (newRole.getRoleFunctions() != null) {
3229 @SuppressWarnings("unchecked")
3230 Set<RoleFunction> roleFunctionList = newRole.getRoleFunctions();
3231 Set<RoleFunction> roleFunctionListNew = new HashSet<>();
3232 Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
3233 while (itetaror.hasNext()) {
3234 Object nextValue = itetaror.next();
3235 RoleFunction roleFun = mapper.convertValue(nextValue, RoleFunction.class);
3236 roleFunctionListNew.add(roleFun);
3238 newRole.setRoleFunctions(roleFunctionListNew);
3244 @SuppressWarnings("unchecked")
3245 public List<CentralizedApp> getCentralizedAppsOfUser(String userId) {
3246 Map<String, String> params = new HashMap<>();
3247 params.put("userId", userId);
3248 List<CentralizedApp> centralizedAppsList = new ArrayList<>();
3250 centralizedAppsList = dataAccessService
3251 .executeNamedQuery("getCentralizedAppsOfUser", params, null);
3252 }catch (Exception e) {
3253 logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
3255 return centralizedAppsList;
3258 @SuppressWarnings("unchecked")
3259 public List<CentralV2Role> getGlobalRolesOfApplication(Long appId) {
3260 Map<String, Long> params = new HashMap<>();
3261 params.put("appId", appId);
3262 List<GlobalRoleWithApplicationRoleFunction> globalRoles = new ArrayList<>();
3264 globalRoles = dataAccessService.executeNamedQuery("getGlobalRoleWithApplicationRoleFunctions", params,
3266 } catch (Exception e) {
3267 logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
3269 List<CentralV2Role> rolesfinalList = new ArrayList<>();
3270 if (globalRoles.size() > 0)
3271 rolesfinalList = finalListOfCentralRoles(globalRoles);
3272 return rolesfinalList;
3275 @SuppressWarnings("unchecked")
3276 private CentralV2Role getGlobalRoleForRequestedApp(long requestedAppId, long roleId) {
3277 CentralV2Role finalGlobalrole = null;
3278 List<GlobalRoleWithApplicationRoleFunction> roleWithApplicationRoleFucntions = new ArrayList<>();
3279 Map<String, Long> params = new HashMap<>();
3280 params.put("roleId", roleId);
3281 params.put("requestedAppId", requestedAppId);
3283 roleWithApplicationRoleFucntions = dataAccessService.executeNamedQuery("getGlobalRoleForRequestedApp",
3285 } catch (Exception e) {
3286 logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRoleForRequestedApp failed", e);
3288 if (roleWithApplicationRoleFucntions.size() > 0) {
3289 List<CentralV2Role> rolesfinalList = finalListOfCentralRoles(roleWithApplicationRoleFucntions);
3290 finalGlobalrole = rolesfinalList.get(0);
3292 List<EPRole> roleList = getPortalAppRoleInfo(roleId);
3293 finalGlobalrole = convertRoleToCentralV2Role(roleList.get(0));
3295 return finalGlobalrole;
3298 private List<CentralV2Role> finalListOfCentralRoles(List<GlobalRoleWithApplicationRoleFunction> globalRoles) {
3299 List<CentralV2Role> rolesfinalList = new ArrayList<>();
3300 for (GlobalRoleWithApplicationRoleFunction role : globalRoles) {
3301 boolean found = false;
3302 for (CentralV2Role cenRole : rolesfinalList) {
3303 if (role.getRoleId().equals(cenRole.getId())) {
3304 SortedSet<CentralV2RoleFunction> roleFunctions = cenRole.getRoleFunctions();
3305 CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
3306 roleFunctions.add(cenRoleFun);
3307 cenRole.setRoleFunctions(roleFunctions);
3313 CentralV2Role cenrole = new CentralV2Role();
3314 cenrole.setName(role.getRoleName());
3315 cenrole.setId(role.getRoleId());
3316 cenrole.setActive(role.isActive());
3317 cenrole.setPriority(role.getPriority());
3318 SortedSet<CentralV2RoleFunction> roleFunctions = new TreeSet<>();
3319 CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
3320 roleFunctions.add(cenRoleFun);
3321 cenrole.setRoleFunctions(roleFunctions);
3322 rolesfinalList.add(cenrole);
3325 return rolesfinalList;
3328 private CentralV2RoleFunction createCentralRoleFunctionForGlobalRole(GlobalRoleWithApplicationRoleFunction role) {
3332 CentralV2RoleFunction cenRoleFun;
3333 if(role.getFunctionCd().contains(FUNCTION_PIPE)){
3334 instance = EcompPortalUtils.getFunctionCode(role.getFunctionCd());
3335 type = EcompPortalUtils.getFunctionType(role.getFunctionCd());
3336 action = EcompPortalUtils.getFunctionAction(role.getFunctionCd());
3337 cenRoleFun = new CentralV2RoleFunction(null, instance, role.getFunctionName(), null, type, action, null);
3339 type = getFunctionCodeType(role.getFunctionCd());
3340 action = getFunctionCodeAction(role.getFunctionCd());
3341 cenRoleFun = new CentralV2RoleFunction(null, role.getFunctionCd(), role.getFunctionName(), null, type, action, null);
3346 @SuppressWarnings("unchecked")
3348 public List<EPRole> getGlobalRolesOfPortal() {
3349 List<EPRole> globalRoles = new ArrayList<>();
3351 globalRoles = dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null);
3352 } catch (Exception e) {
3353 logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRolesOfPortal failed", e);
3358 private CentralV2Role convertRoleToCentralV2Role(EPRole role) {
3359 return new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
3360 role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
3361 new TreeSet<>(), new TreeSet<>(), new TreeSet<>());
3366 public List<CentralRoleFunction> convertCentralRoleFunctionToRoleFunctionObject(List<CentralV2RoleFunction> answer) {
3367 List<CentralRoleFunction> addRoleFuncList = new ArrayList<>();
3368 for(CentralV2RoleFunction cenRoleFunc : answer){
3369 CentralRoleFunction setRoleFunc = new CentralRoleFunction();
3370 setRoleFunc.setCode(cenRoleFunc.getCode());
3371 setRoleFunc.setName(cenRoleFunc.getName());
3372 addRoleFuncList.add(setRoleFunc);
3374 return addRoleFuncList;
3378 public CentralUser getUserRoles(String loginId, String uebkey) throws Exception {
3379 CentralUser sendUserRoles = null;
3382 CentralV2User cenV2User = getV2UserAppRoles(loginId, uebkey);
3383 sendUserRoles = convertV2UserRolesToOlderVersion(cenV2User);
3384 } catch (Exception e) {
3385 logger.error(EELFLoggerDelegate.errorLogger, "getUserRoles: failed", e);
3388 return sendUserRoles;
3393 * It returns V2 CentralUser object if user has any roles and permissions
3397 * @return CentralUser object
3400 private CentralV2User getV2UserAppRoles(String loginId, String uebkey) throws Exception {
3402 List<EPUser> epUserList;
3403 List<EPApp> appList = getApp(uebkey);
3404 app = appList.get(0);
3405 epUserList = getUser(loginId);
3406 EPUser user = epUserList.get(0);
3407 Set<EPUserApp> userAppSet = user.getEPUserApps();
3408 return createEPUser(user, userAppSet, app);
3412 * It converts V2 CentralUser object to old version CentralUser object
3415 * @return EPUser object
3417 private CentralUser convertV2UserRolesToOlderVersion(CentralV2User cenV2User) {
3418 Set<CentralV2UserApp> userV2Apps = cenV2User.getUserApps();
3419 Set<CentralUserApp> userApps = new TreeSet<>();
3420 for(CentralV2UserApp userApp : userV2Apps){
3421 CentralApp app = userApp.getApp();
3422 CentralUserApp cua = new CentralUserApp();
3423 cua.setUserId(null);
3425 SortedSet<CentralRoleFunction> cenRoleFunction = new TreeSet<>();
3426 for(CentralV2RoleFunction cenV2RoleFunc : userApp.getRole().getRoleFunctions() ){
3427 CentralRoleFunction cenRoleFunc = new CentralRoleFunction(cenV2RoleFunc.getCode(), cenV2RoleFunc.getName());
3428 cenRoleFunction.add(cenRoleFunc);
3430 CentralRole role = new CentralRole(userApp.getRole().getId(), userApp.getRole().getName(), userApp.getRole().getActive(), userApp.getRole().getPriority(),
3435 return new CentralUser(cenV2User.getId(), cenV2User.getCreated(), cenV2User.getModified(),
3436 cenV2User.getCreatedId(),cenV2User.getModifiedId(),
3437 cenV2User.getRowNum(), cenV2User.getOrgId(), cenV2User.getManagerId(), cenV2User.getFirstName(),
3438 cenV2User.getMiddleInitial(), cenV2User.getLastName(), cenV2User.getPhone(), cenV2User.getFax(),
3439 cenV2User.getCellular(),cenV2User.getEmail(),cenV2User.getAddressId(),cenV2User.getAlertMethodCd(),
3440 cenV2User.getHrid(),cenV2User.getOrgUserId(),cenV2User.getOrgCode(),cenV2User.getAddress1(),
3441 cenV2User.getAddress2(),cenV2User.getCity(),cenV2User.getState(),cenV2User.getZipCode(),cenV2User.getCountry(),
3442 cenV2User.getOrgManagerUserId(),cenV2User.getLocationClli(),cenV2User.getBusinessCountryCode(),
3443 cenV2User.getBusinessCountryName(),cenV2User.getBusinessUnit(),cenV2User.getBusinessUnitName(),
3444 cenV2User.getDepartment(),cenV2User.getDepartmentName(),cenV2User.getCompanyCode(),
3445 cenV2User.getCompany(),cenV2User.getZipCodeSuffix(),cenV2User.getJobTitle(),
3446 cenV2User.getCommandChain(),cenV2User.getSiloStatus(),cenV2User.getCostCenter(),
3447 cenV2User.getFinancialLocCode(),cenV2User.getLoginId(),cenV2User.getLoginPwd(),
3448 cenV2User.getLastLoginDate(),cenV2User.isActive(),cenV2User.isInternal(),cenV2User.getSelectedProfileId(),cenV2User.getTimeZoneId(),
3449 cenV2User.isOnline(),cenV2User.getChatId(),
3454 public List<CentralRole> convertV2CentralRoleListToOldVerisonCentralRoleList(List<CentralV2Role> v2CenRoleList) {
3455 List<CentralRole> cenRoleList = new ArrayList<>();
3456 for(CentralV2Role v2CenRole : v2CenRoleList){
3457 SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
3458 for(CentralV2RoleFunction v2CenRoleFunc: v2CenRole.getRoleFunctions()){
3459 CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName());
3460 cenRoleFuncList.add(roleFunc);
3462 CentralRole role = new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.getActive(), v2CenRole.getPriority(), cenRoleFuncList);
3463 cenRoleList.add(role);
3469 public ResponseEntity<String> getNameSpaceIfExists(EPApp app) throws Exception {
3470 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3471 HttpEntity<String> entity = new HttpEntity<>(headers);
3472 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Connecting to External Auth system");
3473 ResponseEntity<String> response = null;
3476 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
3477 + "nss/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
3478 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Finished ",
3479 response.getStatusCode().value());
3480 } catch (HttpClientErrorException e) {
3481 logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e);
3482 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3483 if (e.getStatusCode() == HttpStatus.NOT_FOUND)
3484 throw new InvalidApplicationException("Invalid NameSpace");
3492 public CentralRole convertV2CentralRoleToOldVerisonCentralRole(CentralV2Role v2CenRole) {
3493 SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
3494 for (CentralV2RoleFunction v2CenRoleFunc : v2CenRole.getRoleFunctions()) {
3495 CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName());
3496 cenRoleFuncList.add(roleFunc);
3498 return new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.getActive(), v2CenRole.getPriority(),
3502 @SuppressWarnings("unchecked")
3504 public Integer bulkUploadUsersSingleRole(String uebkey, Long roleId, String modifiedRoleName) throws Exception {
3505 EPApp app = getApp(uebkey).get(0);
3506 final Map<String, String> params = new HashMap<>();
3507 params.put("uebKey", app.getUebKey());
3508 params.put("roleId", String.valueOf(roleId));
3509 List<BulkUploadUserRoles> userRolesList = null;
3510 Integer userRolesAdded = 0;
3511 if (app.getCentralAuth()) {
3512 userRolesList = dataAccessService.executeNamedQuery("getBulkUsersForSingleRole", params, null);
3513 for (BulkUploadUserRoles userRolesUpload : userRolesList) {
3514 userRolesUpload.setRoleName(modifiedRoleName);
3515 if(!userRolesUpload.getOrgUserId().equals("su1234")){
3516 addUserRoleInExternalSystem(userRolesUpload);
3521 return userRolesAdded;
3525 public String encodeFunctionCode(String funCode){
3526 String encodedString = funCode;
3527 List<Pattern> encodingList = new ArrayList<>();
3528 encodingList.add(Pattern.compile("/"));
3529 encodingList.add(Pattern.compile("-"));
3530 for (Pattern xssInputPattern : encodingList) {
3531 encodedString = xssInputPattern.matcher(encodedString)
3532 .replaceAll("%" + Hex.encodeHexString(xssInputPattern.toString().getBytes()));
3534 encodedString = encodedString.replaceAll("\\*", "%"+ Hex.encodeHexString("*".getBytes()));
3535 return encodedString;
3539 public void bulkUploadRoleFunc(UploadRoleFunctionExtSystem data, EPApp app) throws Exception {
3540 ObjectMapper mapper = new ObjectMapper();
3541 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3543 ExternalAccessRolePerms extRolePerms;
3544 ExternalAccessPerms extPerms;
3545 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + data.getType(), encodeFunctionCode(data.getInstance()), data.getAction());
3546 String appNameSpace = "";
3547 if(data.getIsGlobalRolePartnerFunc()) {
3548 appNameSpace = epAppService.getApp(1l).getNameSpace();
3550 appNameSpace = app.getNameSpace();
3552 extRolePerms = new ExternalAccessRolePerms(extPerms,
3554 + data.getRoleName().replaceAll(
3555 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
3557 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
3558 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
3559 updateRoleFunctionInExternalSystem(updateRolePerms, entity);
3560 } catch (HttpClientErrorException e) {
3561 logger.error(EELFLoggerDelegate.errorLogger,
3562 "HttpClientErrorException - Failed to add role function in external central auth system", e);
3563 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3565 } catch (Exception e) {
3566 logger.error(EELFLoggerDelegate.errorLogger,
3567 "addFunctionInExternalSystem: Failed to add role fucntion in external central auth system", e);
3573 private void updateRoleFunctionInExternalSystem(String updateRolePerms, HttpEntity<String> entity) {
3574 logger.debug(EELFLoggerDelegate.debugLogger, "bulkUploadRoleFunc: {} for POST: {}",
3575 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
3576 ResponseEntity<String> addPermResponse = template.exchange(
3577 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
3578 HttpMethod.POST, entity, String.class);
3579 logger.debug(EELFLoggerDelegate.debugLogger,
3580 "bulkUploadRoleFunc: Finished adding permission for POST: {} and status code: {} ",
3581 addPermResponse.getStatusCode().value(), updateRolePerms);
3585 public void syncApplicationUserRolesFromExtAuthSystem(String loginId) throws Exception {
3587 if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
3588 name = loginId + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
3590 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3591 HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
3592 ResponseEntity<String> getResponse = getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
3593 List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
3594 String res = getResponse.getBody();
3595 JSONObject jsonObj = null;
3596 JSONArray extRoles = null;
3597 if (!res.equals("{}")) {
3598 jsonObj = new JSONObject(res);
3599 extRoles = jsonObj.getJSONArray("role");
3601 updateUserRolesInLocal(userRoleDetailList, extRoles, loginId);
3604 @SuppressWarnings("unchecked")
3605 private void updateUserRolesInLocal(List<ExternalAccessUserRoleDetail> userRoleDetailList, JSONArray extRoles,
3606 String loginId) throws InvalidUserException {
3607 HashMap<String, String> userParams = new HashMap<>();
3608 userParams.put("orgUserId", loginId);
3609 // Get all centralized applications existing user roles from local
3610 List<CentralizedAppRoles> currentUserAppRoles = dataAccessService
3611 .executeNamedQuery("getUserCentralizedAppRoles", userParams, null);
3612 EPUser user = getUser(loginId).get(0);
3613 // Get all centralized applications roles from local
3614 HashMap<String, CentralizedAppRoles> cenAppRolesMap = getCentralizedAppRoleList();
3615 HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap = getCurrentUserCentralizedAppRoles(
3616 currentUserAppRoles);
3617 // Get all centralized applications + admin role from local
3618 HashMap<String, EPApp> centralisedAppsMap = getCentralizedAdminAppsInfo();
3619 if (extRoles != null) {
3620 ExternalAccessUserRoleDetail userRoleDetail = null;
3621 for (int i = 0; i < extRoles.length(); i++) {
3622 if (!extRoles.getJSONObject(i).getString("name").endsWith(ADMIN)
3623 && !extRoles.getJSONObject(i).getString("name").endsWith(OWNER)) {
3624 userRoleDetail = new ExternalAccessUserRoleDetail(extRoles.getJSONObject(i).getString("name"),
3626 userRoleDetailList.add(userRoleDetail);
3629 addUserRolesInLocal(userRoleDetailList, user, cenAppRolesMap, currentCentralizedUserAppRolesMap,
3630 centralisedAppsMap);
3634 private void addUserRolesInLocal(List<ExternalAccessUserRoleDetail> userRoleDetailList, EPUser user,
3635 HashMap<String, CentralizedAppRoles> cenAppRolesMap,
3636 HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap,
3637 HashMap<String, EPApp> centralisedAppsMap) {
3638 for (ExternalAccessUserRoleDetail extUserRoleDetail : userRoleDetailList) {
3640 // check if user already has role in local
3641 if (!currentCentralizedUserAppRolesMap.containsKey(extUserRoleDetail.getName())) {
3642 CentralizedAppRoles getCenAppRole = cenAppRolesMap.get(extUserRoleDetail.getName());
3643 if (getCenAppRole != null) {
3644 logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Adding user role from external auth system {}",
3645 extUserRoleDetail.toString());
3646 EPUserApp userApp = new EPUserApp();
3647 EPApp app = new EPApp();
3648 app.setId(getCenAppRole.getAppId());
3649 EPRole epRole = new EPRole();
3650 epRole.setId(getCenAppRole.getRoleId());
3651 userApp.setApp(app);
3652 userApp.setUserId(user.getId());
3653 userApp.setRole(epRole);
3654 dataAccessService.saveDomainObject(userApp, null);
3655 logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Finished user role from external auth system {}",
3656 extUserRoleDetail.toString());
3657 } else if (getCenAppRole == null // check if user has app account admin role
3658 && extUserRoleDetail.getName().endsWith(PortalConstants.ADMIN_ROLE.replaceAll(
3659 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
3660 EPApp app = centralisedAppsMap.get(extUserRoleDetail.getName());
3662 logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Adding user role from external auth system {}",
3663 extUserRoleDetail.toString());
3664 EPUserApp userApp = new EPUserApp();
3665 EPRole epRole = new EPRole();
3666 epRole.setId(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
3667 userApp.setApp(app);
3668 userApp.setUserId(user.getId());
3669 userApp.setRole(epRole);
3670 dataAccessService.saveDomainObject(userApp, null);
3671 logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Finished user role from external auth system {}",
3672 extUserRoleDetail.toString());
3676 } catch (Exception e) {
3677 logger.error(EELFLoggerDelegate.errorLogger,
3678 "addUserRolesInLocal - Failed to update user role in local from external auth system {} ",
3679 extUserRoleDetail.toString(), e);
3684 @SuppressWarnings("unchecked")
3685 private HashMap<String, EPApp> getCentralizedAdminAppsInfo() {
3686 List<EPApp> centralizedApps = dataAccessService
3687 .executeNamedQuery("getCentralizedApps", null, null);
3688 HashMap<String, EPApp> centralisedAppsMap = new HashMap<>();
3689 for (EPApp cenApp : centralizedApps) {
3690 centralisedAppsMap.put(cenApp.getNameSpace()+ "." +
3691 PortalConstants.ADMIN_ROLE.replaceAll(
3692 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), cenApp);
3694 return centralisedAppsMap;
3697 private HashMap<String, CentralizedAppRoles> getCurrentUserCentralizedAppRoles(
3698 List<CentralizedAppRoles> currentUserAppRoles) {
3699 HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap = new HashMap<>();
3700 for (CentralizedAppRoles cenAppUserRole : currentUserAppRoles) {
3701 currentCentralizedUserAppRolesMap.put(
3702 cenAppUserRole.getAppNameSpace() + "." + cenAppUserRole.getRoleName()
3703 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
3706 return currentCentralizedUserAppRolesMap;
3709 @SuppressWarnings("unchecked")
3710 private HashMap<String, CentralizedAppRoles> getCentralizedAppRoleList() {
3711 List<CentralizedAppRoles> centralizedAppRoles = dataAccessService
3712 .executeNamedQuery("getAllCentralizedAppsRoles", null, null);
3713 HashMap<String, CentralizedAppRoles> cenAppRolesMap = new HashMap<>();
3714 for (CentralizedAppRoles CentralizedAppRole : centralizedAppRoles) {
3716 CentralizedAppRole.getAppNameSpace() + "." + CentralizedAppRole.getRoleName()
3717 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
3718 CentralizedAppRole);
3720 return cenAppRolesMap;
3724 public ResponseEntity<String> getUserRolesFromExtAuthSystem(String name, HttpEntity<String> getUserRolesEntity) {
3725 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles");
3726 ResponseEntity<String> getResponse = template
3727 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
3728 + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class);
3729 if (getResponse.getStatusCode().value() == 200) {
3730 logger.debug(EELFLoggerDelegate.debugLogger, "getAllUserRoleFromExtAuthSystem: Finished GET user roles from external system and received user roles {}",
3731 getResponse.getBody());
3734 logger.error(EELFLoggerDelegate.errorLogger, "getAllUserRoleFromExtAuthSystem: Failed GET user roles from external system and received user roles {}",getResponse.getBody() );
3735 EPLogUtil.logExternalAuthAccessAlarm(logger, getResponse.getStatusCode());