2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
8 * Unless otherwise specified, all software contained herein is licensed
9 * under the Apache License, Version 2.0 (the “License”);
10 * you may not use this software except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * Unless otherwise specified, all documentation contained herein is licensed
22 * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
23 * you may not use this documentation except in compliance with the License.
24 * You may obtain a copy of the License at
26 * https://creativecommons.org/licenses/by/4.0/
28 * Unless required by applicable law or agreed to in writing, documentation
29 * distributed under the License is distributed on an "AS IS" BASIS,
30 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31 * See the License for the specific language governing permissions and
32 * limitations under the License.
34 * ============LICENSE_END============================================
36 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
38 package org.openecomp.portalapp.portal.service;
40 import java.util.ArrayList;
41 import java.util.HashMap;
42 import java.util.HashSet;
43 import java.util.Iterator;
44 import java.util.LinkedHashMap;
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.lang.StringUtils;
53 import org.hibernate.Query;
54 import org.hibernate.Session;
55 import org.hibernate.SessionFactory;
56 import org.hibernate.Transaction;
57 import org.json.JSONArray;
58 import org.json.JSONObject;
59 import org.openecomp.portalapp.portal.domain.CentralRoleFunction;
60 import org.openecomp.portalapp.portal.domain.EPApp;
61 import org.openecomp.portalapp.portal.domain.EPAppRoleFunction;
62 import org.openecomp.portalapp.portal.domain.EPRole;
63 import org.openecomp.portalapp.portal.domain.EPUser;
64 import org.openecomp.portalapp.portal.domain.EPUserApp;
65 import org.openecomp.portalapp.portal.domain.ExternalRoleDetails;
66 import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
67 import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
68 import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
69 import org.openecomp.portalapp.portal.transport.BulkUploadRoleFunction;
70 import org.openecomp.portalapp.portal.transport.BulkUploadUserRoles;
71 import org.openecomp.portalapp.portal.transport.CentralApp;
72 import org.openecomp.portalapp.portal.transport.CentralRole;
73 import org.openecomp.portalapp.portal.transport.CentralUser;
74 import org.openecomp.portalapp.portal.transport.CentralUserApp;
75 import org.openecomp.portalapp.portal.transport.EcompUserRoles;
76 import org.openecomp.portalapp.portal.transport.ExternalAccessPerms;
77 import org.openecomp.portalapp.portal.transport.ExternalAccessPermsDetail;
78 import org.openecomp.portalapp.portal.transport.ExternalAccessRole;
79 import org.openecomp.portalapp.portal.transport.ExternalAccessRolePerms;
80 import org.openecomp.portalapp.portal.transport.ExternalAccessUser;
81 import org.openecomp.portalapp.portal.transport.ExternalRoleDescription;
82 import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
83 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
84 import org.openecomp.portalapp.portal.utils.PortalConstants;
85 import org.openecomp.portalsdk.core.domain.Role;
86 import org.openecomp.portalsdk.core.domain.RoleFunction;
87 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
88 import org.openecomp.portalsdk.core.restful.domain.EcompRole;
89 import org.openecomp.portalsdk.core.restful.domain.EcompUser;
90 import org.openecomp.portalsdk.core.service.DataAccessService;
91 import org.openecomp.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.ResponseEntity;
98 import org.springframework.stereotype.Service;
99 import org.springframework.transaction.annotation.Transactional;
100 import org.springframework.web.client.HttpClientErrorException;
101 import org.springframework.web.client.RestTemplate;
103 import com.fasterxml.jackson.core.JsonProcessingException;
104 import com.fasterxml.jackson.databind.DeserializationFeature;
105 import com.fasterxml.jackson.databind.ObjectMapper;
106 import com.fasterxml.jackson.databind.type.TypeFactory;
108 @Service("externalAccessRolesService")
109 @EnableAspectJAutoProxy
112 public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesService {
114 private static final String AND_FUNCTION_CD_EQUALS = " and function_cd = '";
116 private static final String OWNER = ".owner";
118 private static final String ADMIN = ".admin";
120 private static final String ACCOUNT_ADMINISTRATOR = ".Account_Administrator";
122 private static final String FUNCTION_CD_LIKE_CLAUSE = " and function_cd like '%";
124 private static final String FUNCTION_PIPE = "|";
126 private static final String IS_NULL_STRING = "null";
128 private static final String EXTERNAL_AUTH_PERMS = "perms";
130 private static final String EXTERNAL_AUTH_ROLE_DESCRIPTION = "description";
132 private static final String WHERE_APP_ID_EQUALS = " where app_id = ";
134 private static final String IS_EMPTY_JSON_STRING = "{}";
136 private static final String CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE = "Connecting to External Auth system";
138 private static final String WHERE_ROLE_ID_EQUALS = " where role_id = ";
140 private static final String APP_ROLE_ID = "appRoleId";
142 private static final String APP_ID = "appId";
144 private static final String PRIORITY = "priority";
146 private static final String ACTIVE = "active";
148 private static final String ROLE_NAME = "name";
150 private static final String ID = "id";
152 private static final String WHERE_ROLE_NAME_EQUALS = " where role_name = '";
154 private static final String APP_ID_EQUALS = " app_id = ";
156 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesServiceImpl.class);
159 private DataAccessService dataAccessService;
162 private SessionFactory sessionFactory;
164 RestTemplate template = new RestTemplate();
166 @SuppressWarnings("unchecked")
167 public List<EPRole> getAppRoles(Long appId) throws Exception {
168 List<EPRole> applicationRoles = null;
169 String filter = null;
172 filter = " where app_id is null";
174 filter = WHERE_APP_ID_EQUALS + appId;
176 applicationRoles = dataAccessService.getList(EPRole.class, filter, null, null);
177 } catch (Exception e) {
178 logger.error(EELFLoggerDelegate.errorLogger, "getAppRoles: failed", e);
179 throw new Exception(e.getMessage());
181 return applicationRoles;
184 @SuppressWarnings("unchecked")
186 public List<EPApp> getApp(String uebkey) throws Exception {
187 List<EPApp> app = null;
189 app = (List<EPApp>) dataAccessService.getList(EPApp.class, " where ueb_key = '" + uebkey + "'", null, null);
190 if(!app.get(0).getEnabled() && !app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)){
191 throw new Exception("Application:"+app.get(0).getName()+" is Unavailable");
193 } catch (Exception e) {
194 logger.error(EELFLoggerDelegate.errorLogger, "getApp: failed", e);
195 throw new Exception(e.getMessage());
201 * It returns single application role from external auth system
204 * @return JSON string which contains application role details
207 private String getSingleAppRole(String addRole, EPApp app) throws Exception {
208 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
209 HttpEntity<String> entity = new HttpEntity<>(headers);
210 logger.debug(EELFLoggerDelegate.debugLogger, "getSingleAppRole: Connecting to External Auth system");
211 ResponseEntity<String> response = template
213 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
214 + app.getNameSpace() + "." + addRole.replaceAll(" ", "_"),
215 HttpMethod.GET, entity, String.class);
216 logger.debug(EELFLoggerDelegate.debugLogger,
217 "getSingleAppRole: Finished GET app role from External Auth system and status code: {} ", response.getStatusCode().value());
218 return response.getBody();
222 public boolean addRole(Role addRole, String uebkey) throws Exception {
223 boolean response = false;
224 ResponseEntity<String> addResponse = null;
225 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
226 EPApp app = getApp(uebkey).get(0);
227 String newRole = updateExistingRoleInExternalSystem(addRole, app);
228 HttpEntity<String> entity = new HttpEntity<>(newRole, headers);
229 logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Connecting to External Auth system");
230 addResponse = template.exchange(
231 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
232 HttpMethod.POST, entity, String.class);
233 if (addResponse.getStatusCode().value() == 201) {
235 logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Finished adding role in the External Auth system and response code: {} ", addResponse.getStatusCode().value());
237 if (addResponse.getStatusCode().value() == 406) {
238 logger.error(EELFLoggerDelegate.errorLogger,
239 "addRole: Failed to add in the External Auth system due to {} and status code: {}", addResponse.getBody(), addResponse.getStatusCode().value());
246 * It deletes record in external auth system
249 * @return JSON String which has status code and response body
252 private ResponseEntity<String> deleteRoleInExternalSystem(String delRole) throws Exception {
253 ResponseEntity<String> delResponse = null;
254 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
255 HttpEntity<String> entity = new HttpEntity<>(delRole, headers);
256 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
257 delResponse = template.exchange(
258 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role?force=true",
259 HttpMethod.DELETE, entity, String.class);
260 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: Finished DELETE operation in the External Auth system and status code: {} ", delResponse.getStatusCode().value());
265 * It updates role in external auth system
267 * @param updateExtRole
269 * @return true if success else false
271 * If updateRoleInExternalSystem fails we catch it in logger for detail message
273 @SuppressWarnings("unchecked")
274 private boolean updateRoleInExternalSystem(Role updateExtRole, EPApp app) throws Exception {
275 boolean response = false;
276 ObjectMapper mapper = new ObjectMapper();
277 ResponseEntity<String> deleteResponse = null;
278 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
279 ExternalAccessRolePerms extRolePerms = null;
280 ExternalAccessPerms extPerms = null;
281 List<EPRole> epRoleList = null;
282 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
283 epRoleList = dataAccessService.getList(EPRole.class,
284 WHERE_ROLE_ID_EQUALS + updateExtRole.getId() + " and app_id is null", null, null);
286 epRoleList = dataAccessService.getList(EPRole.class,
287 " where app_role_id = " + updateExtRole.getId() + " and app_id = " + app.getId(), null, null);
289 String appRole = getSingleAppRole(epRoleList.get(0).getName(), app);
290 if (!appRole.equals(IS_EMPTY_JSON_STRING)) {
291 JSONObject jsonObj = new JSONObject(appRole);
292 JSONArray extRole = jsonObj.getJSONArray("role");
293 if (!extRole.getJSONObject(0).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
294 String roleName = extRole.getJSONObject(0).getString(ROLE_NAME);
295 Map<String, String> delRoleKeyMapper = new HashMap<>();
296 delRoleKeyMapper.put(ROLE_NAME, roleName);
297 String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
298 deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
299 if (deleteResponse.getStatusCode().value() != 200) {
300 throw new Exception(deleteResponse.getBody());
302 addRole(updateExtRole, app.getUebKey());
304 String desc = extRole.getJSONObject(0).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
305 String name = extRole.getJSONObject(0).getString(ROLE_NAME);
306 List<ExternalAccessPerms> list = null;
307 if (extRole.getJSONObject(0).has(EXTERNAL_AUTH_PERMS)) {
308 JSONArray perms = extRole.getJSONObject(0).getJSONArray(EXTERNAL_AUTH_PERMS);
309 list = mapper.readValue(perms.toString(), TypeFactory.defaultInstance()
310 .constructCollectionType(List.class, ExternalAccessPerms.class));
312 ExternalRoleDescription sysRoleList = mapper.readValue(desc, ExternalRoleDescription.class);
313 // If role name or role functions are updated then delete record in External System and add new record to avoid conflicts
314 Boolean existingRoleActive;
315 boolean isActiveValueChanged;
316 // check role active status
317 existingRoleActive = new Boolean(sysRoleList.getActive());
318 isActiveValueChanged = existingRoleActive.equals(updateExtRole.getActive());
319 if (!sysRoleList.getName().equals(updateExtRole.getName())) {
320 Map<String, String> delRoleKeyMapper = new HashMap<>();
321 delRoleKeyMapper.put(ROLE_NAME, name);
322 String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
323 deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
324 if (deleteResponse.getStatusCode().value() != 200) {
325 logger.error(EELFLoggerDelegate.errorLogger, "updateRoleInExternalSystem: Failed to delete role in external system due to {} ", deleteResponse.getBody());
326 throw new Exception(deleteResponse.getBody());
328 addRole(updateExtRole, app.getUebKey());
329 addRoleFunctionsInExternalSystem(updateExtRole, mapper, app);
331 boolean checkPriorityStatus = StringUtils.equals(String.valueOf(sysRoleList.getPriority()),String.valueOf(updateExtRole.getPriority()));
332 ExternalAccessRole updateRole = new ExternalAccessRole();
333 if (!isActiveValueChanged
334 || !checkPriorityStatus
335 || sysRoleList.getId().equals(IS_NULL_STRING)
336 || !sysRoleList.getId().equals(String.valueOf(epRoleList.get(0).getId()))) {
337 String updateDesc = "";
338 String appId = (app.getId().equals(PortalConstants.PORTAL_APP_ID)) ? " app_id is null"
339 : APP_ID_EQUALS + app.getId();
340 List<EPRole> getRole = dataAccessService.getList(EPRole.class,
341 WHERE_ROLE_NAME_EQUALS + updateExtRole.getName() + "' and " + appId, null, null);
342 Map<String, String> extSystemUpdateRoleJsonMapper = new LinkedHashMap<>();
343 extSystemUpdateRoleJsonMapper.put(ID, String.valueOf(getRole.get(0).getId()));
344 extSystemUpdateRoleJsonMapper.put(ROLE_NAME, String.valueOf(updateExtRole.getName()));
345 extSystemUpdateRoleJsonMapper.put(ACTIVE, String.valueOf(updateExtRole.getActive()));
346 extSystemUpdateRoleJsonMapper.put(PRIORITY, String.valueOf(updateExtRole.getPriority()));
347 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
348 extSystemUpdateRoleJsonMapper.put(APP_ID, "null");
349 extSystemUpdateRoleJsonMapper.put(APP_ROLE_ID, "null");
351 extSystemUpdateRoleJsonMapper.put(APP_ID, String.valueOf(app.getId()));
352 extSystemUpdateRoleJsonMapper.put(APP_ROLE_ID, String.valueOf(getRole.get(0).getAppRoleId()));
355 updateDesc = mapper.writeValueAsString(extSystemUpdateRoleJsonMapper);
356 updateRole.setName(app.getNameSpace() + "." + updateExtRole.getName().replaceAll(" ", "_"));
357 updateRole.setDescription(updateDesc);
358 String updateRoleDesc = mapper.writeValueAsString(updateRole);
359 HttpEntity<String> entity = new HttpEntity<>(updateRoleDesc, headers);
360 logger.debug(EELFLoggerDelegate.debugLogger,
361 "updateRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
362 ResponseEntity<String> updatePermsResponse = template.exchange(
363 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
364 HttpMethod.PUT, entity, String.class);
365 logger.debug(EELFLoggerDelegate.debugLogger,
366 "updateRoleInExternalSystem: Finished updating in External Auth system and status code: {} ",
367 updatePermsResponse.getStatusCode().value());
369 List<RoleFunction> roleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole);
370 Map<String, RoleFunction> updateRoleFunc = new HashMap<>();
371 for (RoleFunction addPerm : roleFunctionListNew) {
372 updateRoleFunc.put(addPerm.getCode(), addPerm);
374 final Map<String, ExternalAccessPerms> extRolePermMap = new HashMap<>();
375 // Update permissions in the ExternalAccess System
377 for (ExternalAccessPerms perm : list) {
378 if (!updateRoleFunc.containsKey(perm.getInstance())) {
379 removePermForRole(perm, mapper, name, headers);
381 extRolePermMap.put(perm.getInstance(), perm);
385 if (!roleFunctionListNew.isEmpty()) {
386 for (RoleFunction roleFunc : roleFunctionListNew) {
387 if (!extRolePermMap.containsKey(roleFunc.getCode())) {
388 String checkType = roleFunc.getCode().contains("menu") ? "menu" : "url";
389 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, roleFunc.getCode(),
391 extRolePerms = new ExternalAccessRolePerms(extPerms,
392 app.getNameSpace() + "." + updateExtRole.getName().replaceAll(" ", "_"));
393 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
394 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
395 logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
396 ResponseEntity<String> addResponse = template.exchange(
397 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
399 HttpMethod.POST, entity, String.class);
400 if (addResponse.getStatusCode().value() != 201) {
402 logger.debug(EELFLoggerDelegate.debugLogger,
403 "updateRoleInExternalSystem: Connected to External Auth system but something went wrong! due to {} and statuscode: {}",
404 addResponse.getStatusCode().getReasonPhrase(),
405 addResponse.getStatusCode().value());
408 logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: Finished adding permissions to roles in External Auth system and status code: {} ", addResponse.getStatusCode().value());
415 // It seems like role exists in local DB but not in External Access system
416 addRole(updateExtRole, app.getUebKey());
417 List<RoleFunction> roleFunctionListUpdate = convertSetToListOfRoleFunctions(updateExtRole);
419 if (!roleFunctionListUpdate.isEmpty()) {
420 addRoleFunctionsInExternalSystem(updateExtRole, mapper, app);
428 * It adds functions to the role in external auth system
430 * @param updateExtRole
431 * @param addPermsMapper
433 * @return true if success else false
436 private boolean addRoleFunctionsInExternalSystem(Role updateExtRole, ObjectMapper addPermsMapper, EPApp app)
438 boolean response = false;
439 ExternalAccessRolePerms extAddRolePerms = null;
440 ExternalAccessPerms extAddPerms = null;
441 List<RoleFunction> roleFunctionListAdd = convertSetToListOfRoleFunctions(updateExtRole);
442 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
443 for (RoleFunction roleFunc : roleFunctionListAdd) {
444 String checkType = roleFunc.getCode().contains("menu") ? "menu" : "url";
445 extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, roleFunc.getCode(), "*");
446 extAddRolePerms = new ExternalAccessRolePerms(extAddPerms,
447 app.getNameSpace() + "." + updateExtRole.getName().replaceAll(" ", "_"));
448 String updateRolePerms = addPermsMapper.writeValueAsString(extAddRolePerms);
449 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
450 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
451 ResponseEntity<String> addResponse = template.exchange(
452 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
453 HttpMethod.POST, entity, String.class);
454 if (addResponse.getStatusCode().value() != 201) {
456 logger.debug(EELFLoggerDelegate.debugLogger,
457 "addRoleFunctionsInExternalSystem: While adding permission to the role in External Auth system something went wrong! due to {} and statuscode: {}",
458 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
461 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system and status code: {} ", addResponse.getStatusCode().value());
469 * It converts list of functions in updateExtRole parameter to the RoleFunction object
471 * @param updateExtRole
472 * @return list of functions
474 @SuppressWarnings("unchecked")
475 private List<RoleFunction> convertSetToListOfRoleFunctions(Role updateExtRole) {
476 Set<RoleFunction> roleFunctionSetList = updateExtRole.getRoleFunctions();
477 List<RoleFunction> roleFunctionList = new ArrayList<>();
478 ObjectMapper roleFuncMapper = new ObjectMapper();
479 Iterator<RoleFunction> itetaror = roleFunctionSetList.iterator();
480 while (itetaror.hasNext()) {
481 Object nextValue = itetaror.next();
482 RoleFunction roleFunction = roleFuncMapper.convertValue(nextValue, RoleFunction.class);
483 roleFunctionList.add(roleFunction);
485 return roleFunctionList.stream().distinct().collect(Collectors.toList());
489 * It delete permissions/functions in the external auth system
497 private void removePermForRole(ExternalAccessPerms perm, ObjectMapper permMapper, String name, HttpHeaders headers)
499 ExternalAccessRolePerms extAccessRolePerms = new ExternalAccessRolePerms(perm, name);
500 String permDetails = permMapper.writeValueAsString(extAccessRolePerms);
501 HttpEntity<String> deleteEntity = new HttpEntity<>(permDetails, headers);
502 logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
503 ResponseEntity<String> deletePermResponse = template
504 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/"
505 + name + "/perm", HttpMethod.DELETE, deleteEntity, String.class);
506 if (deletePermResponse.getStatusCode().value() != 200) {
507 throw new Exception(deletePermResponse.getBody());
509 logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: Finished deleting permission to role in External Auth system and status code: {}",
510 deletePermResponse.getStatusCode().value());
514 * It will create new role in the External Auth System
518 * @return true if successfully added in the system else false
520 * If fails to add role in the system
522 private boolean addNewRoleInExternalSystem(List<EPRole> newRole, EPApp app) throws Exception {
523 boolean response = false;
524 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
525 ObjectMapper mapper = new ObjectMapper();
526 String addNewRole = "";
527 ExternalAccessRole extRole = new ExternalAccessRole();
528 String addDesc = null;
529 Map<String, String> extSystemJsonMapper = new LinkedHashMap<>();
530 extSystemJsonMapper.put(ID, String.valueOf(newRole.get(0).getId()));
531 extSystemJsonMapper.put(ROLE_NAME, String.valueOf(newRole.get(0).getName()));
532 extSystemJsonMapper.put(ACTIVE, String.valueOf(newRole.get(0).getActive()));
533 extSystemJsonMapper.put(PRIORITY, String.valueOf(newRole.get(0).getPriority()));
534 extSystemJsonMapper.put(APP_ID, String.valueOf(newRole.get(0).getAppId()));
535 extSystemJsonMapper.put(APP_ROLE_ID, String.valueOf(newRole.get(0).getAppRoleId()));
536 addDesc = mapper.writeValueAsString(extSystemJsonMapper);
537 extRole.setName(app.getNameSpace() + "." + newRole.get(0).getName().replaceAll(" ", "_"));
538 extRole.setDescription(addDesc);
539 addNewRole = mapper.writeValueAsString(extRole);
540 HttpEntity<String> deleteEntity = new HttpEntity<>(addNewRole, headers);
541 logger.debug(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
542 ResponseEntity<String> addNewRoleInExternalSystem = template.exchange(
543 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
544 HttpMethod.POST, deleteEntity, String.class);
545 if (addNewRoleInExternalSystem.getStatusCode().value() != 201) {
546 throw new Exception(addNewRoleInExternalSystem.getBody());
548 logger.debug(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: Finished adding into External Auth system and status code: {}",
549 addNewRoleInExternalSystem.getStatusCode().value());
557 * It updates existing role in the External Auth System
560 * It Contains role information
562 * @return string which is formatted to match with the external auth system
563 * @throws JsonProcessingException
565 @SuppressWarnings("unchecked")
566 private String updateExistingRoleInExternalSystem(Role addRole, EPApp app) throws JsonProcessingException {
567 ObjectMapper mapper = new ObjectMapper();
568 String addNewRole = "";
569 ExternalAccessRole extRole = new ExternalAccessRole();
570 List<EPRole> role = null;
571 String addDesc = null;
572 Map<String, String> extSystemUpdateRole = new LinkedHashMap<>();
573 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
574 role = dataAccessService.getList(EPRole.class, WHERE_ROLE_ID_EQUALS + addRole.getId() + " and app_id is null", null, null);
576 role = dataAccessService.getList(EPRole.class, " where app_role_id = " + addRole.getId() + " and app_id ="+app.getId(), null, null);
578 extSystemUpdateRole.put(ID, String.valueOf(role.get(0).getId()));
579 extSystemUpdateRole.put(ROLE_NAME, String.valueOf(addRole.getName()));
580 extSystemUpdateRole.put(ACTIVE, String.valueOf(role.get(0).getActive()));
581 extSystemUpdateRole.put(PRIORITY, String.valueOf(role.get(0).getPriority()));
582 extSystemUpdateRole.put(APP_ID, String.valueOf(role.get(0).getAppId()));
583 extSystemUpdateRole.put(APP_ROLE_ID, String.valueOf(role.get(0).getAppRoleId()));
584 addDesc = mapper.writeValueAsString(extSystemUpdateRole);
585 extRole.setName(app.getNameSpace() + "." + addRole.getName().replaceAll(" ", "_"));
586 extRole.setDescription(addDesc);
587 addNewRole = mapper.writeValueAsString(extRole);
592 * It create a role in the external auth system and then in our local
596 * @return true else false
599 @SuppressWarnings("unchecked")
601 private boolean addRoleInEcompDB(Role addRoleInDB, EPApp app) throws Exception {
602 boolean result = false;
603 List<EPRole> applicationRoles = null;
604 EPRole epRole = null;
605 Set<RoleFunction> roleFunctionList = addRoleInDB.getRoleFunctions();
606 List<RoleFunction> roleFunctionListNew = new ArrayList<>();
607 ObjectMapper mapper = new ObjectMapper();
608 Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
609 while (itetaror.hasNext()) {
610 Object nextValue = itetaror.next();
611 RoleFunction roleFunction = mapper.convertValue(nextValue, RoleFunction.class);
612 roleFunctionListNew.add(roleFunction);
614 List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct().collect(Collectors.toList());
616 if (addRoleInDB.getId() == null) { // check if it is new role
617 checkIfRoleExitsInExternalSystem(addRoleInDB, app);
618 EPRole epRoleNew = new EPRole();
619 epRoleNew.setActive(addRoleInDB.getActive());
620 epRoleNew.setName(addRoleInDB.getName());
621 epRoleNew.setPriority(addRoleInDB.getPriority());
622 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
623 epRoleNew.setAppId(null);
625 epRoleNew.setAppId(app.getId());
627 dataAccessService.saveDomainObject(epRoleNew, null);
628 List<EPRole> getRoleCreated = null;
629 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
630 List<EPRole> roleCreated = dataAccessService.getList(EPRole.class,
631 WHERE_ROLE_NAME_EQUALS + addRoleInDB.getName() + "' and app_id = " + app.getId(), null,
633 EPRole epUpdateRole = roleCreated.get(0);
634 epUpdateRole.setAppRoleId(epUpdateRole.getId());
635 dataAccessService.saveDomainObject(epUpdateRole, null);
636 getRoleCreated = dataAccessService.getList(EPRole.class,
637 WHERE_ROLE_NAME_EQUALS + addRoleInDB.getName() + "' and app_id = " + app.getId(), null,
640 getRoleCreated = dataAccessService.getList(EPRole.class,
641 WHERE_ROLE_NAME_EQUALS + addRoleInDB.getName() + "' and app_id is null", null, null);
643 // Add role in External Auth system
644 result = addNewRoleInExternalSystem(getRoleCreated, app);
645 } else { // if role already exists then update it
646 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
647 applicationRoles = dataAccessService.getList(EPRole.class,
648 " where app_id is null " + " and role_id = " + addRoleInDB.getId(), null, null);
650 applicationRoles = dataAccessService.getList(EPRole.class,
651 WHERE_APP_ID_EQUALS + app.getId() + " and app_role_id = " + addRoleInDB.getId(), null, null);
653 if (applicationRoles.isEmpty()) {
654 applicationRoles = dataAccessService.getList(EPRole.class,
655 WHERE_APP_ID_EQUALS + app.getId() + " and role_name = '" + addRoleInDB.getName() + "'", null,
658 updateRoleInExternalSystem(addRoleInDB, app);
659 deleteRoleFunction(app, applicationRoles);
660 if (!applicationRoles.isEmpty()) {
661 epRole = applicationRoles.get(0);
662 epRole.setName(addRoleInDB.getName());
663 epRole.setPriority(addRoleInDB.getPriority());
664 epRole.setActive(addRoleInDB.getActive());
665 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
666 epRole.setAppId(null);
667 epRole.setAppRoleId(null);
668 } else if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)
669 && applicationRoles.get(0).getAppRoleId() == null) {
670 epRole.setAppRoleId(epRole.getId());
672 dataAccessService.saveDomainObject(epRole, null);
675 saveRoleFunction(listWithoutDuplicates, app, applicationRoles);
678 } catch (Exception e) {
679 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInEcompDB is failed", e);
680 throw new Exception(e.getMessage());
687 * It validates whether role exists in external auth system
694 private void checkIfRoleExitsInExternalSystem(Role checkRole, EPApp app) throws Exception {
695 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
696 String roleName = app.getNameSpace() + "." + checkRole.getName().replaceAll(" ", "_");
697 HttpEntity<String> checkRoleEntity = new HttpEntity<>(headers);
698 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRoleExitsInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
699 ResponseEntity<String> checkRoleInExternalSystem = template
700 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
701 + roleName, HttpMethod.GET, checkRoleEntity, String.class);
702 if (!checkRoleInExternalSystem.getBody().equals(IS_EMPTY_JSON_STRING)) {
703 logger.debug("checkIfRoleExitsInExternalSystem: Role already exists in external system {} and status code: {} ", checkRoleInExternalSystem.getBody(), checkRoleInExternalSystem.getStatusCode().value());
704 throw new Exception("Role already exists in external system");
709 * It saves list of functions to the role in portal
711 * @param roleFunctionListNew
713 * @param applicationRoles
716 @SuppressWarnings("unchecked")
717 private void saveRoleFunction(List<RoleFunction> roleFunctionListNew, EPApp app, List<EPRole> applicationRoles)
719 for (RoleFunction roleFunc : roleFunctionListNew) {
720 EPAppRoleFunction appRoleFunc = new EPAppRoleFunction();
721 appRoleFunc.setAppId(app.getId());
722 appRoleFunc.setRoleId(applicationRoles.get(0).getId());
723 // query to check if function code is different for safe operation
724 List<CentralRoleFunction> roleFunction = dataAccessService.getList(CentralRoleFunction.class,
725 WHERE_APP_ID_EQUALS+ app.getId()+FUNCTION_CD_LIKE_CLAUSE + roleFunc.getCode() + "'", null, null);
726 appRoleFunc.setCode(roleFunction.get(0).getCode());
727 dataAccessService.saveDomainObject(appRoleFunc, null);
732 * It deletes all EPAppRoleFunction records in the portal
737 @SuppressWarnings("unchecked")
738 private void deleteRoleFunction(EPApp app, List<EPRole> role) {
739 List<EPAppRoleFunction> appRoleFunctionList = dataAccessService.getList(EPAppRoleFunction.class,
740 WHERE_APP_ID_EQUALS + app.getId() + " and role_id = " + role.get(0).getId(), null, null);
741 if (!appRoleFunctionList.isEmpty()) {
742 for (EPAppRoleFunction approleFunction : appRoleFunctionList) {
743 dataAccessService.deleteDomainObject(approleFunction, null);
749 @SuppressWarnings("unchecked")
750 public List<EPUser> getUser(String loginId){
751 return (List<EPUser>) dataAccessService.getList(EPUser.class,
752 " where org_user_id = '" + loginId + "'", null, null);
756 public String getUserWithRoles(String loginId, String uebkey) throws Exception {
757 final Map<String, String> params = new HashMap<>();
758 List<EPUser> userList = null;
759 CentralUser cenUser = null;
761 String result = null;
763 params.put("orgUserIdValue", loginId);
764 List<EPApp> appList = getApp(uebkey);
765 if (!appList.isEmpty()) {
766 app = appList.get(0);
767 userList = getUser(loginId);
768 if (!userList.isEmpty()) {
769 EPUser user = userList.get(0);
770 ObjectMapper mapper = new ObjectMapper();
771 Set<EPUserApp> userAppSet = user.getEPUserApps();
772 cenUser = createEPUser(user, userAppSet, app);
773 result = mapper.writeValueAsString(cenUser);
774 } else if (userList.isEmpty()) {
775 throw new Exception("User not found");
778 throw new Exception("Application not found");
780 } catch (Exception e) {
781 logger.error(EELFLoggerDelegate.errorLogger, "getUser: failed", e);
782 throw new Exception(e.getMessage());
788 public List<CentralRole> getRolesForApp(String uebkey) throws Exception {
789 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Entering into getRolesForApp");
790 List<CentralRole> roleList = new ArrayList<>();
791 final Map<String, Long> params = new HashMap<>();
793 List<EPApp> app = getApp(uebkey);
794 List<EPRole> appRolesList = getAppRoles(app.get(0).getId());
795 createCentralRoleObject(app, appRolesList, roleList, params);
796 } catch (Exception e) {
797 throw new Exception("getRolesForApp Failed", e);
799 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Finished getRolesForApp");
803 @SuppressWarnings("unchecked")
805 public List<CentralRoleFunction> getRoleFuncList(String uebkey) throws Exception {
806 EPApp app = getApp(uebkey).get(0);
807 List<CentralRoleFunction> finalRoleList = new ArrayList<>();
808 final Map<String, Long> params = new HashMap<>();
809 params.put(APP_ID, app.getId());
810 // Sync all functions from external system into Ecomp portal DB
811 logger.debug(EELFLoggerDelegate.debugLogger, "getRoleFuncList: Entering into syncRoleFunctionFromExternalAccessSystem");
812 syncRoleFunctionFromExternalAccessSystem(app);
813 logger.debug(EELFLoggerDelegate.debugLogger, "getRoleFuncList: Finished syncRoleFunctionFromExternalAccessSystem");
814 List<CentralRoleFunction> getRoleFuncList = dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null);
815 for(CentralRoleFunction roleFuncItem : getRoleFuncList ){
816 if(roleFuncItem.getCode().contains(FUNCTION_PIPE)){
818 int count = StringUtils.countMatches(roleFuncItem.getCode(), FUNCTION_PIPE);
820 code = roleFuncItem.getCode().substring(
821 roleFuncItem.getCode().indexOf(FUNCTION_PIPE) + 1,
822 roleFuncItem.getCode().lastIndexOf(FUNCTION_PIPE));
824 code = roleFuncItem.getCode()
825 .substring(roleFuncItem.getCode().lastIndexOf(FUNCTION_PIPE) + 1);
827 roleFuncItem.setCode(code);
828 finalRoleList.add(roleFuncItem);
830 finalRoleList.add(roleFuncItem);
833 return finalRoleList;
837 * It returns user detail information which is deep copy of EPUser.class object
845 @SuppressWarnings("unchecked")
846 private CentralUser createEPUser(EPUser userInfo, Set<EPUserApp> userAppSet, EPApp app) throws Exception {
848 final Map<String, Long> params = new HashMap<>();
849 CentralUser userAppList = new CentralUser();
850 CentralUser user1 = null;
852 userAppList.userApps = new TreeSet<CentralUserApp>();
853 for (EPUserApp userApp : userAppSet) {
854 if (userApp.getRole().getActive()) {
855 EPApp epApp = userApp.getApp();
856 String globalRole = userApp.getRole().getName().toLowerCase();
857 if (((epApp.getId().equals(app.getId()))
858 && (!userApp.getRole().getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)))
859 || ((epApp.getId().equals(PortalConstants.PORTAL_APP_ID))
860 && (globalRole.toLowerCase().startsWith("global_")))) {
861 CentralUserApp cua = new CentralUserApp();
863 CentralApp cenApp = new CentralApp(1L, epApp.getCreated(), epApp.getModified(),
864 epApp.getCreatedId(), epApp.getModifiedId(), epApp.getRowNum(), epApp.getName(),
865 epApp.getImageUrl(), epApp.getDescription(), epApp.getNotes(), epApp.getUrl(),
866 epApp.getAlternateUrl(), epApp.getAppRestEndpoint(), epApp.getMlAppName(),
867 epApp.getMlAppAdminId(), String.valueOf(epApp.getMotsId()), epApp.getAppPassword(),
868 String.valueOf(epApp.getOpen()), String.valueOf(epApp.getEnabled()),
869 epApp.getThumbnail(), epApp.getUsername(), epApp.getUebKey(), epApp.getUebSecret(),
870 epApp.getUebTopicName());
872 params.put("roleId", userApp.getRole().getId());
873 params.put(APP_ID, userApp.getApp().getId());
874 List<CentralRoleFunction> appRoleFunctionList = dataAccessService
875 .executeNamedQuery("getAppRoleFunctionList", params, null);
876 SortedSet<CentralRoleFunction> roleFunctionSet = new TreeSet<>();
877 for (CentralRoleFunction roleFunc : appRoleFunctionList) {
878 String functionCode = "";
879 if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
880 int count = StringUtils.countMatches(roleFunc.getCode(), FUNCTION_PIPE);
881 String finalFunctionCodeVal;
883 finalFunctionCodeVal = roleFunc.getCode().substring(
884 roleFunc.getCode().indexOf(FUNCTION_PIPE) + 1,
885 roleFunc.getCode().lastIndexOf(FUNCTION_PIPE));
887 finalFunctionCodeVal = roleFunc.getCode()
888 .substring(roleFunc.getCode().lastIndexOf(FUNCTION_PIPE) + 1);
890 functionCode = finalFunctionCodeVal;
892 functionCode = roleFunc.getCode();
894 CentralRoleFunction cenRoleFunc = new CentralRoleFunction(roleFunc.getId(), functionCode,
895 roleFunc.getName(), null, null);
896 roleFunctionSet.add(cenRoleFunc);
898 Long userRoleId = null;
899 if (globalRole.toLowerCase().startsWith("global_")
900 && epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) {
901 userRoleId = userApp.getRole().getId();
903 userRoleId = userApp.getRole().getAppRoleId();
905 CentralRole cenRole = new CentralRole(userRoleId, userApp.getRole().getCreated(),
906 userApp.getRole().getModified(), userApp.getRole().getCreatedId(),
907 userApp.getRole().getModifiedId(), userApp.getRole().getRowNum(),
908 userApp.getRole().getName(), userApp.getRole().getActive(),
909 userApp.getRole().getPriority(), roleFunctionSet, null, null);
910 cua.setRole(cenRole);
912 userAppList.userApps.add(cua);
917 user1 = new CentralUser(null, userInfo.getCreated(), userInfo.getModified(), userInfo.getCreatedId(),
918 userInfo.getModifiedId(), userInfo.getRowNum(), userInfo.getOrgId(), userInfo.getManagerId(),
919 userInfo.getFirstName(), userInfo.getMiddleInitial(), userInfo.getLastName(), userInfo.getPhone(),
920 userInfo.getFax(), userInfo.getCellular(), userInfo.getEmail(), userInfo.getAddressId(),
921 userInfo.getAlertMethodCd(), userInfo.getHrid(), userInfo.getOrgUserId(), userInfo.getOrgCode(),
922 userInfo.getAddress1(), userInfo.getAddress2(), userInfo.getCity(), userInfo.getState(),
923 userInfo.getZipCode(), userInfo.getCountry(), userInfo.getOrgManagerUserId(),
924 userInfo.getLocationClli(), userInfo.getBusinessCountryCode(), userInfo.getBusinessCountryName(),
925 userInfo.getBusinessUnit(), userInfo.getBusinessUnitName(), userInfo.getDepartment(),
926 userInfo.getDepartmentName(), userInfo.getCompanyCode(), userInfo.getCompany(),
927 userInfo.getZipCodeSuffix(), userInfo.getJobTitle(), userInfo.getCommandChain(),
928 userInfo.getSiloStatus(), userInfo.getCostCenter(), userInfo.getFinancialLocCode(),
929 userInfo.getLoginId(), userInfo.getLoginPwd(), userInfo.getLastLoginDate(), userInfo.getActive(),
930 userInfo.getInternal(), userInfo.getSelectedProfileId(), userInfo.getTimeZoneId(),
931 userInfo.isOnline(), userInfo.getChatId(), userAppList.userApps, null);
932 } catch (Exception e) {
933 logger.error(EELFLoggerDelegate.errorLogger, "createEPUser: createEPUser failed", e);
934 throw new Exception(e.getMessage());
940 @SuppressWarnings("unchecked")
942 public CentralRole getRoleInfo(Long roleId, String uebkey) throws Exception {
943 final Map<String, Long> params = new HashMap<>();
944 List<CentralRole> roleList = new ArrayList<>();
945 CentralRole cenRole = new CentralRole();
946 List<EPRole> roleInfo = null;
947 List<EPApp> app = null;
949 app = getApp(uebkey);
951 throw new Exception("Application not found");
953 String filter = null;
954 if (app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
955 filter = WHERE_ROLE_ID_EQUALS + roleId + " and app_id is null ";
957 filter = " where app_role_id = " + roleId + " and app_id = " + app.get(0).getId();
960 roleInfo = dataAccessService.getList(EPRole.class, filter, null, null);
961 roleList = createCentralRoleObject(app, roleInfo, roleList, params);
962 if (roleList.isEmpty()) {
966 } catch (Exception e) {
967 logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo: failed", e);
968 throw new Exception(e.getMessage());
971 return roleList.get(0);
976 * It returns list of app roles along with role functions and which went through deep copy
984 @SuppressWarnings("unchecked")
985 private List<CentralRole> createCentralRoleObject(List<EPApp> app, List<EPRole> roleInfo,
986 List<CentralRole> roleList, Map<String, Long> params) {
987 for (EPRole role : roleInfo) {
988 params.put("roleId", role.getId());
989 params.put(APP_ID, app.get(0).getId());
990 List<CentralRoleFunction> cenRoleFuncList = dataAccessService.executeNamedQuery("getAppRoleFunctionList",
992 SortedSet<CentralRoleFunction> roleFunctionSet = new TreeSet<>();
993 for (CentralRoleFunction roleFunc : cenRoleFuncList) {
994 String functionCode = "";
995 if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
996 int count = StringUtils.countMatches(roleFunc.getCode(), FUNCTION_PIPE);
997 String finalFunctionCodeVal;
999 finalFunctionCodeVal = roleFunc.getCode().substring(
1000 roleFunc.getCode().indexOf(FUNCTION_PIPE) + 1,
1001 roleFunc.getCode().lastIndexOf(FUNCTION_PIPE));
1003 finalFunctionCodeVal = roleFunc.getCode()
1004 .substring(roleFunc.getCode().lastIndexOf(FUNCTION_PIPE) + 1);
1005 functionCode = finalFunctionCodeVal;
1007 functionCode = roleFunc.getCode();
1009 CentralRoleFunction cenRoleFunc = new CentralRoleFunction(role.getId(), functionCode,
1010 roleFunc.getName(), null, null);
1011 roleFunctionSet.add(cenRoleFunc);
1013 SortedSet<CentralRole> childRoles = new TreeSet<>();
1014 CentralRole cenRole = null;
1015 if (role.getAppRoleId() == null) {
1016 cenRole = new CentralRole(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
1017 role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
1018 roleFunctionSet, childRoles, null);
1020 cenRole = new CentralRole(role.getAppRoleId(), role.getCreated(), role.getModified(),
1021 role.getCreatedId(), role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(),
1022 role.getPriority(), roleFunctionSet, childRoles, null);
1024 roleList.add(cenRole);
1029 @SuppressWarnings("unchecked")
1031 public CentralRoleFunction getRoleFunction(String functionCode, String uebkey) throws Exception {
1032 CentralRoleFunction roleFunc = null;
1033 EPApp app = getApp(uebkey).get(0);
1034 List<CentralRoleFunction> getRoleFuncList = null;
1035 final Map<String, String> params = new HashMap<>();
1037 params.put("functionCode", functionCode);
1038 params.put(APP_ID, String.valueOf(app.getId()));
1039 getRoleFuncList = dataAccessService.executeNamedQuery("getRoleFunction", params, null);
1040 if (getRoleFuncList.isEmpty()) {
1043 String functionCodeFormat = getRoleFuncList.get(0).getCode();
1044 if(functionCodeFormat.contains(FUNCTION_PIPE)){
1045 String newfunctionCodeFormat = functionCodeFormat.substring(functionCodeFormat.lastIndexOf(FUNCTION_PIPE)+1);
1046 roleFunc = new CentralRoleFunction(getRoleFuncList.get(0).getId(), newfunctionCodeFormat, getRoleFuncList.get(0).getName(), getRoleFuncList.get(0).getAppId(), getRoleFuncList.get(0).getEditUrl());
1048 roleFunc = new CentralRoleFunction(getRoleFuncList.get(0).getId(), functionCodeFormat, getRoleFuncList.get(0).getName(), getRoleFuncList.get(0).getAppId(), getRoleFuncList.get(0).getEditUrl());
1051 } catch (Exception e) {
1052 logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction: failed", e);
1053 throw new Exception("getRoleFunction failed", e);
1059 public boolean saveCentralRoleFunction(CentralRoleFunction domainCentralRoleFunction, EPApp app) throws Exception {
1060 boolean saveOrUpdateFunction = false;
1062 addRoleFunctionInExternalSystem(domainCentralRoleFunction, app);
1063 dataAccessService.saveDomainObject(domainCentralRoleFunction, null);
1064 saveOrUpdateFunction = true;
1065 } catch (Exception e) {
1066 logger.error(EELFLoggerDelegate.errorLogger, "saveCentralRoleFunction: failed", e);
1067 saveOrUpdateFunction = false;
1069 return saveOrUpdateFunction;
1073 * It creates application permission in external auth system
1075 * @param domainCentralRoleFunction
1079 @SuppressWarnings("unchecked")
1080 private void addRoleFunctionInExternalSystem(CentralRoleFunction domainCentralRoleFunction, EPApp app)
1082 ObjectMapper mapper = new ObjectMapper();
1083 ExternalAccessPerms extPerms = new ExternalAccessPerms();
1084 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1085 List<CentralRoleFunction> appRoleFunc = dataAccessService.getList(CentralRoleFunction.class,
1086 WHERE_APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + domainCentralRoleFunction.getCode() + "'", null, null);
1087 String roleFuncName = null;
1088 if (!appRoleFunc.isEmpty()) {
1089 roleFuncName = appRoleFunc.get(0).getCode();
1091 roleFuncName = domainCentralRoleFunction.getCode();
1093 String checkType = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url";
1094 HttpEntity<String> getSinglePermEntity = new HttpEntity<>(headers);
1095 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} ", CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1096 ResponseEntity<String> getResponse = template.exchange(
1097 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perms/"
1098 + app.getNameSpace() + "." + checkType + "/" + roleFuncName + "/*",
1099 HttpMethod.GET, getSinglePermEntity, String.class);
1100 if (getResponse.getStatusCode().value() != 200) {
1101 EPLogUtil.logExternalAuthAccessAlarm(logger, getResponse.getStatusCode());
1102 throw new Exception(getResponse.getBody());
1104 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished GET permission from External Auth system and response: {} ", getResponse.getBody());
1105 String res = getResponse.getBody();
1106 if (res.equals(IS_EMPTY_JSON_STRING)) {
1108 extPerms.setAction("*");
1109 extPerms.setInstance(domainCentralRoleFunction.getCode());
1110 extPerms.setType(app.getNameSpace() + "." + checkType);
1111 extPerms.setDescription(domainCentralRoleFunction.getName());
1112 String updateRole = mapper.writeValueAsString(extPerms);
1113 HttpEntity<String> entity = new HttpEntity<>(updateRole, headers);
1114 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1115 ResponseEntity<String> addPermResponse= template.exchange(
1116 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
1117 HttpMethod.POST, entity, String.class);
1118 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished adding permission in and status code: {} ", addPermResponse.getStatusCode().value());
1119 } catch(HttpClientErrorException e){
1120 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to add function in external central auth system", e);
1121 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1122 }catch (Exception e) {
1123 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionInExternalSystem: Failed to add fucntion in external central auth system",
1128 extPerms.setAction("*");
1129 extPerms.setInstance(domainCentralRoleFunction.getCode());
1130 extPerms.setType(app.getNameSpace() + "." + checkType);
1131 extPerms.setDescription(domainCentralRoleFunction.getName());
1132 String updateRole = mapper.writeValueAsString(extPerms);
1133 HttpEntity<String> entity = new HttpEntity<>(updateRole, headers);
1134 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1135 ResponseEntity<String> updatePermResponse = template.exchange(
1136 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
1137 HttpMethod.PUT, entity, String.class);
1138 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished updating permission in External Auth system and response: {} ", updatePermResponse.getBody());
1139 } catch(HttpClientErrorException e){
1140 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to add function in external central auth system", e);
1141 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1142 } catch (Exception e) {
1143 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionInExternalSystem: Failed to update function in external central auth system",
1151 public boolean deleteCentralRoleFunction(String code, EPApp app) {
1152 boolean deleteFunctionResponse = false;
1154 final Map<String, String> params = new HashMap<>();
1155 params.put("functionCode", code);
1156 params.put(APP_ID, String.valueOf(app.getId()));
1157 CentralRoleFunction domainCentralRoleFunction = (CentralRoleFunction) dataAccessService
1158 .executeNamedQuery("getRoleFunction", params, null).get(0);
1159 deleteRoleFunctionInExternalSystem(domainCentralRoleFunction, app);
1160 // Delete role function dependency records
1161 deleteAppRoleFunctions(code, app);
1162 dataAccessService.deleteDomainObject(domainCentralRoleFunction, null);
1163 deleteFunctionResponse = true;
1164 } catch (Exception e) {
1165 logger.error(EELFLoggerDelegate.errorLogger, "deleteCentralRoleFunction: failed", e);
1167 return deleteFunctionResponse;
1171 * It deletes app function record in portal
1176 private void deleteAppRoleFunctions(String code, EPApp app) {
1177 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
1178 APP_ID_EQUALS + app.getId() + FUNCTION_CD_LIKE_CLAUSE + code + "'", null);
1183 * It deletes permission in the external auth system
1185 * @param domainCentralRoleFunction
1189 private void deleteRoleFunctionInExternalSystem(CentralRoleFunction domainCentralRoleFunction, EPApp app)
1192 ObjectMapper mapper = new ObjectMapper();
1193 ExternalAccessPerms extPerms = new ExternalAccessPerms();
1194 String instanceValue = "";
1195 if(domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)){
1196 instanceValue = domainCentralRoleFunction.getCode().substring(domainCentralRoleFunction.getCode().lastIndexOf(FUNCTION_PIPE)+1);
1198 instanceValue = domainCentralRoleFunction.getCode();
1200 String checkType = instanceValue.contains("menu") ? "menu" : "url";
1201 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1202 extPerms.setAction("*");
1203 extPerms.setInstance(domainCentralRoleFunction.getCode());
1204 extPerms.setType(app.getNameSpace() + "." + checkType);
1205 extPerms.setDescription(domainCentralRoleFunction.getName());
1206 String updateRole = mapper.writeValueAsString(extPerms);
1207 HttpEntity<String> entity = new HttpEntity<>(updateRole, headers);
1208 logger.debug(EELFLoggerDelegate.debugLogger,"deleteRoleFunctionInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1209 ResponseEntity<String> delPermResponse = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1210 + "perm?force=true", HttpMethod.DELETE, entity, String.class);
1211 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleFunctionInExternalSystem: Finished deleting permission in External Auth system and status code: {} ", delPermResponse.getStatusCode().value());
1212 } catch(HttpClientErrorException e){
1213 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to delete functions in External System", e);
1214 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1215 } catch (Exception e) {
1216 if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
1217 logger.debug(EELFLoggerDelegate.debugLogger,
1218 " deleteRoleFunctionInExternalSystem: It seems like function is already deleted in external central auth system but exists in local DB",
1221 logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleFunctionInExternalSystem: Failed to delete functions in External System", e);
1227 public boolean saveRoleForApplication(Role saveRole, String uebkey) throws Exception {
1228 boolean addRoleResponse = false;
1230 EPApp app = getApp(uebkey).get(0);
1231 addRoleInEcompDB(saveRole, app);
1232 addRoleResponse = true;
1233 } catch (Exception e) {
1234 logger.error(EELFLoggerDelegate.errorLogger, "saveRoleForApplication failed", e);
1236 return addRoleResponse;
1239 @SuppressWarnings("unchecked")
1241 public boolean deleteRoleForApplication(String deleteRole, String uebkey) throws Exception {
1242 Session localSession = sessionFactory.openSession();
1243 Transaction transaction = null;
1244 boolean result = false;
1246 transaction = localSession.beginTransaction();
1248 List<EPRole> epRoleList = null;
1249 ResponseEntity<String> deleteResponse = null;
1250 EPApp app = getApp(uebkey).get(0);
1251 if (app.getId() == 1) {
1252 epRoleList = dataAccessService.getList(EPRole.class,
1253 " where app_id is null " + "and role_name = '" + deleteRole + "'", null, null);
1255 epRoleList = dataAccessService.getList(EPRole.class,
1256 WHERE_APP_ID_EQUALS + app.getId() + " and role_name = '" + deleteRole + "'", null, null);
1258 // Delete app role functions before deleting role
1259 deleteRoleFunction(app, epRoleList);
1260 if (app.getId() == 1) {
1261 // Delete fn_user_ role
1262 dataAccessService.deleteDomainObjects(EPUserApp.class,
1263 APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
1265 deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId());
1267 // Delete Role in External System
1268 String deleteRoleKey = "{\"name\":\"" + app.getNameSpace() + "."
1269 + epRoleList.get(0).getName().replaceAll(" ", "_") + "\"}";
1270 deleteResponse = deleteRoleInExternalSystem(deleteRoleKey);
1271 if (deleteResponse.getStatusCode().value() != 200 || deleteResponse.getStatusCode().value() != 404) {
1272 EPLogUtil.logExternalAuthAccessAlarm(logger, deleteResponse.getStatusCode());
1273 logger.error(EELFLoggerDelegate.errorLogger,
1274 "deleteRoleForApplication: Failed to delete role in external auth system! due to {} ",
1275 deleteResponse.getBody());
1277 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: about to commit the transaction");
1278 transaction.commit();
1279 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: committed the transaction");
1280 dataAccessService.deleteDomainObject(epRoleList.get(0), null);
1282 } catch (Exception e) {
1283 logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleForApplication: failed", e);
1286 localSession.close();
1293 * It deletes application user role in external auth system
1300 private void deleteUserRoleInExternalSystem(EPRole role, EPApp app, String LoginId) throws Exception {
1301 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1302 HttpEntity<String> entity = new HttpEntity<>(headers);
1303 logger.debug(EELFLoggerDelegate.debugLogger,"deleteUserRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1304 ResponseEntity<String> getResponse = template
1306 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
1309 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
1310 + "/" + app.getNameSpace() + "." + role.getName().replaceAll(" ", "_"),
1311 HttpMethod.GET, entity, String.class);
1312 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: Finished GET user roles from External Auth system and response: {} ", getResponse.getBody());
1313 if (getResponse.getStatusCode().value() != 200) {
1314 throw new Exception(getResponse.getBody());
1316 String res = getResponse.getBody();
1317 if (!res.equals(IS_EMPTY_JSON_STRING)) {
1318 HttpEntity<String> userRoleentity = new HttpEntity<>(headers);
1319 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1320 ResponseEntity<String> deleteResponse = template
1322 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1323 + "userRole/" + LoginId
1325 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
1326 + "/" + app.getNameSpace() + "." + role.getName().replaceAll(" ", "_"),
1327 HttpMethod.DELETE, userRoleentity, String.class);
1328 if (deleteResponse.getStatusCode().value() != 200) {
1329 throw new Exception("Failed to delete user role");
1331 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: Finished deleting user role in External Auth system and status code: {} ", deleteResponse.getStatusCode().value());
1335 @SuppressWarnings("unchecked")
1337 public List<CentralRole> getActiveRoles(String uebkey) throws Exception {
1338 List<CentralRole> roleList = new ArrayList<>();
1340 List<EPApp> app = getApp(uebkey);
1341 final Map<String, Long> params = new HashMap<>();
1344 if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
1345 appId = app.get(0).getId();
1347 List<EPRole> epRole = dataAccessService.getList(EPRole.class,
1348 WHERE_APP_ID_EQUALS + appId + " and active_yn = 'Y'", null, null);
1349 roleList = createCentralRoleObject(app, epRole, roleList, params);
1350 } catch (Exception e) {
1351 logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles: failed", e);
1352 throw new Exception(e.getMessage());
1358 @SuppressWarnings("unchecked")
1360 public boolean deleteDependencyRoleRecord(Long roleId, String uebkey, String LoginId) throws Exception {
1361 boolean result = false;
1362 Session localSession = sessionFactory.openSession();
1363 Transaction transaction = null;
1366 transaction = localSession.beginTransaction();
1367 List<EPRole> epRoleList = null;
1368 app = getApp(uebkey).get(0);
1369 epRoleList = dataAccessService.getList(EPRole.class,
1370 WHERE_APP_ID_EQUALS + app.getId() + " and app_role_id = " + roleId, null, null);
1371 if (epRoleList.isEmpty()) {
1372 epRoleList = dataAccessService.getList(EPRole.class,
1373 WHERE_APP_ID_EQUALS + app.getId() + " and role_id = " + roleId, null, null);
1375 // Delete User Role in External System before deleting role
1376 deleteUserRoleInExternalSystem(epRoleList.get(0), app, LoginId);
1377 // Delete user app roles
1378 dataAccessService.deleteDomainObjects(EPUserApp.class,
1379 APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
1381 deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId());
1382 logger.debug(EELFLoggerDelegate.debugLogger, "deleteDependencyRoleRecord: about to commit the transaction");
1383 transaction.commit();
1384 logger.debug(EELFLoggerDelegate.debugLogger, "deleteDependencyRoleRecord: committed the transaction");
1386 } catch(HttpClientErrorException e){
1387 logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord: HttpClientErrorException", e);
1388 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1389 } catch (Exception e) {
1390 logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord failed", e);
1391 EcompPortalUtils.rollbackTransaction(transaction,
1392 "deleteDependencyRoleRecord rollback, exception = " + e.toString());
1394 localSession.close();
1400 @SuppressWarnings("unchecked")
1402 public void syncRoleFunctionFromExternalAccessSystem(EPApp app) {
1404 ResponseEntity<String> response = null;
1405 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1406 HttpEntity<String> entity = new HttpEntity<>(headers);
1407 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1409 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1410 + "perms/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
1412 String res = response.getBody();
1413 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Finished GET permissions from External Auth system and response: {} ", response.getBody());
1414 JSONObject jsonObj = new JSONObject(res);
1415 JSONArray extPerms = jsonObj.getJSONArray("perm");
1416 for (int i = 0; i < extPerms.length(); i++) {
1417 if (extPerms.getJSONObject(i).getString("type").equals(app.getNameSpace() + ".access")) {
1422 ExternalAccessPermsDetail permDetails = null;
1423 List<ExternalAccessPermsDetail> permsDetailList = new ArrayList<>();
1424 for (int i = 0; i < extPerms.length(); i++) {
1425 String description = null;
1426 if(extPerms.getJSONObject(i).has("description")){
1427 description = extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
1429 description = extPerms.getJSONObject(i).getString("instance");
1431 if (extPerms.getJSONObject(i).has("roles")) {
1432 ObjectMapper rolesListMapper = new ObjectMapper();
1433 JSONArray resRoles = extPerms.getJSONObject(i).getJSONArray("roles");
1434 List<String> list = rolesListMapper.readValue(resRoles.toString(),
1435 TypeFactory.defaultInstance().constructCollectionType(List.class, String.class));
1436 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
1437 extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
1438 + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
1439 + extPerms.getJSONObject(i).getString("action"),
1440 extPerms.getJSONObject(i).getString("action"), list, description);
1441 permsDetailList.add(permDetails);
1443 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
1444 extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
1445 + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
1446 + extPerms.getJSONObject(i).getString("action"),
1447 extPerms.getJSONObject(i).getString("action"), description);
1448 permsDetailList.add(permDetails);
1452 final Map<String, Long> params = new HashMap<>();
1453 final Map<String, CentralRoleFunction> roleFuncMap = new HashMap<>();
1454 params.put(APP_ID, app.getId());
1455 List<CentralRoleFunction> appFunctions = dataAccessService.executeNamedQuery("getAllRoleFunctions", params,
1457 if (!appFunctions.isEmpty()) {
1458 for (CentralRoleFunction roleFunc : appFunctions) {
1459 roleFuncMap.put(roleFunc.getCode(), roleFunc);
1462 // delete all application role functions
1463 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, APP_ID_EQUALS + app.getId(), null);
1464 // Add if new functions and app role functions were added in external auth system
1465 for (ExternalAccessPermsDetail permsDetail : permsDetailList) {
1466 String code = permsDetail.getInstance();
1467 CentralRoleFunction getFunctionCodeKey = roleFuncMap.get(permsDetail.getInstance());
1468 if (null == getFunctionCodeKey) {
1469 String finalFunctionCodeVal = "";
1470 if (permsDetail.getInstance().contains(FUNCTION_PIPE)) {
1471 int count = StringUtils.countMatches(permsDetail.getInstance(), FUNCTION_PIPE);
1473 finalFunctionCodeVal = permsDetail.getInstance().substring(
1474 permsDetail.getInstance().indexOf(FUNCTION_PIPE) + 1,
1475 permsDetail.getInstance().lastIndexOf(FUNCTION_PIPE));
1477 finalFunctionCodeVal = permsDetail.getInstance()
1478 .substring(permsDetail.getInstance().lastIndexOf(FUNCTION_PIPE) + 1);
1480 finalFunctionCodeVal = permsDetail.getInstance();
1482 CentralRoleFunction checkIfCodeStillExits = roleFuncMap.get(finalFunctionCodeVal);
1483 if (null == checkIfCodeStillExits) {
1484 logger.debug(EELFLoggerDelegate.debugLogger,
1485 "syncRoleFunctionFromExternalAccessSystem: Adding function: {} ", code);
1486 addFunctionInEcompDB(app, permsDetail, code);
1487 logger.debug(EELFLoggerDelegate.debugLogger,
1488 "syncRoleFunctionFromExternalAccessSystem: Finished adding function: {} ", code);
1492 List<EPRole> epRolesList = null;
1493 List<String> roles = permsDetail.getRoles();
1494 if (roles != null) {
1495 for (String roleList : roles) {
1496 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1497 epRolesList = dataAccessService.getList(EPRole.class,
1498 " where app_id is null " + " and role_name = '"
1499 + roleList.substring(app.getNameSpace().length() + 1).replaceAll("_", " ")
1503 epRolesList = dataAccessService.getList(EPRole.class,
1504 WHERE_APP_ID_EQUALS + app.getId() + " and role_name = '"
1505 + roleList.substring(app.getNameSpace().length() + 1).replaceAll("_", " ")
1509 if (epRolesList.isEmpty()) {
1510 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1511 epRolesList = dataAccessService.getList(EPRole.class,
1512 " where app_id is null " + " and role_name = '"
1513 + roleList.substring(app.getNameSpace().length() + 1) + "'",
1516 epRolesList = dataAccessService.getList(EPRole.class,
1517 WHERE_APP_ID_EQUALS + app.getId() + " and role_name = '"
1518 + roleList.substring(app.getNameSpace().length() + 1) + "'",
1521 // Adding new role thats does not exits in Local but exists in external access system
1522 if (epRolesList.isEmpty()) {
1523 Role role = addRoleInDBIfDoesNotExists(app, roleList.substring(app.getNameSpace().length() + 1));
1524 addIfRoleDescriptionNotExitsInExtSystem(role, app);
1525 epRolesList = dataAccessService.getList(EPRole.class,
1526 WHERE_APP_ID_EQUALS + app.getId() + " and role_name = '"
1527 + role.getName() + "'",
1531 // save all application role functions
1532 if (!epRolesList.isEmpty()) {
1534 List<CentralRoleFunction> roleFunctionList = null;
1535 String functionCode = "";
1536 if (permsDetail.getInstance().contains(FUNCTION_PIPE)) {
1537 int count = StringUtils.countMatches(permsDetail.getInstance(), FUNCTION_PIPE);
1538 String finalFunctionCodeVal;
1540 finalFunctionCodeVal = permsDetail.getInstance().substring(
1541 permsDetail.getInstance().indexOf(FUNCTION_PIPE) + 1,
1542 permsDetail.getInstance().lastIndexOf(FUNCTION_PIPE));
1544 finalFunctionCodeVal = permsDetail.getInstance()
1545 .substring(permsDetail.getInstance().lastIndexOf(FUNCTION_PIPE) + 1);
1547 functionCode = finalFunctionCodeVal;
1549 roleFunctionList = dataAccessService.getList(CentralRoleFunction.class,
1550 " where app_id = " + app.getId() + AND_FUNCTION_CD_EQUALS + functionCode + "'",
1552 if (roleFunctionList.isEmpty()) {
1553 roleFunctionList = dataAccessService.getList(CentralRoleFunction.class,
1554 " where app_id = " + app.getId() + AND_FUNCTION_CD_EQUALS + code + "'",
1557 if (!roleFunctionList.isEmpty()) {
1558 EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
1559 addAppRoleFunc.setAppId(app.getId());
1560 addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
1561 addAppRoleFunc.setRoleId(epRolesList.get(0).getId());
1562 dataAccessService.saveDomainObject(addAppRoleFunc, null);
1564 } catch (Exception e) {
1565 logger.error(EELFLoggerDelegate.errorLogger,
1566 "syncRoleFunctionFromExternalAccessSystem: Failed to save app role function ",
1573 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Finished syncRoleFunctionFromExternalAccessSystem");
1574 } catch (Exception e) {
1575 logger.error(EELFLoggerDelegate.errorLogger, "syncRoleFunctionFromExternalAccessSystem: Failed syncRoleFunctionFromExternalAccessSystem", e);
1582 * Add function into local DB
1585 * @param permsDetail
1588 private void addFunctionInEcompDB(EPApp app, ExternalAccessPermsDetail permsDetail, String code) {
1590 CentralRoleFunction addFunction = new CentralRoleFunction();
1591 addFunction.setAppId(app.getId());
1592 addFunction.setCode(code);
1593 addFunction.setName(permsDetail.getDescription());
1594 dataAccessService.saveDomainObject(addFunction, null);
1595 } catch(Exception e){
1596 logger.error(EELFLoggerDelegate.errorLogger, "addFunctionInEcompDB: Failed to add function", e);
1602 * It updates description of a role in external auth system
1608 private void addIfRoleDescriptionNotExitsInExtSystem(Role role, EPApp app) throws Exception {
1609 String addRoleNew = updateExistingRoleInExternalSystem(role, app);
1610 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1612 HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
1614 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
1615 HttpMethod.PUT, entity, String.class);
1616 } catch (HttpClientErrorException e) {
1617 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addIfRoleDescriptionNotExitsInExtSystem",
1619 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1620 } catch (Exception e) {
1621 logger.error(EELFLoggerDelegate.errorLogger, "addIfRoleDescriptionNotExitsInExtSystem: Failed",
1628 * While sync functions form external auth system if new role found we should add in local and return Role.class object
1634 @SuppressWarnings("unchecked")
1635 private Role addRoleInDBIfDoesNotExists(EPApp app, String role) {
1636 Role setNewRole = new Role();
1637 EPRole epRoleNew = new EPRole();
1639 epRoleNew.setActive(true);
1640 epRoleNew.setName(role);
1641 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1642 epRoleNew.setAppId(null);
1644 epRoleNew.setAppId(app.getId());
1646 dataAccessService.saveDomainObject(epRoleNew, null);
1647 List<EPRole> getRoleCreated = null;
1648 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1649 List<EPRole> roleCreated = dataAccessService.getList(EPRole.class,
1650 WHERE_ROLE_NAME_EQUALS + role + "' and app_id = " + app.getId(), null, null);
1651 EPRole epUpdateRole = roleCreated.get(0);
1652 epUpdateRole.setAppRoleId(epUpdateRole.getId());
1653 dataAccessService.saveDomainObject(epUpdateRole, null);
1654 getRoleCreated = dataAccessService.getList(EPRole.class,
1655 WHERE_ROLE_NAME_EQUALS + role + "' and app_id = " + app.getId(), null, null);
1657 getRoleCreated = dataAccessService.getList(EPRole.class,
1658 WHERE_ROLE_NAME_EQUALS + role + "' and app_id is null", null, null);
1660 EPRole roleObject = getRoleCreated.get(0);
1661 setNewRole.setId(roleObject.getId());
1662 setNewRole.setName(roleObject.getName());
1663 setNewRole.setActive(roleObject.getActive());
1664 setNewRole.setPriority(roleObject.getPriority());
1665 } catch (Exception e) {
1666 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInDBIfDoesNotExists: Failed", e);
1672 @SuppressWarnings("unchecked")
1673 public Integer bulkUploadFunctions(String uebkey) throws Exception {
1674 EPApp app = getApp(uebkey).get(0);
1675 List<RoleFunction> roleFuncList = null;
1676 roleFuncList = dataAccessService.getList(RoleFunction.class, null);
1677 CentralRoleFunction cenRoleFunc = null;
1678 Integer functionsAdded = 0;
1680 for (RoleFunction roleFunc : roleFuncList) {
1681 cenRoleFunc = new CentralRoleFunction(roleFunc.getCode(), roleFunc.getName());
1682 addRoleFunctionInExternalSystem(cenRoleFunc, app);
1685 } catch(HttpClientErrorException e){
1686 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadFunctions failed", e);
1687 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1688 } catch (Exception e) {
1689 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions: failed", e.getMessage(), e);
1691 return functionsAdded;
1695 public Integer bulkUploadRoles(String uebkey) throws Exception {
1696 List<EPApp> app = getApp(uebkey);
1697 List<EPRole> roles = getAppRoles(app.get(0).getId());
1698 List<CentralRole> cenRoleList = new ArrayList<>();
1699 final Map<String, Long> params = new HashMap<>();
1700 Integer rolesListAdded = 0;
1702 cenRoleList = createCentralRoleObject(app, roles, cenRoleList, params);
1703 ObjectMapper mapper = new ObjectMapper();
1704 mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
1705 String roleList = mapper.writeValueAsString(cenRoleList);
1706 List<Role> roleObjectList = mapper.readValue(roleList,
1707 TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
1708 for (Role role : roleObjectList) {
1709 addRoleInExternalSystem(role, app.get(0));
1712 } catch (Exception e) {
1713 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles: failed", e);
1714 throw new Exception(e.getMessage());
1716 return rolesListAdded;
1720 * It creating new role in external auth system while doing bulk upload
1726 private void addRoleInExternalSystem(Role role, EPApp app) throws Exception {
1727 String addRoleNew = updateExistingRoleInExternalSystem(role, app);
1728 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1730 HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
1732 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
1733 HttpMethod.POST, entity, String.class);
1734 } catch(HttpClientErrorException e){
1735 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addRoleInExternalSystem", e);
1736 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1737 } catch (Exception e) {
1738 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
1739 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInExternalSystem: Role already exits but does not break functionality", e);
1741 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInExternalSystem: Failed to addRoleInExternalSystem", e.getMessage());
1747 @SuppressWarnings("unchecked")
1748 public Integer bulkUploadRolesFunctions(String uebkey) throws Exception {
1749 EPApp app = getApp(uebkey).get(0);
1750 List<EPRole> roles = getAppRoles(app.getId());
1751 final Map<String, Long> params = new HashMap<>();
1752 Integer roleFunctions = 0;
1754 for (EPRole role : roles) {
1755 params.put("roleId", role.getId());
1756 List<BulkUploadRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("uploadAllRoleFunctions",
1758 if (!appRoleFunc.isEmpty()) {
1759 for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
1760 addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
1765 } catch(HttpClientErrorException e){
1766 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
1767 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1768 } catch (Exception e) {
1769 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
1771 return roleFunctions;
1775 * Its adding a role function while doing bulk upload
1777 * @param addRoleFunc
1781 private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, EPRole role, EPApp app) {
1782 String checkType = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
1783 ExternalAccessRolePerms extRolePerms = null;
1784 ExternalAccessPerms extPerms = null;
1785 ObjectMapper mapper = new ObjectMapper();
1787 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1789 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, addRoleFunc.getFunctionCd(), "*",
1790 addRoleFunc.getFunctionName());
1791 extRolePerms = new ExternalAccessRolePerms(extPerms,
1792 app.getNameSpace() + "." + role.getName().replaceAll(" ", "_"));
1793 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
1794 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
1796 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
1797 HttpMethod.POST, entity, String.class);
1798 } catch (Exception e) {
1799 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
1800 logger.error(EELFLoggerDelegate.errorLogger,
1801 "addRoleFunctionsInExternalSystem: RoleFunction already exits but does not break functionality", e);
1803 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionsInExternalSystem: Failed to addRoleFunctionsInExternalSystem",
1810 public void bulkUploadPartnerFunctions(String uebkey, List<RoleFunction> roleFunctionsList) throws Exception {
1811 EPApp app = getApp(uebkey).get(0);
1812 CentralRoleFunction cenRoleFunc = null;
1813 for (RoleFunction roleFunction : roleFunctionsList) {
1814 cenRoleFunc = new CentralRoleFunction(roleFunction.getCode(), roleFunction.getName());
1815 addRoleFunctionInExternalSystem(cenRoleFunc, app);
1820 public void bulkUploadPartnerRoles(String uebkey, List<Role> roleList) throws Exception {
1821 EPApp app = getApp(uebkey).get(0);
1822 for (Role role : roleList) {
1823 addRoleInExternalSystem(role, app);
1827 @SuppressWarnings("unchecked")
1829 public void bulkUploadPartnerRoleFunctions(String uebkey, List<Role> roleList) throws Exception {
1830 EPApp app = getApp(uebkey).get(0);
1831 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1832 for (Role role : roleList) {
1834 Set<RoleFunction> roleFunctionList = role.getRoleFunctions();
1835 List<RoleFunction> roleFunctionListNew = new ArrayList<>();
1836 ObjectMapper roleFunctionsMapper = new ObjectMapper();
1837 Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
1838 while (itetaror.hasNext()) {
1839 Object nextValue = itetaror.next();
1840 RoleFunction roleFunction = roleFunctionsMapper.convertValue(nextValue, RoleFunction.class);
1841 roleFunctionListNew.add(roleFunction);
1843 List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct()
1844 .collect(Collectors.toList());
1845 for (RoleFunction roleFunction : listWithoutDuplicates) {
1846 String checkType = roleFunction.getCode().contains("menu") ? "menu" : "url";
1847 ExternalAccessRolePerms extRolePerms = null;
1848 ExternalAccessPerms extPerms = null;
1849 ObjectMapper mapper = new ObjectMapper();
1850 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, roleFunction.getCode(),
1852 extRolePerms = new ExternalAccessRolePerms(extPerms,
1853 app.getNameSpace() + "." + role.getName().replaceAll(" ", "_"));
1854 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
1855 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
1856 template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1857 + "role/perm", HttpMethod.PUT, entity, String.class);
1859 } catch (Exception e) {
1860 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
1861 logger.error(EELFLoggerDelegate.errorLogger,
1862 "bulkUploadPartnerRoleFunctions: RoleFunction already exits but does not break functionality");
1864 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerRoleFunctions: Failed to addRoleFunctionsInExternalSystem",
1873 @SuppressWarnings("unchecked")
1875 public void syncApplicationRolesWithEcompDB(EPApp app) {
1877 ResponseEntity<String> response = null;
1878 List<EPRole> finalRoleList = new ArrayList<>();
1879 ExternalRoleDescription ApplicationRole = new ExternalRoleDescription();
1880 ExternalAccessPerms externalAccessPerms = null;
1881 List<String> functionCodelist = new ArrayList<>();
1882 List<ExternalRoleDetails> externalRoleDetailsList = new ArrayList<>();
1883 ObjectMapper mapper = new ObjectMapper();
1884 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1885 HttpEntity<String> entity = new HttpEntity<>(headers);
1886 logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: {} ",
1887 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1889 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1890 + "roles/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
1891 String res = response.getBody();
1892 logger.debug(EELFLoggerDelegate.debugLogger,
1893 "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
1895 JSONObject jsonObj = new JSONObject(res);
1896 JSONArray extRole = jsonObj.getJSONArray("role");
1897 for (int i = 0; i < extRole.length(); i++) {
1898 if (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ADMIN)
1899 || extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + OWNER)
1900 || (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ACCOUNT_ADMINISTRATOR)
1901 && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
1906 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, APP_ID_EQUALS + app.getId(), null);
1907 for (int i = 0; i < extRole.length(); i++) {
1908 ExternalRoleDetails externalRoleDetail = new ExternalRoleDetails();
1909 EPAppRoleFunction ePAppRoleFunction = new EPAppRoleFunction();
1910 JSONObject Role = (JSONObject) extRole.get(i);
1911 if (!extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
1912 ApplicationRole.setActive("true");
1913 ApplicationRole.setAppId(IS_NULL_STRING);
1914 ApplicationRole.setPriority(IS_NULL_STRING);
1915 ApplicationRole.setAppRoleId(IS_NULL_STRING);
1916 String roleName = extRole.getJSONObject(i).getString(ROLE_NAME);
1917 ApplicationRole.setName(roleName.substring(app.getNameSpace().length() + 1));
1919 String desc = extRole.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
1920 ApplicationRole = mapper.readValue(desc, ExternalRoleDescription.class);
1923 SortedSet<ExternalAccessPerms> externalAccessPermsOfRole = new TreeSet<>();
1924 if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_PERMS)) {
1925 JSONArray extPerm = (JSONArray) Role.get(EXTERNAL_AUTH_PERMS);
1926 for (int j = 0; j < extPerm.length(); j++) {
1927 JSONObject perms = extPerm.getJSONObject(j);
1928 externalAccessPerms = new ExternalAccessPerms(perms.getString("type"),
1929 perms.getString("instance"), perms.getString("action"));
1930 ePAppRoleFunction.setCode(externalAccessPerms.getInstance());
1931 functionCodelist.add(ePAppRoleFunction.getCode());
1932 externalAccessPermsOfRole.add(externalAccessPerms);
1936 if (ApplicationRole.getActive().equals(IS_NULL_STRING)) {
1937 externalRoleDetail.setActive(false);
1939 externalRoleDetail.setActive(Boolean.parseBoolean(ApplicationRole.getActive()));
1941 externalRoleDetail.setName(ApplicationRole.getName());
1943 if (ApplicationRole.getAppId().equals(IS_NULL_STRING) && app.getId() == 1) {
1944 externalRoleDetail.setAppId(null);
1945 } else if (ApplicationRole.getAppId().equals(IS_NULL_STRING)) {
1946 externalRoleDetail.setAppId(app.getId());
1948 externalRoleDetail.setAppId(Long.parseLong(ApplicationRole.getAppId()));
1951 if (ApplicationRole.getPriority().equals(IS_NULL_STRING)) {
1952 externalRoleDetail.setPriority(null);
1954 externalRoleDetail.setPriority(Integer.parseInt(ApplicationRole.getPriority()));
1957 if (ApplicationRole.getAppRoleId().equals(IS_NULL_STRING) && app.getId() == 1) {
1958 externalRoleDetail.setAppRoleId(null);
1961 if (!externalAccessPermsOfRole.isEmpty()) {
1962 // Adding functions to roles
1963 for (ExternalAccessPerms externalpermission : externalAccessPermsOfRole) {
1965 logger.debug(EELFLoggerDelegate.debugLogger,
1966 "SyncApplicationRolesWithEcompDB: Adding function to the role: {}",
1967 externalpermission.getInstance());
1968 List<CentralRoleFunction> roleFunction = null;
1969 roleFunction = dataAccessService.getList(
1970 CentralRoleFunction.class, " where function_cd = '"
1971 + externalpermission.getInstance() + "' and " + APP_ID_EQUALS + app.getId(),
1973 if (roleFunction.isEmpty()) {
1974 String funcCode = externalpermission.getType()
1975 .substring(app.getNameSpace().length() + 1) + FUNCTION_PIPE
1976 + externalAccessPerms.getInstance();
1977 roleFunction = dataAccessService.getList(CentralRoleFunction.class,
1978 " where function_cd = '" + funcCode + "' and " + APP_ID_EQUALS + app.getId(), null,
1981 if(!roleFunction.isEmpty()){
1982 EPAppRoleFunction apRoleFunction = new EPAppRoleFunction();
1983 apRoleFunction.setAppId(app.getId());
1984 apRoleFunction.setRoleId(Long.parseLong(ApplicationRole.getId()));
1985 apRoleFunction.setCode(roleFunction.get(0).getCode());
1986 dataAccessService.saveDomainObject(apRoleFunction, null);
1988 } catch (Exception e) {
1989 logger.error(EELFLoggerDelegate.errorLogger,
1990 "SyncApplicationRolesWithEcompDB: Failed to add role function", e);
1994 externalRoleDetailsList.add(externalRoleDetail);
1996 for (ExternalRoleDetails externalRole : externalRoleDetailsList) {
1997 EPRole ecompRole = convertExternalRoleDetailstoEpRole(externalRole);
1998 finalRoleList.add(ecompRole);
2001 List<EPRole> applicationRolesList = new ArrayList<>();
2002 applicationRolesList = getAppRoles(app.getId());
2003 List<String> applicationRoleIdList = new ArrayList<>();
2004 for (EPRole applicationRole : applicationRolesList) {
2005 applicationRoleIdList.add(applicationRole.getName());
2008 List<EPRole> roleListToBeAddInEcompDB = new ArrayList<>();
2009 for (EPRole aafRole : finalRoleList) {
2010 if (!applicationRoleIdList.contains(aafRole.getName())) {
2011 roleListToBeAddInEcompDB.add(aafRole);
2015 // Check if roles exits in external Access system and make it inactive
2016 final Map<String, EPRole> checkRolesInactive = new HashMap<>();
2017 for (EPRole extrole : finalRoleList) {
2018 checkRolesInactive.put(extrole.getName(), extrole);
2020 for (EPRole role : applicationRolesList) {
2022 final Map<String, String> extRoleParams = new HashMap<>();
2023 List<EPRole> roleList = null;
2024 extRoleParams.put("appRoleName", role.getName());
2025 if (!checkRolesInactive.containsKey(role.getName())) {
2026 if (app.getId() == 1) {
2027 roleList = dataAccessService.executeNamedQuery("getPortalAppRoles", extRoleParams, null);
2029 extRoleParams.put(APP_ID, app.getId().toString());
2030 roleList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", extRoleParams, null);
2032 EPRole updateRoleInactive = roleList.get(0);
2033 updateRoleInactive.setActive(false);
2034 dataAccessService.saveDomainObject(updateRoleInactive, null);
2036 } catch (Exception e) {
2037 logger.error(EELFLoggerDelegate.errorLogger,
2038 "syncApplicationRolesWithEcompDB: Failed to de-activate role ", e);
2042 // It checks properties in the external auth system app role description and updates role in local
2043 for (EPRole roleItem : finalRoleList) {
2044 final Map<String, String> roleParams = new HashMap<>();
2045 List<EPRole> currentList = null;
2046 roleParams.put("appRoleName", roleItem.getName());
2047 if (app.getId() == 1) {
2048 currentList = dataAccessService.executeNamedQuery("getPortalAppRoles", roleParams, null);
2050 roleParams.put(APP_ID, app.getId().toString());
2051 currentList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", roleParams, null);
2054 if (!currentList.isEmpty()) {
2056 Boolean aafRoleActive;
2057 Boolean localRoleActive;
2059 aafRoleActive = Boolean.valueOf(roleItem.getActive());
2060 localRoleActive = Boolean.valueOf(currentList.get(0).getActive());
2061 result = aafRoleActive.equals(localRoleActive);
2062 EPRole updateRole = currentList.get(0);
2065 updateRole.setActive(roleItem.getActive());
2066 dataAccessService.saveDomainObject(updateRole, null);
2068 if (roleItem.getPriority() != null
2069 && !currentList.get(0).getPriority().equals(roleItem.getPriority())) {
2070 updateRole.setPriority(roleItem.getPriority());
2071 dataAccessService.saveDomainObject(updateRole, null);
2073 } catch (Exception e) {
2074 logger.error(EELFLoggerDelegate.errorLogger,
2075 "syncApplicationRolesWithEcompDB: Failed to update role ", e);
2080 EPRole roleToBeAddedInEcompDB = new EPRole();
2081 for (int i = 0; i < roleListToBeAddInEcompDB.size(); i++) {
2083 roleToBeAddedInEcompDB = roleListToBeAddInEcompDB.get(i);
2084 if (app.getId() == 1) {
2085 roleToBeAddedInEcompDB.setAppRoleId(null);
2087 dataAccessService.saveDomainObject(roleToBeAddedInEcompDB, null);
2088 List<EPRole> getRoleCreatedInSync = null;
2089 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2090 getRoleCreatedInSync = dataAccessService.getList(EPRole.class,
2091 WHERE_ROLE_NAME_EQUALS + roleToBeAddedInEcompDB.getName() + "' and app_id = "+app.getId(), null, null);
2092 EPRole epUpdateRole = getRoleCreatedInSync.get(0);
2093 epUpdateRole.setAppRoleId(epUpdateRole.getId());
2094 dataAccessService.saveDomainObject(epUpdateRole, null);
2096 List<EPRole> roleList = new ArrayList<>();
2097 final Map<String, String> params = new HashMap<>();
2099 params.put("appRoleName", roleToBeAddedInEcompDB.getName());
2100 if (app.getId() == 1) {
2101 roleList = dataAccessService.executeNamedQuery("getPortalAppRoles", params, null);
2103 params.put(APP_ID, app.getId().toString());
2104 roleList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", params, null);
2106 EPRole role = roleList.get(0);
2107 Role aaFrole = new Role();
2108 aaFrole.setId(role.getId());
2109 aaFrole.setActive(role.getActive());
2110 aaFrole.setPriority(role.getPriority());
2111 aaFrole.setName(role.getName());
2112 updateRoleInExternalSystem(aaFrole, app);
2113 } catch (Exception e) {
2114 logger.error(EELFLoggerDelegate.errorLogger,
2115 "SyncApplicationRolesWithEcompDB: Failed to add or update role in external auth system", e);
2118 logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: Finished");
2119 } catch (HttpClientErrorException e) {
2120 logger.error(EELFLoggerDelegate.errorLogger, "Failed to SyncApplicationRolesWithEcompDB", e);
2121 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2122 } catch (Exception e) {
2123 logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed ", e);
2129 * It converts from ExternalRoleDetails.class object to EPRole.class object
2131 * @param externalRoleDetails
2132 * @return EPRole object
2134 private EPRole convertExternalRoleDetailstoEpRole(ExternalRoleDetails externalRoleDetails) {
2135 EPRole role = new EPRole();
2136 role.setActive(externalRoleDetails.isActive());
2137 role.setAppId(externalRoleDetails.getAppId());
2138 role.setAppRoleId(externalRoleDetails.getAppRoleId());
2139 role.setName(externalRoleDetails.getName());
2140 role.setPriority(externalRoleDetails.getPriority());
2144 @SuppressWarnings("unchecked")
2146 public Integer bulkUploadUserRoles(String uebkey) throws Exception {
2147 EPApp app = getApp(uebkey).get(0);
2148 final Map<String, String> params = new HashMap<>();
2149 params.put("uebKey", app.getUebKey());
2150 List<BulkUploadUserRoles> userRolesList = null;
2151 Integer userRolesAdded = 0;
2152 if (app.getCentralAuth()) {
2153 userRolesList = dataAccessService.executeNamedQuery("getBulkUserRoles", params, null);
2154 for (BulkUploadUserRoles userRolesUpload : userRolesList) {
2155 addUserRoleInExternalSystem(userRolesUpload);
2159 return userRolesAdded;
2163 * Its adding a user role in external auth system while doing bulk upload
2165 * @param userRolesUpload
2167 private void addUserRoleInExternalSystem(BulkUploadUserRoles userRolesUpload) {
2170 ObjectMapper mapper = new ObjectMapper();
2171 if (EPCommonSystemProperties
2172 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
2173 name = userRolesUpload.getOrgUserId()
2174 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
2176 ExternalAccessUser extUser = new ExternalAccessUser(name,
2177 userRolesUpload.getAppNameSpace() + "." + userRolesUpload.getRoleName().replaceAll(" ", "_"));
2178 String userRole = mapper.writeValueAsString(extUser);
2179 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2180 HttpEntity<String> entity = new HttpEntity<>(userRole, headers);
2182 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
2183 HttpMethod.POST, entity, String.class);
2184 } catch(HttpClientErrorException e){
2185 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addUserRoleInExternalSystem", e);
2186 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2187 } catch (Exception e) {
2188 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2189 logger.error(EELFLoggerDelegate.errorLogger, "addUserRoleInExternalSystem: UserRole already exits but does not break functionality");
2191 logger.error(EELFLoggerDelegate.errorLogger, "addUserRoleInExternalSystem: Failed to addUserRoleInExternalSystem", e.getMessage());
2197 public void deleteRoleDependencyRecords(Session localSession, Long roleId, Long appId) throws Exception {
2202 //It should delete only when it portal's roleId
2203 if(appId.equals(PortalConstants.PORTAL_APP_ID)){
2204 // Delete from fn_role_function
2205 sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
2206 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2207 query = localSession.createSQLQuery(sql);
2208 query.executeUpdate();
2210 // Delete from fn_role_composite
2211 sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId;
2212 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2213 query = localSession.createSQLQuery(sql);
2214 query.executeUpdate();
2217 // Delete from ep_app_role_function
2218 sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId;
2219 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2220 query = localSession.createSQLQuery(sql);
2221 query.executeUpdate();
2223 // Delete from ep_role_notification
2224 sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
2225 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2226 query = localSession.createSQLQuery(sql);
2227 query.executeUpdate();
2229 // Delete from fn_user_pseudo_role
2230 sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
2231 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2232 query = localSession.createSQLQuery(sql);
2233 query.executeUpdate();
2235 // Delete form EP_WIDGET_CATALOG_ROLE
2236 sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId;
2237 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2238 query = localSession.createSQLQuery(sql);
2239 query.executeUpdate();
2241 // Delete form EP_WIDGET_CATALOG_ROLE
2242 sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId;
2243 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2244 query = localSession.createSQLQuery(sql);
2245 query.executeUpdate();
2247 // Delete form fn_menu_functional_roles
2248 sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
2249 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2250 query = localSession.createSQLQuery(sql);
2251 query.executeUpdate();
2253 } catch (Exception e) {
2254 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e);
2255 throw new Exception("delete Failed" + e.getMessage());
2260 @SuppressWarnings("unchecked")
2262 public List<String> getMenuFunctionsList(String uebkey) throws Exception {
2263 List<String> appMenuFunctionsList = null;
2265 EPApp app = getApp(uebkey).get(0);
2266 final Map<String, Long> appParams = new HashMap<>();
2267 appParams.put(APP_ID, app.getId());
2268 appMenuFunctionsList = dataAccessService.executeNamedQuery("getMenuFunctions", appParams, null);
2269 } catch (Exception e) {
2270 logger.error(EELFLoggerDelegate.errorLogger, "getMenuFunctionsList: Failed", e);
2271 return appMenuFunctionsList;
2273 return appMenuFunctionsList;
2276 @SuppressWarnings({ "unchecked"})
2278 public List<EcompUser> getAllAppUsers(String uebkey) throws Exception {
2279 List<String> usersList = new ArrayList<>();
2280 List<EcompUser> usersfinalList = new ArrayList<>();
2282 EPApp app = getApp(uebkey).get(0);
2283 final Map<String, Long> appParams = new HashMap<>();
2284 appParams.put("appId", app.getId());
2285 List<EcompUserRoles> userList = (List<EcompUserRoles>) dataAccessService
2286 .executeNamedQuery("ApplicationUserRoles", appParams, null);
2287 for (EcompUserRoles ecompUserRole : userList) {
2288 boolean found = false;
2289 Set<EcompRole> roles = null;
2290 for (EcompUser user : usersfinalList) {
2291 if (user.getOrgUserId().equals(ecompUserRole.getOrgUserId())) {
2292 EcompRole ecompRole = new EcompRole();
2293 ecompRole.setId(ecompUserRole.getRoleId());
2294 ecompRole.setName(ecompUserRole.getRoleName());
2295 roles = user.getRoles();
2296 roles.add(ecompRole);
2297 user.setRoles(roles);
2304 EcompUser epUser = new EcompUser();
2305 epUser.setOrgId(ecompUserRole.getOrgId());
2306 epUser.setManagerId(ecompUserRole.getManagerId());
2307 epUser.setFirstName(ecompUserRole.getFirstName());
2308 epUser.setLastName(ecompUserRole.getLastName());
2309 epUser.setPhone(ecompUserRole.getPhone());
2310 epUser.setEmail(ecompUserRole.getEmail());
2311 epUser.setOrgUserId(ecompUserRole.getOrgUserId());
2312 epUser.setOrgCode(ecompUserRole.getOrgCode());
2313 epUser.setOrgManagerUserId(ecompUserRole.getOrgManagerUserId());
2314 epUser.setJobTitle(ecompUserRole.getJobTitle());
2315 epUser.setLoginId(ecompUserRole.getLoginId());
2316 epUser.setActive(true);
2317 roles = new HashSet<>();
2318 EcompRole ecompRole = new EcompRole();
2319 ecompRole.setId(ecompUserRole.getRoleId());
2320 ecompRole.setName(ecompUserRole.getRoleName());
2321 roles.add(ecompRole);
2322 epUser.setRoles(roles);
2323 usersfinalList.add(epUser);
2326 ObjectMapper mapper = new ObjectMapper();
2328 for (EcompUser u1 : usersfinalList) {
2329 String str = mapper.writeValueAsString(u1);
2332 } catch (Exception e) {
2333 logger.error(EELFLoggerDelegate.errorLogger, "getAllUsers failed", e);
2336 return usersfinalList;