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.stream.Collectors;
52 import org.apache.commons.codec.DecoderException;
53 import org.hibernate.Query;
54 import org.hibernate.Session;
55 import org.hibernate.SessionFactory;
56 import org.hibernate.Transaction;
57 import org.hibernate.criterion.Criterion;
58 import org.hibernate.criterion.Restrictions;
59 import org.json.JSONArray;
60 import org.json.JSONObject;
61 import org.onap.portalapp.portal.domain.CentralV2RoleFunction;
62 import org.onap.portalapp.portal.domain.CentralizedApp;
63 import org.onap.portalapp.portal.domain.EPApp;
64 import org.onap.portalapp.portal.domain.EPAppRoleFunction;
65 import org.onap.portalapp.portal.domain.EPRole;
66 import org.onap.portalapp.portal.domain.EPUser;
67 import org.onap.portalapp.portal.domain.EPUserApp;
68 import org.onap.portalapp.portal.domain.ExternalRoleDetails;
69 import org.onap.portalapp.portal.ecomp.model.UploadRoleFunctionExtSystem;
70 import org.onap.portalapp.portal.exceptions.DeleteDomainObjectFailedException;
71 import org.onap.portalapp.portal.exceptions.ExternalAuthSystemException;
72 import org.onap.portalapp.portal.exceptions.InactiveApplicationException;
73 import org.onap.portalapp.portal.exceptions.InvalidApplicationException;
74 import org.onap.portalapp.portal.exceptions.InvalidUserException;
75 import org.onap.portalapp.portal.exceptions.RoleFunctionException;
76 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
77 import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
78 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
79 import org.onap.portalapp.portal.transport.*;
80 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
81 import org.onap.portalapp.portal.utils.EcompPortalUtils;
82 import org.onap.portalapp.portal.utils.PortalConstants;
83 import org.onap.portalapp.util.EPUserUtils;
84 import org.onap.portalsdk.core.domain.Role;
85 import org.onap.portalsdk.core.domain.RoleFunction;
86 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
87 import org.onap.portalsdk.core.restful.domain.EcompRole;
88 import org.onap.portalsdk.core.restful.domain.EcompRoleFunction;
89 import org.onap.portalsdk.core.restful.domain.EcompUser;
90 import org.onap.portalsdk.core.service.DataAccessService;
91 import org.onap.portalsdk.core.util.SystemProperties;
92 import org.springframework.beans.factory.annotation.Autowired;
93 import org.springframework.context.annotation.EnableAspectJAutoProxy;
94 import org.springframework.http.HttpEntity;
95 import org.springframework.http.HttpHeaders;
96 import org.springframework.http.HttpMethod;
97 import org.springframework.http.HttpStatus;
98 import org.springframework.http.ResponseEntity;
99 import org.springframework.stereotype.Service;
100 import org.springframework.transaction.annotation.Transactional;
101 import org.springframework.web.client.HttpClientErrorException;
102 import org.springframework.web.client.RestTemplate;
104 import com.fasterxml.jackson.core.JsonProcessingException;
105 import com.fasterxml.jackson.databind.DeserializationFeature;
106 import com.fasterxml.jackson.databind.ObjectMapper;
107 import com.fasterxml.jackson.databind.type.TypeFactory;
109 @Service("externalAccessRolesService")
110 @EnableAspectJAutoProxy
113 public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesService {
114 private static final String APP_ROLE_NAME_PARAM = "appRoleName";
115 private static final String GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM = "getRoletoUpdateInExternalAuthSystem";
116 private static final String GET_PORTAL_APP_ROLES_QUERY = "getPortalAppRoles";
117 private static final String GET_ROLE_FUNCTION_QUERY = "getRoleFunction";
118 private static final String FUNCTION_CODE_PARAMS = "functionCode";
119 private static final String AND_FUNCTION_CD_EQUALS = " and function_cd = '";
120 private static final String OWNER = ".owner";
121 private static final String ADMIN = ".admin";
122 private static final String ACCOUNT_ADMINISTRATOR = ".Account_Administrator";
123 private static final String FUNCTION_PIPE = "|";
124 private static final String EXTERNAL_AUTH_PERMS = "perms";
125 private static final String EXTERNAL_AUTH_ROLE_DESCRIPTION = "description";
126 private static final String IS_EMPTY_JSON_STRING = "{}";
127 private static final String CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE = "Connecting to External Auth system";
128 private static final String APP_ID = "appId";
129 private static final String ROLE_NAME = "name";
130 private static final String APP_ID_EQUALS = " app_id = ";
131 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesServiceImpl.class);
133 private DataAccessService dataAccessService;
135 private EPAppService epAppService;
137 private SessionFactory sessionFactory;
139 EPRoleService ePRoleService;
140 RestTemplate template = new RestTemplate();
141 // These decode values are based on HexDecoder
142 static final String decodeValueOfForwardSlash = "2f";
143 static final String decodeValueOfHiphen = "2d";
144 static final String decodeValueOfStar = "2a";
146 @SuppressWarnings("unchecked")
148 public List<EPRole> getAppRoles(Long appId) throws Exception {
149 List<EPRole> applicationRoles = null;
150 final Map<String, Long> appParams = new HashMap<>();
153 applicationRoles = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
155 appParams.put("appId", appId);
156 applicationRoles = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
158 } catch (Exception e) {
159 logger.error(EELFLoggerDelegate.errorLogger, "getAppRoles: failed", e);
162 return applicationRoles;
165 @SuppressWarnings("unchecked")
167 public List<EPApp> getApp(String uebkey) throws Exception {
168 List<EPApp> app = null;
170 final Map<String, String> appUebkeyParams = new HashMap<>();
171 appUebkeyParams.put("appKey", uebkey);
172 app = dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null);
173 if (!app.isEmpty() && !app.get(0).getEnabled()
174 && !app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
175 throw new InactiveApplicationException("Application:" + app.get(0).getName() + " is Unavailable");
177 } catch (Exception e) {
178 logger.error(EELFLoggerDelegate.errorLogger, "getApp: failed", e);
185 * It returns single application role from external auth system
189 * @return JSON string which contains application role details
192 private String getSingleAppRole(String addRole, EPApp app) throws Exception {
193 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
194 HttpEntity<String> entity = new HttpEntity<>(headers);
195 ResponseEntity<String> response = null;
196 logger.debug(EELFLoggerDelegate.debugLogger, "getSingleAppRole: Connecting to External Auth system");
197 response = template.exchange(
198 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
199 + app.getNameSpace() + "." + addRole
200 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
201 HttpMethod.GET, entity, String.class);
202 logger.debug(EELFLoggerDelegate.debugLogger,
203 "getSingleAppRole: Finished GET app role from External Auth system and status code: {} ",
204 response.getStatusCode().value());
205 return response.getBody();
209 public boolean addRole(Role addRole, String uebkey) throws Exception {
210 boolean response = false;
211 ResponseEntity<String> addResponse = null;
212 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
213 EPApp app = getApp(uebkey).get(0);
214 String newRole = updateExistingRoleInExternalSystem(addRole, app);
215 HttpEntity<String> entity = new HttpEntity<>(newRole, headers);
216 logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Connecting to External Auth system");
217 addResponse = template.exchange(
218 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
219 HttpMethod.POST, entity, String.class);
220 if (addResponse.getStatusCode().value() == 201) {
222 logger.debug(EELFLoggerDelegate.debugLogger,
223 "addRole: Finished adding role in the External Auth system and response code: {} ",
224 addResponse.getStatusCode().value());
226 if (addResponse.getStatusCode().value() == 406) {
227 logger.error(EELFLoggerDelegate.errorLogger,
228 "addRole: Failed to add in the External Auth system due to {} and status code: {}",
229 addResponse.getBody(), addResponse.getStatusCode().value());
236 * It deletes record in external auth system
239 * @return JSON String which has status code and response body
242 private ResponseEntity<String> deleteRoleInExternalSystem(String delRole) throws Exception {
243 ResponseEntity<String> delResponse = null;
244 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
245 HttpEntity<String> entity = new HttpEntity<>(delRole, headers);
246 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: {} for DELETE: {}",
247 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, delRole);
248 delResponse = template.exchange(
249 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role?force=true",
250 HttpMethod.DELETE, entity, String.class);
251 logger.debug(EELFLoggerDelegate.debugLogger,
252 "deleteRoleInExternalSystem: Finished DELETE operation in the External Auth system {} and status code: {} ",
253 delRole, delResponse.getStatusCode().value());
258 * It updates role in external auth system
260 * @param updateExtRole
262 * @return true if success else false
263 * @throws Exception If updateRoleInExternalSystem fails we catch it in logger
266 private boolean updateRoleInExternalSystem(Role updateExtRole, EPApp app, boolean isGlobalRole) throws Exception {
267 boolean response = false;
268 ObjectMapper mapper = new ObjectMapper();
269 ResponseEntity<String> deleteResponse = null;
270 List<EPRole> epRoleList = null;
271 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)
272 || (isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
273 epRoleList = getPortalAppRoleInfo(updateExtRole.getId());
275 epRoleList = getPartnerAppRoleInfo(updateExtRole.getId(), app);
277 // Assigning functions to global role
278 if ((isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
279 List<RoleFunction> globalRoleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole);
280 EPApp portalAppInfo = epAppService.getApp(PortalConstants.PORTAL_APP_ID);
281 addFunctionsTOGlobalRole(epRoleList, updateExtRole, globalRoleFunctionListNew, mapper, app, portalAppInfo);
284 String appRole = getSingleAppRole(epRoleList.get(0).getName(), app);
285 List<RoleFunction> roleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole);
286 if (!appRole.equals(IS_EMPTY_JSON_STRING)) {
287 JSONObject jsonObj = new JSONObject(appRole);
288 JSONArray extRole = jsonObj.getJSONArray("role");
289 if (!extRole.getJSONObject(0).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
290 String roleName = extRole.getJSONObject(0).getString(ROLE_NAME);
291 Map<String, String> delRoleKeyMapper = new HashMap<>();
292 delRoleKeyMapper.put(ROLE_NAME, roleName);
293 String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
294 deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
295 if (deleteResponse.getStatusCode().value() != 200) {
296 throw new ExternalAuthSystemException(deleteResponse.getBody());
298 addRole(updateExtRole, app.getUebKey());
300 String desc = extRole.getJSONObject(0).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
301 String name = extRole.getJSONObject(0).getString(ROLE_NAME);
302 List<ExternalAccessPerms> list = new ArrayList<>();
303 if (extRole.getJSONObject(0).has(EXTERNAL_AUTH_PERMS)) {
304 JSONArray perms = extRole.getJSONObject(0).getJSONArray(EXTERNAL_AUTH_PERMS);
305 list = mapper.readValue(perms.toString(), TypeFactory.defaultInstance()
306 .constructCollectionType(List.class, ExternalAccessPerms.class));
308 // If role name or role functions are updated then delete
309 // record in External System and add new record to avoid
311 boolean isRoleNameChanged = false;
312 if (!desc.equals(updateExtRole.getName())) {
313 isRoleNameChanged = true;
314 deleteRoleInExtSystem(mapper, name);
315 addRole(updateExtRole, app.getUebKey());
316 // add partner functions to the global role in External
318 if (!list.isEmpty() && isGlobalRole) {
319 addPartnerHasRoleFunctionsToGlobalRole(list, mapper, app, updateExtRole);
322 perm -> EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace()));
323 // if role name is changes please ignore the previous
324 // functions in External Auth
325 // and update with user requested functions
326 addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name, list);
328 // Delete role in External System if role is inactive
329 if (!updateExtRole.getActive()) {
330 deleteRoleInExtSystem(mapper, name);
332 if (!isRoleNameChanged) {
333 response = addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name,
338 // It seems like role exists in local DB but not in External
340 if (updateExtRole.getActive()) {
341 addRole(updateExtRole, app.getUebKey());
342 ExternalAccessRolePerms extAddRolePerms = null;
343 ExternalAccessPerms extAddPerms = null;
344 List<RoleFunction> roleFunctionListAdd = convertSetToListOfRoleFunctions(updateExtRole);
345 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
346 for (RoleFunction roleFunc : roleFunctionListAdd) {
347 extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + roleFunc.getType(),
348 roleFunc.getCode(), roleFunc.getAction());
349 extAddRolePerms = new ExternalAccessRolePerms(extAddPerms,
350 app.getNameSpace() + "." + updateExtRole.getName().replaceAll(
351 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
352 response = addRoleFuncExtSysRestAPI(mapper, extAddRolePerms, headers);
360 private void deleteRoleInExtSystem(ObjectMapper mapper, String name)
361 throws JsonProcessingException, Exception, ExternalAuthSystemException {
362 ResponseEntity<String> deleteResponse;
363 Map<String, String> delRoleKeyMapper = new HashMap<>();
364 delRoleKeyMapper.put(ROLE_NAME, name);
365 String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
366 deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
367 if (deleteResponse.getStatusCode().value() != 200) {
368 logger.error(EELFLoggerDelegate.errorLogger,
369 "updateRoleInExternalSystem: Failed to delete role in external system due to {} ",
370 deleteResponse.getBody());
371 throw new ExternalAuthSystemException(deleteResponse.getBody());
375 private boolean addRemoveFunctionsToRole(Role updateExtRole, EPApp app, ObjectMapper mapper,
376 List<RoleFunction> roleFunctionListNew, String name, List<ExternalAccessPerms> list) throws Exception {
378 Map<String, RoleFunction> updateRoleFunc = new HashMap<>();
379 for (RoleFunction addPerm : roleFunctionListNew) {
380 updateRoleFunc.put(addPerm.getCode(), addPerm);
382 final Map<String, ExternalAccessPerms> extRolePermMap = new HashMap<>();
383 final Map<String, ExternalAccessPerms> extRolePermMapPipes = new HashMap<>();
384 list.removeIf(perm -> !EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace()));
385 // Update permissions in the ExternalAccess System
386 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
387 if (!list.isEmpty()) {
388 for (ExternalAccessPerms perm : list) {
389 RoleFunction roleFunc = updateRoleFunc.get(perm.getType().substring(app.getNameSpace().length() + 1)
390 + FUNCTION_PIPE + perm.getInstance() + FUNCTION_PIPE + perm.getAction());
391 if (roleFunc == null) {
392 RoleFunction roleFuncPipeFilter = updateRoleFunc.get(perm.getInstance());
393 if (roleFuncPipeFilter == null)
394 removePermForRole(perm, mapper, name, headers);
396 extRolePermMap.put(perm.getInstance(), perm);
397 extRolePermMapPipes.put(perm.getType().substring(app.getNameSpace().length() + 1) + FUNCTION_PIPE
398 + perm.getInstance() + FUNCTION_PIPE + perm.getAction(), perm);
402 if (!roleFunctionListNew.isEmpty()) {
403 for (RoleFunction roleFunc : roleFunctionListNew) {
404 if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
405 ExternalAccessPerms perm = extRolePermMapPipes.get(roleFunc.getCode());
407 response = addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers,
411 if (!extRolePermMap.containsKey(EcompPortalUtils.getFunctionCode(roleFunc.getCode()))) {
412 response = addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers,
422 * Adds function to the role in the external auth system while editing a role or
423 * updating new functions to a role
426 private boolean addFunctionsToRoleInExternalAuthSystem(Role updateExtRole, EPApp app, ObjectMapper mapper,
427 HttpHeaders headers, RoleFunction roleFunc) throws JsonProcessingException {
429 ExternalAccessRolePerms extRolePerms;
430 ExternalAccessPerms extPerms;
434 if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
435 code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
436 type = EcompPortalUtils.getFunctionType(roleFunc.getCode());
437 action = getFunctionCodeAction(roleFunc.getCode());
439 code = roleFunc.getCode();
440 type = roleFunc.getCode().contains("menu") ? "menu" : "url";
443 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, code, action);
444 extRolePerms = new ExternalAccessRolePerms(extPerms, app.getNameSpace() + "." + updateExtRole.getName()
445 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
446 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
447 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
448 logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: {} for POST: {}",
449 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
450 ResponseEntity<String> addResponse = template.exchange(
451 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
452 HttpMethod.POST, entity, String.class);
453 if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 409) {
455 logger.debug(EELFLoggerDelegate.debugLogger,
456 "updateRoleInExternalSystem: Connected to External Auth system but something went wrong! due to {} and statuscode: {}",
457 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
460 logger.debug(EELFLoggerDelegate.debugLogger,
461 "updateRoleInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ",
462 updateRolePerms, addResponse.getStatusCode().value());
467 private void addPartnerHasRoleFunctionsToGlobalRole(List<ExternalAccessPerms> permslist, ObjectMapper mapper,
468 EPApp app, Role updateExtRole) throws Exception {
469 for (ExternalAccessPerms perm : permslist) {
470 if (!EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace())) {
471 ExternalAccessRolePerms extAddGlobalRolePerms = null;
472 ExternalAccessPerms extAddPerms = null;
473 extAddPerms = new ExternalAccessPerms(perm.getType(), perm.getInstance(), perm.getAction());
474 extAddGlobalRolePerms = new ExternalAccessRolePerms(extAddPerms,
475 app.getNameSpace() + "." + updateExtRole.getName().replaceAll(
476 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
477 String addPerms = mapper.writeValueAsString(extAddGlobalRolePerms);
478 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
479 HttpEntity<String> entity = new HttpEntity<>(addPerms, headers);
480 logger.debug(EELFLoggerDelegate.debugLogger, "addPartnerHasRoleFunctionsToGlobalRole: {} ",
481 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
483 ResponseEntity<String> addResponse = template
484 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
485 + "role/perm", HttpMethod.POST, entity, String.class);
486 if (addResponse.getStatusCode().value() != 201) {
487 logger.debug(EELFLoggerDelegate.debugLogger,
488 "addPartnerHasRoleFunctionsToGlobalRole: While adding permission to the role in External Auth system something went wrong! due to {} and statuscode: {}",
489 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
491 logger.debug(EELFLoggerDelegate.debugLogger,
492 "addPartnerHasRoleFunctionsToGlobalRole: Finished adding permissions to roles in External Auth system and status code: {} ",
493 addResponse.getStatusCode().value());
495 } catch (Exception e) {
496 logger.error(EELFLoggerDelegate.errorLogger,
497 "addPartnerHasRoleFunctionsToGlobalRole: Failed for POST request: {} due to ", addPerms, e);
503 @SuppressWarnings("unchecked")
504 private void addFunctionsTOGlobalRole(List<EPRole> epRoleList, Role updateExtRole,
505 List<RoleFunction> roleFunctionListNew, ObjectMapper mapper, EPApp app, EPApp portalAppInfo)
508 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addFunctionsTOGlobalRole");
509 // GET Permissions from External Auth System
510 JSONArray extPerms = getExtAuthPermissions(app);
511 List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);
512 final Map<String, ExternalAccessPermsDetail> existingPermsWithRoles = new HashMap<>();
513 final Map<String, ExternalAccessPermsDetail> existingPermsWithRolesWithPipes = new HashMap<>();
514 final Map<String, RoleFunction> userRquestedFunctionsMap = new HashMap<>();
515 final Map<String, RoleFunction> userRquestedFunctionsMapPipesFilter = new HashMap<>();
516 for (ExternalAccessPermsDetail permDetail : permsDetailList) {
517 existingPermsWithRoles.put(EcompPortalUtils.getFunctionCode(permDetail.getInstance()), permDetail);
518 existingPermsWithRolesWithPipes.put(permDetail.getInstance(), permDetail);
520 // Add If function does not exists for role in External Auth System
521 for (RoleFunction roleFunc : roleFunctionListNew) {
522 String roleFuncCode = "";
523 ExternalAccessPermsDetail permsDetail;
524 if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
525 roleFuncCode = roleFunc.getCode();
526 permsDetail = existingPermsWithRolesWithPipes.get(roleFunc.getCode());
528 roleFuncCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
529 permsDetail = existingPermsWithRoles.get(roleFuncCode);
531 if (null == permsDetail.getRoles()
532 || !permsDetail.getRoles()
533 .contains(portalAppInfo.getNameSpace() + FUNCTION_PIPE
534 + epRoleList.get(0).getName().replaceAll(
535 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
537 addRoleFunctionsToGlobalRoleInExternalSystem(roleFunc, updateExtRole, mapper, app, portalAppInfo);
539 userRquestedFunctionsMap.put(roleFuncCode, roleFunc);
540 userRquestedFunctionsMapPipesFilter.put(EcompPortalUtils.getFunctionCode(roleFuncCode), roleFunc);
542 // Delete functions if exists in External Auth System but not in
545 final Map<String, Long> epAppRoleFuncParams = new HashMap<>();
546 epAppRoleFuncParams.put("requestedAppId", app.getId());
547 epAppRoleFuncParams.put("roleId", updateExtRole.getId());
548 List<GlobalRoleWithApplicationRoleFunction> globalRoleFunctionList = dataAccessService
549 .executeNamedQuery("getGlobalRoleForRequestedApp", epAppRoleFuncParams, null);
550 for (GlobalRoleWithApplicationRoleFunction globalRoleFunc : globalRoleFunctionList) {
551 String globalRoleFuncWithoutPipes = "";
552 RoleFunction roleFunc = null;
553 if (globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
554 globalRoleFuncWithoutPipes = globalRoleFunc.getFunctionCd();
555 roleFunc = userRquestedFunctionsMap.get(globalRoleFuncWithoutPipes);
557 globalRoleFuncWithoutPipes = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd());
558 roleFunc = userRquestedFunctionsMapPipesFilter.get(globalRoleFuncWithoutPipes);
560 if (roleFunc == null) {
561 ExternalAccessPermsDetail permDetailFromMap = globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)
562 ? existingPermsWithRolesWithPipes.get(globalRoleFuncWithoutPipes)
563 : existingPermsWithRoles.get(globalRoleFuncWithoutPipes);
564 ExternalAccessPerms perm = new ExternalAccessPerms(permDetailFromMap.getType(),
565 EcompPortalUtils.getFunctionCode(permDetailFromMap.getInstance()),
566 permDetailFromMap.getAction());
567 String roleName = portalAppInfo.getNameSpace() + "." + globalRoleFunc.getRoleName()
568 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_");
569 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
570 removePermForRole(perm, mapper, roleName, headers);
573 logger.debug(EELFLoggerDelegate.debugLogger, "Finished addFunctionsTOGlobalRole");
574 } catch (Exception e) {
575 logger.error(EELFLoggerDelegate.errorLogger, "addFunctionsTOGlobalRole: Failed", e);
580 private void addRoleFunctionsToGlobalRoleInExternalSystem(RoleFunction addFunction, Role globalRole,
581 ObjectMapper mapper, EPApp app, EPApp portalAppInfo) throws Exception {
583 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addRoleFunctionsToGlobalRoleInExternalSystem");
584 ExternalAccessRolePerms extAddRolePerms = null;
585 ExternalAccessPerms extAddPerms = null;
586 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
590 if (addFunction.getCode().contains(FUNCTION_PIPE)) {
591 code = EcompPortalUtils.getFunctionCode(addFunction.getCode());
592 type = getFunctionCodeType(addFunction.getCode());
593 action = getFunctionCodeAction(addFunction.getCode());
595 code = addFunction.getCode();
596 type = addFunction.getCode().contains("menu") ? "menu" : "url";
599 extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, code, action);
600 extAddRolePerms = new ExternalAccessRolePerms(extAddPerms, portalAppInfo.getNameSpace() + "." + globalRole
601 .getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
602 String updateRolePerms = mapper.writeValueAsString(extAddRolePerms);
603 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
604 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} ",
605 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
606 ResponseEntity<String> addResponse = template.exchange(
607 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
608 HttpMethod.POST, entity, String.class);
609 if (addResponse.getStatusCode().value() != 201) {
610 logger.debug(EELFLoggerDelegate.debugLogger,
611 "addRoleFunctionsInExternalSystem: While adding permission to the role in External Auth system something went wrong! due to {} and statuscode: {}",
612 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
614 logger.debug(EELFLoggerDelegate.debugLogger,
615 "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system and status code: {} ",
616 addResponse.getStatusCode().value());
618 logger.debug(EELFLoggerDelegate.debugLogger, "Finished addRoleFunctionsToGlobalRoleInExternalSystem");
619 } catch (Exception e) {
620 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionsToGlobalRoleInExternalSystem: Failed", e);
625 private boolean addRoleFuncExtSysRestAPI(ObjectMapper addPermsMapper, ExternalAccessRolePerms extAddRolePerms,
626 HttpHeaders headers) throws JsonProcessingException {
628 String updateRolePerms = addPermsMapper.writeValueAsString(extAddRolePerms);
629 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
630 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} for POST: {} ",
631 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
632 ResponseEntity<String> addResponse = template.exchange(
633 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
634 HttpMethod.POST, entity, String.class);
635 if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 409) {
637 logger.debug(EELFLoggerDelegate.debugLogger,
638 "addRoleFunctionsInExternalSystem: While adding permission to the role in External Auth system something went wrong! due to {} and statuscode: {}",
639 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
642 logger.debug(EELFLoggerDelegate.debugLogger,
643 "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ",
644 updateRolePerms, addResponse.getStatusCode().value());
651 * It converts list of functions in updateExtRole parameter to the RoleFunction
654 * @param updateExtRole
655 * @return list of functions
657 @SuppressWarnings("unchecked")
658 private List<RoleFunction> convertSetToListOfRoleFunctions(Role updateExtRole) {
659 Set<RoleFunction> roleFunctionSetList = updateExtRole.getRoleFunctions();
660 List<RoleFunction> roleFunctionList = new ArrayList<>();
661 ObjectMapper roleFuncMapper = new ObjectMapper();
662 Iterator<RoleFunction> itetaror = roleFunctionSetList.iterator();
663 while (itetaror.hasNext()) {
664 Object nextValue = itetaror.next();
665 RoleFunction roleFunction = roleFuncMapper.convertValue(nextValue, RoleFunction.class);
666 roleFunctionList.add(roleFunction);
668 return roleFunctionList.stream().distinct().collect(Collectors.toList());
672 * It delete permissions/functions in the external auth system
678 * @throws JsonProcessingException
681 private void removePermForRole(ExternalAccessPerms perm, ObjectMapper permMapper, String name, HttpHeaders headers)
682 throws ExternalAuthSystemException, JsonProcessingException {
683 ExternalAccessRolePerms extAccessRolePerms = new ExternalAccessRolePerms(perm, name);
684 String permDetails = permMapper.writeValueAsString(extAccessRolePerms);
686 HttpEntity<String> deleteEntity = new HttpEntity<>(permDetails, headers);
687 logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: {} for DELETE: {} ",
688 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, permDetails);
689 ResponseEntity<String> deletePermResponse = template
690 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
691 + "role/" + name + "/perm", HttpMethod.DELETE, deleteEntity, String.class);
692 if (deletePermResponse.getStatusCode().value() != 200) {
693 throw new ExternalAuthSystemException(deletePermResponse.getBody());
695 logger.debug(EELFLoggerDelegate.debugLogger,
696 "removePermForRole: Finished deleting permission to role in External Auth system: {} and status code: {}",
697 permDetails, deletePermResponse.getStatusCode().value());
698 } catch (Exception e) {
699 if (e.getMessage().contains("404")) {
700 logger.error(EELFLoggerDelegate.errorLogger, "Failed to add role for DELETE request: {} due to {}",
701 permDetails, e.getMessage());
709 * It will create new role in the External Auth System
713 * @return true if successfully added in the system else false
714 * @throws Exception If fails to add role in the system
716 private void addNewRoleInExternalSystem(List<EPRole> newRole, EPApp app)
717 throws Exception, HttpClientErrorException {
719 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
720 ObjectMapper mapper = new ObjectMapper();
721 String addNewRole = "";
722 ExternalAccessRole extRole = new ExternalAccessRole();
723 extRole.setName(app.getNameSpace() + "." + newRole.get(0).getName()
724 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
725 extRole.setDescription(String.valueOf(newRole.get(0).getName()));
726 addNewRole = mapper.writeValueAsString(extRole);
727 HttpEntity<String> postEntity = new HttpEntity<>(addNewRole, headers);
728 logger.debug(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: {} for POST: {} ",
729 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addNewRole);
730 ResponseEntity<String> addNewRoleInExternalSystem = template.exchange(
731 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
732 HttpMethod.POST, postEntity, String.class);
733 if (addNewRoleInExternalSystem.getStatusCode().value() == 201) {
734 logger.debug(EELFLoggerDelegate.debugLogger,
735 "addNewRoleInExternalSystem: Finished adding into External Auth system for POST: {} and status code: {}",
736 addNewRole, addNewRoleInExternalSystem.getStatusCode().value());
738 } catch (HttpClientErrorException ht) {
739 dataAccessService.deleteDomainObjects(EPRole.class, " role_id = " + newRole.get(0).getId(), null);
740 logger.error(EELFLoggerDelegate.debugLogger,
741 "addNewRoleInExternalSystem: Failed to add in External Auth system and status code: {}", ht);
742 throw new HttpClientErrorException(ht.getStatusCode());
748 * It updates existing role in the External Auth System
750 * @param addRole It Contains role information
752 * @return string which is formatted to match with the external auth system
753 * @throws JsonProcessingException
755 private String updateExistingRoleInExternalSystem(Role addRole, EPApp app) throws JsonProcessingException {
756 ObjectMapper mapper = new ObjectMapper();
757 String addNewRole = "";
758 ExternalAccessRole extRole = new ExternalAccessRole();
759 extRole.setName(app.getNameSpace() + "." + addRole.getName()
760 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
761 extRole.setDescription(String.valueOf(addRole.getName()));
762 addNewRole = mapper.writeValueAsString(extRole);
767 * It create a role in the external auth system and then in our local
771 * @return true else false
774 @SuppressWarnings("unchecked")
775 @Transactional(rollbackFor = Exception.class)
776 public boolean addRoleInEcompDB(Role addRoleInDB, EPApp app) throws Exception {
777 boolean result = false;
778 EPRole epRole = null;
779 Set<RoleFunction> roleFunctionList = addRoleInDB.getRoleFunctions();
780 List<RoleFunction> roleFunctionListNew = new ArrayList<>();
781 ObjectMapper mapper = new ObjectMapper();
782 Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
783 while (itetaror.hasNext()) {
784 Object nextValue = itetaror.next();
785 RoleFunction roleFunction = mapper.convertValue(nextValue, RoleFunction.class);
786 roleFunctionListNew.add(roleFunction);
788 List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct().collect(Collectors.toList());
790 if (addRoleInDB.getId() == null) { // check if it is new role
791 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
792 checkIfRoleExitsInExternalSystem(addRoleInDB, app);
794 EPRole epRoleNew = new EPRole();
795 epRoleNew.setActive(addRoleInDB.getActive());
796 epRoleNew.setName(addRoleInDB.getName());
797 epRoleNew.setPriority(addRoleInDB.getPriority());
798 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
799 epRoleNew.setAppId(null);
801 epRoleNew.setAppId(app.getId());
803 dataAccessService.saveDomainObject(epRoleNew, null);
804 List<EPRole> getRoleCreated = null;
805 final Map<String, String> epAppRoleParams = new HashMap<>();
806 final Map<String, String> epAppPortalRoleParams = new HashMap<>();
807 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
808 epAppRoleParams.put("appId", String.valueOf(app.getId()));
809 epAppRoleParams.put(APP_ROLE_NAME_PARAM, addRoleInDB.getName());
810 List<EPRole> roleCreated = dataAccessService
811 .executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, epAppRoleParams, null);
812 EPRole epUpdateRole = roleCreated.get(0);
813 epUpdateRole.setAppRoleId(epUpdateRole.getId());
814 dataAccessService.saveDomainObject(epUpdateRole, null);
815 getRoleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
816 epAppRoleParams, null);
818 epAppPortalRoleParams.put(APP_ROLE_NAME_PARAM, addRoleInDB.getName());
819 getRoleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY,
820 epAppPortalRoleParams, null);
822 // Add role in External Auth system
823 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
824 addNewRoleInExternalSystem(getRoleCreated, app);
827 } else { // if role already exists then update it
828 EPRole globalRole = null;
829 List<EPRole> applicationRoles;
830 List<EPRole> globalRoleList = getGlobalRolesOfPortal();
831 boolean isGlobalRole = false;
832 if (!globalRoleList.isEmpty()) {
833 EPRole role = globalRoleList.stream().filter(x -> addRoleInDB.getId().equals(x.getId())).findAny()
840 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)
841 || (globalRole != null && app.getId() != globalRole.getAppId())) {
842 applicationRoles = getPortalAppRoleInfo(addRoleInDB.getId());
844 applicationRoles = getPartnerAppRoleInfo(addRoleInDB.getId(), app);
846 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
847 updateRoleInExternalSystem(addRoleInDB, app, isGlobalRole);
848 // Add all user to the re-named role in external auth system
849 if (!applicationRoles.isEmpty()
850 && !addRoleInDB.getName().equals(applicationRoles.get(0).getName())) {
851 bulkUploadUsersSingleRole(app.getUebKey(), applicationRoles.get(0).getId(),
852 addRoleInDB.getName());
855 deleteRoleFunction(app, applicationRoles);
856 if (!applicationRoles.isEmpty()) {
857 epRole = applicationRoles.get(0);
858 epRole.setName(addRoleInDB.getName());
859 epRole.setPriority(addRoleInDB.getPriority());
860 epRole.setActive(addRoleInDB.getActive());
861 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
862 epRole.setAppId(null);
863 epRole.setAppRoleId(null);
864 } else if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)
865 && applicationRoles.get(0).getAppRoleId() == null) {
866 epRole.setAppRoleId(epRole.getId());
868 dataAccessService.saveDomainObject(epRole, null);
870 Long roleAppId = null;
871 if (globalRole != null && !app.getId().equals(globalRole.getAppId()))
872 roleAppId = PortalConstants.PORTAL_APP_ID;
873 saveRoleFunction(listWithoutDuplicates, app, applicationRoles, roleAppId);
876 } catch (Exception e) {
877 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInEcompDB is failed", e);
885 * It validates whether role exists in external auth system
889 * @throws Exception If role exits
891 private void checkIfRoleExitsInExternalSystem(Role checkRole, EPApp app) throws Exception {
892 getNameSpaceIfExists(app);
893 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
894 String roleName = app.getNameSpace() + "." + checkRole.getName()
895 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_");
896 HttpEntity<String> checkRoleEntity = new HttpEntity<>(headers);
897 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRoleExitsInExternalSystem: {} ",
898 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
899 ResponseEntity<String> checkRoleInExternalSystem = template
900 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
901 + roleName, HttpMethod.GET, checkRoleEntity, String.class);
902 if (!checkRoleInExternalSystem.getBody().equals(IS_EMPTY_JSON_STRING)) {
904 "checkIfRoleExitsInExternalSystem: Role already exists in external system {} and status code: {} ",
905 checkRoleInExternalSystem.getBody(), checkRoleInExternalSystem.getStatusCode().value());
906 throw new ExternalAuthSystemException(" Role already exists in external system");
911 * It saves list of functions to the role in portal
913 * @param roleFunctionListNew
915 * @param applicationRoles
918 @SuppressWarnings("unchecked")
919 private void saveRoleFunction(List<RoleFunction> roleFunctionListNew, EPApp app, List<EPRole> applicationRoles,
920 Long roleAppId) throws Exception {
921 final Map<String, String> getAppFunctionParams = new HashMap<>();
922 for (RoleFunction roleFunc : roleFunctionListNew) {
923 String code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
924 EPAppRoleFunction appRoleFunc = new EPAppRoleFunction();
925 appRoleFunc.setAppId(app.getId());
926 appRoleFunc.setRoleId(applicationRoles.get(0).getId());
927 appRoleFunc.setRoleAppId(String.valueOf(roleAppId));
928 getAppFunctionParams.put("appId", String.valueOf(app.getId()));
929 getAppFunctionParams.put(FUNCTION_CODE_PARAMS, roleFunc.getCode());
930 // query to check if function code has pipes
931 List<CentralV2RoleFunction> roleFunction = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY,
932 getAppFunctionParams, null);
933 if (roleFunction.isEmpty()) {
934 getAppFunctionParams.put(FUNCTION_CODE_PARAMS, code);
935 roleFunction = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null);
937 if (roleFunction.size() > 1) {
938 CentralV2RoleFunction getExactFunctionCode = appFunctionListFilter(code, roleFunction);
939 appRoleFunc.setCode(getExactFunctionCode.getCode());
941 appRoleFunc.setCode(roleFunction.get(0).getCode());
943 dataAccessService.saveDomainObject(appRoleFunc, null);
949 * It filters the app functions which starts with similar name in the result set
952 * @param roleFunction
953 * @return CentralRoleFunction
955 private CentralV2RoleFunction appFunctionListFilter(String roleFuncCode, List<CentralV2RoleFunction> roleFunction) {
956 final Map<String, CentralV2RoleFunction> appFunctionsFilter = new HashMap<>();
957 final Map<String, CentralV2RoleFunction> appFunctionsFilterPipes = new HashMap<>();
958 CentralV2RoleFunction getExactFunctionCode = null;
959 for (CentralV2RoleFunction cenRoleFunction : roleFunction) {
960 appFunctionsFilter.put(cenRoleFunction.getCode(), cenRoleFunction);
961 appFunctionsFilterPipes.put(EcompPortalUtils.getFunctionCode(cenRoleFunction.getCode()), cenRoleFunction);
963 getExactFunctionCode = appFunctionsFilter.get(roleFuncCode);
964 if (getExactFunctionCode == null) {
965 getExactFunctionCode = appFunctionsFilterPipes.get(roleFuncCode);
967 return getExactFunctionCode;
971 * It deletes all EPAppRoleFunction records in the portal
976 @SuppressWarnings("unchecked")
977 private void deleteRoleFunction(EPApp app, List<EPRole> role) {
978 final Map<String, Long> appRoleFuncsParams = new HashMap<>();
979 appRoleFuncsParams.put("appId", app.getId());
980 appRoleFuncsParams.put("roleId", role.get(0).getId());
981 List<EPAppRoleFunction> appRoleFunctionList = dataAccessService
982 .executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null);
983 if (!appRoleFunctionList.isEmpty()) {
984 for (EPAppRoleFunction approleFunction : appRoleFunctionList) {
985 dataAccessService.deleteDomainObject(approleFunction, null);
991 @SuppressWarnings("unchecked")
992 public List<EPUser> getUser(String loginId) throws InvalidUserException {
993 final Map<String, String> userParams = new HashMap<>();
994 userParams.put("org_user_id", loginId);
995 List<EPUser> userList = dataAccessService.executeNamedQuery("getEPUserByOrgUserId", userParams, null);
996 if (userList.isEmpty()) {
997 throw new InvalidUserException("User not found");
1003 public String getV2UserWithRoles(String loginId, String uebkey) throws Exception {
1004 final Map<String, String> params = new HashMap<>();
1005 List<EPUser> userList = null;
1006 CentralV2User cenV2User = null;
1007 String result = null;
1009 params.put("orgUserIdValue", loginId);
1010 List<EPApp> appList = getApp(uebkey);
1011 if (!appList.isEmpty()) {
1012 userList = getUser(loginId);
1013 if (!userList.isEmpty()) {
1014 ObjectMapper mapper = new ObjectMapper();
1015 cenV2User = getV2UserAppRoles(loginId, uebkey);
1016 result = mapper.writeValueAsString(cenV2User);
1017 } else if (userList.isEmpty()) {
1018 throw new InvalidUserException("User not found");
1021 throw new InactiveApplicationException("Application not found");
1023 } catch (Exception e) {
1024 logger.error(EELFLoggerDelegate.errorLogger, "getUser: failed", e);
1031 public List<CentralV2Role> getRolesForApp(String uebkey) throws Exception {
1032 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Entering into getRolesForApp");
1033 List<CentralV2Role> roleList = new ArrayList<>();
1034 final Map<String, Long> params = new HashMap<>();
1036 List<EPApp> app = getApp(uebkey);
1037 List<EPRole> appRolesList = getAppRoles(app.get(0).getId());
1038 roleList = createCentralRoleObject(app, appRolesList, roleList, params);
1039 if (app.get(0).getId() != PortalConstants.PORTAL_APP_ID) {
1040 List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
1041 List<EPRole> globalRolesList = getGlobalRolesOfPortal();
1042 List<CentralV2Role> portalsGlobalRolesFinlaList = new ArrayList<>();
1043 if (!globalRolesList.isEmpty()) {
1044 for (EPRole eprole : globalRolesList) {
1045 CentralV2Role cenRole = convertRoleToCentralV2Role(eprole);
1046 portalsGlobalRolesFinlaList.add(cenRole);
1048 roleList.addAll(globalRoleList);
1049 for (CentralV2Role role : portalsGlobalRolesFinlaList) {
1050 CentralV2Role result = roleList.stream().filter(x -> role.getId().equals(x.getId())).findAny()
1056 for (EPRole role : globalRolesList) {
1057 CentralV2Role cenRole = convertRoleToCentralV2Role(role);
1058 roleList.add(cenRole);
1062 } catch (Exception e) {
1063 logger.error(EELFLoggerDelegate.errorLogger, "getRolesForApp: Failed!", e);
1066 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Finished!");
1067 return roleList.stream().distinct().collect(Collectors.toList());
1070 @SuppressWarnings("unchecked")
1072 public List<CentralV2RoleFunction> getRoleFuncList(String uebkey) throws Exception {
1073 EPApp app = getApp(uebkey).get(0);
1074 List<CentralV2RoleFunction> finalRoleList = new ArrayList<>();
1075 final Map<String, Long> params = new HashMap<>();
1076 params.put(APP_ID, app.getId());
1077 List<CentralV2RoleFunction> getRoleFuncList = dataAccessService.executeNamedQuery("getAllRoleFunctions", params,
1079 for (CentralV2RoleFunction roleFuncItem : getRoleFuncList) {
1080 String code = EcompPortalUtils.getFunctionCode(roleFuncItem.getCode());
1082 if (roleFuncItem.getCode().contains("|"))
1083 type = EcompPortalUtils.getFunctionType(roleFuncItem.getCode());
1085 type = getFunctionCodeType(roleFuncItem.getCode());
1086 String action = getFunctionCodeAction(roleFuncItem.getCode());
1087 roleFuncItem.setCode(EPUserUtils.decodeFunctionCode(code));
1088 roleFuncItem.setType(type);
1089 roleFuncItem.setAction(action);
1090 finalRoleList.add(roleFuncItem);
1092 return finalRoleList;
1096 public String getFunctionCodeAction(String roleFuncItem) {
1097 return (!roleFuncItem.contains(FUNCTION_PIPE)) ? "*" : EcompPortalUtils.getFunctionAction(roleFuncItem);
1101 public String getFunctionCodeType(String roleFuncItem) {
1103 if ((roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))
1104 || (!roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))) {
1106 } else if (checkIfCodeHasNoPipesAndHasTypeUrl(roleFuncItem) || checkIfCodeHasPipesAndHasTypeUrl(roleFuncItem)
1107 || checkIfCodeHasNoPipesAndHasNoTypeUrl(roleFuncItem)) {
1109 } else if (roleFuncItem.contains(FUNCTION_PIPE)
1110 && (!roleFuncItem.contains("menu") || roleFuncItem.contains("url"))) {
1111 type = EcompPortalUtils.getFunctionType(roleFuncItem);
1118 * It check whether function code has no pipes and no url string in it
1120 * @param roleFuncItem
1121 * @return true or false
1123 private boolean checkIfCodeHasNoPipesAndHasNoTypeUrl(String roleFuncItem) {
1124 return !roleFuncItem.contains(FUNCTION_PIPE) && !roleFuncItem.contains("url");
1129 * It check whether function code has pipes and url string in it
1131 * @param roleFuncItem
1132 * @return true or false
1134 private boolean checkIfCodeHasPipesAndHasTypeUrl(String roleFuncItem) {
1135 return roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
1140 * It check whether function code has no pipes and has url string in it
1142 * @param roleFuncItem
1143 * @return true or false
1145 private boolean checkIfCodeHasNoPipesAndHasTypeUrl(String roleFuncItem) {
1146 return !roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
1150 * It returns user detail information which is deep copy of EPUser.class object
1158 @SuppressWarnings("unchecked")
1159 private CentralV2User createEPUser(EPUser userInfo, Set<EPUserApp> userAppSet, EPApp app) throws Exception {
1160 final Map<String, Long> params = new HashMap<>();
1161 CentralV2User userAppList = new CentralV2User.CentralV2UserBuilder().createCentralV2User();
1162 CentralV2User user1 = null;
1163 final Map<String, Long> params1 = new HashMap<>();
1164 List<EPRole> globalRoleList = new ArrayList<>();
1166 if (app.getId() != PortalConstants.PORTAL_APP_ID) {
1167 params1.put("userId", userInfo.getId());
1168 params1.put("appId", app.getId());
1169 globalRoleList = dataAccessService.executeNamedQuery("userAppGlobalRoles", params1, null);
1171 userAppList.setUserApps(new TreeSet<CentralV2UserApp>());
1172 for (EPUserApp userApp : userAppSet) {
1173 if (userApp.getRole().getActive()) {
1174 EPApp epApp = userApp.getApp();
1175 String globalRole = userApp.getRole().getName().toLowerCase();
1176 if (((epApp.getId().equals(app.getId()))
1177 && (!userApp.getRole().getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)))
1178 || ((epApp.getId().equals(PortalConstants.PORTAL_APP_ID))
1179 && (globalRole.toLowerCase().startsWith("global_")))) {
1180 CentralV2UserApp cua = new CentralV2UserApp();
1181 cua.setUserId(null);
1182 CentralApp cenApp = new CentralApp(1L, epApp.getCreated(), epApp.getModified(),
1183 epApp.getCreatedId(), epApp.getModifiedId(), epApp.getRowNum(), epApp.getName(),
1184 epApp.getImageUrl(), epApp.getDescription(), epApp.getNotes(), epApp.getUrl(),
1185 epApp.getAlternateUrl(), epApp.getAppRestEndpoint(), epApp.getMlAppName(),
1186 epApp.getMlAppAdminId(), String.valueOf(epApp.getMotsId()), epApp.getAppPassword(),
1187 String.valueOf(epApp.getOpen()), String.valueOf(epApp.getEnabled()),
1188 epApp.getThumbnail(), epApp.getUsername(), epApp.getUebKey(), epApp.getUebSecret(),
1189 epApp.getUebTopicName());
1190 cenApp.setAppPassword(EPCommonSystemProperties.APP_DISPLAY_PASSWORD);
1193 if (globalRole.toLowerCase().startsWith("global_")
1194 && epApp.getId().equals(PortalConstants.PORTAL_APP_ID)
1195 && !epApp.getId().equals(app.getId())) {
1196 appId = app.getId();
1197 EPRole result = null;
1198 if (globalRoleList.size() > 0)
1199 result = globalRoleList.stream()
1200 .filter(x -> userApp.getRole().getId().equals(x.getId())).findAny()
1205 appId = userApp.getApp().getId();
1207 params.put("roleId", userApp.getRole().getId());
1208 params.put(APP_ID, appId);
1209 List<CentralV2RoleFunction> appRoleFunctionList = dataAccessService
1210 .executeNamedQuery("getAppRoleFunctionList", params, null);
1211 SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>();
1212 for (CentralV2RoleFunction roleFunc : appRoleFunctionList) {
1213 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1214 String type = getFunctionCodeType(roleFunc.getCode());
1215 String action = getFunctionCodeAction(roleFunc.getCode());
1216 CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(roleFunc.getId(),
1217 functionCode, roleFunc.getName(), null, type, action, null);
1218 roleFunctionSet.add(cenRoleFunc);
1220 Long userRoleId = null;
1221 if (globalRole.toLowerCase().startsWith("global_")
1222 || epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1223 userRoleId = userApp.getRole().getId();
1225 userRoleId = userApp.getRole().getAppRoleId();
1227 CentralV2Role cenRole = new CentralV2Role(userRoleId, userApp.getRole().getCreated(),
1228 userApp.getRole().getModified(), userApp.getRole().getCreatedId(),
1229 userApp.getRole().getModifiedId(), userApp.getRole().getRowNum(),
1230 userApp.getRole().getName(), userApp.getRole().getActive(),
1231 userApp.getRole().getPriority(), roleFunctionSet, null, null);
1232 cua.setRole(cenRole);
1233 userAppList.getUserApps().add(cua);
1237 user1 = new CentralV2User.CentralV2UserBuilder().setId(null).setCreated(userInfo.getCreated())
1238 .setModified(userInfo.getModified()).setCreatedId(userInfo.getCreatedId())
1239 .setModifiedId(userInfo.getModifiedId()).setRowNum(userInfo.getRowNum())
1240 .setOrgId(userInfo.getOrgId()).setManagerId(userInfo.getManagerId())
1241 .setFirstName(userInfo.getFirstName()).setMiddleInitial(userInfo.getMiddleInitial())
1242 .setLastName(userInfo.getLastName()).setPhone(userInfo.getPhone()).setFax(userInfo.getFax())
1243 .setCellular(userInfo.getCellular()).setEmail(userInfo.getEmail())
1244 .setAddressId(userInfo.getAddressId()).setAlertMethodCd(userInfo.getAlertMethodCd())
1245 .setHrid(userInfo.getHrid()).setOrgUserId(userInfo.getOrgUserId()).setOrgCode(userInfo.getOrgCode())
1246 .setAddress1(userInfo.getAddress1()).setAddress2(userInfo.getAddress2()).setCity(userInfo.getCity())
1247 .setState(userInfo.getState()).setZipCode(userInfo.getZipCode()).setCountry(userInfo.getCountry())
1248 .setOrgManagerUserId(userInfo.getOrgManagerUserId()).setLocationClli(userInfo.getLocationClli())
1249 .setBusinessCountryCode(userInfo.getBusinessCountryCode())
1250 .setBusinessCountryName(userInfo.getBusinessCountryName())
1251 .setBusinessUnit(userInfo.getBusinessUnit()).setBusinessUnitName(userInfo.getBusinessUnitName())
1252 .setDepartment(userInfo.getDepartment()).setDepartmentName(userInfo.getDepartmentName())
1253 .setCompanyCode(userInfo.getCompanyCode()).setCompany(userInfo.getCompany())
1254 .setZipCodeSuffix(userInfo.getZipCodeSuffix()).setJobTitle(userInfo.getJobTitle())
1255 .setCommandChain(userInfo.getCommandChain()).setSiloStatus(userInfo.getSiloStatus())
1256 .setCostCenter(userInfo.getCostCenter()).setFinancialLocCode(userInfo.getFinancialLocCode())
1257 .setLoginId(userInfo.getLoginId()).setLoginPwd(userInfo.getLoginPwd())
1258 .setLastLoginDate(userInfo.getLastLoginDate()).setActive(userInfo.getActive())
1259 .setInternal(userInfo.getInternal()).setSelectedProfileId(userInfo.getSelectedProfileId())
1260 .setTimeZoneId(userInfo.getTimeZoneId()).setOnline(userInfo.isOnline())
1261 .setChatId(userInfo.getChatId()).setUserApps(userAppList.getUserApps()).setPseudoRoles(null)
1262 .createCentralV2User();
1263 } catch (Exception e) {
1264 logger.error(EELFLoggerDelegate.errorLogger, "createEPUser: createEPUser failed", e);
1271 public CentralV2Role getRoleInfo(Long roleId, String uebkey) throws Exception {
1272 final Map<String, Long> params = new HashMap<>();
1273 List<CentralV2Role> roleList = new ArrayList<>();
1274 CentralV2Role cenRole = new CentralV2Role();
1275 List<EPRole> roleInfo = null;
1276 List<EPApp> app = null;
1278 app = getApp(uebkey);
1279 if (app.isEmpty()) {
1280 throw new InactiveApplicationException("Application not found");
1282 if (app.get(0).getId() != PortalConstants.PORTAL_APP_ID) {
1283 List<EPRole> globalRoleList = new ArrayList<>();
1284 globalRoleList = getGlobalRolesOfPortal();
1285 if (globalRoleList.size() > 0) {
1286 EPRole result = globalRoleList.stream().filter(x -> roleId.equals(x.getId())).findAny()
1289 return getGlobalRoleForRequestedApp(app.get(0).getId(), roleId);
1292 if (app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
1293 roleInfo = getPortalAppRoleInfo(roleId);
1295 roleInfo = getPartnerAppRoleInfo(roleId, app.get(0));
1297 roleList = createCentralRoleObject(app, roleInfo, roleList, params);
1298 if (roleList.isEmpty()) {
1301 } catch (Exception e) {
1302 logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo: failed", e);
1305 return roleList.get(0);
1308 @SuppressWarnings("unchecked")
1309 private List<EPRole> getPartnerAppRoleInfo(Long roleId, EPApp app) {
1310 List<EPRole> roleInfo;
1311 final Map<String, Long> getPartnerAppRoleParams = new HashMap<>();
1312 getPartnerAppRoleParams.put("appRoleId", roleId);
1313 getPartnerAppRoleParams.put("appId", app.getId());
1314 roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams, null);
1315 if (roleInfo.isEmpty()) {
1316 getPartnerAppRoleParams.put("appRoleId", roleId);
1317 roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleById", getPartnerAppRoleParams, null);
1323 @SuppressWarnings("unchecked")
1324 public List<EPRole> getPortalAppRoleInfo(Long roleId) {
1325 List<EPRole> roleInfo;
1326 final Map<String, Long> getPortalAppRoleParams = new HashMap<>();
1327 getPortalAppRoleParams.put("roleId", roleId);
1328 roleInfo = dataAccessService.executeNamedQuery("getPortalAppRoleByRoleId", getPortalAppRoleParams, null);
1334 * It returns list of app roles along with role functions and which went through
1342 * @throws DecoderException
1344 @SuppressWarnings("unchecked")
1346 public List<CentralV2Role> createCentralRoleObject(List<EPApp> app, List<EPRole> roleInfo,
1347 List<CentralV2Role> roleList, Map<String, Long> params) throws RoleFunctionException {
1348 for (EPRole role : roleInfo) {
1349 params.put("roleId", role.getId());
1350 params.put(APP_ID, app.get(0).getId());
1351 List<CentralV2RoleFunction> cenRoleFuncList = dataAccessService.executeNamedQuery("getAppRoleFunctionList",
1353 SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>();
1354 for (CentralV2RoleFunction roleFunc : cenRoleFuncList) {
1355 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1356 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
1357 String type = getFunctionCodeType(roleFunc.getCode());
1358 String action = getFunctionCodeAction(roleFunc.getCode());
1359 CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(role.getId(), functionCode,
1360 roleFunc.getName(), null, type, action, null);
1361 roleFunctionSet.add(cenRoleFunc);
1363 SortedSet<CentralV2Role> childRoles = new TreeSet<>();
1364 SortedSet<CentralV2Role> parentRoles = new TreeSet<>();
1365 CentralV2Role cenRole = null;
1366 if (role.getAppRoleId() == null) {
1367 cenRole = new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
1368 role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
1369 roleFunctionSet, childRoles, parentRoles);
1371 cenRole = new CentralV2Role(role.getAppRoleId(), role.getCreated(), role.getModified(),
1372 role.getCreatedId(), role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(),
1373 role.getPriority(), roleFunctionSet, childRoles, parentRoles);
1375 roleList.add(cenRole);
1380 @SuppressWarnings("unchecked")
1382 public CentralV2RoleFunction getRoleFunction(String functionCode, String uebkey) throws Exception {
1383 String code = EcompPortalUtils.getFunctionCode(functionCode);
1384 String encodedCode = EcompPortalUtils.encodeFunctionCode(code);
1385 CentralV2RoleFunction roleFunc = null;
1386 EPApp app = getApp(uebkey).get(0);
1387 List<CentralV2RoleFunction> getRoleFuncList = null;
1388 final Map<String, String> params = new HashMap<>();
1390 params.put(FUNCTION_CODE_PARAMS, functionCode);
1391 params.put(APP_ID, String.valueOf(app.getId()));
1392 getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
1393 if (getRoleFuncList.isEmpty()) {
1394 params.put(FUNCTION_CODE_PARAMS, encodedCode);
1395 getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
1396 if (getRoleFuncList.isEmpty()) {
1400 if (getRoleFuncList.size() > 1) {
1401 CentralV2RoleFunction cenV2RoleFunction = appFunctionListFilter(encodedCode, getRoleFuncList);
1402 if (cenV2RoleFunction == null)
1404 roleFunc = checkIfPipesExitsInFunctionCode(cenV2RoleFunction);
1406 // Check even if single record have pipes
1407 if (!getRoleFuncList.isEmpty() && getRoleFuncList.get(0).getCode().contains(FUNCTION_PIPE)) {
1408 roleFunc = checkIfPipesExitsInFunctionCode(getRoleFuncList.get(0));
1410 roleFunc = getRoleFuncList.get(0);
1413 } catch (Exception e) {
1414 logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction: failed", e);
1420 private CentralV2RoleFunction checkIfPipesExitsInFunctionCode(CentralV2RoleFunction getRoleFuncList) {
1421 CentralV2RoleFunction roleFunc;
1422 String functionCodeFormat = getRoleFuncList.getCode();
1423 if (functionCodeFormat.contains(FUNCTION_PIPE)) {
1424 String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(functionCodeFormat);
1425 String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(functionCodeFormat);
1426 String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(functionCodeFormat);
1427 roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), newfunctionCodeFormat,
1428 getRoleFuncList.getName(), getRoleFuncList.getAppId(), newfunctionTypeFormat,
1429 newfunctionActionFormat, getRoleFuncList.getEditUrl());
1431 roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), functionCodeFormat, getRoleFuncList.getName(),
1432 getRoleFuncList.getAppId(), getRoleFuncList.getEditUrl());
1438 public boolean saveCentralRoleFunction(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
1440 boolean saveOrUpdateFunction = false;
1442 if(EcompPortalUtils.checkFunctionCodeHasEncodePattern(domainCentralRoleFunction.getCode()))
1443 domainCentralRoleFunction.setCode(EcompPortalUtils.encodeFunctionCode(domainCentralRoleFunction.getCode()));
1444 final Map<String, String> functionParams = new HashMap<>();
1445 functionParams.put("appId", String.valueOf(app.getId()));
1446 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1447 addRoleFunctionInExternalSystem(domainCentralRoleFunction, app);
1449 if (domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null) {
1450 domainCentralRoleFunction.setCode(domainCentralRoleFunction.getType() + FUNCTION_PIPE
1451 + domainCentralRoleFunction.getCode() + FUNCTION_PIPE + domainCentralRoleFunction.getAction());
1453 domainCentralRoleFunction.setAppId(app.getId());
1454 dataAccessService.saveDomainObject(domainCentralRoleFunction, null);
1455 saveOrUpdateFunction = true;
1456 } catch (Exception e) {
1457 logger.error(EELFLoggerDelegate.errorLogger, "saveCentralRoleFunction: failed", e);
1460 return saveOrUpdateFunction;
1464 * It creates application permission in external auth system
1466 * @param domainCentralRoleFunction
1470 private void addRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
1472 ObjectMapper mapper = new ObjectMapper();
1473 ExternalAccessPerms extPerms = new ExternalAccessPerms();
1474 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1476 String instance = "";
1478 if ((domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null)
1479 || domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)) {
1480 type = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)
1481 ? EcompPortalUtils.getFunctionType(domainCentralRoleFunction.getCode())
1482 : domainCentralRoleFunction.getType();
1483 instance = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)
1484 ? EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode())
1485 : domainCentralRoleFunction.getCode();
1486 action = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)
1487 ? EcompPortalUtils.getFunctionAction(domainCentralRoleFunction.getCode())
1488 : domainCentralRoleFunction.getAction();
1490 type = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url";
1491 instance = domainCentralRoleFunction.getCode();
1494 // get Permissions from External Auth System
1495 JSONArray extPermsList = getExtAuthPermissions(app);
1496 List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPermsList);
1497 String requestedPerm = type + FUNCTION_PIPE + instance + FUNCTION_PIPE + action;
1498 boolean checkIfFunctionsExits = permsDetailList.stream()
1499 .anyMatch(permsDetail -> permsDetail.getInstance().equals(requestedPerm));
1500 if (!checkIfFunctionsExits) {
1502 extPerms.setAction(action);
1503 extPerms.setInstance(instance);
1504 extPerms.setType(app.getNameSpace() + "." + type);
1505 extPerms.setDescription(domainCentralRoleFunction.getName());
1506 String addFunction = mapper.writeValueAsString(extPerms);
1507 HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
1508 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for POST: {}",
1509 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
1510 ResponseEntity<String> addPermResponse = template.exchange(
1511 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
1512 HttpMethod.POST, entity, String.class);
1513 logger.debug(EELFLoggerDelegate.debugLogger,
1514 "addRoleFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ",
1515 addPermResponse.getStatusCode().value(), addFunction);
1516 } catch (HttpClientErrorException e) {
1517 logger.error(EELFLoggerDelegate.errorLogger,
1518 "HttpClientErrorException - Failed to add function in external central auth system", e);
1519 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1521 } catch (Exception e) {
1522 logger.error(EELFLoggerDelegate.errorLogger,
1523 "addRoleFunctionInExternalSystem: Failed to add fucntion in external central auth system", e);
1528 extPerms.setAction(action);
1529 extPerms.setInstance(instance);
1530 extPerms.setType(app.getNameSpace() + "." + type);
1531 extPerms.setDescription(domainCentralRoleFunction.getName());
1532 String updateRoleFunction = mapper.writeValueAsString(extPerms);
1533 HttpEntity<String> entity = new HttpEntity<>(updateRoleFunction, headers);
1534 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for PUT: {}",
1535 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRoleFunction);
1536 ResponseEntity<String> updatePermResponse = template.exchange(
1537 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
1538 HttpMethod.PUT, entity, String.class);
1539 logger.debug(EELFLoggerDelegate.debugLogger,
1540 "addRoleFunctionInExternalSystem: Finished updating permission in External Auth system {} and response: {} ",
1541 updateRoleFunction, updatePermResponse.getStatusCode().value());
1542 } catch (HttpClientErrorException e) {
1543 logger.error(EELFLoggerDelegate.errorLogger,
1544 "HttpClientErrorException - Failed to add function in external central auth system", e);
1545 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1547 } catch (Exception e) {
1548 logger.error(EELFLoggerDelegate.errorLogger,
1549 "addRoleFunctionInExternalSystem: Failed to update function in external central auth system",
1556 @SuppressWarnings("unchecked")
1558 @Transactional(rollbackFor = Exception.class)
1559 public boolean deleteCentralRoleFunction(String code, EPApp app) {
1560 boolean deleteFunctionResponse = false;
1562 final Map<String, String> params = new HashMap<>();
1563 params.put(FUNCTION_CODE_PARAMS, code);
1564 params.put(APP_ID, String.valueOf(app.getId()));
1565 List<CentralV2RoleFunction> domainCentralRoleFunction = dataAccessService
1566 .executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
1567 CentralV2RoleFunction appFunctionCode = appFunctionListFilter(code, domainCentralRoleFunction);
1568 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1569 deleteRoleFunctionInExternalSystem(appFunctionCode, app);
1570 // Delete role function dependency records
1571 deleteAppRoleFunctions(appFunctionCode.getCode(), app);
1573 dataAccessService.deleteDomainObject(appFunctionCode, null);
1574 deleteFunctionResponse = true;
1575 } catch (Exception e) {
1576 logger.error(EELFLoggerDelegate.errorLogger, "deleteCentralRoleFunction: failed", e);
1578 return deleteFunctionResponse;
1582 * It deletes app function record in portal
1587 private void deleteAppRoleFunctions(String code, EPApp app) {
1588 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
1589 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + code + "'", null);
1594 * It deletes permission in the external auth system
1596 * @param domainCentralRoleFunction
1600 private void deleteRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
1603 ObjectMapper mapper = new ObjectMapper();
1604 ExternalAccessPerms extPerms = new ExternalAccessPerms();
1605 String instanceValue = EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode());
1606 String checkType = getFunctionCodeType(domainCentralRoleFunction.getCode());
1607 String actionValue = getFunctionCodeAction(domainCentralRoleFunction.getCode());
1608 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1609 extPerms.setAction(actionValue);
1610 extPerms.setInstance(instanceValue);
1611 extPerms.setType(app.getNameSpace() + "." + checkType);
1612 extPerms.setDescription(domainCentralRoleFunction.getName());
1613 String deleteRoleFunction = mapper.writeValueAsString(extPerms);
1614 HttpEntity<String> entity = new HttpEntity<>(deleteRoleFunction, headers);
1615 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleFunctionInExternalSystem: {} for DELETE: {} ",
1616 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, deleteRoleFunction);
1617 ResponseEntity<String> delPermResponse = template
1618 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1619 + "perm?force=true", HttpMethod.DELETE, entity, String.class);
1620 logger.debug(EELFLoggerDelegate.debugLogger,
1621 "deleteRoleFunctionInExternalSystem: Finished deleting permission in External Auth system {} and status code: {} ",
1622 deleteRoleFunction, delPermResponse.getStatusCode().value());
1623 } catch (HttpClientErrorException e) {
1624 logger.error(EELFLoggerDelegate.errorLogger,
1625 "HttpClientErrorException - Failed to delete functions in External System", e);
1626 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1627 } catch (Exception e) {
1628 if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
1629 logger.debug(EELFLoggerDelegate.debugLogger,
1630 " deleteRoleFunctionInExternalSystem: It seems like function is already deleted in external central auth system but exists in local DB",
1633 logger.error(EELFLoggerDelegate.errorLogger,
1634 "deleteRoleFunctionInExternalSystem: Failed to delete functions in External System", e);
1640 public ExternalRequestFieldsValidator saveRoleForApplication(Role saveRole, String uebkey) throws Exception {
1641 boolean response = false;
1642 String message = "";
1644 EPApp app = getApp(uebkey).get(0);
1645 addRoleInEcompDB(saveRole, app);
1647 } catch (Exception e) {
1648 message = e.getMessage();
1649 logger.error(EELFLoggerDelegate.errorLogger, "saveRoleForApplication failed", e);
1651 return new ExternalRequestFieldsValidator(response, message);
1654 @SuppressWarnings("unchecked")
1656 public boolean deleteRoleForApplication(String deleteRole, String uebkey) throws Exception {
1657 Session localSession = sessionFactory.openSession();
1658 Transaction transaction = null;
1659 boolean result = false;
1661 List<EPRole> epRoleList = null;
1662 EPApp app = getApp(uebkey).get(0);
1663 final Map<String, String> deleteRoleParams = new HashMap<>();
1664 deleteRoleParams.put(APP_ROLE_NAME_PARAM, deleteRole);
1665 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1666 epRoleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, deleteRoleParams, null);
1668 deleteRoleParams.put(APP_ID, String.valueOf(app.getId()));
1669 epRoleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
1670 deleteRoleParams, null);
1672 if (!epRoleList.isEmpty()) {
1673 transaction = localSession.beginTransaction();
1674 // Delete app role functions before deleting role
1675 deleteRoleFunction(app, epRoleList);
1676 if (app.getId() == 1) {
1677 // Delete fn_user_ role
1678 dataAccessService.deleteDomainObjects(EPUserApp.class,
1679 APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
1680 boolean isPortalRequest = false;
1681 deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest);
1683 deleteRoleInExternalAuthSystem(epRoleList, app);
1684 transaction.commit();
1685 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: committed the transaction");
1686 dataAccessService.deleteDomainObject(epRoleList.get(0), null);
1689 } catch (Exception e) {
1690 logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleForApplication: failed", e);
1693 localSession.close();
1700 * It deletes role for application in external auth system
1702 * @param epRoleList contains role information
1703 * @param app contains application information
1706 private void deleteRoleInExternalAuthSystem(List<EPRole> epRoleList, EPApp app) throws Exception {
1707 ResponseEntity<String> deleteResponse;
1708 ResponseEntity<String> res = getNameSpaceIfExists(app);
1709 if (res.getStatusCode() == HttpStatus.OK) {
1710 // Delete Role in External System
1711 String deleteRoleKey = "{\"name\":\"" + app.getNameSpace() + "." + epRoleList.get(0).getName()
1712 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_") + "\"}";
1713 deleteResponse = deleteRoleInExternalSystem(deleteRoleKey);
1714 if (deleteResponse.getStatusCode().value() != 200 && deleteResponse.getStatusCode().value() != 404) {
1715 EPLogUtil.logExternalAuthAccessAlarm(logger, deleteResponse.getStatusCode());
1716 logger.error(EELFLoggerDelegate.errorLogger,
1717 "deleteRoleForApplication: Failed to delete role in external auth system! due to {} ",
1718 deleteResponse.getBody());
1720 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: about to commit the transaction");
1726 * It deletes application user role in external auth system
1733 private void deleteUserRoleInExternalSystem(EPRole role, EPApp app, String LoginId) throws Exception {
1734 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1735 HttpEntity<String> entity = new HttpEntity<>(headers);
1736 getNameSpaceIfExists(app);
1737 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} ",
1738 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1739 ResponseEntity<String> getResponse = template.exchange(
1740 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
1742 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
1743 + "/" + app.getNameSpace() + "."
1745 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
1746 HttpMethod.GET, entity, String.class);
1747 logger.debug(EELFLoggerDelegate.debugLogger,
1748 "deleteUserRoleInExternalSystem: Finished GET user roles from External Auth system and response: {} ",
1749 getResponse.getBody());
1750 if (getResponse.getStatusCode().value() != 200) {
1751 throw new ExternalAuthSystemException(getResponse.getBody());
1753 String res = getResponse.getBody();
1754 if (!res.equals(IS_EMPTY_JSON_STRING)) {
1755 HttpEntity<String> userRoleentity = new HttpEntity<>(headers);
1756 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} ",
1757 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1758 ResponseEntity<String> deleteResponse = template.exchange(
1759 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
1761 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
1762 + "/" + app.getNameSpace() + "."
1763 + role.getName().replaceAll(
1764 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
1765 HttpMethod.DELETE, userRoleentity, String.class);
1766 if (deleteResponse.getStatusCode().value() != 200) {
1767 throw new ExternalAuthSystemException("Failed to delete user role");
1769 logger.debug(EELFLoggerDelegate.debugLogger,
1770 "deleteUserRoleInExternalSystem: Finished deleting user role in External Auth system and status code: {} ",
1771 deleteResponse.getStatusCode().value());
1775 @SuppressWarnings("unchecked")
1777 public List<CentralV2Role> getActiveRoles(String uebkey) throws Exception {
1778 List<CentralV2Role> roleList = new ArrayList<>();
1780 List<EPApp> app = getApp(uebkey);
1781 final Map<String, Long> params = new HashMap<>();
1784 if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
1785 appId = app.get(0).getId();
1787 List<Criterion> restrictionsList = new ArrayList<Criterion>();
1788 Criterion active_ynCrt = Restrictions.eq("active", Boolean.TRUE);
1791 appIdCrt = Restrictions.isNull("appId");
1793 appIdCrt = Restrictions.eq("appId", appId);
1794 Criterion andCrit = Restrictions.and(active_ynCrt, appIdCrt);
1795 restrictionsList.add(andCrit);
1796 List<EPRole> epRole = (List<EPRole>) dataAccessService.getList(EPRole.class, null, restrictionsList, null);
1797 roleList = createCentralRoleObject(app, epRole, roleList, params);
1798 List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
1799 if (globalRoleList.size() > 0)
1800 roleList.addAll(globalRoleList);
1801 } catch (Exception e) {
1802 logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles: failed", e);
1809 @Transactional(rollbackFor = Exception.class)
1810 public ExternalRequestFieldsValidator deleteDependencyRoleRecord(Long roleId, String uebkey, String LoginId)
1812 Session localSession = sessionFactory.openSession();
1813 String message = "";
1814 Transaction transaction = null;
1815 boolean response = false;
1818 transaction = localSession.beginTransaction();
1819 List<EPRole> epRoleList = null;
1820 app = getApp(uebkey).get(0);
1821 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1822 epRoleList = getPortalAppRoleInfo(roleId);
1824 epRoleList = getPartnerAppRoleInfo(roleId, app);
1826 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1827 // Delete User Role in External System before deleting role
1828 deleteUserRoleInExternalSystem(epRoleList.get(0), app, LoginId);
1830 // Delete user app roles
1831 dataAccessService.deleteDomainObjects(EPUserApp.class,
1832 APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
1833 boolean isPortalRequest = false;
1834 deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest);
1835 transaction.commit();
1836 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1837 // Final call to delete role once all dependencies has been
1839 deleteRoleInExternalAuthSystem(epRoleList, app);
1841 dataAccessService.deleteDomainObjects(EPRole.class, " role_id = " + epRoleList.get(0).getId(), null);
1842 logger.debug(EELFLoggerDelegate.debugLogger, "deleteDependencyRoleRecord: committed the transaction");
1844 } catch (HttpClientErrorException e) {
1845 logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord: HttpClientErrorException", e);
1846 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1847 message = e.getMessage();
1848 } catch (Exception e) {
1849 logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord failed", e);
1850 EcompPortalUtils.rollbackTransaction(transaction,
1851 "deleteDependencyRoleRecord rollback, exception = " + e.toString());
1852 message = e.getMessage();
1854 localSession.close();
1856 return new ExternalRequestFieldsValidator(response, message);
1860 @SuppressWarnings("unchecked")
1862 public void syncRoleFunctionFromExternalAccessSystem(EPApp app) {
1864 // get Permissions from External Auth System
1865 JSONArray extPerms = getExtAuthPermissions(app);
1866 List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);
1867 // get functions in DB
1868 final Map<String, Long> params = new HashMap<>();
1869 final Map<String, CentralV2RoleFunction> roleFuncMap = new HashMap<>();
1870 params.put(APP_ID, app.getId());
1871 List<CentralV2RoleFunction> appFunctions = dataAccessService.executeNamedQuery("getAllRoleFunctions",
1873 if (!appFunctions.isEmpty()) {
1874 for (CentralV2RoleFunction roleFunc : appFunctions) {
1875 roleFuncMap.put(roleFunc.getCode(), roleFunc);
1878 // get Roles for portal in DB
1879 List<EPRole> portalRoleList = getGlobalRolesOfPortal();
1880 final Map<String, EPRole> existingPortalRolesMap = new HashMap<>();
1881 for (EPRole epRole : portalRoleList) {
1882 existingPortalRolesMap.put(epRole.getName().replaceAll(
1883 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), epRole);
1886 final Map<String, EPRole> currentRolesInDB = getAppRoleNamesWithUnderscoreMap(app);
1887 // store External Permissions with Pipe and without Pipe (just
1889 final Map<String, ExternalAccessPermsDetail> extAccessPermsContainsPipeMap = new HashMap<>();
1890 final Map<String, ExternalAccessPermsDetail> extAccessPermsMap = new HashMap<>();
1891 for (ExternalAccessPermsDetail permsDetailInfoWithPipe : permsDetailList) {
1892 extAccessPermsContainsPipeMap.put(permsDetailInfoWithPipe.getInstance(), permsDetailInfoWithPipe);
1893 String finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetailInfoWithPipe.getInstance());
1894 extAccessPermsMap.put(finalFunctionCodeVal, permsDetailInfoWithPipe);
1896 // Add if new functions and app role functions were added in
1897 // external auth system
1898 for (ExternalAccessPermsDetail permsDetail : permsDetailList) {
1899 String code = permsDetail.getInstance();
1900 CentralV2RoleFunction getFunctionCodeKey = roleFuncMap.get(permsDetail.getInstance());
1901 List<CentralV2RoleFunction> roleFunctionList = addGetLocalFunction(app, roleFuncMap, permsDetail, code,
1902 getFunctionCodeKey);
1903 List<String> roles = permsDetail.getRoles();
1904 if (roles != null) {
1905 // Check if function has any roles and which does not exist
1906 // in External Auth System. If exists delete in local
1907 addRemoveIfFunctionsRolesIsSyncWithExternalAuth(app, currentRolesInDB, roleFunctionList, roles,
1908 existingPortalRolesMap);
1911 // Check if function does exits in External Auth System but exits in
1912 // local then delete function and its dependencies
1913 for (CentralV2RoleFunction roleFunc : appFunctions) {
1915 ExternalAccessPermsDetail getFunctionCodeContainsPipeKey = extAccessPermsContainsPipeMap
1916 .get(roleFunc.getCode());
1917 if (null == getFunctionCodeContainsPipeKey) {
1918 ExternalAccessPermsDetail getFunctionCodeKey = extAccessPermsMap.get(roleFunc.getCode());
1919 if (null == getFunctionCodeKey) {
1920 deleteAppRoleFuncDoesNotExitsInExtSystem(app, roleFunc);
1923 } catch (Exception e) {
1924 logger.error(EELFLoggerDelegate.errorLogger,
1925 "syncRoleFunctionFromExternalAccessSystem: Failed to delete function", e);
1928 logger.debug(EELFLoggerDelegate.debugLogger,
1929 "syncRoleFunctionFromExternalAccessSystem: Finished syncRoleFunctionFromExternalAccessSystem");
1930 } catch (Exception e) {
1931 logger.error(EELFLoggerDelegate.errorLogger,
1932 "syncRoleFunctionFromExternalAccessSystem: Failed syncRoleFunctionFromExternalAccessSystem", e);
1936 @SuppressWarnings("unchecked")
1937 private void addRemoveIfFunctionsRolesIsSyncWithExternalAuth(EPApp app, final Map<String, EPRole> currentRolesInDB,
1938 List<CentralV2RoleFunction> roleFunctionList, List<String> roles,
1939 Map<String, EPRole> existingPortalRolesMap) throws Exception {
1940 if (!roleFunctionList.isEmpty()) {
1941 final Map<String, String> appRoleFuncParams = new HashMap<>();
1942 final Map<String, LocalRole> currentAppRoleFunctionsMap = new HashMap<>();
1943 final Map<String, String> currentRolesInExtSystem = new HashMap<>();
1944 appRoleFuncParams.put("functionCd", roleFunctionList.get(0).getCode());
1945 appRoleFuncParams.put("appId", String.valueOf(app.getId()));
1946 List<LocalRole> localRoleList = dataAccessService.executeNamedQuery("getCurrentAppRoleFunctions",
1947 appRoleFuncParams, null);
1948 for (LocalRole localRole : localRoleList) {
1949 currentAppRoleFunctionsMap.put(localRole.getRolename().replaceAll(
1950 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), localRole);
1952 for (String addRole : roles) {
1953 currentRolesInExtSystem.put(addRole.substring(addRole.indexOf(FUNCTION_PIPE) + 1), addRole);
1955 for (String extAuthrole : roles) {
1956 String roleNameSpace = extAuthrole.substring(0, extAuthrole.indexOf(FUNCTION_PIPE));
1957 boolean isNameSpaceMatching = EcompPortalUtils.checkNameSpaceMatching(roleNameSpace,
1958 app.getNameSpace());
1959 if (isNameSpaceMatching) {
1960 if (!currentAppRoleFunctionsMap
1961 .containsKey(extAuthrole.substring(app.getNameSpace().length() + 1))) {
1962 EPRole localAddFuntionRole = currentRolesInDB
1963 .get(extAuthrole.substring(app.getNameSpace().length() + 1));
1964 if (localAddFuntionRole == null) {
1965 checkAndAddRoleInDB(app, currentRolesInDB, roleFunctionList, extAuthrole);
1967 EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
1968 addAppRoleFunc.setAppId(app.getId());
1969 addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
1970 addAppRoleFunc.setRoleId(localAddFuntionRole.getId());
1971 dataAccessService.saveDomainObject(addAppRoleFunc, null);
1974 // This block is to save global role function if exists
1976 String extAuthAppRoleName = extAuthrole.substring(extAuthrole.indexOf(FUNCTION_PIPE) + 1);
1977 boolean checkIfGlobalRoleExists = existingPortalRolesMap.containsKey(extAuthAppRoleName);
1978 if (checkIfGlobalRoleExists) {
1979 final Map<String, Long> params = new HashMap<>();
1980 EPRole role = existingPortalRolesMap.get(extAuthAppRoleName);
1981 EPAppRoleFunction addGlobalRoleFunctions = new EPAppRoleFunction();
1982 params.put("appId", app.getId());
1983 params.put("roleId", role.getId());
1984 List<EPAppRoleFunction> currentGlobalRoleFunctionsList = dataAccessService
1985 .executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", params, null);
1986 boolean checkIfRoleFunctionExists = currentGlobalRoleFunctionsList.stream()
1987 .anyMatch(currentGlobalRoleFunction -> currentGlobalRoleFunction.getCode()
1988 .equals(roleFunctionList.get(0).getCode()));
1989 if (role != null && !checkIfRoleFunctionExists) {
1990 addGlobalRoleFunctions.setAppId(app.getId());
1991 addGlobalRoleFunctions.setRoleId(role.getId());
1992 if (!app.getId().equals(role.getAppRoleId())) {
1993 addGlobalRoleFunctions.setRoleAppId((PortalConstants.PORTAL_APP_ID).toString());
1995 addGlobalRoleFunctions.setRoleAppId(null);
1997 addGlobalRoleFunctions.setCode(roleFunctionList.get(0).getCode());
1998 dataAccessService.saveDomainObject(addGlobalRoleFunctions, null);
2003 for (LocalRole localRoleDelete : localRoleList) {
2004 if (!currentRolesInExtSystem.containsKey(localRoleDelete.getRolename()
2005 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
2006 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
2007 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunctionList.get(0).getCode()
2008 + "'" + " and role_id = " + localRoleDelete.getRoleId().longValue(),
2015 private void deleteAppRoleFuncDoesNotExitsInExtSystem(EPApp app, CentralV2RoleFunction roleFunc) {
2016 logger.debug(EELFLoggerDelegate.debugLogger,
2017 "syncRoleFunctionFromExternalAccessSystem: Deleting app role function {}", roleFunc.getCode());
2018 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
2019 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() + "'", null);
2020 logger.debug(EELFLoggerDelegate.debugLogger,
2021 "syncRoleFunctionFromExternalAccessSystem: Deleted app role function {}", roleFunc.getCode());
2022 logger.debug(EELFLoggerDelegate.debugLogger,
2023 "syncRoleFunctionFromExternalAccessSystem: Deleting app function {}", roleFunc.getCode());
2024 dataAccessService.deleteDomainObjects(CentralV2RoleFunction.class,
2025 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() + "'", null);
2026 logger.debug(EELFLoggerDelegate.debugLogger,
2027 "syncRoleFunctionFromExternalAccessSystem: Deleted app function {}", roleFunc.getCode());
2030 private void checkAndAddRoleInDB(EPApp app, final Map<String, EPRole> currentRolesInDB,
2031 List<CentralV2RoleFunction> roleFunctionList, String roleList) throws Exception {
2032 if (!currentRolesInDB.containsKey(roleList.substring(app.getNameSpace().length() + 1))) {
2033 Role role = addRoleInDBIfDoesNotExists(app, roleList.substring(app.getNameSpace().length() + 1));
2034 addRoleDescriptionInExtSystem(role, app);
2035 if (!roleFunctionList.isEmpty()) {
2037 if (!roleFunctionList.isEmpty()) {
2038 EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
2039 addAppRoleFunc.setAppId(app.getId());
2040 addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
2041 addAppRoleFunc.setRoleId(role.getId());
2042 dataAccessService.saveDomainObject(addAppRoleFunc, null);
2044 } catch (Exception e) {
2045 logger.error(EELFLoggerDelegate.errorLogger,
2046 "syncRoleFunctionFromExternalAccessSystem: Failed to save app role function ", e);
2052 @SuppressWarnings("unchecked")
2053 private List<CentralV2RoleFunction> addGetLocalFunction(EPApp app,
2054 final Map<String, CentralV2RoleFunction> roleFuncMap, ExternalAccessPermsDetail permsDetail, String code,
2055 CentralV2RoleFunction getFunctionCodeKey) {
2056 String finalFunctionCodeVal = addToLocalIfFunctionNotExists(app, roleFuncMap, permsDetail, code,
2057 getFunctionCodeKey);
2058 final Map<String, String> appSyncFuncsParams = new HashMap<>();
2059 appSyncFuncsParams.put("appId", String.valueOf(app.getId()));
2060 appSyncFuncsParams.put("functionCd", finalFunctionCodeVal);
2061 List<CentralV2RoleFunction> roleFunctionList = null;
2062 roleFunctionList = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams,
2064 if (roleFunctionList.isEmpty()) {
2065 appSyncFuncsParams.put("functionCd", code);
2066 roleFunctionList = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams,
2069 return roleFunctionList;
2072 private String addToLocalIfFunctionNotExists(EPApp app, final Map<String, CentralV2RoleFunction> roleFuncMap,
2073 ExternalAccessPermsDetail permsDetail, String code, CentralV2RoleFunction getFunctionCodeKey) {
2074 String finalFunctionCodeVal = "";
2075 if (null == getFunctionCodeKey) {
2076 finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetail.getInstance());
2077 CentralV2RoleFunction checkIfCodeStillExits = roleFuncMap.get(finalFunctionCodeVal);
2078 // If function does not exist in local then add!
2079 if (null == checkIfCodeStillExits) {
2080 logger.debug(EELFLoggerDelegate.debugLogger,
2081 "syncRoleFunctionFromExternalAccessSystem: Adding function: {} ", code);
2082 addFunctionInEcompDB(app, permsDetail, code);
2083 logger.debug(EELFLoggerDelegate.debugLogger,
2084 "syncRoleFunctionFromExternalAccessSystem: Finished adding function: {} ", code);
2087 return finalFunctionCodeVal;
2090 @SuppressWarnings("unchecked")
2092 public Map<String, EPRole> getAppRoleNamesWithUnderscoreMap(EPApp app) {
2093 final Map<String, EPRole> currentRolesInDB = new HashMap<>();
2094 List<EPRole> getCurrentRoleList = null;
2095 final Map<String, Long> appParams = new HashMap<>();
2096 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2097 getCurrentRoleList = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
2099 appParams.put("appId", app.getId());
2100 getCurrentRoleList = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
2102 for (EPRole role : getCurrentRoleList) {
2103 currentRolesInDB.put(role.getName()
2104 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), role);
2106 return currentRolesInDB;
2109 @SuppressWarnings("unchecked")
2110 private Map<String, EPRole> getAppRoleNamesMap(EPApp app) {
2111 final Map<String, EPRole> currentRolesInDB = new HashMap<>();
2112 List<EPRole> getCurrentRoleList = null;
2113 final Map<String, Long> appParams = new HashMap<>();
2114 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2115 getCurrentRoleList = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
2117 appParams.put("appId", app.getId());
2118 getCurrentRoleList = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
2120 for (EPRole role : getCurrentRoleList) {
2121 currentRolesInDB.put(role.getName(), role);
2123 return currentRolesInDB;
2126 private List<ExternalAccessPermsDetail> getExtAuthPerrmissonList(EPApp app, JSONArray extPerms) throws IOException {
2127 ExternalAccessPermsDetail permDetails = null;
2128 List<ExternalAccessPermsDetail> permsDetailList = new ArrayList<>();
2129 for (int i = 0; i < extPerms.length(); i++) {
2130 String description = null;
2131 if (extPerms.getJSONObject(i).has("description")) {
2132 description = extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
2134 description = extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1) + "|"
2135 + extPerms.getJSONObject(i).getString("instance") + "|"
2136 + extPerms.getJSONObject(i).getString("action");
2138 if (extPerms.getJSONObject(i).has("roles")) {
2139 ObjectMapper rolesListMapper = new ObjectMapper();
2140 JSONArray resRoles = extPerms.getJSONObject(i).getJSONArray("roles");
2141 List<String> list = rolesListMapper.readValue(resRoles.toString(),
2142 TypeFactory.defaultInstance().constructCollectionType(List.class, String.class));
2143 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
2144 extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
2145 + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
2146 + extPerms.getJSONObject(i).getString("action"),
2147 extPerms.getJSONObject(i).getString("action"), list, description);
2148 permsDetailList.add(permDetails);
2150 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
2151 extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
2152 + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
2153 + extPerms.getJSONObject(i).getString("action"),
2154 extPerms.getJSONObject(i).getString("action"), description);
2155 permsDetailList.add(permDetails);
2158 return permsDetailList;
2161 private JSONArray getExtAuthPermissions(EPApp app) throws Exception {
2162 ResponseEntity<String> response = null;
2163 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2164 HttpEntity<String> entity = new HttpEntity<>(headers);
2165 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: {} ",
2166 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2167 response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
2168 + "perms/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
2169 String res = response.getBody();
2170 logger.debug(EELFLoggerDelegate.debugLogger,
2171 "syncRoleFunctionFromExternalAccessSystem: Finished GET permissions from External Auth system and response: {} ",
2172 response.getBody());
2173 JSONObject jsonObj = new JSONObject(res);
2174 JSONArray extPerms = jsonObj.getJSONArray("perm");
2175 for (int i = 0; i < extPerms.length(); i++) {
2176 if (extPerms.getJSONObject(i).getString("type").equals(app.getNameSpace() + ".access")) {
2186 * Add function into local DB
2189 * @param permsDetail
2192 private void addFunctionInEcompDB(EPApp app, ExternalAccessPermsDetail permsDetail, String code) {
2194 CentralV2RoleFunction addFunction = new CentralV2RoleFunction();
2195 addFunction.setAppId(app.getId());
2196 addFunction.setCode(code);
2197 addFunction.setName(permsDetail.getDescription());
2198 dataAccessService.saveDomainObject(addFunction, null);
2199 } catch (Exception e) {
2200 logger.error(EELFLoggerDelegate.errorLogger, "addFunctionInEcompDB: Failed to add function", e);
2206 * It updates description of a role in external auth system
2212 private boolean addRoleDescriptionInExtSystem(Role role, EPApp app) throws Exception {
2213 boolean status = false;
2215 String addRoleNew = updateExistingRoleInExternalSystem(role, app);
2216 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2217 HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
2219 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
2220 HttpMethod.PUT, entity, String.class);
2222 } catch (HttpClientErrorException e) {
2223 logger.error(EELFLoggerDelegate.errorLogger,
2224 "HttpClientErrorException - Failed to addRoleDescriptionInExtSystem", e);
2225 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2226 } catch (Exception e) {
2227 logger.error(EELFLoggerDelegate.errorLogger, "addRoleDescriptionInExtSystem: Failed", e);
2234 * While sync functions form external auth system if new role found we should
2235 * add in local and return Role.class object
2241 @SuppressWarnings("unchecked")
2242 private Role addRoleInDBIfDoesNotExists(EPApp app, String role) {
2243 Role setNewRole = new Role();
2245 // functions can have new role created in External Auth System
2248 boolean isCreated = checkIfRoleExitsElseCreateInSyncFunctions(role, app);
2249 final Map<String, String> getRoleByNameParams = new HashMap<>();
2250 List<EPRole> getRoleCreated = null;
2251 getRoleByNameParams.put(APP_ROLE_NAME_PARAM, role);
2252 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2253 getRoleByNameParams.put("appId", String.valueOf(app.getId()));
2254 List<EPRole> roleCreated = dataAccessService
2255 .executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, getRoleByNameParams, null);
2257 EPRole epUpdateRole = roleCreated.get(0);
2258 epUpdateRole.setAppRoleId(epUpdateRole.getId());
2259 dataAccessService.saveDomainObject(epUpdateRole, null);
2260 getRoleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
2261 getRoleByNameParams, null);
2263 getRoleCreated = roleCreated;
2266 getRoleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, getRoleByNameParams,
2269 if (getRoleCreated != null && !getRoleCreated.isEmpty()) {
2270 EPRole roleObject = getRoleCreated.get(0);
2271 setNewRole.setId(roleObject.getId());
2272 setNewRole.setName(roleObject.getName());
2273 setNewRole.setActive(roleObject.getActive());
2274 setNewRole.setPriority(roleObject.getPriority());
2276 } catch (Exception e) {
2277 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInDBIfDoesNotExists: Failed", e);
2282 @SuppressWarnings("unchecked")
2283 private boolean checkIfRoleExitsElseCreateInSyncFunctions(String role, EPApp app) {
2284 boolean isCreated = false;
2285 final Map<String, String> roleParams = new HashMap<>();
2286 roleParams.put(APP_ROLE_NAME_PARAM, role);
2287 List<EPRole> roleCreated = null;
2288 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2289 roleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, roleParams, null);
2291 roleParams.put("appId", String.valueOf(app.getId()));
2292 roleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams,
2295 if (roleCreated == null || roleCreated.isEmpty()) {
2296 roleParams.put("appId", String.valueOf(app.getId()));
2297 EPRole epRoleNew = new EPRole();
2298 epRoleNew.setActive(true);
2299 epRoleNew.setName(role);
2300 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2301 epRoleNew.setAppId(null);
2303 epRoleNew.setAppId(app.getId());
2305 dataAccessService.saveDomainObject(epRoleNew, null);
2314 @SuppressWarnings("unchecked")
2315 public Integer bulkUploadFunctions(String uebkey) throws Exception {
2316 EPApp app = getApp(uebkey).get(0);
2317 List<RoleFunction> roleFuncList = dataAccessService.executeNamedQuery("getAllFunctions", null, null);
2318 CentralV2RoleFunction cenRoleFunc = null;
2319 Integer functionsAdded = 0;
2321 for (RoleFunction roleFunc : roleFuncList) {
2322 cenRoleFunc = new CentralV2RoleFunction(roleFunc.getCode(), roleFunc.getName());
2323 addRoleFunctionInExternalSystem(cenRoleFunc, app);
2326 } catch (HttpClientErrorException e) {
2327 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadFunctions failed", e);
2328 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2329 } catch (Exception e) {
2330 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions: failed", e.getMessage(), e);
2332 return functionsAdded;
2336 public Integer bulkUploadRoles(String uebkey) throws Exception {
2337 List<EPApp> app = getApp(uebkey);
2338 List<EPRole> roles = getAppRoles(app.get(0).getId());
2339 List<CentralV2Role> cenRoleList = new ArrayList<>();
2340 final Map<String, Long> params = new HashMap<>();
2341 Integer rolesListAdded = 0;
2343 cenRoleList = createCentralRoleObject(app, roles, cenRoleList, params);
2344 ObjectMapper mapper = new ObjectMapper();
2345 mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
2346 String roleList = mapper.writeValueAsString(cenRoleList);
2347 List<Role> roleObjectList = mapper.readValue(roleList,
2348 TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
2349 for (Role role : roleObjectList) {
2350 addRoleInExternalSystem(role, app.get(0));
2353 if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
2354 // Add Account Admin role in External AUTH System
2356 String addAccountAdminRole = "";
2357 ExternalAccessRole extRole = new ExternalAccessRole();
2358 extRole.setName(app.get(0).getNameSpace() + "." + PortalConstants.ADMIN_ROLE
2359 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2360 addAccountAdminRole = mapper.writeValueAsString(extRole);
2361 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2362 HttpEntity<String> entity = new HttpEntity<>(addAccountAdminRole, headers);
2364 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
2365 HttpMethod.POST, entity, String.class);
2367 } catch (HttpClientErrorException e) {
2368 logger.error(EELFLoggerDelegate.errorLogger,
2369 "HttpClientErrorException - Failed to create Account Admin role", e);
2370 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2371 } catch (Exception e) {
2372 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2373 logger.error(EELFLoggerDelegate.errorLogger,
2374 "bulkUploadRoles: Account Admin Role already exits but does not break functionality",
2377 logger.error(EELFLoggerDelegate.errorLogger,
2378 "bulkUploadRoles: Failed to create Account Admin role", e.getMessage());
2382 } catch (Exception e) {
2383 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles: failed", e);
2386 return rolesListAdded;
2390 * It creating new role in external auth system while doing bulk upload
2396 private void addRoleInExternalSystem(Role role, EPApp app) throws Exception {
2397 String addRoleNew = updateExistingRoleInExternalSystem(role, app);
2398 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2400 HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
2402 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
2403 HttpMethod.POST, entity, String.class);
2404 } catch (HttpClientErrorException e) {
2405 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addRoleInExternalSystem",
2407 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2408 } catch (Exception e) {
2409 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2410 logger.error(EELFLoggerDelegate.errorLogger,
2411 "addRoleInExternalSystem: Role already exits but does not break functionality", e);
2413 logger.error(EELFLoggerDelegate.errorLogger,
2414 "addRoleInExternalSystem: Failed to addRoleInExternalSystem", e.getMessage());
2420 @SuppressWarnings("unchecked")
2421 public Integer bulkUploadRolesFunctions(String uebkey) throws Exception {
2422 EPApp app = getApp(uebkey).get(0);
2423 List<EPRole> roles = getAppRoles(app.getId());
2424 final Map<String, Long> params = new HashMap<>();
2425 Integer roleFunctions = 0;
2427 for (EPRole role : roles) {
2428 params.put("roleId", role.getId());
2429 List<BulkUploadRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("uploadAllRoleFunctions",
2431 if (!appRoleFunc.isEmpty()) {
2432 for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
2433 addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
2438 } catch (HttpClientErrorException e) {
2439 logger.error(EELFLoggerDelegate.errorLogger,
2440 "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
2441 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2442 } catch (Exception e) {
2443 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
2445 return roleFunctions;
2449 * Its adding a role function while doing bulk upload
2451 * @param addRoleFunc
2455 private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, EPRole role, EPApp app) {
2457 String instance = "";
2459 if (addRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
2460 type = EcompPortalUtils.getFunctionType(addRoleFunc.getFunctionCd());
2461 instance = EcompPortalUtils.getFunctionCode(addRoleFunc.getFunctionCd());
2462 action = EcompPortalUtils.getFunctionAction(addRoleFunc.getFunctionCd());
2464 type = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
2465 instance = addRoleFunc.getFunctionCd();
2468 ExternalAccessRolePerms extRolePerms = null;
2469 ExternalAccessPerms extPerms = null;
2470 ObjectMapper mapper = new ObjectMapper();
2472 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2473 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, instance, action,
2474 addRoleFunc.getFunctionName());
2475 extRolePerms = new ExternalAccessRolePerms(extPerms, app.getNameSpace() + "." + role.getName()
2476 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2477 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
2478 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
2480 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
2481 HttpMethod.POST, entity, String.class);
2482 } catch (Exception e) {
2483 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2484 logger.error(EELFLoggerDelegate.errorLogger,
2485 "addRoleFunctionsInExternalSystem: RoleFunction already exits but does not break functionality",
2488 logger.error(EELFLoggerDelegate.errorLogger,
2489 "addRoleFunctionsInExternalSystem: Failed to addRoleFunctionsInExternalSystem", e.getMessage());
2494 @SuppressWarnings("unchecked")
2496 public Integer bulkUploadPartnerFunctions(String uebkey) throws Exception {
2497 EPApp app = getApp(uebkey).get(0);
2498 final Map<String, Long> params = new HashMap<>();
2499 params.put("appId", app.getId());
2500 List<CentralV2RoleFunction> roleFuncList = dataAccessService.executeNamedQuery("getPartnerAppFunctions", params,
2502 Integer functionsAdded = 0;
2504 for (CentralV2RoleFunction roleFunc : roleFuncList) {
2505 addFunctionInExternalSystem(roleFunc, app);
2508 } catch (HttpClientErrorException e) {
2509 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadPartnerFunctions failed",
2511 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2512 } catch (Exception e) {
2513 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerFunctions: failed", e.getMessage(), e);
2515 return functionsAdded;
2518 private void addFunctionInExternalSystem(CentralV2RoleFunction roleFunc, EPApp app) throws Exception {
2519 ObjectMapper mapper = new ObjectMapper();
2520 ExternalAccessPerms extPerms = new ExternalAccessPerms();
2521 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2523 String instance = "";
2525 if ((roleFunc.getCode().contains(FUNCTION_PIPE))
2526 || (roleFunc.getType() != null && roleFunc.getAction() != null)) {
2527 type = EcompPortalUtils.getFunctionType(roleFunc.getCode());
2528 instance = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
2529 action = EcompPortalUtils.getFunctionAction(roleFunc.getCode());
2531 type = roleFunc.getCode().contains("menu") ? "menu" : "url";
2532 instance = roleFunc.getCode();
2536 extPerms.setAction(action);
2537 extPerms.setInstance(instance);
2538 extPerms.setType(app.getNameSpace() + "." + type);
2539 extPerms.setDescription(roleFunc.getName());
2540 String addFunction = mapper.writeValueAsString(extPerms);
2541 HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
2542 logger.debug(EELFLoggerDelegate.debugLogger, "addFunctionInExternalSystem: {} for POST: {}",
2543 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
2544 ResponseEntity<String> addPermResponse = template.exchange(
2545 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
2546 HttpMethod.POST, entity, String.class);
2547 logger.debug(EELFLoggerDelegate.debugLogger,
2548 "addFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ",
2549 addPermResponse.getStatusCode().value(), addFunction);
2550 } catch (HttpClientErrorException e) {
2551 logger.error(EELFLoggerDelegate.errorLogger,
2552 "HttpClientErrorException - Failed to add function in external central auth system", e);
2553 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2555 } catch (Exception e) {
2556 logger.error(EELFLoggerDelegate.errorLogger,
2557 "addFunctionInExternalSystem: Failed to add fucntion in external central auth system", e);
2563 public void bulkUploadPartnerRoles(String uebkey, List<Role> roleList) throws Exception {
2564 EPApp app = getApp(uebkey).get(0);
2565 for (Role role : roleList) {
2566 addRoleInExternalSystem(role, app);
2570 @SuppressWarnings("unchecked")
2572 public Integer bulkUploadPartnerRoleFunctions(String uebkey) throws Exception {
2573 EPApp app = getApp(uebkey).get(0);
2574 List<EPRole> roles = getAppRoles(app.getId());
2575 final Map<String, Long> params = new HashMap<>();
2576 Integer roleFunctions = 0;
2578 for (EPRole role : roles) {
2579 params.put("roleId", role.getId());
2580 List<BulkUploadRoleFunction> appRoleFunc = dataAccessService
2581 .executeNamedQuery("uploadPartnerRoleFunctions", params, null);
2582 if (!appRoleFunc.isEmpty()) {
2583 for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
2584 addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
2589 // upload global role functions to ext auth system
2590 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2591 roleFunctions = bulkUploadGlobalRoleFunctions(app, roleFunctions);
2593 } catch (HttpClientErrorException e) {
2594 logger.error(EELFLoggerDelegate.errorLogger,
2595 "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
2596 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2597 } catch (Exception e) {
2598 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
2600 return roleFunctions;
2603 @SuppressWarnings("unchecked")
2604 private Integer bulkUploadGlobalRoleFunctions(EPApp app, Integer roleFunctions) throws Exception {
2606 EPApp portalApp = epAppService.getApp(1l);
2607 final Map<String, Long> params = new HashMap<>();
2608 params.put("appId", app.getId());
2609 List<GlobalRoleWithApplicationRoleFunction> globalRoleFuncs = dataAccessService
2610 .executeNamedQuery("getBulkUploadPartnerGlobalRoleFunctions", params, null);
2611 ObjectMapper mapper = new ObjectMapper();
2612 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2613 for (GlobalRoleWithApplicationRoleFunction globalRoleFunc : globalRoleFuncs) {
2614 ExternalAccessRolePerms extRolePerms;
2615 ExternalAccessPerms extPerms;
2617 String instance = "";
2619 if (globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
2620 type = EcompPortalUtils.getFunctionType(globalRoleFunc.getFunctionCd());
2621 instance = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd());
2622 action = EcompPortalUtils.getFunctionAction(globalRoleFunc.getFunctionCd());
2624 type = globalRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
2625 instance = globalRoleFunc.getFunctionCd();
2628 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, instance, action);
2629 extRolePerms = new ExternalAccessRolePerms(extPerms,
2630 portalApp.getNameSpace() + "." + globalRoleFunc.getRoleName().replaceAll(
2631 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2632 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
2633 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
2634 updateRoleFunctionInExternalSystem(updateRolePerms, entity);
2637 } catch (HttpClientErrorException e) {
2638 logger.error(EELFLoggerDelegate.errorLogger,
2639 "HttpClientErrorException - Failed to add role function in external central auth system", e);
2640 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2642 } catch (Exception e) {
2643 logger.error(EELFLoggerDelegate.errorLogger,
2644 "bulkUploadGlobalRoleFunctions: Failed to add role fucntion in external central auth system", e);
2647 return roleFunctions;
2652 public void syncApplicationRolesWithEcompDB(EPApp app) {
2654 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Started");
2655 // Sync functions and roles assigned to it which also creates new roles if does
2656 // not exits in portal
2657 syncRoleFunctionFromExternalAccessSystem(app);
2658 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Finished");
2659 ObjectMapper mapper = new ObjectMapper();
2660 logger.debug(EELFLoggerDelegate.debugLogger, "Entering to getAppRolesJSONFromExtAuthSystem");
2661 // Get Permissions from External Auth System
2662 JSONArray extRole = getAppRolesJSONFromExtAuthSystem(app);
2663 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into getExternalRoleDetailsList");
2665 List<ExternalRoleDetails> externalRoleDetailsList = getExternalRoleDetailsList(app, mapper, extRole);
2666 List<EPRole> finalRoleList = new ArrayList<>();
2667 for (ExternalRoleDetails externalRole : externalRoleDetailsList) {
2668 EPRole ecompRole = convertExternalRoleDetailstoEpRole(externalRole);
2669 finalRoleList.add(ecompRole);
2671 List<EPRole> applicationRolesList;
2672 applicationRolesList = getAppRoles(app.getId());
2673 List<String> applicationRoleIdList = new ArrayList<>();
2674 for (EPRole applicationRole : applicationRolesList) {
2675 applicationRoleIdList.add(applicationRole.getName());
2677 List<EPRole> roleListToBeAddInEcompDB = new ArrayList<>();
2678 for (EPRole aafRole : finalRoleList) {
2679 if (!applicationRoleIdList.contains(aafRole.getName())) {
2680 roleListToBeAddInEcompDB.add(aafRole);
2683 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into inactiveRolesNotInExternalAuthSystem");
2684 // Check if roles exits in external Access system and if not make inactive in DB
2685 inactiveRolesNotInExternalAuthSystem(app, finalRoleList, applicationRolesList);
2686 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addNewRoleInEcompDBUpdateDescInExtAuthSystem");
2687 // Add new roles in DB and updates role description in External Auth System
2688 addNewRoleInEcompDBUpdateDescInExtAuthSystem(app, roleListToBeAddInEcompDB);
2689 logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: Finished");
2690 } catch (HttpClientErrorException e) {
2691 logger.error(EELFLoggerDelegate.errorLogger,
2692 "syncApplicationRolesWithEcompDB: Failed due to the External Auth System", e);
2693 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2694 } catch (Exception e) {
2695 logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed ", e);
2701 * It adds new roles in DB and updates description in External Auth System
2704 * @param roleListToBeAddInEcompDB
2706 @SuppressWarnings("unchecked")
2707 private void addNewRoleInEcompDBUpdateDescInExtAuthSystem(EPApp app, List<EPRole> roleListToBeAddInEcompDB) {
2708 EPRole roleToBeAddedInEcompDB;
2709 for (int i = 0; i < roleListToBeAddInEcompDB.size(); i++) {
2711 roleToBeAddedInEcompDB = roleListToBeAddInEcompDB.get(i);
2712 if (app.getId() == 1) {
2713 roleToBeAddedInEcompDB.setAppRoleId(null);
2715 dataAccessService.saveDomainObject(roleToBeAddedInEcompDB, null);
2716 List<EPRole> getRoleCreatedInSync = null;
2717 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2718 final Map<String, String> globalRoleParams = new HashMap<>();
2719 globalRoleParams.put("appId", String.valueOf(app.getId()));
2720 globalRoleParams.put("appRoleName", roleToBeAddedInEcompDB.getName());
2721 getRoleCreatedInSync = dataAccessService
2722 .executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, globalRoleParams, null);
2723 EPRole epUpdateRole = getRoleCreatedInSync.get(0);
2724 epUpdateRole.setAppRoleId(epUpdateRole.getId());
2725 dataAccessService.saveDomainObject(epUpdateRole, null);
2727 List<EPRole> roleList = new ArrayList<>();
2728 final Map<String, String> params = new HashMap<>();
2729 params.put(APP_ROLE_NAME_PARAM, roleToBeAddedInEcompDB.getName());
2730 boolean isPortalRole = false;
2731 if (app.getId() == 1) {
2732 isPortalRole = true;
2733 roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, params, null);
2735 isPortalRole = false;
2736 params.put(APP_ID, app.getId().toString());
2737 roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, params,
2740 EPRole role = roleList.get(0);
2741 Role aaFrole = new Role();
2742 aaFrole.setId(role.getId());
2743 aaFrole.setActive(role.getActive());
2744 aaFrole.setPriority(role.getPriority());
2745 aaFrole.setName(role.getName());
2746 updateRoleInExternalSystem(aaFrole, app, isPortalRole);
2747 } catch (Exception e) {
2748 logger.error(EELFLoggerDelegate.errorLogger,
2749 "SyncApplicationRolesWithEcompDB: Failed to add or update role in external auth system", e);
2756 * It de-activates application roles in DB if not present in External Auth
2760 * @param finalRoleList contains list of current roles present in
2761 * External Auth System
2762 * @param applicationRolesList contains list of current roles present in DB
2764 @SuppressWarnings("unchecked")
2765 private void inactiveRolesNotInExternalAuthSystem(EPApp app, List<EPRole> finalRoleList,
2766 List<EPRole> applicationRolesList) {
2767 final Map<String, EPRole> checkRolesInactive = new HashMap<>();
2768 for (EPRole extrole : finalRoleList) {
2769 checkRolesInactive.put(extrole.getName(), extrole);
2771 for (EPRole role : applicationRolesList) {
2773 final Map<String, String> extRoleParams = new HashMap<>();
2774 List<EPRole> roleList = null;
2775 extRoleParams.put(APP_ROLE_NAME_PARAM, role.getName());
2776 if (!checkRolesInactive.containsKey(role.getName())) {
2777 if (app.getId() == 1) {
2778 roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, extRoleParams, null);
2780 extRoleParams.put(APP_ID, app.getId().toString());
2781 roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
2782 extRoleParams, null);
2784 if (!roleList.isEmpty()) {
2785 EPRole updateRoleInactive = roleList.get(0);
2786 updateRoleInactive.setActive(false);
2787 dataAccessService.saveDomainObject(updateRoleInactive, null);
2790 } catch (Exception e) {
2791 logger.error(EELFLoggerDelegate.errorLogger,
2792 "syncApplicationRolesWithEcompDB: Failed to de-activate role ", e);
2798 @SuppressWarnings("unchecked")
2799 public List<ExternalRoleDetails> getExternalRoleDetailsList(EPApp app, ObjectMapper mapper, JSONArray extRole)
2800 throws IOException {
2801 List<ExternalRoleDetails> externalRoleDetailsList = new ArrayList<>();
2802 ExternalAccessPerms externalAccessPerms = new ExternalAccessPerms();
2803 List<String> functionCodelist = new ArrayList<>();
2804 Map<String, EPRole> curRolesMap = getAppRoleNamesMap(app);
2805 Map<String, EPRole> curRolesUnderscoreMap = getAppRoleNamesWithUnderscoreMap(app);
2806 for (int i = 0; i < extRole.length(); i++) {
2807 ExternalRoleDetails externalRoleDetail = new ExternalRoleDetails();
2808 EPAppRoleFunction ePAppRoleFunction = new EPAppRoleFunction();
2809 JSONObject Role = (JSONObject) extRole.get(i);
2810 String name = extRole.getJSONObject(i).getString(ROLE_NAME);
2811 String actualRoleName = name.substring(app.getNameSpace().length() + 1);
2812 if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
2813 actualRoleName = extRole.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
2815 SortedSet<ExternalAccessPerms> externalAccessPermsOfRole = new TreeSet<>();
2816 if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_PERMS)) {
2817 JSONArray extPerm = (JSONArray) Role.get(EXTERNAL_AUTH_PERMS);
2818 for (int j = 0; j < extPerm.length(); j++) {
2819 JSONObject perms = extPerm.getJSONObject(j);
2820 boolean isNamespaceMatching = EcompPortalUtils.checkNameSpaceMatching(perms.getString("type"),
2821 app.getNameSpace());
2822 if (isNamespaceMatching) {
2823 externalAccessPerms = new ExternalAccessPerms(perms.getString("type"),
2824 perms.getString("instance"), perms.getString("action"));
2825 ePAppRoleFunction.setCode(externalAccessPerms.getInstance());
2826 functionCodelist.add(ePAppRoleFunction.getCode());
2827 externalAccessPermsOfRole.add(externalAccessPerms);
2831 externalRoleDetail.setActive(true);
2832 externalRoleDetail.setName(actualRoleName);
2833 if (app.getId() == 1) {
2834 externalRoleDetail.setAppId(null);
2836 externalRoleDetail.setAppId(app.getId());
2838 EPRole currRole = null;
2839 currRole = (!extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION))
2840 ? curRolesUnderscoreMap.get(actualRoleName)
2841 : curRolesMap.get(actualRoleName);
2843 if (currRole != null)
2844 roleId = currRole.getId();
2845 final Map<String, EPAppRoleFunction> roleFunctionsMap = new HashMap<>();
2846 final Map<String, Long> appRoleFuncsParams = new HashMap<>();
2847 if (roleId != null) {
2848 appRoleFuncsParams.put("appId", app.getId());
2849 appRoleFuncsParams.put("roleId", roleId);
2850 // get role functions from DB
2851 List<EPAppRoleFunction> appRoleFunctions = dataAccessService
2852 .executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null);
2853 if (!appRoleFunctions.isEmpty()) {
2854 for (EPAppRoleFunction roleFunc : appRoleFunctions) {
2855 roleFunctionsMap.put(roleFunc.getCode(), roleFunc);
2859 if (!externalAccessPermsOfRole.isEmpty()) {
2860 // Adding functions to role
2861 for (ExternalAccessPerms externalpermission : externalAccessPermsOfRole) {
2862 EPAppRoleFunction checkRoleFunctionExits = roleFunctionsMap.get(externalpermission.getInstance());
2863 if (checkRoleFunctionExits == null) {
2864 String funcCode = externalpermission.getType().substring(app.getNameSpace().length() + 1)
2865 + FUNCTION_PIPE + externalpermission.getInstance() + FUNCTION_PIPE
2866 + externalpermission.getAction();
2867 EPAppRoleFunction checkRoleFunctionPipeExits = roleFunctionsMap.get(funcCode);
2868 if (checkRoleFunctionPipeExits == null) {
2870 final Map<String, String> appFuncsParams = new HashMap<>();
2871 appFuncsParams.put("appId", String.valueOf(app.getId()));
2872 appFuncsParams.put("functionCd", externalpermission.getInstance());
2873 logger.debug(EELFLoggerDelegate.debugLogger,
2874 "SyncApplicationRolesWithEcompDB: Adding function to the role: {}",
2875 externalpermission.getInstance());
2876 List<CentralV2RoleFunction> roleFunction = null;
2877 roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId",
2878 appFuncsParams, null);
2879 if (roleFunction.isEmpty()) {
2880 appFuncsParams.put("functionCd", funcCode);
2881 roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId",
2882 appFuncsParams, null);
2884 if (!roleFunction.isEmpty()) {
2885 EPAppRoleFunction apRoleFunction = new EPAppRoleFunction();
2886 apRoleFunction.setAppId(app.getId());
2887 apRoleFunction.setRoleId(roleId);
2888 apRoleFunction.setCode(roleFunction.get(0).getCode());
2889 dataAccessService.saveDomainObject(apRoleFunction, null);
2891 } catch (Exception e) {
2892 logger.error(EELFLoggerDelegate.errorLogger,
2893 "SyncApplicationRolesWithEcompDB: Failed to add role function", e);
2899 externalRoleDetailsList.add(externalRoleDetail);
2901 return externalRoleDetailsList;
2905 public JSONArray getAppRolesJSONFromExtAuthSystem(EPApp app) throws Exception {
2906 ResponseEntity<String> response = null;
2907 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2908 HttpEntity<String> entity = new HttpEntity<>(headers);
2909 logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: {} ",
2910 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2911 response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
2912 + "roles/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
2913 String res = response.getBody();
2914 logger.debug(EELFLoggerDelegate.debugLogger,
2915 "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
2917 JSONObject jsonObj = new JSONObject(res);
2918 JSONArray extRole = jsonObj.getJSONArray("role");
2919 for (int i = 0; i < extRole.length(); i++) {
2920 if (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ADMIN)
2921 || extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + OWNER)
2922 || (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ACCOUNT_ADMINISTRATOR)
2923 && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
2932 public JSONArray getAllUsersByRole(String roleName) throws Exception {
2933 ResponseEntity<String> response = null;
2934 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2935 HttpEntity<String> entity = new HttpEntity<>(headers);
2936 logger.debug(EELFLoggerDelegate.debugLogger, "getAllUsersByRole: {} ",
2937 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2938 response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
2939 + "userRoles/role/" + roleName, HttpMethod.GET, entity, String.class);
2940 String res = response.getBody();
2941 logger.debug(EELFLoggerDelegate.debugLogger,
2942 "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
2944 if (res == null || res.trim().isEmpty())
2946 JSONObject jsonObj = new JSONObject(res);
2947 JSONArray extRole = jsonObj.getJSONArray("userRole");
2953 * It converts from ExternalRoleDetails.class object to EPRole.class object
2955 * @param externalRoleDetails
2956 * @return EPRole object
2958 private EPRole convertExternalRoleDetailstoEpRole(ExternalRoleDetails externalRoleDetails) {
2959 EPRole role = new EPRole();
2960 role.setActive(true);
2961 role.setAppId(externalRoleDetails.getAppId());
2962 role.setAppRoleId(externalRoleDetails.getAppRoleId());
2963 role.setName(externalRoleDetails.getName());
2964 role.setPriority(externalRoleDetails.getPriority());
2968 @SuppressWarnings("unchecked")
2970 public Integer bulkUploadUserRoles(String uebkey) throws Exception {
2971 EPApp app = getApp(uebkey).get(0);
2972 final Map<String, String> params = new HashMap<>();
2973 params.put("uebKey", app.getUebKey());
2974 List<BulkUploadUserRoles> userRolesList = null;
2975 Integer userRolesAdded = 0;
2976 if (app.getCentralAuth()) {
2977 userRolesList = dataAccessService.executeNamedQuery("getBulkUserRoles", params, null);
2978 for (BulkUploadUserRoles userRolesUpload : userRolesList) {
2979 if (!userRolesUpload.getOrgUserId().equals("su1234")) {
2980 addUserRoleInExternalSystem(userRolesUpload);
2985 return userRolesAdded;
2989 * Its adding a user role in external auth system while doing bulk upload
2991 * @param userRolesUpload
2993 private void addUserRoleInExternalSystem(BulkUploadUserRoles userRolesUpload) {
2996 ObjectMapper mapper = new ObjectMapper();
2997 if (EPCommonSystemProperties
2998 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
2999 name = userRolesUpload.getOrgUserId()
3000 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
3002 ExternalAccessUser extUser = new ExternalAccessUser(name,
3003 userRolesUpload.getAppNameSpace() + "." + userRolesUpload.getRoleName()
3004 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
3005 String userRole = mapper.writeValueAsString(extUser);
3006 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3007 HttpEntity<String> entity = new HttpEntity<>(userRole, headers);
3009 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
3010 HttpMethod.POST, entity, String.class);
3011 } catch (HttpClientErrorException e) {
3012 logger.error(EELFLoggerDelegate.errorLogger,
3013 "HttpClientErrorException - Failed to addUserRoleInExternalSystem", e);
3014 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3015 } catch (Exception e) {
3016 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
3017 logger.error(EELFLoggerDelegate.errorLogger,
3018 "addUserRoleInExternalSystem: UserRole already exits but does not break functionality");
3020 logger.error(EELFLoggerDelegate.errorLogger,
3021 "addUserRoleInExternalSystem: Failed to addUserRoleInExternalSystem", e);
3027 public void deleteRoleDependencyRecords(Session localSession, Long roleId, Long appId, boolean isPortalRequest)
3032 // It should delete only when it portal's roleId
3033 if (appId.equals(PortalConstants.PORTAL_APP_ID)) {
3034 // Delete from fn_role_function
3035 sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
3036 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3037 query = localSession.createSQLQuery(sql);
3038 query.executeUpdate();
3039 // Delete from fn_role_composite
3040 sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId;
3041 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3042 query = localSession.createSQLQuery(sql);
3043 query.executeUpdate();
3045 // Delete from ep_app_role_function
3046 sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId;
3047 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3048 query = localSession.createSQLQuery(sql);
3049 query.executeUpdate();
3050 // Delete from ep_role_notification
3051 sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
3052 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3053 query = localSession.createSQLQuery(sql);
3054 query.executeUpdate();
3055 // Delete from fn_user_pseudo_role
3056 sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
3057 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3058 query = localSession.createSQLQuery(sql);
3059 query.executeUpdate();
3060 // Delete form EP_WIDGET_CATALOG_ROLE
3061 sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId;
3062 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3063 query = localSession.createSQLQuery(sql);
3064 query.executeUpdate();
3065 // Delete form EP_WIDGET_CATALOG_ROLE
3066 sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId;
3067 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3068 query = localSession.createSQLQuery(sql);
3069 query.executeUpdate();
3070 if (!isPortalRequest) {
3071 // Delete form fn_menu_functional_roles
3072 sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
3073 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3074 query = localSession.createSQLQuery(sql);
3075 query.executeUpdate();
3077 } catch (Exception e) {
3078 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e);
3079 throw new DeleteDomainObjectFailedException("delete Failed" + e.getMessage());
3083 @SuppressWarnings("unchecked")
3085 public List<String> getMenuFunctionsList(String uebkey) throws Exception {
3086 List<String> appMenuFunctionsList = null;
3087 List<String> appMenuFunctionsFinalList = new ArrayList<>();
3089 EPApp app = getApp(uebkey).get(0);
3090 final Map<String, Long> appParams = new HashMap<>();
3091 appParams.put(APP_ID, app.getId());
3092 appMenuFunctionsList = dataAccessService.executeNamedQuery("getMenuFunctions", appParams, null);
3093 for (String appMenuFunction : appMenuFunctionsList) {
3094 if (appMenuFunction.contains(FUNCTION_PIPE)) {
3095 appMenuFunctionsFinalList.add(EcompPortalUtils.getFunctionCode(appMenuFunction));
3097 appMenuFunctionsFinalList.add(appMenuFunction);
3100 } catch (Exception e) {
3101 logger.error(EELFLoggerDelegate.errorLogger, "getMenuFunctionsList: Failed", e);
3102 return appMenuFunctionsFinalList;
3104 return appMenuFunctionsFinalList;
3107 @SuppressWarnings({ "unchecked" })
3109 public List<EcompUser> getAllAppUsers(String uebkey) throws Exception {
3110 List<String> usersList = new ArrayList<>();
3111 List<EcompUser> usersfinalList = new ArrayList<>();
3113 EPApp app = getApp(uebkey).get(0);
3114 final Map<String, Long> appParams = new HashMap<>();
3115 appParams.put("appId", app.getId());
3116 List<EcompUserRoles> userList = (List<EcompUserRoles>) dataAccessService
3117 .executeNamedQuery("ApplicationUserRoles", appParams, null);
3118 for (EcompUserRoles ecompUserRole : userList) {
3119 boolean found = false;
3120 Set<EcompRole> roles = null;
3121 for (EcompUser user : usersfinalList) {
3122 if (user.getOrgUserId().equals(ecompUserRole.getOrgUserId())) {
3123 EcompRole ecompRole = new EcompRole();
3124 ecompRole.setId(ecompUserRole.getRoleId());
3125 ecompRole.setName(ecompUserRole.getRoleName());
3126 roles = user.getRoles();
3127 EcompRole role = roles.stream().filter(x -> x.getName().equals(ecompUserRole.getRoleName()))
3128 .findAny().orElse(null);
3129 SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
3131 roleFunctionSet = (SortedSet<EcompRoleFunction>) role.getRoleFunctions();
3133 String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
3134 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
3135 EcompRoleFunction epRoleFunction = new EcompRoleFunction();
3136 epRoleFunction.setName(ecompUserRole.getFunctionName());
3137 epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
3138 epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
3139 epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
3140 roleFunctionSet.add(epRoleFunction);
3141 ecompRole.setRoleFunctions(roleFunctionSet);
3142 roles.add(ecompRole);
3143 user.setRoles(roles);
3149 EcompUser epUser = new EcompUser();
3150 epUser.setOrgId(ecompUserRole.getOrgId());
3151 epUser.setManagerId(ecompUserRole.getManagerId());
3152 epUser.setFirstName(ecompUserRole.getFirstName());
3153 epUser.setLastName(ecompUserRole.getLastName());
3154 epUser.setPhone(ecompUserRole.getPhone());
3155 epUser.setEmail(ecompUserRole.getEmail());
3156 epUser.setOrgUserId(ecompUserRole.getOrgUserId());
3157 epUser.setOrgCode(ecompUserRole.getOrgCode());
3158 epUser.setOrgManagerUserId(ecompUserRole.getOrgManagerUserId());
3159 epUser.setJobTitle(ecompUserRole.getJobTitle());
3160 epUser.setLoginId(ecompUserRole.getLoginId());
3161 epUser.setActive(true);
3162 roles = new HashSet<>();
3163 EcompRole ecompRole = new EcompRole();
3164 ecompRole.setId(ecompUserRole.getRoleId());
3165 ecompRole.setName(ecompUserRole.getRoleName());
3166 SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
3167 String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
3168 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
3169 EcompRoleFunction epRoleFunction = new EcompRoleFunction();
3170 epRoleFunction.setName(ecompUserRole.getFunctionName());
3171 epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
3172 epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
3173 epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
3174 roleFunctionSet.add(epRoleFunction);
3175 ecompRole.setRoleFunctions(roleFunctionSet);
3176 roles.add(ecompRole);
3177 epUser.setRoles(roles);
3178 usersfinalList.add(epUser);
3181 ObjectMapper mapper = new ObjectMapper();
3182 for (EcompUser u1 : usersfinalList) {
3183 String str = mapper.writeValueAsString(u1);
3186 } catch (Exception e) {
3187 logger.error(EELFLoggerDelegate.errorLogger, "getAllUsers failed", e);
3190 return usersfinalList;
3194 public Role ConvertCentralRoleToRole(String result) {
3195 ObjectMapper mapper = new ObjectMapper();
3196 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
3197 Role newRole = new Role();
3199 newRole = mapper.readValue(result, Role.class);
3200 } catch (IOException e) {
3201 logger.error(EELFLoggerDelegate.errorLogger, "Failed to convert the result to Role Object", e);
3203 if (newRole.getRoleFunctions() != null) {
3204 @SuppressWarnings("unchecked")
3205 Set<RoleFunction> roleFunctionList = newRole.getRoleFunctions();
3206 Set<RoleFunction> roleFunctionListNew = new HashSet<>();
3207 Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
3208 while (itetaror.hasNext()) {
3209 Object nextValue = itetaror.next();
3210 RoleFunction roleFun = mapper.convertValue(nextValue, RoleFunction.class);
3211 roleFunctionListNew.add(roleFun);
3213 newRole.setRoleFunctions(roleFunctionListNew);
3219 @SuppressWarnings("unchecked")
3220 public List<CentralizedApp> getCentralizedAppsOfUser(String userId) {
3221 Map<String, String> params = new HashMap<>();
3222 params.put("userId", userId);
3223 List<CentralizedApp> centralizedAppsList = new ArrayList<>();
3225 centralizedAppsList = dataAccessService.executeNamedQuery("getCentralizedAppsOfUser", params, null);
3226 } catch (Exception e) {
3227 logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
3229 return centralizedAppsList;
3232 @SuppressWarnings("unchecked")
3233 public List<CentralV2Role> getGlobalRolesOfApplication(Long appId) {
3234 Map<String, Long> params = new HashMap<>();
3235 params.put("appId", appId);
3236 List<GlobalRoleWithApplicationRoleFunction> globalRoles = new ArrayList<>();
3238 globalRoles = dataAccessService.executeNamedQuery("getGlobalRoleWithApplicationRoleFunctions", params,
3240 } catch (Exception e) {
3241 logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
3243 List<CentralV2Role> rolesfinalList = new ArrayList<>();
3244 if (globalRoles.size() > 0)
3245 rolesfinalList = finalListOfCentralRoles(globalRoles);
3246 return rolesfinalList;
3249 @SuppressWarnings("unchecked")
3250 private CentralV2Role getGlobalRoleForRequestedApp(long requestedAppId, long roleId) {
3251 CentralV2Role finalGlobalrole = null;
3252 List<GlobalRoleWithApplicationRoleFunction> roleWithApplicationRoleFucntions = new ArrayList<>();
3253 Map<String, Long> params = new HashMap<>();
3254 params.put("roleId", roleId);
3255 params.put("requestedAppId", requestedAppId);
3257 roleWithApplicationRoleFucntions = dataAccessService.executeNamedQuery("getGlobalRoleForRequestedApp",
3259 } catch (Exception e) {
3260 logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRoleForRequestedApp failed", e);
3262 if (roleWithApplicationRoleFucntions.size() > 0) {
3263 List<CentralV2Role> rolesfinalList = finalListOfCentralRoles(roleWithApplicationRoleFucntions);
3264 finalGlobalrole = rolesfinalList.get(0);
3266 List<EPRole> roleList = getPortalAppRoleInfo(roleId);
3267 finalGlobalrole = convertRoleToCentralV2Role(roleList.get(0));
3269 return finalGlobalrole;
3272 private List<CentralV2Role> finalListOfCentralRoles(List<GlobalRoleWithApplicationRoleFunction> globalRoles) {
3273 List<CentralV2Role> rolesfinalList = new ArrayList<>();
3274 for (GlobalRoleWithApplicationRoleFunction role : globalRoles) {
3275 boolean found = false;
3276 for (CentralV2Role cenRole : rolesfinalList) {
3277 if (role.getRoleId().equals(cenRole.getId())) {
3278 SortedSet<CentralV2RoleFunction> roleFunctions = cenRole.getRoleFunctions();
3279 CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
3280 roleFunctions.add(cenRoleFun);
3281 cenRole.setRoleFunctions(roleFunctions);
3287 CentralV2Role cenrole = new CentralV2Role();
3288 cenrole.setName(role.getRoleName());
3289 cenrole.setId(role.getRoleId());
3290 cenrole.setActive(role.isActive());
3291 cenrole.setPriority(role.getPriority());
3292 SortedSet<CentralV2RoleFunction> roleFunctions = new TreeSet<>();
3293 CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
3294 roleFunctions.add(cenRoleFun);
3295 cenrole.setRoleFunctions(roleFunctions);
3296 rolesfinalList.add(cenrole);
3299 return rolesfinalList;
3302 private CentralV2RoleFunction createCentralRoleFunctionForGlobalRole(GlobalRoleWithApplicationRoleFunction role) {
3306 CentralV2RoleFunction cenRoleFun;
3307 if (role.getFunctionCd().contains(FUNCTION_PIPE)) {
3308 instance = EcompPortalUtils.getFunctionCode(role.getFunctionCd());
3309 type = EcompPortalUtils.getFunctionType(role.getFunctionCd());
3310 action = EcompPortalUtils.getFunctionAction(role.getFunctionCd());
3311 cenRoleFun = new CentralV2RoleFunction(null, instance, role.getFunctionName(), null, type, action, null);
3313 type = getFunctionCodeType(role.getFunctionCd());
3314 action = getFunctionCodeAction(role.getFunctionCd());
3315 cenRoleFun = new CentralV2RoleFunction(null, role.getFunctionCd(), role.getFunctionName(), null, type,
3321 @SuppressWarnings("unchecked")
3323 public List<EPRole> getGlobalRolesOfPortal() {
3324 List<EPRole> globalRoles = new ArrayList<>();
3326 globalRoles = dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null);
3327 } catch (Exception e) {
3328 logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRolesOfPortal failed", e);
3333 private CentralV2Role convertRoleToCentralV2Role(EPRole role) {
3334 return new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
3335 role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
3336 new TreeSet<>(), new TreeSet<>(), new TreeSet<>());
3340 public List<CentralRoleFunction> convertCentralRoleFunctionToRoleFunctionObject(
3341 List<CentralV2RoleFunction> answer) {
3342 List<CentralRoleFunction> addRoleFuncList = new ArrayList<>();
3343 for (CentralV2RoleFunction cenRoleFunc : answer) {
3344 CentralRoleFunction setRoleFunc = new CentralRoleFunction();
3345 setRoleFunc.setCode(cenRoleFunc.getCode());
3346 setRoleFunc.setName(cenRoleFunc.getName());
3347 addRoleFuncList.add(setRoleFunc);
3349 return addRoleFuncList;
3353 public CentralUser getUserRoles(String loginId, String uebkey) throws Exception {
3354 CentralUser sendUserRoles = null;
3356 CentralV2User cenV2User = getV2UserAppRoles(loginId, uebkey);
3357 sendUserRoles = convertV2UserRolesToOlderVersion(cenV2User);
3358 } catch (Exception e) {
3359 logger.error(EELFLoggerDelegate.errorLogger, "getUserRoles: failed", e);
3362 return sendUserRoles;
3367 * It returns V2 CentralUser object if user has any roles and permissions
3371 * @return CentralUser object
3374 private CentralV2User getV2UserAppRoles(String loginId, String uebkey) throws Exception {
3376 List<EPUser> epUserList;
3377 List<EPApp> appList = getApp(uebkey);
3378 app = appList.get(0);
3379 epUserList = getUser(loginId);
3380 EPUser user = epUserList.get(0);
3381 Set<EPUserApp> userAppSet = user.getEPUserApps();
3382 return createEPUser(user, userAppSet, app);
3385 private List<EcompRole> getUserAppRoles(EPApp app, EPUser user) {
3386 final Map<String, Long> userParams = new HashMap<>();
3387 userParams.put("appId", app.getId());
3388 userParams.put("userId", user.getId());
3389 @SuppressWarnings("unchecked")
3390 List<EPUserAppCurrentRoles> userAppsRolesList = dataAccessService.executeNamedQuery("getUserAppCurrentRoles",
3392 List<EcompRole> setUserRoles = new ArrayList<>();
3393 for (EPUserAppCurrentRoles role : userAppsRolesList) {
3394 logger.debug(EELFLoggerDelegate.debugLogger, "In getUserAppRoles()- get userRolename = {}",
3395 role.getRoleName());
3396 EcompRole ecompRole = new EcompRole();
3397 ecompRole.setId(role.getRoleId());
3398 ecompRole.setName(role.getRoleName());
3399 setUserRoles.add(ecompRole);
3401 logger.debug(EELFLoggerDelegate.debugLogger, "In getUserAppRoles()- get userrole list size = {}",
3402 setUserRoles.size());
3403 return setUserRoles;
3407 public List<EcompRole> missingUserApplicationRoles(String uebkey, String loginId, Set<EcompRole> CurrentUserRoles)
3409 List<EPApp> appList = getApp(uebkey);
3410 EPApp app = appList.get(0);
3411 List<EPUser> epUserList;
3412 epUserList = getUser(loginId);
3413 List<EcompRole> missingUserAppRoles = new ArrayList<>();
3414 List<String> roleNamesList = CurrentUserRoles.stream().map(EcompRole::getName).collect(Collectors.toList());
3415 logger.debug(EELFLoggerDelegate.debugLogger, "Roles of User from hibernate :" + roleNamesList);
3416 List<EcompRole> userApplicationsRolesfromDB = getUserAppRoles(app, epUserList.get(0));
3417 if (userApplicationsRolesfromDB.size() > 0) {
3418 missingUserAppRoles = userApplicationsRolesfromDB.stream().filter(x -> !roleNamesList.contains(x.getName()))
3419 .collect(Collectors.toList());
3421 List<String> MissingroleNamesList = missingUserAppRoles.stream().map(EcompRole::getName)
3422 .collect(Collectors.toList());
3423 logger.debug(EELFLoggerDelegate.debugLogger, "MissingUserAppRoles():" + MissingroleNamesList);
3425 List<EcompRole> finalMissingRoleList = new ArrayList<>();
3426 if (missingUserAppRoles.size() > 0) {
3427 final Map<String, Long> params = new HashMap<>();
3428 for (EcompRole role : missingUserAppRoles) {
3429 params.put("roleId", role.getId());
3430 params.put(APP_ID, app.getId());
3432 EcompRole epRole = new EcompRole();
3433 epRole.setId(role.getId());
3434 epRole.setName(role.getName());
3435 @SuppressWarnings("unchecked")
3436 List<CentralV2RoleFunction> appRoleFunctionList = dataAccessService
3437 .executeNamedQuery("getAppRoleFunctionList", params, null);
3438 SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
3439 for (CentralV2RoleFunction roleFunc : appRoleFunctionList) {
3440 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
3441 String type = getFunctionCodeType(roleFunc.getCode());
3442 String action = getFunctionCodeAction(roleFunc.getCode());
3443 EcompRoleFunction fun = new EcompRoleFunction();
3444 fun.setAction(action);
3445 fun.setCode(functionCode);
3447 fun.setName(roleFunc.getName());
3448 roleFunctionSet.add(fun);
3451 epRole.setRoleFunctions(roleFunctionSet);
3452 finalMissingRoleList.add(epRole);
3456 return finalMissingRoleList;
3460 * It converts V2 CentralUser object to old version CentralUser object
3463 * @return EPUser object
3465 private CentralUser convertV2UserRolesToOlderVersion(CentralV2User cenV2User) {
3466 Set<CentralV2UserApp> userV2Apps = cenV2User.getUserApps();
3467 Set<CentralUserApp> userApps = new TreeSet<>();
3468 for (CentralV2UserApp userApp : userV2Apps) {
3469 CentralApp app = userApp.getApp();
3470 CentralUserApp cua = new CentralUserApp();
3471 cua.setUserId(null);
3473 SortedSet<CentralRoleFunction> cenRoleFunction = new TreeSet<>();
3474 for (CentralV2RoleFunction cenV2RoleFunc : userApp.getRole().getRoleFunctions()) {
3475 CentralRoleFunction cenRoleFunc = new CentralRoleFunction(cenV2RoleFunc.getCode(),
3476 cenV2RoleFunc.getName());
3477 cenRoleFunction.add(cenRoleFunc);
3479 CentralRole role = new CentralRole(userApp.getRole().getId(), userApp.getRole().getName(),
3480 userApp.getRole().getActive(), userApp.getRole().getPriority(), cenRoleFunction);
3484 return new CentralUser.CentralUserBuilder().setId(cenV2User.getId()).setCreated(cenV2User.getCreated())
3485 .setModified(cenV2User.getModified()).setCreatedId(cenV2User.getCreatedId())
3486 .setModifiedId(cenV2User.getModifiedId()).setRowNum(cenV2User.getRowNum())
3487 .setOrgId(cenV2User.getOrgId()).setManagerId(cenV2User.getManagerId())
3488 .setFirstName(cenV2User.getFirstName()).setMiddleInitial(cenV2User.getMiddleInitial())
3489 .setLastName(cenV2User.getLastName()).setPhone(cenV2User.getPhone()).setFax(cenV2User.getFax())
3490 .setCellular(cenV2User.getCellular()).setEmail(cenV2User.getEmail())
3491 .setAddressId(cenV2User.getAddressId()).setAlertMethodCd(cenV2User.getAlertMethodCd())
3492 .setHrid(cenV2User.getHrid()).setOrgUserId(cenV2User.getOrgUserId()).setOrgCode(cenV2User.getOrgCode())
3493 .setAddress1(cenV2User.getAddress1()).setAddress2(cenV2User.getAddress2()).setCity(cenV2User.getCity())
3494 .setState(cenV2User.getState()).setZipCode(cenV2User.getZipCode()).setCountry(cenV2User.getCountry())
3495 .setOrgManagerUserId(cenV2User.getOrgManagerUserId()).setLocationClli(cenV2User.getLocationClli())
3496 .setBusinessCountryCode(cenV2User.getBusinessCountryCode())
3497 .setBusinessCountryName(cenV2User.getBusinessCountryName()).setBusinessUnit(cenV2User.getBusinessUnit())
3498 .setBusinessUnitName(cenV2User.getBusinessUnitName()).setDepartment(cenV2User.getDepartment())
3499 .setDepartmentName(cenV2User.getDepartmentName()).setCompanyCode(cenV2User.getCompanyCode())
3500 .setCompany(cenV2User.getCompany()).setZipCodeSuffix(cenV2User.getZipCodeSuffix())
3501 .setJobTitle(cenV2User.getJobTitle()).setCommandChain(cenV2User.getCommandChain())
3502 .setSiloStatus(cenV2User.getSiloStatus()).setCostCenter(cenV2User.getCostCenter())
3503 .setFinancialLocCode(cenV2User.getFinancialLocCode()).setLoginId(cenV2User.getLoginId())
3504 .setLoginPwd(cenV2User.getLoginPwd()).setLastLoginDate(cenV2User.getLastLoginDate())
3505 .setActive(cenV2User.isActive()).setInternal(cenV2User.isInternal())
3506 .setSelectedProfileId(cenV2User.getSelectedProfileId()).setTimeZoneId(cenV2User.getTimeZoneId())
3507 .setOnline(cenV2User.isOnline()).setChatId(cenV2User.getChatId()).setUserApps(userApps)
3508 .createCentralUser();
3512 public List<CentralRole> convertV2CentralRoleListToOldVerisonCentralRoleList(List<CentralV2Role> v2CenRoleList) {
3513 List<CentralRole> cenRoleList = new ArrayList<>();
3514 for (CentralV2Role v2CenRole : v2CenRoleList) {
3515 SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
3516 for (CentralV2RoleFunction v2CenRoleFunc : v2CenRole.getRoleFunctions()) {
3517 CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(),
3518 v2CenRoleFunc.getName());
3519 cenRoleFuncList.add(roleFunc);
3521 CentralRole role = new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.getActive(),
3522 v2CenRole.getPriority(), cenRoleFuncList);
3523 cenRoleList.add(role);
3529 public ResponseEntity<String> getNameSpaceIfExists(EPApp app) throws Exception {
3530 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3531 HttpEntity<String> entity = new HttpEntity<>(headers);
3532 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Connecting to External Auth system");
3533 ResponseEntity<String> response = null;
3536 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
3537 + "nss/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
3538 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Finished ",
3539 response.getStatusCode().value());
3540 } catch (HttpClientErrorException e) {
3541 logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e);
3542 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3543 if (e.getStatusCode() == HttpStatus.NOT_FOUND)
3544 throw new InvalidApplicationException("Invalid NameSpace");
3552 public CentralRole convertV2CentralRoleToOldVerisonCentralRole(CentralV2Role v2CenRole) {
3553 SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
3554 for (CentralV2RoleFunction v2CenRoleFunc : v2CenRole.getRoleFunctions()) {
3555 CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName());
3556 cenRoleFuncList.add(roleFunc);
3558 return new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.getActive(), v2CenRole.getPriority(),
3562 @SuppressWarnings("unchecked")
3564 public Integer bulkUploadUsersSingleRole(String uebkey, Long roleId, String modifiedRoleName) throws Exception {
3565 EPApp app = getApp(uebkey).get(0);
3566 final Map<String, String> params = new HashMap<>();
3567 params.put("uebKey", app.getUebKey());
3568 params.put("roleId", String.valueOf(roleId));
3569 List<BulkUploadUserRoles> userRolesList = null;
3570 Integer userRolesAdded = 0;
3571 if (app.getCentralAuth()) {
3572 userRolesList = dataAccessService.executeNamedQuery("getBulkUsersForSingleRole", params, null);
3573 for (BulkUploadUserRoles userRolesUpload : userRolesList) {
3574 userRolesUpload.setRoleName(modifiedRoleName);
3575 if (!userRolesUpload.getOrgUserId().equals("su1234")) {
3576 addUserRoleInExternalSystem(userRolesUpload);
3581 return userRolesAdded;
3585 public void bulkUploadRoleFunc(UploadRoleFunctionExtSystem data, EPApp app) throws Exception {
3586 ObjectMapper mapper = new ObjectMapper();
3587 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3589 ExternalAccessRolePerms extRolePerms;
3590 ExternalAccessPerms extPerms;
3591 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + data.getType(),
3592 EcompPortalUtils.encodeFunctionCode(data.getInstance()), data.getAction());
3593 String appNameSpace = "";
3594 if (data.getIsGlobalRolePartnerFunc()) {
3595 appNameSpace = epAppService.getApp(1l).getNameSpace();
3597 appNameSpace = app.getNameSpace();
3599 extRolePerms = new ExternalAccessRolePerms(extPerms, appNameSpace + "." + data.getRoleName()
3600 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
3601 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
3602 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
3603 updateRoleFunctionInExternalSystem(updateRolePerms, entity);
3604 } catch (HttpClientErrorException e) {
3605 logger.error(EELFLoggerDelegate.errorLogger,
3606 "HttpClientErrorException - Failed to add role function in external central auth system", e);
3607 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3609 } catch (Exception e) {
3610 logger.error(EELFLoggerDelegate.errorLogger,
3611 "addFunctionInExternalSystem: Failed to add role fucntion in external central auth system", e);
3616 private void updateRoleFunctionInExternalSystem(String updateRolePerms, HttpEntity<String> entity) {
3617 logger.debug(EELFLoggerDelegate.debugLogger, "bulkUploadRoleFunc: {} for POST: {}",
3618 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
3619 ResponseEntity<String> addPermResponse = template.exchange(
3620 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
3621 HttpMethod.POST, entity, String.class);
3622 logger.debug(EELFLoggerDelegate.debugLogger,
3623 "bulkUploadRoleFunc: Finished adding permission for POST: {} and status code: {} ",
3624 addPermResponse.getStatusCode().value(), updateRolePerms);
3628 public void syncApplicationUserRolesFromExtAuthSystem(String loginId) throws Exception {
3630 if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
3631 name = loginId + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
3633 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3634 HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
3635 ResponseEntity<String> getResponse = getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
3636 List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
3637 String res = getResponse.getBody();
3638 JSONObject jsonObj = null;
3639 JSONArray extRoles = null;
3640 if (!res.equals("{}")) {
3641 jsonObj = new JSONObject(res);
3642 extRoles = jsonObj.getJSONArray("role");
3644 updateUserRolesInLocal(userRoleDetailList, extRoles, loginId);
3647 @SuppressWarnings("unchecked")
3648 private void updateUserRolesInLocal(List<ExternalAccessUserRoleDetail> userRoleDetailList, JSONArray extRoles,
3649 String loginId) throws InvalidUserException {
3650 HashMap<String, String> userParams = new HashMap<>();
3651 userParams.put("orgUserId", loginId);
3652 // Get all centralized applications existing user roles from local
3653 List<CentralizedAppRoles> currentUserAppRoles = dataAccessService
3654 .executeNamedQuery("getUserCentralizedAppRoles", userParams, null);
3655 EPUser user = getUser(loginId).get(0);
3656 // Get all centralized applications roles from local
3657 HashMap<String, CentralizedAppRoles> cenAppRolesMap = getCentralizedAppRoleList();
3658 HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap = getCurrentUserCentralizedAppRoles(
3659 currentUserAppRoles);
3660 // Get all centralized applications + admin role from local
3661 HashMap<String, EPApp> centralisedAppsMap = getCentralizedAdminAppsInfo();
3662 if (extRoles != null) {
3663 ExternalAccessUserRoleDetail userRoleDetail = null;
3664 for (int i = 0; i < extRoles.length(); i++) {
3665 if (!extRoles.getJSONObject(i).getString("name").endsWith(ADMIN)
3666 && !extRoles.getJSONObject(i).getString("name").endsWith(OWNER)) {
3667 userRoleDetail = new ExternalAccessUserRoleDetail(extRoles.getJSONObject(i).getString("name"),
3669 userRoleDetailList.add(userRoleDetail);
3672 addUserRolesInLocal(userRoleDetailList, user, cenAppRolesMap, currentCentralizedUserAppRolesMap,
3673 centralisedAppsMap);
3677 private void addUserRolesInLocal(List<ExternalAccessUserRoleDetail> userRoleDetailList, EPUser user,
3678 HashMap<String, CentralizedAppRoles> cenAppRolesMap,
3679 HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap,
3680 HashMap<String, EPApp> centralisedAppsMap) {
3681 for (ExternalAccessUserRoleDetail extUserRoleDetail : userRoleDetailList) {
3683 // check if user already has role in local
3684 if (!currentCentralizedUserAppRolesMap.containsKey(extUserRoleDetail.getName())) {
3685 CentralizedAppRoles getCenAppRole = cenAppRolesMap.get(extUserRoleDetail.getName());
3686 if (getCenAppRole != null) {
3687 logger.debug(EELFLoggerDelegate.debugLogger,
3688 "addUserRolesInLocal: Adding user role from external auth system {}",
3689 extUserRoleDetail.toString());
3690 EPUserApp userApp = new EPUserApp();
3691 EPApp app = new EPApp();
3692 app.setId(getCenAppRole.getAppId());
3693 EPRole epRole = new EPRole();
3694 epRole.setId(getCenAppRole.getRoleId());
3695 userApp.setApp(app);
3696 userApp.setUserId(user.getId());
3697 userApp.setRole(epRole);
3698 dataAccessService.saveDomainObject(userApp, null);
3699 logger.debug(EELFLoggerDelegate.debugLogger,
3700 "addUserRolesInLocal: Finished user role from external auth system {}",
3701 extUserRoleDetail.toString());
3702 } else if (getCenAppRole == null // check if user has app
3703 // account admin role
3704 && extUserRoleDetail.getName().endsWith(PortalConstants.ADMIN_ROLE.replaceAll(
3705 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
3706 EPApp app = centralisedAppsMap.get(extUserRoleDetail.getName());
3708 logger.debug(EELFLoggerDelegate.debugLogger,
3709 "addUserRolesInLocal: Adding user role from external auth system {}",
3710 extUserRoleDetail.toString());
3711 EPUserApp userApp = new EPUserApp();
3712 EPRole epRole = new EPRole();
3713 epRole.setId(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
3714 userApp.setApp(app);
3715 userApp.setUserId(user.getId());
3716 userApp.setRole(epRole);
3717 dataAccessService.saveDomainObject(userApp, null);
3718 logger.debug(EELFLoggerDelegate.debugLogger,
3719 "addUserRolesInLocal: Finished user role from external auth system {}",
3720 extUserRoleDetail.toString());
3724 } catch (Exception e) {
3725 logger.error(EELFLoggerDelegate.errorLogger,
3726 "addUserRolesInLocal - Failed to update user role in local from external auth system {} ",
3727 extUserRoleDetail.toString(), e);
3732 @SuppressWarnings("unchecked")
3733 private HashMap<String, EPApp> getCentralizedAdminAppsInfo() {
3734 List<EPApp> centralizedApps = dataAccessService.executeNamedQuery("getCentralizedApps", null, null);
3735 HashMap<String, EPApp> centralisedAppsMap = new HashMap<>();
3736 for (EPApp cenApp : centralizedApps) {
3737 centralisedAppsMap.put(
3738 cenApp.getNameSpace() + "."
3739 + PortalConstants.ADMIN_ROLE.replaceAll(
3740 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
3743 return centralisedAppsMap;
3746 private HashMap<String, CentralizedAppRoles> getCurrentUserCentralizedAppRoles(
3747 List<CentralizedAppRoles> currentUserAppRoles) {
3748 HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap = new HashMap<>();
3749 for (CentralizedAppRoles cenAppUserRole : currentUserAppRoles) {
3750 currentCentralizedUserAppRolesMap.put(
3751 cenAppUserRole.getAppNameSpace() + "."
3752 + cenAppUserRole.getRoleName().replaceAll(
3753 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
3756 return currentCentralizedUserAppRolesMap;
3759 @SuppressWarnings("unchecked")
3760 private HashMap<String, CentralizedAppRoles> getCentralizedAppRoleList() {
3761 List<CentralizedAppRoles> centralizedAppRoles = dataAccessService
3762 .executeNamedQuery("getAllCentralizedAppsRoles", null, null);
3763 HashMap<String, CentralizedAppRoles> cenAppRolesMap = new HashMap<>();
3764 for (CentralizedAppRoles CentralizedAppRole : centralizedAppRoles) {
3766 CentralizedAppRole.getAppNameSpace() + "."
3767 + CentralizedAppRole.getRoleName().replaceAll(
3768 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
3769 CentralizedAppRole);
3771 return cenAppRolesMap;
3775 public ResponseEntity<String> getUserRolesFromExtAuthSystem(String name, HttpEntity<String> getUserRolesEntity) {
3776 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles");
3777 ResponseEntity<String> getResponse = template
3778 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
3779 + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class);
3780 if (getResponse.getStatusCode().value() == 200) {
3781 logger.debug(EELFLoggerDelegate.debugLogger,
3782 "getAllUserRoleFromExtAuthSystem: Finished GET user roles from external system and received user roles {}",
3783 getResponse.getBody());
3785 logger.error(EELFLoggerDelegate.errorLogger,
3786 "getAllUserRoleFromExtAuthSystem: Failed GET user roles from external system and received user roles {}",
3787 getResponse.getBody());
3788 EPLogUtil.logExternalAuthAccessAlarm(logger, getResponse.getStatusCode());
3794 public Integer updateAppRoleDescription(String uebkey) {
3795 Integer roleDescUpdated = 0;
3798 app = getApp(uebkey).get(0);
3799 List<EPRole> roles = getAppRoles(app.getId());
3800 for (EPRole epRole : roles) {
3801 Role role = new Role();
3802 role.setName(epRole.getName());
3803 boolean status = addRoleDescriptionInExtSystem(role, app);
3807 } catch (Exception e) {
3808 logger.error(EELFLoggerDelegate.errorLogger, "updateAppRoleDescription: Failed! ", e);
3810 return roleDescUpdated;