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);
845 } else { // if role already exists then update it
846 EPRole globalRole = null;
847 List<EPRole> applicationRoles;
848 List<EPRole> globalRoleList = getGlobalRolesOfPortal();
849 boolean isGlobalRole = false;
850 if (!globalRoleList.isEmpty()) {
851 EPRole role = globalRoleList.stream().filter(x -> addRoleInDB.getId().equals(x.getId())).findAny()
858 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)
859 || (globalRole != null && app.getId() != globalRole.getAppId())) {
860 applicationRoles = getPortalAppRoleInfo(addRoleInDB.getId());
862 applicationRoles = getPartnerAppRoleInfo(addRoleInDB.getId(), app);
864 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
865 updateRoleInExternalSystem(addRoleInDB, app, isGlobalRole);
866 // Add all user to the re-named role in external auth system
867 if (!applicationRoles.isEmpty()
868 && !addRoleInDB.getName().equals(applicationRoles.get(0).getName())) {
869 bulkUploadUsersSingleRole(app.getUebKey(), applicationRoles.get(0).getId(),
870 addRoleInDB.getName());
873 deleteRoleFunction(app, applicationRoles);
874 if (!applicationRoles.isEmpty()) {
875 epRole = applicationRoles.get(0);
876 epRole.setName(addRoleInDB.getName());
877 epRole.setPriority(addRoleInDB.getPriority());
878 epRole.setActive(addRoleInDB.getActive());
879 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
880 epRole.setAppId(null);
881 epRole.setAppRoleId(null);
882 } else if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)
883 && applicationRoles.get(0).getAppRoleId() == null) {
884 epRole.setAppRoleId(epRole.getId());
886 dataAccessService.saveDomainObject(epRole, null);
888 Long roleAppId = null;
889 if (globalRole != null && !app.getId().equals(globalRole.getAppId()))
890 roleAppId = PortalConstants.PORTAL_APP_ID;
891 saveRoleFunction(listWithoutDuplicates, app, applicationRoles, roleAppId);
894 } catch (Exception e) {
895 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInEcompDB is failed", e);
903 * It validates whether role exists in external auth system
910 private void checkIfRoleExitsInExternalSystem(Role checkRole, EPApp app) throws Exception {
911 getNameSpaceIfExists(app);
912 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
913 String roleName = app.getNameSpace() + "." + checkRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_");
914 HttpEntity<String> checkRoleEntity = new HttpEntity<>(headers);
915 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRoleExitsInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
916 ResponseEntity<String> checkRoleInExternalSystem = template
917 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
918 + roleName, HttpMethod.GET, checkRoleEntity, String.class);
919 if (!checkRoleInExternalSystem.getBody().equals(IS_EMPTY_JSON_STRING)) {
920 logger.debug("checkIfRoleExitsInExternalSystem: Role already exists in external system {} and status code: {} ", checkRoleInExternalSystem.getBody(), checkRoleInExternalSystem.getStatusCode().value());
921 throw new ExternalAuthSystemException(" Role already exists in external system");
926 * It saves list of functions to the role in portal
928 * @param roleFunctionListNew
930 * @param applicationRoles
933 @SuppressWarnings("unchecked")
934 private void saveRoleFunction(List<RoleFunction> roleFunctionListNew, EPApp app, List<EPRole> applicationRoles ,Long roleAppId)
936 final Map<String, String> getAppFunctionParams = new HashMap<>();
938 for (RoleFunction roleFunc : roleFunctionListNew) {
939 String code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
940 EPAppRoleFunction appRoleFunc = new EPAppRoleFunction();
941 appRoleFunc.setAppId(app.getId());
942 appRoleFunc.setRoleId(applicationRoles.get(0).getId());
943 appRoleFunc.setRoleAppId(String.valueOf(roleAppId));
944 getAppFunctionParams.put("appId", String.valueOf(app.getId()));
945 getAppFunctionParams.put(FUNCTION_CODE_PARAMS, roleFunc.getCode());
946 // query to check if function code has pipes
947 List<CentralV2RoleFunction> roleFunction = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null);
948 if(roleFunction.isEmpty()){
949 getAppFunctionParams.put(FUNCTION_CODE_PARAMS, code);
950 roleFunction = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null);
952 if(roleFunction.size() > 1){
953 CentralV2RoleFunction getExactFunctionCode = appFunctionListFilter(code, roleFunction);
954 appRoleFunc.setCode(getExactFunctionCode.getCode());
956 appRoleFunc.setCode(roleFunction.get(0).getCode());
959 dataAccessService.saveDomainObject(appRoleFunc, null);
965 * It filters the app functions which starts with similar name in the result set
968 * @param roleFunction
969 * @return CentralRoleFunction
971 private CentralV2RoleFunction appFunctionListFilter(String roleFuncCode, List<CentralV2RoleFunction> roleFunction) {
972 final Map<String, CentralV2RoleFunction> appFunctionsFilter = new HashMap<>();
973 final Map<String, CentralV2RoleFunction> appFunctionsFilterPipes = new HashMap<>();
974 CentralV2RoleFunction getExactFunctionCode = null;
975 for(CentralV2RoleFunction cenRoleFunction : roleFunction){
976 appFunctionsFilter.put(cenRoleFunction.getCode(), cenRoleFunction);
977 appFunctionsFilterPipes.put(EcompPortalUtils.getFunctionCode(cenRoleFunction.getCode()), cenRoleFunction);
979 getExactFunctionCode = appFunctionsFilter.get(roleFuncCode);
980 if(getExactFunctionCode == null){
981 getExactFunctionCode = appFunctionsFilterPipes.get(roleFuncCode);
983 return getExactFunctionCode;
987 * It deletes all EPAppRoleFunction records in the portal
992 @SuppressWarnings("unchecked")
993 private void deleteRoleFunction(EPApp app, List<EPRole> role) {
994 final Map<String, Long> appRoleFuncsParams = new HashMap<>();
995 appRoleFuncsParams.put("appId", app.getId());
996 appRoleFuncsParams.put("roleId", role.get(0).getId());
997 List<EPAppRoleFunction> appRoleFunctionList = dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null);
998 if (!appRoleFunctionList.isEmpty()) {
999 for (EPAppRoleFunction approleFunction : appRoleFunctionList) {
1000 dataAccessService.deleteDomainObject(approleFunction, null);
1006 @SuppressWarnings("unchecked")
1007 public List<EPUser> getUser(String loginId) throws InvalidUserException{
1008 final Map<String, String> userParams = new HashMap<>();
1009 userParams.put("org_user_id", loginId);
1010 List<EPUser> userList = dataAccessService.executeNamedQuery("getEPUserByOrgUserId", userParams, null);
1011 if (userList.isEmpty()) {
1012 throw new InvalidUserException("User not found");
1018 public String getV2UserWithRoles(String loginId, String uebkey) throws Exception {
1019 final Map<String, String> params = new HashMap<>();
1020 List<EPUser> userList = null;
1021 CentralV2User cenV2User = null;
1022 String result = null;
1024 params.put("orgUserIdValue", loginId);
1025 List<EPApp> appList = getApp(uebkey);
1026 if (!appList.isEmpty()) {
1027 userList = getUser(loginId);
1028 if (!userList.isEmpty()) {
1029 ObjectMapper mapper = new ObjectMapper();
1030 cenV2User = getV2UserAppRoles(loginId, uebkey);
1031 result = mapper.writeValueAsString(cenV2User);
1032 } else if (userList.isEmpty()) {
1033 throw new InvalidUserException("User not found");
1036 throw new InactiveApplicationException("Application not found");
1038 } catch (Exception e) {
1039 logger.error(EELFLoggerDelegate.errorLogger, "getUser: failed", e);
1046 public List<CentralV2Role> getRolesForApp(String uebkey) throws Exception {
1047 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Entering into getRolesForApp");
1048 List<CentralV2Role> roleList = new ArrayList<>();
1049 final Map<String, Long> params = new HashMap<>();
1051 List<EPApp> app = getApp(uebkey);
1052 List<EPRole> appRolesList = getAppRoles(app.get(0).getId());
1053 roleList = createCentralRoleObject(app, appRolesList, roleList, params);
1054 if(app.get(0).getId() != PortalConstants.PORTAL_APP_ID){
1055 List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
1056 List<EPRole> globalRolesList = getGlobalRolesOfPortal();
1057 List<CentralV2Role> portalsGlobalRolesFinlaList = new ArrayList<>();
1058 if (!globalRolesList.isEmpty()) {
1059 for (EPRole eprole : globalRolesList) {
1060 CentralV2Role cenRole = convertRoleToCentralV2Role(eprole);
1061 portalsGlobalRolesFinlaList.add(cenRole);
1063 roleList.addAll(globalRoleList);
1064 for (CentralV2Role role : portalsGlobalRolesFinlaList) {
1065 CentralV2Role result = roleList.stream()
1066 .filter(x -> role.getId().equals(x.getId())).findAny().orElse(null);
1071 for (EPRole role : globalRolesList) {
1072 CentralV2Role cenRole = convertRoleToCentralV2Role(role);
1073 roleList.add(cenRole);
1077 } catch (Exception e) {
1078 logger.error(EELFLoggerDelegate.errorLogger, "getRolesForApp: Failed!", e);
1081 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Finished!");
1082 return roleList.stream().distinct().collect(Collectors.toList());
1085 @SuppressWarnings("unchecked")
1087 public List<CentralV2RoleFunction> getRoleFuncList(String uebkey) throws Exception {
1088 EPApp app = getApp(uebkey).get(0);
1089 List<CentralV2RoleFunction> finalRoleList = new ArrayList<>();
1090 final Map<String, Long> params = new HashMap<>();
1091 params.put(APP_ID, app.getId());
1092 List<CentralV2RoleFunction> getRoleFuncList = dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null);
1093 for (CentralV2RoleFunction roleFuncItem : getRoleFuncList) {
1094 String code = EcompPortalUtils.getFunctionCode(roleFuncItem.getCode());
1095 String type = getFunctionCodeType(roleFuncItem.getCode());
1096 String action = getFunctionCodeAction(roleFuncItem.getCode());
1097 roleFuncItem.setCode(EPUserUtils.decodeFunctionCode(code));
1098 roleFuncItem.setType(type);
1099 roleFuncItem.setAction(action);
1100 finalRoleList.add(roleFuncItem);
1102 return finalRoleList;
1107 public String getFunctionCodeAction(String roleFuncItem) {
1108 return (!roleFuncItem.contains(FUNCTION_PIPE)) ? "*"
1109 : EcompPortalUtils.getFunctionAction(roleFuncItem);
1113 public String getFunctionCodeType(String roleFuncItem) {
1115 if ((roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))
1116 || (!roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))) {
1118 } else if (checkIfCodeHasNoPipesAndHasTypeUrl(roleFuncItem)
1119 ||checkIfCodeHasPipesAndHasTypeUrl(roleFuncItem)
1120 ||checkIfCodeHasNoPipesAndHasNoTypeUrl(roleFuncItem)) {
1122 } else if (roleFuncItem.contains(FUNCTION_PIPE)
1123 && (!roleFuncItem.contains("menu") || roleFuncItem.contains("url"))) {
1124 type = EcompPortalUtils.getFunctionType(roleFuncItem);
1131 * It check whether function code has no pipes and no url string in it
1133 * @param roleFuncItem
1134 * @return true or false
1136 private boolean checkIfCodeHasNoPipesAndHasNoTypeUrl(String roleFuncItem) {
1137 return !roleFuncItem.contains(FUNCTION_PIPE) && !roleFuncItem.contains("url");
1142 * It check whether function code has pipes and url string in it
1144 * @param roleFuncItem
1145 * @return true or false
1147 private boolean checkIfCodeHasPipesAndHasTypeUrl(String roleFuncItem) {
1148 return roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
1153 * It check whether function code has no pipes and has url string in it
1155 * @param roleFuncItem
1156 * @return true or false
1158 private boolean checkIfCodeHasNoPipesAndHasTypeUrl(String roleFuncItem) {
1159 return !roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
1163 * It returns user detail information which is deep copy of EPUser.class object
1171 @SuppressWarnings("unchecked")
1172 private CentralV2User createEPUser(EPUser userInfo, Set<EPUserApp> userAppSet, EPApp app) throws Exception {
1173 final Map<String, Long> params = new HashMap<>();
1174 CentralV2User userAppList = new CentralV2User();
1175 CentralV2User user1 = null;
1176 final Map<String, Long> params1 = new HashMap<>();
1177 List<EPRole> globalRoleList = new ArrayList<>();
1179 if (app.getId() != PortalConstants.PORTAL_APP_ID) {
1180 params1.put("userId", userInfo.getId());
1181 params1.put("appId", app.getId());
1182 globalRoleList = dataAccessService.executeNamedQuery("userAppGlobalRoles", params1, null);
1184 userAppList.setUserApps(new TreeSet<CentralV2UserApp>());
1185 for (EPUserApp userApp : userAppSet) {
1186 if (userApp.getRole().getActive()) {
1187 EPApp epApp = userApp.getApp();
1188 String globalRole = userApp.getRole().getName().toLowerCase();
1189 if (((epApp.getId().equals(app.getId()))
1190 && (!userApp.getRole().getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)))
1191 || ((epApp.getId().equals(PortalConstants.PORTAL_APP_ID))
1192 && (globalRole.toLowerCase().startsWith("global_")))) {
1193 CentralV2UserApp cua = new CentralV2UserApp();
1194 cua.setUserId(null);
1195 CentralApp cenApp = new CentralApp(1L, epApp.getCreated(), epApp.getModified(),
1196 epApp.getCreatedId(), epApp.getModifiedId(), epApp.getRowNum(), epApp.getName(),
1197 epApp.getImageUrl(), epApp.getDescription(), epApp.getNotes(), epApp.getUrl(),
1198 epApp.getAlternateUrl(), epApp.getAppRestEndpoint(), epApp.getMlAppName(),
1199 epApp.getMlAppAdminId(), String.valueOf(epApp.getMotsId()), epApp.getAppPassword(),
1200 String.valueOf(epApp.getOpen()), String.valueOf(epApp.getEnabled()),
1201 epApp.getThumbnail(), epApp.getUsername(), epApp.getUebKey(), epApp.getUebSecret(),
1202 epApp.getUebTopicName());
1205 if (globalRole.toLowerCase().startsWith("global_")
1206 && epApp.getId().equals(PortalConstants.PORTAL_APP_ID)
1207 && !epApp.getId().equals(app.getId())) {
1208 appId = app.getId();
1209 EPRole result = null;
1210 if (globalRoleList.size() > 0)
1211 result = globalRoleList.stream()
1212 .filter(x -> userApp.getRole().getId().equals(x.getId())).findAny()
1217 appId = userApp.getApp().getId();
1219 params.put("roleId", userApp.getRole().getId());
1220 params.put(APP_ID, appId);
1221 List<CentralV2RoleFunction> appRoleFunctionList = dataAccessService
1222 .executeNamedQuery("getAppRoleFunctionList", params, null);
1223 SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>();
1224 for (CentralV2RoleFunction roleFunc : appRoleFunctionList) {
1225 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1226 String type = getFunctionCodeType(roleFunc.getCode());
1227 String action = getFunctionCodeAction(roleFunc.getCode());
1228 CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(roleFunc.getId(),
1229 functionCode, roleFunc.getName(), null, type, action, null);
1230 roleFunctionSet.add(cenRoleFunc);
1232 Long userRoleId = null;
1233 if (globalRole.toLowerCase().startsWith("global_")
1234 || epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1235 userRoleId = userApp.getRole().getId();
1237 userRoleId = userApp.getRole().getAppRoleId();
1239 CentralV2Role cenRole = new CentralV2Role(userRoleId, userApp.getRole().getCreated(),
1240 userApp.getRole().getModified(), userApp.getRole().getCreatedId(),
1241 userApp.getRole().getModifiedId(), userApp.getRole().getRowNum(),
1242 userApp.getRole().getName(), userApp.getRole().getActive(),
1243 userApp.getRole().getPriority(), roleFunctionSet, null, null);
1244 cua.setRole(cenRole);
1246 userAppList.getUserApps().add(cua);
1251 user1 = new CentralV2User(null, userInfo.getCreated(), userInfo.getModified(), userInfo.getCreatedId(),
1252 userInfo.getModifiedId(), userInfo.getRowNum(), userInfo.getOrgId(), userInfo.getManagerId(),
1253 userInfo.getFirstName(), userInfo.getMiddleInitial(), userInfo.getLastName(), userInfo.getPhone(),
1254 userInfo.getFax(), userInfo.getCellular(), userInfo.getEmail(), userInfo.getAddressId(),
1255 userInfo.getAlertMethodCd(), userInfo.getHrid(), userInfo.getOrgUserId(), userInfo.getOrgCode(),
1256 userInfo.getAddress1(), userInfo.getAddress2(), userInfo.getCity(), userInfo.getState(),
1257 userInfo.getZipCode(), userInfo.getCountry(), userInfo.getOrgManagerUserId(),
1258 userInfo.getLocationClli(), userInfo.getBusinessCountryCode(), userInfo.getBusinessCountryName(),
1259 userInfo.getBusinessUnit(), userInfo.getBusinessUnitName(), userInfo.getDepartment(),
1260 userInfo.getDepartmentName(), userInfo.getCompanyCode(), userInfo.getCompany(),
1261 userInfo.getZipCodeSuffix(), userInfo.getJobTitle(), userInfo.getCommandChain(),
1262 userInfo.getSiloStatus(), userInfo.getCostCenter(), userInfo.getFinancialLocCode(),
1263 userInfo.getLoginId(), userInfo.getLoginPwd(), userInfo.getLastLoginDate(), userInfo.getActive(),
1264 userInfo.getInternal(), userInfo.getSelectedProfileId(), userInfo.getTimeZoneId(),
1265 userInfo.isOnline(), userInfo.getChatId(), userAppList.getUserApps(), null);
1266 } catch (Exception e) {
1267 logger.error(EELFLoggerDelegate.errorLogger, "createEPUser: createEPUser failed", e);
1274 public CentralV2Role getRoleInfo(Long roleId, String uebkey) throws Exception {
1275 final Map<String, Long> params = new HashMap<>();
1276 List<CentralV2Role> roleList = new ArrayList<>();
1277 CentralV2Role cenRole = new CentralV2Role();
1278 List<EPRole> roleInfo = null;
1279 List<EPApp> app = null;
1281 app = getApp(uebkey);
1282 if (app.isEmpty()) {
1283 throw new InactiveApplicationException("Application not found");
1285 if (app.get(0).getId() != PortalConstants.PORTAL_APP_ID) {
1286 List<EPRole> globalRoleList = new ArrayList<>();
1287 globalRoleList = getGlobalRolesOfPortal();
1288 if (globalRoleList.size() > 0) {
1289 EPRole result = globalRoleList.stream().filter(x -> roleId.equals(x.getId())).findAny()
1292 return getGlobalRoleForRequestedApp(app.get(0).getId(), roleId);
1295 if (app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
1296 roleInfo = getPortalAppRoleInfo(roleId);
1298 roleInfo = getPartnerAppRoleInfo(roleId, app.get(0));
1300 roleList = createCentralRoleObject(app, roleInfo, roleList, params);
1301 if (roleList.isEmpty()) {
1305 } catch (Exception e) {
1306 logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo: failed", e);
1310 return roleList.get(0);
1313 @SuppressWarnings("unchecked")
1314 private List<EPRole> getPartnerAppRoleInfo(Long roleId, EPApp app) {
1315 List<EPRole> roleInfo;
1316 final Map<String, Long> getPartnerAppRoleParams = new HashMap<>();
1317 getPartnerAppRoleParams.put("appRoleId", roleId);
1318 getPartnerAppRoleParams.put("appId", app.getId());
1319 roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams, null);
1320 if(roleInfo.isEmpty()) {
1321 getPartnerAppRoleParams.put("appRoleId", roleId);
1322 roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleById", getPartnerAppRoleParams, null);
1327 @SuppressWarnings("unchecked")
1328 private List<EPRole> getPortalAppRoleInfo(Long roleId) {
1329 List<EPRole> roleInfo;
1330 final Map<String, Long> getPortalAppRoleParams = new HashMap<>();
1331 getPortalAppRoleParams.put("roleId", roleId);
1332 roleInfo = dataAccessService.executeNamedQuery("getPortalAppRoleByRoleId", getPortalAppRoleParams, null);
1338 * It returns list of app roles along with role functions and which went through deep copy
1345 * @throws DecoderException
1347 @SuppressWarnings("unchecked")
1348 private List<CentralV2Role> createCentralRoleObject(List<EPApp> app, List<EPRole> roleInfo,
1349 List<CentralV2Role> roleList, Map<String, Long> params) throws RoleFunctionException {
1350 for (EPRole role : roleInfo) {
1351 params.put("roleId", role.getId());
1352 params.put(APP_ID, app.get(0).getId());
1353 List<CentralV2RoleFunction> cenRoleFuncList = dataAccessService.executeNamedQuery("getAppRoleFunctionList",
1355 SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>();
1356 for (CentralV2RoleFunction roleFunc : cenRoleFuncList) {
1357 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1358 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
1359 String type = getFunctionCodeType(roleFunc.getCode());
1360 String action = getFunctionCodeAction(roleFunc.getCode());
1361 CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(role.getId(), functionCode,
1362 roleFunc.getName(), null, type, action, null);
1363 roleFunctionSet.add(cenRoleFunc);
1365 SortedSet<CentralV2Role> childRoles = new TreeSet<>();
1366 SortedSet<CentralV2Role> parentRoles = new TreeSet<>();
1367 CentralV2Role cenRole = null;
1368 if (role.getAppRoleId() == null) {
1369 cenRole = new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
1370 role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
1371 roleFunctionSet, childRoles, parentRoles);
1373 cenRole = new CentralV2Role(role.getAppRoleId(), role.getCreated(), role.getModified(),
1374 role.getCreatedId(), role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(),
1375 role.getPriority(), roleFunctionSet, childRoles, parentRoles);
1377 roleList.add(cenRole);
1382 @SuppressWarnings("unchecked")
1384 public CentralV2RoleFunction getRoleFunction(String functionCode, String uebkey) throws Exception {
1385 String code = EcompPortalUtils.getFunctionCode(functionCode);
1386 String encodedCode = encodeFunctionCode(code);
1387 CentralV2RoleFunction roleFunc = null;
1388 EPApp app = getApp(uebkey).get(0);
1389 List<CentralV2RoleFunction> getRoleFuncList = null;
1390 final Map<String, String> params = new HashMap<>();
1392 params.put(FUNCTION_CODE_PARAMS, functionCode);
1393 params.put(APP_ID, String.valueOf(app.getId()));
1394 getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
1395 if (getRoleFuncList.isEmpty()) {
1396 params.put(FUNCTION_CODE_PARAMS, encodedCode);
1397 getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
1398 if (getRoleFuncList.isEmpty()) {
1402 if (getRoleFuncList.size() > 1) {
1403 CentralV2RoleFunction cenV2RoleFunction = appFunctionListFilter(encodedCode, getRoleFuncList);
1404 if (cenV2RoleFunction == null)
1406 roleFunc = checkIfPipesExitsInFunctionCode(cenV2RoleFunction);
1408 // Check even if single record have pipes
1409 if (!getRoleFuncList.isEmpty() && getRoleFuncList.get(0).getCode().contains(FUNCTION_PIPE)) {
1410 roleFunc = checkIfPipesExitsInFunctionCode(getRoleFuncList.get(0));
1412 roleFunc = getRoleFuncList.get(0);
1415 } catch (Exception e) {
1416 logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction: failed", e);
1422 private CentralV2RoleFunction checkIfPipesExitsInFunctionCode(CentralV2RoleFunction getRoleFuncList) {
1423 CentralV2RoleFunction roleFunc;
1424 String functionCodeFormat = getRoleFuncList.getCode();
1425 if (functionCodeFormat.contains(FUNCTION_PIPE)) {
1426 String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(functionCodeFormat);
1427 String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(functionCodeFormat);
1428 String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(functionCodeFormat);
1429 roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), newfunctionCodeFormat,
1430 getRoleFuncList.getName(), getRoleFuncList.getAppId(), newfunctionTypeFormat, newfunctionActionFormat,
1431 getRoleFuncList.getEditUrl());
1433 roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), functionCodeFormat,
1434 getRoleFuncList.getName(), getRoleFuncList.getAppId(),
1435 getRoleFuncList.getEditUrl());
1441 public boolean saveCentralRoleFunction(CentralV2RoleFunction domainCentralRoleFunction, EPApp app) throws Exception {
1442 boolean saveOrUpdateFunction = false;
1444 domainCentralRoleFunction.setCode(encodeFunctionCode(domainCentralRoleFunction.getCode()));
1445 final Map<String, String> functionParams = new HashMap<>();
1446 functionParams.put("appId", String.valueOf(app.getId()));
1447 if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1448 addRoleFunctionInExternalSystem(domainCentralRoleFunction, app);
1450 if(domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null){
1451 domainCentralRoleFunction.setCode(domainCentralRoleFunction.getType()+
1452 FUNCTION_PIPE+domainCentralRoleFunction.getCode()+FUNCTION_PIPE+domainCentralRoleFunction.getAction());
1454 domainCentralRoleFunction.setAppId(app.getId());
1455 dataAccessService.saveDomainObject(domainCentralRoleFunction, null);
1456 saveOrUpdateFunction = true;
1457 } catch (Exception e) {
1458 logger.error(EELFLoggerDelegate.errorLogger, "saveCentralRoleFunction: failed", e);
1461 return saveOrUpdateFunction;
1465 * It creates application permission in external auth system
1467 * @param domainCentralRoleFunction
1471 private void addRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
1473 ObjectMapper mapper = new ObjectMapper();
1474 ExternalAccessPerms extPerms = new ExternalAccessPerms();
1475 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1477 String instance = "";
1479 if((domainCentralRoleFunction.getType()!=null && domainCentralRoleFunction.getAction()!=null) || domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)){
1480 type = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) ? EcompPortalUtils.getFunctionType(domainCentralRoleFunction.getCode()) : domainCentralRoleFunction.getType();
1481 instance = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) ? EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode()) : domainCentralRoleFunction.getCode();
1482 action = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) ? EcompPortalUtils.getFunctionAction(domainCentralRoleFunction.getCode()) : domainCentralRoleFunction.getAction();
1484 type = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url";
1485 instance = domainCentralRoleFunction.getCode();
1488 // get Permissions from External Auth System
1489 JSONArray extPermsList = getExtAuthPermissions(app);
1490 List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPermsList);
1491 String requestedPerm = type+FUNCTION_PIPE+instance+FUNCTION_PIPE+action;
1492 boolean checkIfFunctionsExits = permsDetailList.stream().anyMatch(permsDetail -> permsDetail.getInstance().equals(requestedPerm));
1493 if (!checkIfFunctionsExits) {
1495 extPerms.setAction(action);
1496 extPerms.setInstance(instance);
1497 extPerms.setType(app.getNameSpace() + "." + type);
1498 extPerms.setDescription(domainCentralRoleFunction.getName());
1499 String addFunction = mapper.writeValueAsString(extPerms);
1500 HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
1501 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for POST: {}" , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
1502 ResponseEntity<String> addPermResponse= template.exchange(
1503 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
1504 HttpMethod.POST, entity, String.class);
1505 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ", addPermResponse.getStatusCode().value(), addFunction);
1506 } catch(HttpClientErrorException e){
1507 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to add function in external central auth system", e);
1508 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1510 }catch (Exception e) {
1511 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionInExternalSystem: Failed to add fucntion in external central auth system",
1517 extPerms.setAction(action);
1518 extPerms.setInstance(instance);
1519 extPerms.setType(app.getNameSpace() + "." + type);
1520 extPerms.setDescription(domainCentralRoleFunction.getName());
1521 String updateRoleFunction = mapper.writeValueAsString(extPerms);
1522 HttpEntity<String> entity = new HttpEntity<>(updateRoleFunction, headers);
1523 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for PUT: {}" , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRoleFunction);
1524 ResponseEntity<String> updatePermResponse = template.exchange(
1525 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
1526 HttpMethod.PUT, entity, String.class);
1527 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished updating permission in External Auth system {} and response: {} ", updateRoleFunction, updatePermResponse.getStatusCode().value());
1528 } catch(HttpClientErrorException e){
1529 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to add function in external central auth system", e);
1530 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1532 } catch (Exception e) {
1533 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionInExternalSystem: Failed to update function in external central auth system",e);
1539 @SuppressWarnings("unchecked")
1541 @Transactional(rollbackFor = Exception.class)
1542 public boolean deleteCentralRoleFunction(String code, EPApp app) {
1543 boolean deleteFunctionResponse = false;
1545 final Map<String, String> params = new HashMap<>();
1546 params.put(FUNCTION_CODE_PARAMS, code);
1547 params.put(APP_ID, String.valueOf(app.getId()));
1548 List<CentralV2RoleFunction> domainCentralRoleFunction = dataAccessService
1549 .executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
1550 CentralV2RoleFunction appFunctionCode = appFunctionListFilter(code, domainCentralRoleFunction);
1551 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1552 deleteRoleFunctionInExternalSystem(appFunctionCode, app);
1553 // Delete role function dependency records
1554 deleteAppRoleFunctions(appFunctionCode.getCode(), app);
1556 dataAccessService.deleteDomainObject(appFunctionCode, null);
1557 deleteFunctionResponse = true;
1558 } catch (Exception e) {
1559 logger.error(EELFLoggerDelegate.errorLogger, "deleteCentralRoleFunction: failed", e);
1561 return deleteFunctionResponse;
1565 * It deletes app function record in portal
1570 private void deleteAppRoleFunctions(String code, EPApp app) {
1571 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
1572 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + code + "'", null);
1577 * It deletes permission in the external auth system
1579 * @param domainCentralRoleFunction
1583 private void deleteRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
1586 ObjectMapper mapper = new ObjectMapper();
1587 ExternalAccessPerms extPerms = new ExternalAccessPerms();
1588 String instanceValue = EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode());
1589 String checkType = getFunctionCodeType(domainCentralRoleFunction.getCode());
1590 String actionValue = getFunctionCodeAction(domainCentralRoleFunction.getCode());
1591 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1592 extPerms.setAction(actionValue);
1593 extPerms.setInstance(instanceValue);
1594 extPerms.setType(app.getNameSpace() + "." + checkType);
1595 extPerms.setDescription(domainCentralRoleFunction.getName());
1596 String deleteRoleFunction = mapper.writeValueAsString(extPerms);
1597 HttpEntity<String> entity = new HttpEntity<>(deleteRoleFunction, headers);
1598 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleFunctionInExternalSystem: {} for DELETE: {} ",
1599 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, deleteRoleFunction);
1600 ResponseEntity<String> delPermResponse = template
1601 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1602 + "perm?force=true", HttpMethod.DELETE, entity, String.class);
1603 logger.debug(EELFLoggerDelegate.debugLogger,
1604 "deleteRoleFunctionInExternalSystem: Finished deleting permission in External Auth system {} and status code: {} ",
1605 deleteRoleFunction, delPermResponse.getStatusCode().value());
1606 } catch(HttpClientErrorException e){
1607 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to delete functions in External System", e);
1608 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1609 } catch (Exception e) {
1610 if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
1611 logger.debug(EELFLoggerDelegate.debugLogger,
1612 " deleteRoleFunctionInExternalSystem: It seems like function is already deleted in external central auth system but exists in local DB",
1615 logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleFunctionInExternalSystem: Failed to delete functions in External System", e);
1621 public ExternalRequestFieldsValidator saveRoleForApplication(Role saveRole, String uebkey) throws Exception {
1622 boolean response = false;
1623 String message = "";
1625 EPApp app = getApp(uebkey).get(0);
1626 addRoleInEcompDB(saveRole, app);
1628 } catch (Exception e) {
1629 message = e.getMessage();
1630 logger.error(EELFLoggerDelegate.errorLogger, "saveRoleForApplication failed", e);
1632 return new ExternalRequestFieldsValidator(response,message);
1635 @SuppressWarnings("unchecked")
1637 public boolean deleteRoleForApplication(String deleteRole, String uebkey) throws Exception {
1638 Session localSession = sessionFactory.openSession();
1639 Transaction transaction = null;
1640 boolean result = false;
1642 List<EPRole> epRoleList = null;
1643 EPApp app = getApp(uebkey).get(0);
1644 final Map<String, String> deleteRoleParams = new HashMap<>();
1645 deleteRoleParams.put(APP_ROLE_NAME_PARAM, deleteRole);
1646 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1647 epRoleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, deleteRoleParams, null);
1649 deleteRoleParams.put(APP_ID, String.valueOf(app.getId()));
1650 epRoleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, deleteRoleParams, null);
1652 if (!epRoleList.isEmpty()) {
1653 transaction = localSession.beginTransaction();
1654 // Delete app role functions before deleting role
1655 deleteRoleFunction(app, epRoleList);
1656 if (app.getId() == 1) {
1657 // Delete fn_user_ role
1658 dataAccessService.deleteDomainObjects(EPUserApp.class,
1659 APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
1660 boolean isPortalRequest = false;
1661 deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest);
1663 deleteRoleInExternalAuthSystem(epRoleList, app);
1664 transaction.commit();
1665 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: committed the transaction");
1666 dataAccessService.deleteDomainObject(epRoleList.get(0), null);
1669 } catch (Exception e) {
1670 logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleForApplication: failed", e);
1673 localSession.close();
1680 * It deletes role for application in external auth system
1682 * @param epRoleList contains role information
1683 * @param app contains application information
1686 private void deleteRoleInExternalAuthSystem(List<EPRole> epRoleList, EPApp app) throws Exception {
1687 ResponseEntity<String> deleteResponse;
1688 ResponseEntity<String> res = getNameSpaceIfExists(app);
1689 if (res.getStatusCode() == HttpStatus.OK) {
1690 // Delete Role in External System
1691 String deleteRoleKey = "{\"name\":\"" + app.getNameSpace() + "." + epRoleList.get(0).getName()
1692 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_") + "\"}";
1693 deleteResponse = deleteRoleInExternalSystem(deleteRoleKey);
1694 if (deleteResponse.getStatusCode().value() != 200 && deleteResponse.getStatusCode().value() != 404) {
1695 EPLogUtil.logExternalAuthAccessAlarm(logger, deleteResponse.getStatusCode());
1696 logger.error(EELFLoggerDelegate.errorLogger,
1697 "deleteRoleForApplication: Failed to delete role in external auth system! due to {} ",
1698 deleteResponse.getBody());
1700 logger.debug(EELFLoggerDelegate.debugLogger,
1701 "deleteRoleForApplication: about to commit the transaction");
1707 * It deletes application user role in external auth system
1714 private void deleteUserRoleInExternalSystem(EPRole role, EPApp app, String LoginId) throws Exception {
1715 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1716 HttpEntity<String> entity = new HttpEntity<>(headers);
1717 getNameSpaceIfExists(app);
1718 logger.debug(EELFLoggerDelegate.debugLogger,"deleteUserRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1719 ResponseEntity<String> getResponse = template
1721 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
1724 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
1725 + "/" + app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
1726 HttpMethod.GET, entity, String.class);
1727 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: Finished GET user roles from External Auth system and response: {} ", getResponse.getBody());
1728 if (getResponse.getStatusCode().value() != 200) {
1729 throw new ExternalAuthSystemException(getResponse.getBody());
1731 String res = getResponse.getBody();
1732 if (!res.equals(IS_EMPTY_JSON_STRING)) {
1733 HttpEntity<String> userRoleentity = new HttpEntity<>(headers);
1734 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1735 ResponseEntity<String> deleteResponse = template
1737 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1738 + "userRole/" + LoginId
1740 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
1741 + "/" + app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
1742 HttpMethod.DELETE, userRoleentity, String.class);
1743 if (deleteResponse.getStatusCode().value() != 200) {
1744 throw new ExternalAuthSystemException("Failed to delete user role");
1746 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: Finished deleting user role in External Auth system and status code: {} ", deleteResponse.getStatusCode().value());
1750 @SuppressWarnings("unchecked")
1752 public List<CentralV2Role> getActiveRoles(String uebkey) throws Exception {
1753 List<CentralV2Role> roleList = new ArrayList<>();
1755 List<EPApp> app = getApp(uebkey);
1756 final Map<String, Long> params = new HashMap<>();
1759 if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
1760 appId = app.get(0).getId();
1762 List<Criterion> restrictionsList = new ArrayList<Criterion>();
1763 Criterion active_ynCrt = Restrictions.eq("active", Boolean.TRUE);
1766 appIdCrt = Restrictions.isNull("appId");
1768 appIdCrt = Restrictions.eq("appId", appId);
1769 Criterion andCrit = Restrictions.and(active_ynCrt, appIdCrt);
1770 restrictionsList.add(andCrit);
1771 List<EPRole> epRole = (List<EPRole>) dataAccessService.getList(EPRole.class, null, restrictionsList, null);
1772 roleList = createCentralRoleObject(app, epRole, roleList, params);
1773 List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
1774 if (globalRoleList.size() > 0)
1775 roleList.addAll(globalRoleList);
1776 } catch (Exception e) {
1777 logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles: failed", e);
1785 @Transactional(rollbackFor = Exception.class)
1786 public ExternalRequestFieldsValidator deleteDependencyRoleRecord(Long roleId, String uebkey, String LoginId) throws Exception {
1787 Session localSession = sessionFactory.openSession();
1788 String message = "";
1789 Transaction transaction = null;
1790 boolean response = false;
1793 transaction = localSession.beginTransaction();
1794 List<EPRole> epRoleList = null;
1795 app = getApp(uebkey).get(0);
1796 if(app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1797 epRoleList = getPortalAppRoleInfo(roleId);
1799 epRoleList = getPartnerAppRoleInfo(roleId, app);
1801 if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1802 // Delete User Role in External System before deleting role
1803 deleteUserRoleInExternalSystem(epRoleList.get(0), app, LoginId);
1805 // Delete user app roles
1806 dataAccessService.deleteDomainObjects(EPUserApp.class,
1807 APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
1808 boolean isPortalRequest = false;
1809 deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest);
1810 transaction.commit();
1811 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1812 // Final call to delete role once all dependencies has been deleted
1813 deleteRoleInExternalAuthSystem(epRoleList, app);
1815 dataAccessService.deleteDomainObjects(EPRole.class, " role_id = "+ epRoleList.get(0).getId(), null);
1816 logger.debug(EELFLoggerDelegate.debugLogger, "deleteDependencyRoleRecord: committed the transaction");
1818 } catch(HttpClientErrorException e){
1819 logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord: HttpClientErrorException", e);
1820 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1821 message = e.getMessage();
1822 } catch (Exception e) {
1823 logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord failed", e);
1824 EcompPortalUtils.rollbackTransaction(transaction,
1825 "deleteDependencyRoleRecord rollback, exception = " + e.toString());
1826 message = e.getMessage();
1828 localSession.close();
1830 return new ExternalRequestFieldsValidator(response,message);
1834 @SuppressWarnings("unchecked")
1836 public void syncRoleFunctionFromExternalAccessSystem(EPApp app) {
1839 // get Permissions from External Auth System
1840 JSONArray extPerms = getExtAuthPermissions(app);
1841 List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);
1843 // get functions in DB
1844 final Map<String, Long> params = new HashMap<>();
1845 final Map<String, CentralV2RoleFunction> roleFuncMap = new HashMap<>();
1846 params.put(APP_ID, app.getId());
1847 List<CentralV2RoleFunction> appFunctions = dataAccessService.executeNamedQuery("getAllRoleFunctions", params,
1849 if (!appFunctions.isEmpty()) {
1850 for (CentralV2RoleFunction roleFunc : appFunctions) {
1851 roleFuncMap.put(roleFunc.getCode(), roleFunc);
1855 // get Roles for portal in DB
1856 List<EPRole> portalRoleList = getGlobalRolesOfPortal();
1857 final Map<String, EPRole> existingPortalRolesMap = new HashMap<>();
1858 for(EPRole epRole : portalRoleList){
1859 existingPortalRolesMap.put(epRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), epRole);
1863 final Map<String, EPRole> currentRolesInDB = getCurrentRolesInDB(app);
1865 // store External Permissions with Pipe and without Pipe (just instance)
1866 final Map<String, ExternalAccessPermsDetail> extAccessPermsContainsPipeMap = new HashMap<>();
1867 final Map<String, ExternalAccessPermsDetail> extAccessPermsMap = new HashMap<>();
1868 for (ExternalAccessPermsDetail permsDetailInfoWithPipe : permsDetailList) {
1869 extAccessPermsContainsPipeMap.put(permsDetailInfoWithPipe.getInstance(), permsDetailInfoWithPipe);
1870 String finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetailInfoWithPipe.getInstance());
1871 extAccessPermsMap.put(finalFunctionCodeVal, permsDetailInfoWithPipe);
1874 // Add if new functions and app role functions were added in
1875 // external auth system
1876 for (ExternalAccessPermsDetail permsDetail : permsDetailList) {
1877 String code = permsDetail.getInstance();
1878 CentralV2RoleFunction getFunctionCodeKey = roleFuncMap.get(permsDetail.getInstance());
1879 List<CentralV2RoleFunction> roleFunctionList = addGetLocalFunction(app, roleFuncMap, permsDetail, code,
1880 getFunctionCodeKey);
1881 List<String> roles = permsDetail.getRoles();
1882 if (roles != null) {
1883 // Check if function has any roles and which does not exist
1884 // in External Auth System. If exists delete in local
1885 addRemoveIfFunctionsRolesIsSyncWithExternalAuth(app, currentRolesInDB, roleFunctionList, roles, existingPortalRolesMap);
1889 // Check if function does exits in External Auth System but exits in
1890 // local then delete function and its dependencies
1891 for (CentralV2RoleFunction roleFunc : appFunctions) {
1893 ExternalAccessPermsDetail getFunctionCodeContainsPipeKey = extAccessPermsContainsPipeMap
1894 .get(roleFunc.getCode());
1895 if (null == getFunctionCodeContainsPipeKey) {
1896 ExternalAccessPermsDetail getFunctionCodeKey = extAccessPermsMap.get(roleFunc.getCode());
1897 if (null == getFunctionCodeKey) {
1898 deleteAppRoleFuncDoesNotExitsInExtSystem(app, roleFunc);
1901 } catch (Exception e) {
1902 logger.error(EELFLoggerDelegate.errorLogger,
1903 "syncRoleFunctionFromExternalAccessSystem: Failed to delete function", e);
1908 logger.debug(EELFLoggerDelegate.debugLogger,
1909 "syncRoleFunctionFromExternalAccessSystem: Finished syncRoleFunctionFromExternalAccessSystem");
1910 } catch (Exception e) {
1911 logger.error(EELFLoggerDelegate.errorLogger,
1912 "syncRoleFunctionFromExternalAccessSystem: Failed syncRoleFunctionFromExternalAccessSystem", e);
1917 @SuppressWarnings("unchecked")
1918 private void addRemoveIfFunctionsRolesIsSyncWithExternalAuth(EPApp app, final Map<String, EPRole> currentRolesInDB,
1919 List<CentralV2RoleFunction> roleFunctionList, List<String> roles, Map<String, EPRole> existingPortalRolesMap)
1921 if (!roleFunctionList.isEmpty()) {
1922 final Map<String, String> appRoleFuncParams = new HashMap<>();
1923 final Map<String, LocalRole> currentAppRoleFunctionsMap = new HashMap<>();
1924 final Map<String, String> currentRolesInExtSystem = new HashMap<>();
1925 appRoleFuncParams.put("functionCd", roleFunctionList.get(0).getCode());
1926 appRoleFuncParams.put("appId", String.valueOf(app.getId()));
1927 List<LocalRole> localRoleList = dataAccessService.executeNamedQuery("getCurrentAppRoleFunctions",
1928 appRoleFuncParams, null);
1929 for (LocalRole localRole : localRoleList) {
1930 currentAppRoleFunctionsMap.put(localRole.getRolename().replaceAll(
1931 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), localRole);
1933 for (String addRole : roles) {
1934 currentRolesInExtSystem.put(addRole.substring(addRole.indexOf(FUNCTION_PIPE)+1), addRole);
1936 for (String extAuthrole : roles) {
1937 String roleNameSpace = extAuthrole.substring(0, extAuthrole.indexOf(FUNCTION_PIPE));
1938 boolean isNameSpaceMatching = EcompPortalUtils.checkNameSpaceMatching(roleNameSpace, app.getNameSpace());
1939 if (isNameSpaceMatching) {
1940 if (!currentAppRoleFunctionsMap
1941 .containsKey(extAuthrole.substring(app.getNameSpace().length() + 1))) {
1942 EPRole localAddFuntionRole = currentRolesInDB
1943 .get(extAuthrole.substring(app.getNameSpace().length() + 1));
1944 if (localAddFuntionRole == null) {
1945 checkAndAddRoleInDB(app, currentRolesInDB, roleFunctionList, extAuthrole);
1947 EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
1948 addAppRoleFunc.setAppId(app.getId());
1949 addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
1950 addAppRoleFunc.setRoleId(localAddFuntionRole.getId());
1951 dataAccessService.saveDomainObject(addAppRoleFunc, null);
1954 // This block is to save global role function if exists
1956 String extAuthAppRoleName = extAuthrole.substring(extAuthrole.indexOf(FUNCTION_PIPE) + 1);
1957 boolean checkIfGlobalRoleExists = existingPortalRolesMap.containsKey(extAuthAppRoleName);
1958 if (checkIfGlobalRoleExists) {
1959 final Map<String, Long> params = new HashMap<>();
1960 EPRole role = existingPortalRolesMap.get(extAuthAppRoleName);
1961 EPAppRoleFunction addGlobalRoleFunctions = new EPAppRoleFunction();
1962 params.put("appId", app.getId());
1963 params.put("roleId", role.getId());
1964 List<EPAppRoleFunction> currentGlobalRoleFunctionsList = dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", params, null);
1965 boolean checkIfRoleFunctionExists = currentGlobalRoleFunctionsList.stream().anyMatch(currentGlobalRoleFunction -> currentGlobalRoleFunction.getCode().equals(roleFunctionList.get(0).getCode()));
1966 if (role != null && !checkIfRoleFunctionExists) {
1967 addGlobalRoleFunctions.setAppId(app.getId());
1968 addGlobalRoleFunctions.setRoleId(role.getId());
1969 if (!app.getId().equals(role.getAppRoleId())) {
1970 addGlobalRoleFunctions.setRoleAppId((PortalConstants.PORTAL_APP_ID).toString());
1972 addGlobalRoleFunctions.setRoleAppId(null);
1974 addGlobalRoleFunctions.setCode(roleFunctionList.get(0).getCode());
1975 dataAccessService.saveDomainObject(addGlobalRoleFunctions, null);
1980 for (LocalRole localRoleDelete : localRoleList) {
1981 if (!currentRolesInExtSystem.containsKey(localRoleDelete.getRolename()
1982 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
1983 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
1984 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunctionList.get(0).getCode()
1985 + "'" + " and role_id = " + localRoleDelete.getRoleId().longValue(),
1992 private void deleteAppRoleFuncDoesNotExitsInExtSystem(EPApp app, CentralV2RoleFunction roleFunc) {
1993 logger.debug(EELFLoggerDelegate.debugLogger,
1994 "syncRoleFunctionFromExternalAccessSystem: Deleting app role function {}",
1995 roleFunc.getCode());
1996 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
1997 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() +"'", null);
1998 logger.debug(EELFLoggerDelegate.debugLogger,
1999 "syncRoleFunctionFromExternalAccessSystem: Deleted app role function {}",
2000 roleFunc.getCode());
2002 logger.debug(EELFLoggerDelegate.debugLogger,
2003 "syncRoleFunctionFromExternalAccessSystem: Deleting app function {}",
2004 roleFunc.getCode());
2005 dataAccessService.deleteDomainObjects(CentralV2RoleFunction.class,
2006 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() +"'", null);
2007 logger.debug(EELFLoggerDelegate.debugLogger,
2008 "syncRoleFunctionFromExternalAccessSystem: Deleted app function {}",
2009 roleFunc.getCode());
2012 private void checkAndAddRoleInDB(EPApp app, final Map<String, EPRole> currentRolesInDB,
2013 List<CentralV2RoleFunction> roleFunctionList, String roleList) throws Exception {
2014 if (!currentRolesInDB.containsKey(
2015 roleList.substring(app.getNameSpace().length() + 1))) {
2016 Role role = addRoleInDBIfDoesNotExists(app,
2017 roleList.substring(app.getNameSpace().length() + 1));
2018 addIfRoleDescriptionNotExitsInExtSystem(role, app);
2019 if (!roleFunctionList.isEmpty()) {
2021 if (!roleFunctionList.isEmpty()) {
2022 EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
2023 addAppRoleFunc.setAppId(app.getId());
2024 addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
2025 addAppRoleFunc.setRoleId(role.getId());
2026 dataAccessService.saveDomainObject(addAppRoleFunc, null);
2028 } catch (Exception e) {
2029 logger.error(EELFLoggerDelegate.errorLogger,
2030 "syncRoleFunctionFromExternalAccessSystem: Failed to save app role function ",
2037 @SuppressWarnings("unchecked")
2038 private List<CentralV2RoleFunction> addGetLocalFunction(EPApp app, final Map<String, CentralV2RoleFunction> roleFuncMap,
2039 ExternalAccessPermsDetail permsDetail, String code, CentralV2RoleFunction getFunctionCodeKey) {
2040 String finalFunctionCodeVal = addToLocalIfFunctionNotExists(app, roleFuncMap, permsDetail, code,
2041 getFunctionCodeKey);
2042 final Map<String, String> appSyncFuncsParams = new HashMap<>();
2043 appSyncFuncsParams.put("appId", String.valueOf(app.getId()));
2044 appSyncFuncsParams.put("functionCd", finalFunctionCodeVal);
2045 List<CentralV2RoleFunction> roleFunctionList = null;
2046 roleFunctionList = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams,
2048 if (roleFunctionList.isEmpty()) {
2049 appSyncFuncsParams.put("functionCd", code);
2050 roleFunctionList = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams,
2053 return roleFunctionList;
2056 private String addToLocalIfFunctionNotExists(EPApp app, final Map<String, CentralV2RoleFunction> roleFuncMap,
2057 ExternalAccessPermsDetail permsDetail, String code, CentralV2RoleFunction getFunctionCodeKey
2059 String finalFunctionCodeVal = "";
2060 if (null == getFunctionCodeKey) {
2061 finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetail.getInstance());
2062 CentralV2RoleFunction checkIfCodeStillExits = roleFuncMap.get(finalFunctionCodeVal);
2063 // If function does not exist in local then add!
2064 if (null == checkIfCodeStillExits) {
2065 logger.debug(EELFLoggerDelegate.debugLogger,
2066 "syncRoleFunctionFromExternalAccessSystem: Adding function: {} ", code);
2067 addFunctionInEcompDB(app, permsDetail, code);
2068 logger.debug(EELFLoggerDelegate.debugLogger,
2069 "syncRoleFunctionFromExternalAccessSystem: Finished adding function: {} ", code);
2072 return finalFunctionCodeVal;
2075 @SuppressWarnings("unchecked")
2077 public Map<String, EPRole> getCurrentRolesInDB(EPApp app) {
2078 final Map<String, EPRole> currentRolesInDB = new HashMap<>();
2079 List<EPRole> getCurrentRoleList = null;
2080 final Map<String, Long> appParams = new HashMap<>();
2081 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2082 getCurrentRoleList = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
2084 appParams.put("appId", app.getId());
2085 getCurrentRoleList = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
2087 for (EPRole role : getCurrentRoleList) {
2088 currentRolesInDB.put(role.getName()
2089 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), role);
2091 return currentRolesInDB;
2094 private List<ExternalAccessPermsDetail> getExtAuthPerrmissonList(EPApp app, JSONArray extPerms)
2096 ExternalAccessPermsDetail permDetails = null;
2097 List<ExternalAccessPermsDetail> permsDetailList = new ArrayList<>();
2098 for (int i = 0; i < extPerms.length(); i++) {
2099 String description = null;
2100 if (extPerms.getJSONObject(i).has("description")) {
2101 description = extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
2103 description = extPerms.getJSONObject(i).getString("type")+"|"+extPerms.getJSONObject(i).getString("instance")
2104 +"|"+extPerms.getJSONObject(i).getString("action");
2106 if (extPerms.getJSONObject(i).has("roles")) {
2107 ObjectMapper rolesListMapper = new ObjectMapper();
2108 JSONArray resRoles = extPerms.getJSONObject(i).getJSONArray("roles");
2109 List<String> list = rolesListMapper.readValue(resRoles.toString(),
2110 TypeFactory.defaultInstance().constructCollectionType(List.class, String.class));
2111 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
2112 extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
2113 + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
2114 + extPerms.getJSONObject(i).getString("action"),
2115 extPerms.getJSONObject(i).getString("action"), list, description);
2116 permsDetailList.add(permDetails);
2118 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
2119 extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
2120 + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
2121 + extPerms.getJSONObject(i).getString("action"),
2122 extPerms.getJSONObject(i).getString("action"), description);
2123 permsDetailList.add(permDetails);
2126 return permsDetailList;
2129 private JSONArray getExtAuthPermissions(EPApp app) throws Exception {
2130 ResponseEntity<String> response = null;
2131 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2132 HttpEntity<String> entity = new HttpEntity<>(headers);
2133 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: {} ",
2134 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2136 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
2137 + "perms/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
2139 String res = response.getBody();
2140 logger.debug(EELFLoggerDelegate.debugLogger,
2141 "syncRoleFunctionFromExternalAccessSystem: Finished GET permissions from External Auth system and response: {} ",
2142 response.getBody());
2143 JSONObject jsonObj = new JSONObject(res);
2144 JSONArray extPerms = jsonObj.getJSONArray("perm");
2145 for (int i = 0; i < extPerms.length(); i++) {
2146 if (extPerms.getJSONObject(i).getString("type").equals(app.getNameSpace() + ".access")) {
2156 * Add function into local DB
2159 * @param permsDetail
2162 private void addFunctionInEcompDB(EPApp app, ExternalAccessPermsDetail permsDetail, String code) {
2164 CentralV2RoleFunction addFunction = new CentralV2RoleFunction();
2165 addFunction.setAppId(app.getId());
2166 addFunction.setCode(code);
2167 addFunction.setName(permsDetail.getDescription());
2168 dataAccessService.saveDomainObject(addFunction, null);
2169 } catch(Exception e){
2170 logger.error(EELFLoggerDelegate.errorLogger, "addFunctionInEcompDB: Failed to add function", e);
2176 * It updates description of a role in external auth system
2182 private void addIfRoleDescriptionNotExitsInExtSystem(Role role, EPApp app) throws Exception {
2183 String addRoleNew = updateExistingRoleInExternalSystem(role, app);
2184 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2186 HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
2188 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
2189 HttpMethod.PUT, entity, String.class);
2190 } catch (HttpClientErrorException e) {
2191 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addIfRoleDescriptionNotExitsInExtSystem",
2193 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2194 } catch (Exception e) {
2195 logger.error(EELFLoggerDelegate.errorLogger, "addIfRoleDescriptionNotExitsInExtSystem: Failed",
2202 * While sync functions form external auth system if new role found we should add in local and return Role.class object
2208 @SuppressWarnings("unchecked")
2209 private Role addRoleInDBIfDoesNotExists(EPApp app, String role) {
2210 Role setNewRole = new Role();
2212 // functions can have new role created in External Auth System prevent
2214 boolean isCreated = checkIfRoleExitsElseCreateInSyncFunctions(role, app);
2215 final Map<String, String> getRoleByNameParams = new HashMap<>();
2216 List<EPRole> getRoleCreated = null;
2217 getRoleByNameParams.put(APP_ROLE_NAME_PARAM, role);
2218 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2219 getRoleByNameParams.put("appId", String.valueOf(app.getId()));
2220 List<EPRole> roleCreated = dataAccessService
2221 .executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, getRoleByNameParams, null);
2223 EPRole epUpdateRole = roleCreated.get(0);
2224 epUpdateRole.setAppRoleId(epUpdateRole.getId());
2225 dataAccessService.saveDomainObject(epUpdateRole, null);
2226 getRoleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
2227 getRoleByNameParams, null);
2229 getRoleCreated = roleCreated;
2232 getRoleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, getRoleByNameParams,
2235 if (getRoleCreated != null && !getRoleCreated.isEmpty()) {
2236 EPRole roleObject = getRoleCreated.get(0);
2237 setNewRole.setId(roleObject.getId());
2238 setNewRole.setName(roleObject.getName());
2239 setNewRole.setActive(roleObject.getActive());
2240 setNewRole.setPriority(roleObject.getPriority());
2242 } catch (Exception e) {
2243 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInDBIfDoesNotExists: Failed", e);
2248 @SuppressWarnings("unchecked")
2249 private boolean checkIfRoleExitsElseCreateInSyncFunctions(String role, EPApp app) {
2250 boolean isCreated = false;
2251 final Map<String, String> roleParams = new HashMap<>();
2252 roleParams.put(APP_ROLE_NAME_PARAM, role);
2253 List<EPRole> roleCreated = null;
2254 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2255 roleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, roleParams,
2258 roleParams.put("appId", String.valueOf(app.getId()));
2259 roleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams,
2262 if (roleCreated == null || roleCreated.isEmpty()) {
2263 roleParams.put("appId", String.valueOf(app.getId()));
2264 EPRole epRoleNew = new EPRole();
2265 epRoleNew.setActive(true);
2266 epRoleNew.setName(role);
2267 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2268 epRoleNew.setAppId(null);
2270 epRoleNew.setAppId(app.getId());
2272 dataAccessService.saveDomainObject(epRoleNew, null);
2281 @SuppressWarnings("unchecked")
2282 public Integer bulkUploadFunctions(String uebkey) throws Exception {
2283 EPApp app = getApp(uebkey).get(0);
2284 List<RoleFunction> roleFuncList = dataAccessService.executeNamedQuery("getAllFunctions", null, null);
2285 CentralV2RoleFunction cenRoleFunc = null;
2286 Integer functionsAdded = 0;
2288 for (RoleFunction roleFunc : roleFuncList) {
2289 cenRoleFunc = new CentralV2RoleFunction(roleFunc.getCode(), roleFunc.getName());
2290 addRoleFunctionInExternalSystem(cenRoleFunc, app);
2293 } catch(HttpClientErrorException e){
2294 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadFunctions failed", e);
2295 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2296 } catch (Exception e) {
2297 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions: failed", e.getMessage(), e);
2299 return functionsAdded;
2303 public Integer bulkUploadRoles(String uebkey) throws Exception {
2304 List<EPApp> app = getApp(uebkey);
2305 List<EPRole> roles = getAppRoles(app.get(0).getId());
2306 List<CentralV2Role> cenRoleList = new ArrayList<>();
2307 final Map<String, Long> params = new HashMap<>();
2308 Integer rolesListAdded = 0;
2310 cenRoleList = createCentralRoleObject(app, roles, cenRoleList, params);
2311 ObjectMapper mapper = new ObjectMapper();
2312 mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
2313 String roleList = mapper.writeValueAsString(cenRoleList);
2314 List<Role> roleObjectList = mapper.readValue(roleList,
2315 TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
2316 for (Role role : roleObjectList) {
2317 addRoleInExternalSystem(role, app.get(0));
2320 if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
2321 // Add Account Admin role in External AUTH System
2323 String addAccountAdminRole = "";
2324 ExternalAccessRole extRole = new ExternalAccessRole();
2325 extRole.setName(app.get(0).getNameSpace() + "." + PortalConstants.ADMIN_ROLE
2326 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2327 addAccountAdminRole = mapper.writeValueAsString(extRole);
2328 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2329 HttpEntity<String> entity = new HttpEntity<>(addAccountAdminRole, headers);
2331 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
2332 HttpMethod.POST, entity, String.class);
2334 } catch (HttpClientErrorException e) {
2335 logger.error(EELFLoggerDelegate.errorLogger,
2336 "HttpClientErrorException - Failed to create Account Admin role", e);
2337 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2338 } catch (Exception e) {
2339 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2340 logger.error(EELFLoggerDelegate.errorLogger,
2341 "bulkUploadRoles: Account Admin Role already exits but does not break functionality",
2344 logger.error(EELFLoggerDelegate.errorLogger,
2345 "bulkUploadRoles: Failed to create Account Admin role", e.getMessage());
2349 } catch (Exception e) {
2350 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles: failed", e);
2353 return rolesListAdded;
2357 * It creating new role in external auth system while doing bulk upload
2363 private void addRoleInExternalSystem(Role role, EPApp app) throws Exception {
2364 String addRoleNew = updateExistingRoleInExternalSystem(role, app);
2365 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2367 HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
2369 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
2370 HttpMethod.POST, entity, String.class);
2371 } catch(HttpClientErrorException e){
2372 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addRoleInExternalSystem", e);
2373 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2374 } catch (Exception e) {
2375 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2376 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInExternalSystem: Role already exits but does not break functionality", e);
2378 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInExternalSystem: Failed to addRoleInExternalSystem", e.getMessage());
2384 @SuppressWarnings("unchecked")
2385 public Integer bulkUploadRolesFunctions(String uebkey) throws Exception {
2386 EPApp app = getApp(uebkey).get(0);
2387 List<EPRole> roles = getAppRoles(app.getId());
2388 final Map<String, Long> params = new HashMap<>();
2389 Integer roleFunctions = 0;
2391 for (EPRole role : roles) {
2392 params.put("roleId", role.getId());
2393 List<BulkUploadRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("uploadAllRoleFunctions",
2395 if (!appRoleFunc.isEmpty()) {
2396 for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
2397 addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
2402 } catch(HttpClientErrorException e){
2403 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
2404 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2405 } catch (Exception e) {
2406 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
2408 return roleFunctions;
2412 * Its adding a role function while doing bulk upload
2414 * @param addRoleFunc
2418 private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, EPRole role, EPApp app) {
2420 String instance = "";
2422 if(addRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)){
2423 type = EcompPortalUtils.getFunctionType(addRoleFunc.getFunctionCd());
2424 instance = EcompPortalUtils.getFunctionCode(addRoleFunc.getFunctionCd());
2425 action = EcompPortalUtils.getFunctionAction(addRoleFunc.getFunctionCd());
2427 type = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
2428 instance = addRoleFunc.getFunctionCd();
2431 ExternalAccessRolePerms extRolePerms = null;
2432 ExternalAccessPerms extPerms = null;
2433 ObjectMapper mapper = new ObjectMapper();
2435 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2436 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, instance, action,
2437 addRoleFunc.getFunctionName());
2438 extRolePerms = new ExternalAccessRolePerms(extPerms,
2439 app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2440 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
2441 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
2443 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
2444 HttpMethod.POST, entity, String.class);
2445 } catch (Exception e) {
2446 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2447 logger.error(EELFLoggerDelegate.errorLogger,
2448 "addRoleFunctionsInExternalSystem: RoleFunction already exits but does not break functionality", e);
2450 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionsInExternalSystem: Failed to addRoleFunctionsInExternalSystem",
2456 @SuppressWarnings("unchecked")
2458 public Integer bulkUploadPartnerFunctions(String uebkey) throws Exception {
2459 EPApp app = getApp(uebkey).get(0);
2460 final Map<String, Long> params = new HashMap<>();
2461 params.put("appId", app.getId());
2462 List<CentralV2RoleFunction> roleFuncList = dataAccessService.executeNamedQuery("getPartnerAppFunctions", params,
2464 Integer functionsAdded = 0;
2466 for (CentralV2RoleFunction roleFunc : roleFuncList) {
2467 addFunctionInExternalSystem(roleFunc, app);
2470 } catch (HttpClientErrorException e) {
2471 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadPartnerFunctions failed", e);
2472 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2473 } catch (Exception e) {
2474 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerFunctions: failed", e.getMessage(), e);
2476 return functionsAdded;
2479 private void addFunctionInExternalSystem(CentralV2RoleFunction roleFunc, EPApp app) throws Exception {
2480 ObjectMapper mapper = new ObjectMapper();
2481 ExternalAccessPerms extPerms = new ExternalAccessPerms();
2482 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2484 String instance = "";
2486 if ((roleFunc.getCode().contains(FUNCTION_PIPE))
2487 || (roleFunc.getType() != null && roleFunc.getAction() != null)) {
2488 type = EcompPortalUtils.getFunctionType(roleFunc.getCode());
2489 instance = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
2490 action = EcompPortalUtils.getFunctionAction(roleFunc.getCode());
2492 type = roleFunc.getCode().contains("menu") ? "menu" : "url";
2493 instance = roleFunc.getCode();
2497 extPerms.setAction(action);
2498 extPerms.setInstance(instance);
2499 extPerms.setType(app.getNameSpace() + "." + type);
2500 extPerms.setDescription(roleFunc.getName());
2501 String addFunction = mapper.writeValueAsString(extPerms);
2502 HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
2503 logger.debug(EELFLoggerDelegate.debugLogger, "addFunctionInExternalSystem: {} for POST: {}",
2504 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
2505 ResponseEntity<String> addPermResponse = template.exchange(
2506 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
2507 HttpMethod.POST, entity, String.class);
2508 logger.debug(EELFLoggerDelegate.debugLogger,
2509 "addFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ",
2510 addPermResponse.getStatusCode().value(), addFunction);
2511 } catch (HttpClientErrorException e) {
2512 logger.error(EELFLoggerDelegate.errorLogger,
2513 "HttpClientErrorException - Failed to add function in external central auth system", e);
2514 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2516 } catch (Exception e) {
2517 logger.error(EELFLoggerDelegate.errorLogger,
2518 "addFunctionInExternalSystem: Failed to add fucntion in external central auth system", e);
2524 public void bulkUploadPartnerRoles(String uebkey, List<Role> roleList) throws Exception {
2525 EPApp app = getApp(uebkey).get(0);
2526 for (Role role : roleList) {
2527 addRoleInExternalSystem(role, app);
2531 @SuppressWarnings("unchecked")
2533 public Integer bulkUploadPartnerRoleFunctions(String uebkey) throws Exception {
2534 EPApp app = getApp(uebkey).get(0);
2535 List<EPRole> roles = getAppRoles(app.getId());
2536 final Map<String, Long> params = new HashMap<>();
2537 Integer roleFunctions = 0;
2539 for (EPRole role : roles) {
2540 params.put("roleId", role.getId());
2541 List<BulkUploadRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("uploadPartnerRoleFunctions",
2543 if (!appRoleFunc.isEmpty()) {
2544 for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
2545 addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
2550 // upload global role functions to ext auth system
2551 if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2552 roleFunctions = bulkUploadGlobalRoleFunctions(app, roleFunctions);
2554 } catch(HttpClientErrorException e){
2555 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
2556 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2557 } catch (Exception e) {
2558 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
2560 return roleFunctions;
2563 @SuppressWarnings("unchecked")
2564 private Integer bulkUploadGlobalRoleFunctions(EPApp app, Integer roleFunctions) throws Exception {
2566 EPApp portalApp = epAppService.getApp(1l);
2567 final Map<String, Long> params = new HashMap<>();
2568 params.put("appId", app.getId());
2569 List<GlobalRoleWithApplicationRoleFunction> globalRoleFuncs = dataAccessService
2570 .executeNamedQuery("getBulkUploadPartnerGlobalRoleFunctions", params, null);
2571 ObjectMapper mapper = new ObjectMapper();
2572 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2573 for (GlobalRoleWithApplicationRoleFunction globalRoleFunc : globalRoleFuncs) {
2574 ExternalAccessRolePerms extRolePerms;
2575 ExternalAccessPerms extPerms;
2577 String instance = "";
2579 if (globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
2580 type = EcompPortalUtils.getFunctionType(globalRoleFunc.getFunctionCd());
2581 instance = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd());
2582 action = EcompPortalUtils.getFunctionAction(globalRoleFunc.getFunctionCd());
2584 type = globalRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
2585 instance = globalRoleFunc.getFunctionCd();
2588 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, instance, action);
2589 extRolePerms = new ExternalAccessRolePerms(extPerms, portalApp.getNameSpace() + "." + globalRoleFunc.getRoleName()
2590 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2591 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
2592 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
2593 updateRoleFunctionInExternalSystem(updateRolePerms, entity);
2596 } catch (HttpClientErrorException e) {
2597 logger.error(EELFLoggerDelegate.errorLogger,
2598 "HttpClientErrorException - Failed to add role function in external central auth system", e);
2599 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2601 } catch (Exception e) {
2602 logger.error(EELFLoggerDelegate.errorLogger,
2603 "bulkUploadGlobalRoleFunctions: Failed to add role fucntion in external central auth system", e);
2606 return roleFunctions;
2611 public void syncApplicationRolesWithEcompDB(EPApp app) {
2613 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Started");
2614 //Sync functions and roles assigned to it which also creates new roles if does not exits in portal
2615 syncRoleFunctionFromExternalAccessSystem(app);
2616 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Finished");
2618 ObjectMapper mapper = new ObjectMapper();
2619 logger.debug(EELFLoggerDelegate.debugLogger, "Entering to getAppRolesJSONFromExtAuthSystem");
2620 // Get Permissions from External Auth System
2621 JSONArray extRole = getAppRolesJSONFromExtAuthSystem(app);
2623 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);
2650 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addNewRoleInEcompDBUpdateDescInExtAuthSystem");
2651 // Add new roles in DB and updates role description in External Auth System
2652 addNewRoleInEcompDBUpdateDescInExtAuthSystem(app, roleListToBeAddInEcompDB);
2653 logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: Finished");
2654 } catch (HttpClientErrorException e) {
2655 logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed due to the External Auth System", e);
2656 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2657 } catch (Exception e) {
2658 logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed ", e);
2664 * It adds new roles in DB and updates description in External Auth System
2667 * @param roleListToBeAddInEcompDB
2669 @SuppressWarnings("unchecked")
2670 private void addNewRoleInEcompDBUpdateDescInExtAuthSystem(EPApp app, List<EPRole> roleListToBeAddInEcompDB) {
2671 EPRole roleToBeAddedInEcompDB;
2672 for (int i = 0; i < roleListToBeAddInEcompDB.size(); i++) {
2674 roleToBeAddedInEcompDB = roleListToBeAddInEcompDB.get(i);
2675 if (app.getId() == 1) {
2676 roleToBeAddedInEcompDB.setAppRoleId(null);
2678 dataAccessService.saveDomainObject(roleToBeAddedInEcompDB, null);
2679 List<EPRole> getRoleCreatedInSync = null;
2680 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2681 final Map<String, String> globalRoleParams = new HashMap<>();
2682 globalRoleParams.put("appId", String.valueOf(app.getId()));
2683 globalRoleParams.put("appRoleName", roleToBeAddedInEcompDB.getName());
2684 getRoleCreatedInSync = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, globalRoleParams, null);
2685 EPRole epUpdateRole = getRoleCreatedInSync.get(0);
2686 epUpdateRole.setAppRoleId(epUpdateRole.getId());
2687 dataAccessService.saveDomainObject(epUpdateRole, null);
2689 List<EPRole> roleList = new ArrayList<>();
2690 final Map<String, String> params = new HashMap<>();
2692 params.put(APP_ROLE_NAME_PARAM, roleToBeAddedInEcompDB.getName());
2693 boolean isPortalRole = false;
2694 if (app.getId() == 1) {
2695 isPortalRole = true;
2696 roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, params, null);
2698 isPortalRole = false;
2699 params.put(APP_ID, app.getId().toString());
2700 roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, params, null);
2702 EPRole role = roleList.get(0);
2703 Role aaFrole = new Role();
2704 aaFrole.setId(role.getId());
2705 aaFrole.setActive(role.getActive());
2706 aaFrole.setPriority(role.getPriority());
2707 aaFrole.setName(role.getName());
2708 updateRoleInExternalSystem(aaFrole, app, isPortalRole);
2709 } catch (Exception e) {
2710 logger.error(EELFLoggerDelegate.errorLogger,
2711 "SyncApplicationRolesWithEcompDB: Failed to add or update role in external auth system", e);
2718 * It de-activates application roles in DB if not present in External Auth system
2721 * @param finalRoleList contains list of current roles present in External Auth System
2722 * @param applicationRolesList contains list of current roles present in DB
2724 @SuppressWarnings("unchecked")
2725 private void inactiveRolesNotInExternalAuthSystem(EPApp app, List<EPRole> finalRoleList,
2726 List<EPRole> applicationRolesList) {
2727 final Map<String, EPRole> checkRolesInactive = new HashMap<>();
2728 for (EPRole extrole : finalRoleList) {
2729 checkRolesInactive.put(extrole.getName(), extrole);
2731 for (EPRole role : applicationRolesList) {
2733 final Map<String, String> extRoleParams = new HashMap<>();
2734 List<EPRole> roleList = null;
2735 extRoleParams.put(APP_ROLE_NAME_PARAM, role.getName());
2736 if (!checkRolesInactive.containsKey(role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
2737 if (app.getId() == 1) {
2738 roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, extRoleParams, null);
2740 extRoleParams.put(APP_ID, app.getId().toString());
2741 roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, extRoleParams, null);
2743 if(!roleList.isEmpty()) {
2744 EPRole updateRoleInactive = roleList.get(0);
2745 updateRoleInactive.setActive(false);
2746 dataAccessService.saveDomainObject(updateRoleInactive, null);
2749 } catch (Exception e) {
2750 logger.error(EELFLoggerDelegate.errorLogger,
2751 "syncApplicationRolesWithEcompDB: Failed to de-activate role ", e);
2757 @SuppressWarnings("unchecked")
2758 public List<ExternalRoleDetails> getExternalRoleDetailsList(EPApp app,
2759 ObjectMapper mapper, JSONArray extRole)
2760 throws IOException {
2761 List<ExternalRoleDetails> externalRoleDetailsList = new ArrayList<>();
2762 ExternalAccessPerms externalAccessPerms = new ExternalAccessPerms();
2763 List<String> functionCodelist = new ArrayList<>();
2764 Map<String, EPRole> curRolesMap = getCurrentRolesInDB(app);
2765 for (int i = 0; i < extRole.length(); i++) {
2766 ExternalRoleDetails externalRoleDetail = new ExternalRoleDetails();
2767 EPAppRoleFunction ePAppRoleFunction = new EPAppRoleFunction();
2768 JSONObject Role = (JSONObject) extRole.get(i);
2769 String name = extRole.getJSONObject(i).getString(ROLE_NAME);
2770 String actualRoleName = name.substring(app.getNameSpace().length() + 1);
2771 SortedSet<ExternalAccessPerms> externalAccessPermsOfRole = new TreeSet<>();
2772 if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_PERMS)) {
2773 JSONArray extPerm = (JSONArray) Role.get(EXTERNAL_AUTH_PERMS);
2774 for (int j = 0; j < extPerm.length(); j++) {
2775 JSONObject perms = extPerm.getJSONObject(j);
2776 boolean isNamespaceMatching = EcompPortalUtils.checkNameSpaceMatching(perms.getString("type"),
2777 app.getNameSpace());
2778 if (isNamespaceMatching) {
2779 externalAccessPerms = new ExternalAccessPerms(perms.getString("type"),
2780 perms.getString("instance"), perms.getString("action"));
2781 ePAppRoleFunction.setCode(externalAccessPerms.getInstance());
2782 functionCodelist.add(ePAppRoleFunction.getCode());
2783 externalAccessPermsOfRole.add(externalAccessPerms);
2788 externalRoleDetail.setActive(true);
2789 externalRoleDetail.setName(actualRoleName);
2790 if (app.getId() == 1) {
2791 externalRoleDetail.setAppId(null);
2793 externalRoleDetail.setAppId(app.getId());
2795 // get role functions from DB
2796 EPRole currRole = curRolesMap.get(actualRoleName
2797 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2799 if (currRole != null)
2800 roleId = currRole.getId();
2801 // get role functions from DB
2802 final Map<String, EPAppRoleFunction> roleFunctionsMap = new HashMap<>();
2803 final Map<String, Long> appRoleFuncsParams = new HashMap<>();
2804 if (roleId != null) {
2805 appRoleFuncsParams.put("appId", app.getId());
2806 appRoleFuncsParams.put("roleId", roleId);
2807 List<EPAppRoleFunction> appRoleFunctions = dataAccessService
2808 .executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null);
2809 if (!appRoleFunctions.isEmpty()) {
2810 for (EPAppRoleFunction roleFunc : appRoleFunctions) {
2811 roleFunctionsMap.put(roleFunc.getCode(), roleFunc);
2815 if (!externalAccessPermsOfRole.isEmpty()) {
2816 // Adding functions to role
2817 for (ExternalAccessPerms externalpermission : externalAccessPermsOfRole) {
2818 EPAppRoleFunction checkRoleFunctionExits = roleFunctionsMap.get(externalpermission.getInstance());
2819 if (checkRoleFunctionExits == null) {
2820 String funcCode = externalpermission.getType().substring(app.getNameSpace().length() + 1)
2821 + FUNCTION_PIPE + externalpermission.getInstance() + FUNCTION_PIPE
2822 + externalpermission.getAction();
2823 EPAppRoleFunction checkRoleFunctionPipeExits = roleFunctionsMap.get(funcCode);
2824 if (checkRoleFunctionPipeExits == null) {
2826 final Map<String, String> appFuncsParams = new HashMap<>();
2827 appFuncsParams.put("appId", String.valueOf(app.getId()));
2828 appFuncsParams.put("functionCd", externalpermission.getInstance());
2829 logger.debug(EELFLoggerDelegate.debugLogger,
2830 "SyncApplicationRolesWithEcompDB: Adding function to the role: {}",
2831 externalpermission.getInstance());
2832 List<CentralV2RoleFunction> roleFunction = null;
2833 roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId",
2834 appFuncsParams, null);
2835 if (roleFunction.isEmpty()) {
2836 appFuncsParams.put("functionCd", funcCode);
2837 roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId",
2838 appFuncsParams, null);
2840 if (!roleFunction.isEmpty()) {
2841 EPAppRoleFunction apRoleFunction = new EPAppRoleFunction();
2842 apRoleFunction.setAppId(app.getId());
2843 apRoleFunction.setRoleId(roleId);
2844 apRoleFunction.setCode(roleFunction.get(0).getCode());
2845 dataAccessService.saveDomainObject(apRoleFunction, null);
2847 } catch (Exception e) {
2848 logger.error(EELFLoggerDelegate.errorLogger,
2849 "SyncApplicationRolesWithEcompDB: Failed to add role function", e);
2855 externalRoleDetailsList.add(externalRoleDetail);
2857 return externalRoleDetailsList;
2861 public JSONArray getAppRolesJSONFromExtAuthSystem(EPApp app) throws Exception {
2862 ResponseEntity<String> response = null;
2863 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2864 HttpEntity<String> entity = new HttpEntity<>(headers);
2865 logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: {} ",
2866 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2868 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
2869 + "roles/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
2870 String res = response.getBody();
2871 logger.debug(EELFLoggerDelegate.debugLogger,
2872 "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
2874 JSONObject jsonObj = new JSONObject(res);
2875 JSONArray extRole = jsonObj.getJSONArray("role");
2876 for (int i = 0; i < extRole.length(); i++) {
2877 if (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ADMIN)
2878 || extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + OWNER)
2879 || (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ACCOUNT_ADMINISTRATOR)
2880 && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
2889 public JSONArray getAllUsersByRole(String roleName) throws Exception{
2890 ResponseEntity<String> response = null;
2891 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2892 HttpEntity<String> entity = new HttpEntity<>(headers);
2893 logger.debug(EELFLoggerDelegate.debugLogger, "getAllUsersByRole: {} ",
2894 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2896 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
2897 + "userRoles/role/" + roleName, HttpMethod.GET, entity, String.class);
2898 String res = response.getBody();
2899 logger.debug(EELFLoggerDelegate.debugLogger,
2900 "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
2902 if(res == null || res.trim().isEmpty())
2905 JSONObject jsonObj = new JSONObject(res);
2906 JSONArray extRole = jsonObj.getJSONArray("userRole");
2913 * It converts from ExternalRoleDetails.class object to EPRole.class object
2915 * @param externalRoleDetails
2916 * @return EPRole object
2918 private EPRole convertExternalRoleDetailstoEpRole(ExternalRoleDetails externalRoleDetails) {
2919 EPRole role = new EPRole();
2920 role.setActive(true);
2921 role.setAppId(externalRoleDetails.getAppId());
2922 role.setAppRoleId(externalRoleDetails.getAppRoleId());
2923 role.setName(externalRoleDetails.getName());
2924 role.setPriority(externalRoleDetails.getPriority());
2928 @SuppressWarnings("unchecked")
2930 public Integer bulkUploadUserRoles(String uebkey) throws Exception {
2931 EPApp app = getApp(uebkey).get(0);
2932 final Map<String, String> params = new HashMap<>();
2933 params.put("uebKey", app.getUebKey());
2934 List<BulkUploadUserRoles> userRolesList = null;
2935 Integer userRolesAdded = 0;
2936 if (app.getCentralAuth()) {
2937 userRolesList = dataAccessService.executeNamedQuery("getBulkUserRoles", params, null);
2938 for (BulkUploadUserRoles userRolesUpload : userRolesList) {
2939 if(!userRolesUpload.getOrgUserId().equals("su1234")){
2940 addUserRoleInExternalSystem(userRolesUpload);
2945 return userRolesAdded;
2949 * Its adding a user role in external auth system while doing bulk upload
2951 * @param userRolesUpload
2953 private void addUserRoleInExternalSystem(BulkUploadUserRoles userRolesUpload) {
2956 ObjectMapper mapper = new ObjectMapper();
2957 if (EPCommonSystemProperties
2958 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
2959 name = userRolesUpload.getOrgUserId()
2960 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
2962 ExternalAccessUser extUser = new ExternalAccessUser(name,
2963 userRolesUpload.getAppNameSpace() + "." + userRolesUpload.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2964 String userRole = mapper.writeValueAsString(extUser);
2965 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2966 HttpEntity<String> entity = new HttpEntity<>(userRole, headers);
2968 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
2969 HttpMethod.POST, entity, String.class);
2970 } catch(HttpClientErrorException e){
2971 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addUserRoleInExternalSystem", e);
2972 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2973 } catch (Exception e) {
2974 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2975 logger.error(EELFLoggerDelegate.errorLogger, "addUserRoleInExternalSystem: UserRole already exits but does not break functionality");
2977 logger.error(EELFLoggerDelegate.errorLogger, "addUserRoleInExternalSystem: Failed to addUserRoleInExternalSystem", e);
2983 public void deleteRoleDependencyRecords(Session localSession, Long roleId, Long appId, boolean isPortalRequest) throws Exception {
2988 //It should delete only when it portal's roleId
2989 if(appId.equals(PortalConstants.PORTAL_APP_ID)){
2990 // Delete from fn_role_function
2991 sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
2992 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2993 query = localSession.createSQLQuery(sql);
2994 query.executeUpdate();
2996 // Delete from fn_role_composite
2997 sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId;
2998 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2999 query = localSession.createSQLQuery(sql);
3000 query.executeUpdate();
3003 // Delete from ep_app_role_function
3004 sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId;
3005 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3006 query = localSession.createSQLQuery(sql);
3007 query.executeUpdate();
3009 // Delete from ep_role_notification
3010 sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
3011 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3012 query = localSession.createSQLQuery(sql);
3013 query.executeUpdate();
3015 // Delete from fn_user_pseudo_role
3016 sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
3017 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3018 query = localSession.createSQLQuery(sql);
3019 query.executeUpdate();
3021 // Delete form EP_WIDGET_CATALOG_ROLE
3022 sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId;
3023 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3024 query = localSession.createSQLQuery(sql);
3025 query.executeUpdate();
3027 // Delete form EP_WIDGET_CATALOG_ROLE
3028 sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId;
3029 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3030 query = localSession.createSQLQuery(sql);
3031 query.executeUpdate();
3033 if(!isPortalRequest) {
3034 // Delete form fn_menu_functional_roles
3035 sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
3036 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3037 query = localSession.createSQLQuery(sql);
3038 query.executeUpdate();
3040 } catch (Exception e) {
3041 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e);
3042 throw new DeleteDomainObjectFailedException("delete Failed" + e.getMessage());
3047 @SuppressWarnings("unchecked")
3049 public List<String> getMenuFunctionsList(String uebkey) throws Exception {
3050 List<String> appMenuFunctionsList = null;
3051 List<String> appMenuFunctionsFinalList = new ArrayList<>();
3053 EPApp app = getApp(uebkey).get(0);
3054 final Map<String, Long> appParams = new HashMap<>();
3055 appParams.put(APP_ID, app.getId());
3056 appMenuFunctionsList = dataAccessService.executeNamedQuery("getMenuFunctions", appParams, null);
3057 for(String appMenuFunction : appMenuFunctionsList) {
3058 if(appMenuFunction.contains(FUNCTION_PIPE)) {
3059 appMenuFunctionsFinalList.add(EcompPortalUtils.getFunctionCode(appMenuFunction));
3061 appMenuFunctionsFinalList.add(appMenuFunction);
3064 } catch (Exception e) {
3065 logger.error(EELFLoggerDelegate.errorLogger, "getMenuFunctionsList: Failed", e);
3066 return appMenuFunctionsFinalList;
3068 return appMenuFunctionsFinalList;
3071 @SuppressWarnings({ "unchecked"})
3073 public List<EcompUser> getAllAppUsers(String uebkey) throws Exception {
3074 List<String> usersList = new ArrayList<>();
3075 List<EcompUser> usersfinalList = new ArrayList<>();
3077 EPApp app = getApp(uebkey).get(0);
3078 final Map<String, Long> appParams = new HashMap<>();
3079 appParams.put("appId", app.getId());
3080 List<EcompUserRoles> userList = (List<EcompUserRoles>) dataAccessService
3081 .executeNamedQuery("ApplicationUserRoles", appParams, null);
3082 for (EcompUserRoles ecompUserRole : userList) {
3083 boolean found = false;
3084 Set<EcompRole> roles = null;
3085 for (EcompUser user : usersfinalList) {
3086 if (user.getOrgUserId().equals(ecompUserRole.getOrgUserId())) {
3087 EcompRole ecompRole = new EcompRole();
3088 ecompRole.setId(ecompUserRole.getRoleId());
3089 ecompRole.setName(ecompUserRole.getRoleName());
3090 roles = user.getRoles();
3091 EcompRole role = roles.stream().filter(x -> x.getName().equals(ecompUserRole.getRoleName())).findAny()
3093 SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
3096 roleFunctionSet = (SortedSet<EcompRoleFunction>) role.getRoleFunctions();
3099 String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
3100 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
3101 EcompRoleFunction epRoleFunction = new EcompRoleFunction();
3102 epRoleFunction.setName(ecompUserRole.getFunctionName());
3103 epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
3104 epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
3105 epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
3106 roleFunctionSet.add(epRoleFunction);
3107 ecompRole.setRoleFunctions(roleFunctionSet);
3108 roles.add(ecompRole);
3109 user.setRoles(roles);
3116 EcompUser epUser = new EcompUser();
3117 epUser.setOrgId(ecompUserRole.getOrgId());
3118 epUser.setManagerId(ecompUserRole.getManagerId());
3119 epUser.setFirstName(ecompUserRole.getFirstName());
3120 epUser.setLastName(ecompUserRole.getLastName());
3121 epUser.setPhone(ecompUserRole.getPhone());
3122 epUser.setEmail(ecompUserRole.getEmail());
3123 epUser.setOrgUserId(ecompUserRole.getOrgUserId());
3124 epUser.setOrgCode(ecompUserRole.getOrgCode());
3125 epUser.setOrgManagerUserId(ecompUserRole.getOrgManagerUserId());
3126 epUser.setJobTitle(ecompUserRole.getJobTitle());
3127 epUser.setLoginId(ecompUserRole.getLoginId());
3128 epUser.setActive(true);
3129 roles = new HashSet<>();
3130 EcompRole ecompRole = new EcompRole();
3131 ecompRole.setId(ecompUserRole.getRoleId());
3132 ecompRole.setName(ecompUserRole.getRoleName());
3133 SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
3135 String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
3136 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
3137 EcompRoleFunction epRoleFunction = new EcompRoleFunction();
3138 epRoleFunction.setName(ecompUserRole.getFunctionName());
3139 epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
3140 epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
3141 epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
3142 roleFunctionSet.add(epRoleFunction);
3143 ecompRole.setRoleFunctions(roleFunctionSet);
3144 roles.add(ecompRole);
3145 epUser.setRoles(roles);
3146 usersfinalList.add(epUser);
3149 ObjectMapper mapper = new ObjectMapper();
3151 for (EcompUser u1 : usersfinalList) {
3152 String str = mapper.writeValueAsString(u1);
3155 } catch (Exception e) {
3156 logger.error(EELFLoggerDelegate.errorLogger, "getAllUsers failed", e);
3159 return usersfinalList;
3165 public Role ConvertCentralRoleToRole(String result) {
3166 ObjectMapper mapper = new ObjectMapper();
3167 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
3168 Role newRole = new Role();
3170 newRole = mapper.readValue(result, Role.class);
3171 } catch (IOException e) {
3172 logger.error(EELFLoggerDelegate.errorLogger, "Failed to convert the result to Role Object", e);
3174 if (newRole.getRoleFunctions() != null) {
3175 @SuppressWarnings("unchecked")
3176 Set<RoleFunction> roleFunctionList = newRole.getRoleFunctions();
3177 Set<RoleFunction> roleFunctionListNew = new HashSet<>();
3178 Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
3179 while (itetaror.hasNext()) {
3180 Object nextValue = itetaror.next();
3181 RoleFunction roleFun = mapper.convertValue(nextValue, RoleFunction.class);
3182 roleFunctionListNew.add(roleFun);
3184 newRole.setRoleFunctions(roleFunctionListNew);
3190 @SuppressWarnings("unchecked")
3191 public List<CentralizedApp> getCentralizedAppsOfUser(String userId) {
3192 Map<String, String> params = new HashMap<>();
3193 params.put("userId", userId);
3194 List<CentralizedApp> centralizedAppsList = new ArrayList<>();
3196 centralizedAppsList = dataAccessService
3197 .executeNamedQuery("getCentralizedAppsOfUser", params, null);
3198 }catch (Exception e) {
3199 logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
3201 return centralizedAppsList;
3204 @SuppressWarnings("unchecked")
3205 public List<CentralV2Role> getGlobalRolesOfApplication(Long appId) {
3206 Map<String, Long> params = new HashMap<>();
3207 params.put("appId", appId);
3208 List<GlobalRoleWithApplicationRoleFunction> globalRoles = new ArrayList<>();
3210 globalRoles = dataAccessService.executeNamedQuery("getGlobalRoleWithApplicationRoleFunctions", params,
3212 } catch (Exception e) {
3213 logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
3215 List<CentralV2Role> rolesfinalList = new ArrayList<>();
3216 if (globalRoles.size() > 0)
3217 rolesfinalList = finalListOfCentralRoles(globalRoles);
3218 return rolesfinalList;
3221 @SuppressWarnings("unchecked")
3222 private CentralV2Role getGlobalRoleForRequestedApp(long requestedAppId, long roleId) {
3223 CentralV2Role finalGlobalrole = null;
3224 List<GlobalRoleWithApplicationRoleFunction> roleWithApplicationRoleFucntions = new ArrayList<>();
3225 Map<String, Long> params = new HashMap<>();
3226 params.put("roleId", roleId);
3227 params.put("requestedAppId", requestedAppId);
3229 roleWithApplicationRoleFucntions = dataAccessService.executeNamedQuery("getGlobalRoleForRequestedApp",
3231 } catch (Exception e) {
3232 logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRoleForRequestedApp failed", e);
3234 if (roleWithApplicationRoleFucntions.size() > 0) {
3235 List<CentralV2Role> rolesfinalList = finalListOfCentralRoles(roleWithApplicationRoleFucntions);
3236 finalGlobalrole = rolesfinalList.get(0);
3238 List<EPRole> roleList = getPortalAppRoleInfo(roleId);
3239 finalGlobalrole = convertRoleToCentralV2Role(roleList.get(0));
3241 return finalGlobalrole;
3244 private List<CentralV2Role> finalListOfCentralRoles(List<GlobalRoleWithApplicationRoleFunction> globalRoles) {
3245 List<CentralV2Role> rolesfinalList = new ArrayList<>();
3246 for (GlobalRoleWithApplicationRoleFunction role : globalRoles) {
3247 boolean found = false;
3248 for (CentralV2Role cenRole : rolesfinalList) {
3249 if (role.getRoleId().equals(cenRole.getId())) {
3250 SortedSet<CentralV2RoleFunction> roleFunctions = cenRole.getRoleFunctions();
3251 CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
3252 roleFunctions.add(cenRoleFun);
3253 cenRole.setRoleFunctions(roleFunctions);
3259 CentralV2Role cenrole = new CentralV2Role();
3260 cenrole.setName(role.getRoleName());
3261 cenrole.setId(role.getRoleId());
3262 cenrole.setActive(role.isActive());
3263 cenrole.setPriority(role.getPriority());
3264 SortedSet<CentralV2RoleFunction> roleFunctions = new TreeSet<>();
3265 CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
3266 roleFunctions.add(cenRoleFun);
3267 cenrole.setRoleFunctions(roleFunctions);
3268 rolesfinalList.add(cenrole);
3271 return rolesfinalList;
3274 private CentralV2RoleFunction createCentralRoleFunctionForGlobalRole(GlobalRoleWithApplicationRoleFunction role) {
3278 CentralV2RoleFunction cenRoleFun;
3279 if(role.getFunctionCd().contains(FUNCTION_PIPE)){
3280 instance = EcompPortalUtils.getFunctionCode(role.getFunctionCd());
3281 type = EcompPortalUtils.getFunctionType(role.getFunctionCd());
3282 action = EcompPortalUtils.getFunctionAction(role.getFunctionCd());
3283 cenRoleFun = new CentralV2RoleFunction(null, instance, role.getFunctionName(), null, type, action, null);
3285 type = getFunctionCodeType(role.getFunctionCd());
3286 action = getFunctionCodeAction(role.getFunctionCd());
3287 cenRoleFun = new CentralV2RoleFunction(null, role.getFunctionCd(), role.getFunctionName(), null, type, action, null);
3292 @SuppressWarnings("unchecked")
3294 public List<EPRole> getGlobalRolesOfPortal() {
3295 List<EPRole> globalRoles = new ArrayList<>();
3297 globalRoles = dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null);
3298 } catch (Exception e) {
3299 logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRolesOfPortal failed", e);
3304 private CentralV2Role convertRoleToCentralV2Role(EPRole role) {
3305 return new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
3306 role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
3307 new TreeSet<>(), new TreeSet<>(), new TreeSet<>());
3312 public List<CentralRoleFunction> convertCentralRoleFunctionToRoleFunctionObject(List<CentralV2RoleFunction> answer) {
3313 List<CentralRoleFunction> addRoleFuncList = new ArrayList<>();
3314 for(CentralV2RoleFunction cenRoleFunc : answer){
3315 CentralRoleFunction setRoleFunc = new CentralRoleFunction();
3316 setRoleFunc.setCode(cenRoleFunc.getCode());
3317 setRoleFunc.setName(cenRoleFunc.getName());
3318 addRoleFuncList.add(setRoleFunc);
3320 return addRoleFuncList;
3324 public CentralUser getUserRoles(String loginId, String uebkey) throws Exception {
3325 CentralUser sendUserRoles = null;
3328 CentralV2User cenV2User = getV2UserAppRoles(loginId, uebkey);
3329 sendUserRoles = convertV2UserRolesToOlderVersion(cenV2User);
3330 } catch (Exception e) {
3331 logger.error(EELFLoggerDelegate.errorLogger, "getUserRoles: failed", e);
3334 return sendUserRoles;
3339 * It returns V2 CentralUser object if user has any roles and permissions
3343 * @return CentralUser object
3346 private CentralV2User getV2UserAppRoles(String loginId, String uebkey) throws Exception {
3348 List<EPUser> epUserList;
3349 List<EPApp> appList = getApp(uebkey);
3350 app = appList.get(0);
3351 epUserList = getUser(loginId);
3352 EPUser user = epUserList.get(0);
3353 Set<EPUserApp> userAppSet = user.getEPUserApps();
3354 return createEPUser(user, userAppSet, app);
3358 * It converts V2 CentralUser object to old version CentralUser object
3361 * @return EPUser object
3363 private CentralUser convertV2UserRolesToOlderVersion(CentralV2User cenV2User) {
3364 Set<CentralV2UserApp> userV2Apps = cenV2User.getUserApps();
3365 Set<CentralUserApp> userApps = new TreeSet<>();
3366 for(CentralV2UserApp userApp : userV2Apps){
3367 CentralApp app = userApp.getApp();
3368 CentralUserApp cua = new CentralUserApp();
3369 cua.setUserId(null);
3371 SortedSet<CentralRoleFunction> cenRoleFunction = new TreeSet<>();
3372 for(CentralV2RoleFunction cenV2RoleFunc : userApp.getRole().getRoleFunctions() ){
3373 CentralRoleFunction cenRoleFunc = new CentralRoleFunction(cenV2RoleFunc.getCode(), cenV2RoleFunc.getName());
3374 cenRoleFunction.add(cenRoleFunc);
3376 CentralRole role = new CentralRole(userApp.getRole().getId(), userApp.getRole().getName(), userApp.getRole().getActive(), userApp.getRole().getPriority(),
3381 return new CentralUser(cenV2User.getId(), cenV2User.getCreated(), cenV2User.getModified(),
3382 cenV2User.getCreatedId(),cenV2User.getModifiedId(),
3383 cenV2User.getRowNum(), cenV2User.getOrgId(), cenV2User.getManagerId(), cenV2User.getFirstName(),
3384 cenV2User.getMiddleInitial(), cenV2User.getLastName(), cenV2User.getPhone(), cenV2User.getFax(),
3385 cenV2User.getCellular(),cenV2User.getEmail(),cenV2User.getAddressId(),cenV2User.getAlertMethodCd(),
3386 cenV2User.getHrid(),cenV2User.getOrgUserId(),cenV2User.getOrgCode(),cenV2User.getAddress1(),
3387 cenV2User.getAddress2(),cenV2User.getCity(),cenV2User.getState(),cenV2User.getZipCode(),cenV2User.getCountry(),
3388 cenV2User.getOrgManagerUserId(),cenV2User.getLocationClli(),cenV2User.getBusinessCountryCode(),
3389 cenV2User.getBusinessCountryName(),cenV2User.getBusinessUnit(),cenV2User.getBusinessUnitName(),
3390 cenV2User.getDepartment(),cenV2User.getDepartmentName(),cenV2User.getCompanyCode(),
3391 cenV2User.getCompany(),cenV2User.getZipCodeSuffix(),cenV2User.getJobTitle(),
3392 cenV2User.getCommandChain(),cenV2User.getSiloStatus(),cenV2User.getCostCenter(),
3393 cenV2User.getFinancialLocCode(),cenV2User.getLoginId(),cenV2User.getLoginPwd(),
3394 cenV2User.getLastLoginDate(),cenV2User.isActive(),cenV2User.isInternal(),cenV2User.getSelectedProfileId(),cenV2User.getTimeZoneId(),
3395 cenV2User.isOnline(),cenV2User.getChatId(),
3400 public List<CentralRole> convertV2CentralRoleListToOldVerisonCentralRoleList(List<CentralV2Role> v2CenRoleList) {
3401 List<CentralRole> cenRoleList = new ArrayList<>();
3402 for(CentralV2Role v2CenRole : v2CenRoleList){
3403 SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
3404 for(CentralV2RoleFunction v2CenRoleFunc: v2CenRole.getRoleFunctions()){
3405 CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName());
3406 cenRoleFuncList.add(roleFunc);
3408 CentralRole role = new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.getActive(), v2CenRole.getPriority(), cenRoleFuncList);
3409 cenRoleList.add(role);
3415 public ResponseEntity<String> getNameSpaceIfExists(EPApp app) throws Exception {
3416 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3417 HttpEntity<String> entity = new HttpEntity<>(headers);
3418 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Connecting to External Auth system");
3419 ResponseEntity<String> response = null;
3422 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
3423 + "nss/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
3424 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Finished ",
3425 response.getStatusCode().value());
3426 } catch (HttpClientErrorException e) {
3427 logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e);
3428 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3429 if (e.getStatusCode() == HttpStatus.NOT_FOUND)
3430 throw new InvalidApplicationException("Invalid NameSpace");
3438 public CentralRole convertV2CentralRoleToOldVerisonCentralRole(CentralV2Role v2CenRole) {
3439 SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
3440 for (CentralV2RoleFunction v2CenRoleFunc : v2CenRole.getRoleFunctions()) {
3441 CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName());
3442 cenRoleFuncList.add(roleFunc);
3444 return new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.getActive(), v2CenRole.getPriority(),
3448 @SuppressWarnings("unchecked")
3450 public Integer bulkUploadUsersSingleRole(String uebkey, Long roleId, String modifiedRoleName) throws Exception {
3451 EPApp app = getApp(uebkey).get(0);
3452 final Map<String, String> params = new HashMap<>();
3453 params.put("uebKey", app.getUebKey());
3454 params.put("roleId", String.valueOf(roleId));
3455 List<BulkUploadUserRoles> userRolesList = null;
3456 Integer userRolesAdded = 0;
3457 if (app.getCentralAuth()) {
3458 userRolesList = dataAccessService.executeNamedQuery("getBulkUsersForSingleRole", params, null);
3459 for (BulkUploadUserRoles userRolesUpload : userRolesList) {
3460 userRolesUpload.setRoleName(modifiedRoleName);
3461 if(!userRolesUpload.getOrgUserId().equals("su1234")){
3462 addUserRoleInExternalSystem(userRolesUpload);
3467 return userRolesAdded;
3471 public String encodeFunctionCode(String funCode){
3472 String encodedString = funCode;
3473 List<Pattern> encodingList = new ArrayList<>();
3474 encodingList.add(Pattern.compile("/"));
3475 encodingList.add(Pattern.compile("-"));
3476 for (Pattern xssInputPattern : encodingList) {
3477 encodedString = xssInputPattern.matcher(encodedString)
3478 .replaceAll("%" + Hex.encodeHexString(xssInputPattern.toString().getBytes()));
3480 encodedString = encodedString.replaceAll("\\*", "%"+ Hex.encodeHexString("*".getBytes()));
3481 return encodedString;
3485 public void bulkUploadRoleFunc(UploadRoleFunctionExtSystem data, EPApp app) throws Exception {
3486 ObjectMapper mapper = new ObjectMapper();
3487 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3489 ExternalAccessRolePerms extRolePerms;
3490 ExternalAccessPerms extPerms;
3491 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + data.getType(), encodeFunctionCode(data.getInstance()), data.getAction());
3492 String appNameSpace = "";
3493 if(data.getIsGlobalRolePartnerFunc()) {
3494 appNameSpace = epAppService.getApp(1l).getNameSpace();
3496 appNameSpace = app.getNameSpace();
3498 extRolePerms = new ExternalAccessRolePerms(extPerms,
3500 + data.getRoleName().replaceAll(
3501 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
3503 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
3504 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
3505 updateRoleFunctionInExternalSystem(updateRolePerms, entity);
3506 } catch (HttpClientErrorException e) {
3507 logger.error(EELFLoggerDelegate.errorLogger,
3508 "HttpClientErrorException - Failed to add role function in external central auth system", e);
3509 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3511 } catch (Exception e) {
3512 logger.error(EELFLoggerDelegate.errorLogger,
3513 "addFunctionInExternalSystem: Failed to add role fucntion in external central auth system", e);
3519 private void updateRoleFunctionInExternalSystem(String updateRolePerms, HttpEntity<String> entity) {
3520 logger.debug(EELFLoggerDelegate.debugLogger, "bulkUploadRoleFunc: {} for POST: {}",
3521 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
3522 ResponseEntity<String> addPermResponse = template.exchange(
3523 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
3524 HttpMethod.POST, entity, String.class);
3525 logger.debug(EELFLoggerDelegate.debugLogger,
3526 "bulkUploadRoleFunc: Finished adding permission for POST: {} and status code: {} ",
3527 addPermResponse.getStatusCode().value(), updateRolePerms);
3531 public void syncApplicationUserRolesFromExtAuthSystem(String loginId) throws Exception {
3533 if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
3534 name = loginId + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
3536 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3537 HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
3538 ResponseEntity<String> getResponse = getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
3539 List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
3540 String res = getResponse.getBody();
3541 JSONObject jsonObj = null;
3542 JSONArray extRoles = null;
3543 if (!res.equals("{}")) {
3544 jsonObj = new JSONObject(res);
3545 extRoles = jsonObj.getJSONArray("role");
3547 updateUserRolesInLocal(userRoleDetailList, extRoles, loginId);
3550 @SuppressWarnings("unchecked")
3551 private void updateUserRolesInLocal(List<ExternalAccessUserRoleDetail> userRoleDetailList, JSONArray extRoles,
3552 String loginId) throws InvalidUserException {
3553 HashMap<String, String> userParams = new HashMap<>();
3554 userParams.put("orgUserId", loginId);
3555 // Get all centralized applications existing user roles from local
3556 List<CentralizedAppRoles> currentUserAppRoles = dataAccessService
3557 .executeNamedQuery("getUserCentralizedAppRoles", userParams, null);
3558 EPUser user = getUser(loginId).get(0);
3559 // Get all centralized applications roles from local
3560 HashMap<String, CentralizedAppRoles> cenAppRolesMap = getCentralizedAppRoleList();
3561 HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap = getCurrentUserCentralizedAppRoles(
3562 currentUserAppRoles);
3563 // Get all centralized applications + admin role from local
3564 HashMap<String, EPApp> centralisedAppsMap = getCentralizedAdminAppsInfo();
3565 if (extRoles != null) {
3566 ExternalAccessUserRoleDetail userRoleDetail = null;
3567 for (int i = 0; i < extRoles.length(); i++) {
3568 if (!extRoles.getJSONObject(i).getString("name").endsWith(ADMIN)
3569 && !extRoles.getJSONObject(i).getString("name").endsWith(OWNER)) {
3570 userRoleDetail = new ExternalAccessUserRoleDetail(extRoles.getJSONObject(i).getString("name"),
3572 userRoleDetailList.add(userRoleDetail);
3575 addUserRolesInLocal(userRoleDetailList, user, cenAppRolesMap, currentCentralizedUserAppRolesMap,
3576 centralisedAppsMap);
3580 private void addUserRolesInLocal(List<ExternalAccessUserRoleDetail> userRoleDetailList, EPUser user,
3581 HashMap<String, CentralizedAppRoles> cenAppRolesMap,
3582 HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap,
3583 HashMap<String, EPApp> centralisedAppsMap) {
3584 for (ExternalAccessUserRoleDetail extUserRoleDetail : userRoleDetailList) {
3586 // check if user already has role in local
3587 if (!currentCentralizedUserAppRolesMap.containsKey(extUserRoleDetail.getName())) {
3588 CentralizedAppRoles getCenAppRole = cenAppRolesMap.get(extUserRoleDetail.getName());
3589 if (getCenAppRole != null) {
3590 logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Adding user role from external auth system {}",
3591 extUserRoleDetail.toString());
3592 EPUserApp userApp = new EPUserApp();
3593 EPApp app = new EPApp();
3594 app.setId(getCenAppRole.getAppId());
3595 EPRole epRole = new EPRole();
3596 epRole.setId(getCenAppRole.getRoleId());
3597 userApp.setApp(app);
3598 userApp.setUserId(user.getId());
3599 userApp.setRole(epRole);
3600 dataAccessService.saveDomainObject(userApp, null);
3601 logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Finished user role from external auth system {}",
3602 extUserRoleDetail.toString());
3603 } else if (getCenAppRole == null // check if user has app account admin role
3604 && extUserRoleDetail.getName().endsWith(PortalConstants.ADMIN_ROLE.replaceAll(
3605 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
3606 EPApp app = centralisedAppsMap.get(extUserRoleDetail.getName());
3608 logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Adding user role from external auth system {}",
3609 extUserRoleDetail.toString());
3610 EPUserApp userApp = new EPUserApp();
3611 EPRole epRole = new EPRole();
3612 epRole.setId(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
3613 userApp.setApp(app);
3614 userApp.setUserId(user.getId());
3615 userApp.setRole(epRole);
3616 dataAccessService.saveDomainObject(userApp, null);
3617 logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Finished user role from external auth system {}",
3618 extUserRoleDetail.toString());
3622 } catch (Exception e) {
3623 logger.error(EELFLoggerDelegate.errorLogger,
3624 "addUserRolesInLocal - Failed to update user role in local from external auth system {} ",
3625 extUserRoleDetail.toString(), e);
3630 @SuppressWarnings("unchecked")
3631 private HashMap<String, EPApp> getCentralizedAdminAppsInfo() {
3632 List<EPApp> centralizedApps = dataAccessService
3633 .executeNamedQuery("getCentralizedApps", null, null);
3634 HashMap<String, EPApp> centralisedAppsMap = new HashMap<>();
3635 for (EPApp cenApp : centralizedApps) {
3636 centralisedAppsMap.put(cenApp.getNameSpace()+ "." +
3637 PortalConstants.ADMIN_ROLE.replaceAll(
3638 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), cenApp);
3640 return centralisedAppsMap;
3643 private HashMap<String, CentralizedAppRoles> getCurrentUserCentralizedAppRoles(
3644 List<CentralizedAppRoles> currentUserAppRoles) {
3645 HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap = new HashMap<>();
3646 for (CentralizedAppRoles cenAppUserRole : currentUserAppRoles) {
3647 currentCentralizedUserAppRolesMap.put(
3648 cenAppUserRole.getAppNameSpace() + "." + cenAppUserRole.getRoleName()
3649 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
3652 return currentCentralizedUserAppRolesMap;
3655 @SuppressWarnings("unchecked")
3656 private HashMap<String, CentralizedAppRoles> getCentralizedAppRoleList() {
3657 List<CentralizedAppRoles> centralizedAppRoles = dataAccessService
3658 .executeNamedQuery("getAllCentralizedAppsRoles", null, null);
3659 HashMap<String, CentralizedAppRoles> cenAppRolesMap = new HashMap<>();
3660 for (CentralizedAppRoles CentralizedAppRole : centralizedAppRoles) {
3662 CentralizedAppRole.getAppNameSpace() + "." + CentralizedAppRole.getRoleName()
3663 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
3664 CentralizedAppRole);
3666 return cenAppRolesMap;
3670 public ResponseEntity<String> getUserRolesFromExtAuthSystem(String name, HttpEntity<String> getUserRolesEntity) {
3671 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles");
3672 ResponseEntity<String> getResponse = template
3673 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
3674 + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class);
3675 if (getResponse.getStatusCode().value() == 200) {
3676 logger.debug(EELFLoggerDelegate.debugLogger, "getAllUserRoleFromExtAuthSystem: Finished GET user roles from external system and received user roles {}",
3677 getResponse.getBody());
3680 logger.error(EELFLoggerDelegate.errorLogger, "getAllUserRoleFromExtAuthSystem: Failed GET user roles from external system and received user roles {}",getResponse.getBody() );
3681 EPLogUtil.logExternalAuthAccessAlarm(logger, getResponse.getStatusCode());