1 package org.openecomp.portalapp.portal.service;
3 import java.util.ArrayList;
4 import java.util.HashMap;
5 import java.util.HashSet;
6 import java.util.Iterator;
7 import java.util.LinkedHashMap;
11 import java.util.SortedSet;
12 import java.util.TreeSet;
13 import java.util.stream.Collectors;
15 import org.apache.commons.lang.StringUtils;
16 import org.hibernate.Query;
17 import org.hibernate.Session;
18 import org.hibernate.SessionFactory;
19 import org.hibernate.Transaction;
20 import org.json.JSONArray;
21 import org.json.JSONObject;
22 import org.openecomp.portalapp.portal.domain.CentralRoleFunction;
23 import org.openecomp.portalapp.portal.domain.EPApp;
24 import org.openecomp.portalapp.portal.domain.EPAppRoleFunction;
25 import org.openecomp.portalapp.portal.domain.EPRole;
26 import org.openecomp.portalapp.portal.domain.EPUser;
27 import org.openecomp.portalapp.portal.domain.EPUserApp;
28 import org.openecomp.portalapp.portal.domain.ExternalRoleDetails;
29 import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
30 import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
31 import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
32 import org.openecomp.portalapp.portal.transport.BulkUploadRoleFunction;
33 import org.openecomp.portalapp.portal.transport.BulkUploadUserRoles;
34 import org.openecomp.portalapp.portal.transport.CentralApp;
35 import org.openecomp.portalapp.portal.transport.CentralRole;
36 import org.openecomp.portalapp.portal.transport.CentralUser;
37 import org.openecomp.portalapp.portal.transport.CentralUserApp;
38 import org.openecomp.portalapp.portal.transport.EcompUserRoles;
39 import org.openecomp.portalapp.portal.transport.ExternalAccessPerms;
40 import org.openecomp.portalapp.portal.transport.ExternalAccessPermsDetail;
41 import org.openecomp.portalapp.portal.transport.ExternalAccessRole;
42 import org.openecomp.portalapp.portal.transport.ExternalAccessRolePerms;
43 import org.openecomp.portalapp.portal.transport.ExternalAccessUser;
44 import org.openecomp.portalapp.portal.transport.ExternalRoleDescription;
45 import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
46 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
47 import org.openecomp.portalapp.portal.utils.PortalConstants;
48 import org.openecomp.portalsdk.core.domain.Role;
49 import org.openecomp.portalsdk.core.domain.RoleFunction;
50 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
51 import org.openecomp.portalsdk.core.restful.domain.EcompRole;
52 import org.openecomp.portalsdk.core.restful.domain.EcompUser;
53 import org.openecomp.portalsdk.core.service.DataAccessService;
54 import org.openecomp.portalsdk.core.util.SystemProperties;
55 import org.springframework.beans.factory.annotation.Autowired;
56 import org.springframework.context.annotation.EnableAspectJAutoProxy;
57 import org.springframework.http.HttpEntity;
58 import org.springframework.http.HttpHeaders;
59 import org.springframework.http.HttpMethod;
60 import org.springframework.http.ResponseEntity;
61 import org.springframework.stereotype.Service;
62 import org.springframework.transaction.annotation.Transactional;
63 import org.springframework.web.client.HttpClientErrorException;
64 import org.springframework.web.client.RestTemplate;
66 import com.fasterxml.jackson.core.JsonProcessingException;
67 import com.fasterxml.jackson.databind.DeserializationFeature;
68 import com.fasterxml.jackson.databind.ObjectMapper;
69 import com.fasterxml.jackson.databind.type.TypeFactory;
71 @Service("externalAccessRolesService")
72 @EnableAspectJAutoProxy
75 public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesService {
77 private static final String AND_FUNCTION_CD_EQUALS = " and function_cd = '";
79 private static final String OWNER = ".owner";
81 private static final String ADMIN = ".admin";
83 private static final String ACCOUNT_ADMINISTRATOR = ".Account_Administrator";
85 private static final String FUNCTION_CD_LIKE_CLAUSE = " and function_cd like '%";
87 private static final String FUNCTION_PIPE = "|";
89 private static final String IS_NULL_STRING = "null";
91 private static final String EXTERNAL_AUTH_PERMS = "perms";
93 private static final String EXTERNAL_AUTH_ROLE_DESCRIPTION = "description";
95 private static final String WHERE_APP_ID_EQUALS = " where app_id = ";
97 private static final String IS_EMPTY_JSON_STRING = "{}";
99 private static final String CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE = "Connecting to External Auth system";
101 private static final String WHERE_ROLE_ID_EQUALS = " where role_id = ";
103 private static final String APP_ROLE_ID = "appRoleId";
105 private static final String APP_ID = "appId";
107 private static final String PRIORITY = "priority";
109 private static final String ACTIVE = "active";
111 private static final String ROLE_NAME = "name";
113 private static final String ID = "id";
115 private static final String WHERE_ROLE_NAME_EQUALS = " where role_name = '";
117 private static final String APP_ID_EQUALS = " app_id = ";
119 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesServiceImpl.class);
122 private DataAccessService dataAccessService;
125 private SessionFactory sessionFactory;
127 RestTemplate template = new RestTemplate();
129 @SuppressWarnings("unchecked")
130 public List<EPRole> getAppRoles(Long appId) throws Exception {
131 List<EPRole> applicationRoles = null;
132 String filter = null;
135 filter = " where app_id is null";
137 filter = WHERE_APP_ID_EQUALS + appId;
139 applicationRoles = dataAccessService.getList(EPRole.class, filter, null, null);
140 } catch (Exception e) {
141 logger.error(EELFLoggerDelegate.errorLogger, "getAppRoles: failed", e);
142 throw new Exception(e.getMessage());
144 return applicationRoles;
147 @SuppressWarnings("unchecked")
149 public List<EPApp> getApp(String uebkey) throws Exception {
150 List<EPApp> app = null;
152 app = (List<EPApp>) dataAccessService.getList(EPApp.class, " where ueb_key = '" + uebkey + "'", null, null);
153 if(!app.get(0).getEnabled() && !app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)){
154 throw new Exception("Application:"+app.get(0).getName()+" is Unavailable");
156 } catch (Exception e) {
157 logger.error(EELFLoggerDelegate.errorLogger, "getApp: failed", e);
158 throw new Exception(e.getMessage());
164 * It returns single application role from external auth system
167 * @return JSON string which contains application role details
170 private String getSingleAppRole(String addRole, EPApp app) throws Exception {
171 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
172 HttpEntity<String> entity = new HttpEntity<>(headers);
173 logger.debug(EELFLoggerDelegate.debugLogger, "getSingleAppRole: Connecting to External Auth system");
174 ResponseEntity<String> response = template
176 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
177 + app.getNameSpace() + "." + addRole.replaceAll(" ", "_"),
178 HttpMethod.GET, entity, String.class);
179 logger.debug(EELFLoggerDelegate.debugLogger,
180 "getSingleAppRole: Finished GET app role from External Auth system and status code: {} ", response.getStatusCode().value());
181 return response.getBody();
185 public boolean addRole(Role addRole, String uebkey) throws Exception {
186 boolean response = false;
187 ResponseEntity<String> addResponse = null;
188 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
189 EPApp app = getApp(uebkey).get(0);
190 String newRole = updateExistingRoleInExternalSystem(addRole, app);
191 HttpEntity<String> entity = new HttpEntity<>(newRole, headers);
192 logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Connecting to External Auth system");
193 addResponse = template.exchange(
194 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
195 HttpMethod.POST, entity, String.class);
196 if (addResponse.getStatusCode().value() == 201) {
198 logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Finished adding role in the External Auth system and response code: {} ", addResponse.getStatusCode().value());
200 if (addResponse.getStatusCode().value() == 406) {
201 logger.error(EELFLoggerDelegate.errorLogger,
202 "addRole: Failed to add in the External Auth system due to {} and status code: {}", addResponse.getBody(), addResponse.getStatusCode().value());
209 * It deletes record in external auth system
212 * @return JSON String which has status code and response body
215 private ResponseEntity<String> deleteRoleInExternalSystem(String delRole) throws Exception {
216 ResponseEntity<String> delResponse = null;
217 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
218 HttpEntity<String> entity = new HttpEntity<>(delRole, headers);
219 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
220 delResponse = template.exchange(
221 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role?force=true",
222 HttpMethod.DELETE, entity, String.class);
223 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: Finished DELETE operation in the External Auth system and status code: {} ", delResponse.getStatusCode().value());
228 * It updates role in external auth system
230 * @param updateExtRole
232 * @return true if success else false
234 * If updateRoleInExternalSystem fails we catch it in logger for detail message
236 @SuppressWarnings("unchecked")
237 private boolean updateRoleInExternalSystem(Role updateExtRole, EPApp app) throws Exception {
238 boolean response = false;
239 ObjectMapper mapper = new ObjectMapper();
240 ResponseEntity<String> deleteResponse = null;
241 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
242 ExternalAccessRolePerms extRolePerms = null;
243 ExternalAccessPerms extPerms = null;
244 List<EPRole> epRoleList = null;
245 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
246 epRoleList = dataAccessService.getList(EPRole.class,
247 WHERE_ROLE_ID_EQUALS + updateExtRole.getId() + " and app_id is null", null, null);
249 epRoleList = dataAccessService.getList(EPRole.class,
250 " where app_role_id = " + updateExtRole.getId() + " and app_id = " + app.getId(), null, null);
252 String appRole = getSingleAppRole(epRoleList.get(0).getName(), app);
253 if (!appRole.equals(IS_EMPTY_JSON_STRING)) {
254 JSONObject jsonObj = new JSONObject(appRole);
255 JSONArray extRole = jsonObj.getJSONArray("role");
256 if (!extRole.getJSONObject(0).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
257 String roleName = extRole.getJSONObject(0).getString(ROLE_NAME);
258 Map<String, String> delRoleKeyMapper = new HashMap<>();
259 delRoleKeyMapper.put(ROLE_NAME, roleName);
260 String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
261 deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
262 if (deleteResponse.getStatusCode().value() != 200) {
263 throw new Exception(deleteResponse.getBody());
265 addRole(updateExtRole, app.getUebKey());
267 String desc = extRole.getJSONObject(0).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
268 String name = extRole.getJSONObject(0).getString(ROLE_NAME);
269 List<ExternalAccessPerms> list = null;
270 if (extRole.getJSONObject(0).has(EXTERNAL_AUTH_PERMS)) {
271 JSONArray perms = extRole.getJSONObject(0).getJSONArray(EXTERNAL_AUTH_PERMS);
272 list = mapper.readValue(perms.toString(), TypeFactory.defaultInstance()
273 .constructCollectionType(List.class, ExternalAccessPerms.class));
275 ExternalRoleDescription sysRoleList = mapper.readValue(desc, ExternalRoleDescription.class);
276 // If role name or role functions are updated then delete record in External System and add new record to avoid conflicts
277 Boolean existingRoleActive;
278 boolean isActiveValueChanged;
279 // check role active status
280 existingRoleActive = new Boolean(sysRoleList.getActive());
281 isActiveValueChanged = existingRoleActive.equals(updateExtRole.getActive());
282 if (!sysRoleList.getName().equals(updateExtRole.getName())) {
283 Map<String, String> delRoleKeyMapper = new HashMap<>();
284 delRoleKeyMapper.put(ROLE_NAME, name);
285 String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
286 deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
287 if (deleteResponse.getStatusCode().value() != 200) {
288 logger.error(EELFLoggerDelegate.errorLogger, "updateRoleInExternalSystem: Failed to delete role in external system due to {} ", deleteResponse.getBody());
289 throw new Exception(deleteResponse.getBody());
291 addRole(updateExtRole, app.getUebKey());
292 addRoleFunctionsInExternalSystem(updateExtRole, mapper, app);
294 boolean checkPriorityStatus = StringUtils.equals(String.valueOf(sysRoleList.getPriority()),String.valueOf(updateExtRole.getPriority()));
295 ExternalAccessRole updateRole = new ExternalAccessRole();
296 if (!isActiveValueChanged
297 || !checkPriorityStatus
298 || sysRoleList.getId().equals(IS_NULL_STRING)
299 || !sysRoleList.getId().equals(String.valueOf(epRoleList.get(0).getId()))) {
300 String updateDesc = "";
301 String appId = (app.getId().equals(PortalConstants.PORTAL_APP_ID)) ? " app_id is null"
302 : APP_ID_EQUALS + app.getId();
303 List<EPRole> getRole = dataAccessService.getList(EPRole.class,
304 WHERE_ROLE_NAME_EQUALS + updateExtRole.getName() + "' and " + appId, null, null);
305 Map<String, String> extSystemUpdateRoleJsonMapper = new LinkedHashMap<>();
306 extSystemUpdateRoleJsonMapper.put(ID, String.valueOf(getRole.get(0).getId()));
307 extSystemUpdateRoleJsonMapper.put(ROLE_NAME, String.valueOf(updateExtRole.getName()));
308 extSystemUpdateRoleJsonMapper.put(ACTIVE, String.valueOf(updateExtRole.getActive()));
309 extSystemUpdateRoleJsonMapper.put(PRIORITY, String.valueOf(updateExtRole.getPriority()));
310 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
311 extSystemUpdateRoleJsonMapper.put(APP_ID, "null");
312 extSystemUpdateRoleJsonMapper.put(APP_ROLE_ID, "null");
314 extSystemUpdateRoleJsonMapper.put(APP_ID, String.valueOf(app.getId()));
315 extSystemUpdateRoleJsonMapper.put(APP_ROLE_ID, String.valueOf(getRole.get(0).getAppRoleId()));
318 updateDesc = mapper.writeValueAsString(extSystemUpdateRoleJsonMapper);
319 updateRole.setName(app.getNameSpace() + "." + updateExtRole.getName().replaceAll(" ", "_"));
320 updateRole.setDescription(updateDesc);
321 String updateRoleDesc = mapper.writeValueAsString(updateRole);
322 HttpEntity<String> entity = new HttpEntity<>(updateRoleDesc, headers);
323 logger.debug(EELFLoggerDelegate.debugLogger,
324 "updateRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
325 ResponseEntity<String> updatePermsResponse = template.exchange(
326 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
327 HttpMethod.PUT, entity, String.class);
328 logger.debug(EELFLoggerDelegate.debugLogger,
329 "updateRoleInExternalSystem: Finished updating in External Auth system and status code: {} ",
330 updatePermsResponse.getStatusCode().value());
332 List<RoleFunction> roleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole);
333 Map<String, RoleFunction> updateRoleFunc = new HashMap<>();
334 for (RoleFunction addPerm : roleFunctionListNew) {
335 updateRoleFunc.put(addPerm.getCode(), addPerm);
337 final Map<String, ExternalAccessPerms> extRolePermMap = new HashMap<>();
338 // Update permissions in the ExternalAccess System
340 for (ExternalAccessPerms perm : list) {
341 if (!updateRoleFunc.containsKey(perm.getInstance())) {
342 removePermForRole(perm, mapper, name, headers);
344 extRolePermMap.put(perm.getInstance(), perm);
348 if (!roleFunctionListNew.isEmpty()) {
349 for (RoleFunction roleFunc : roleFunctionListNew) {
350 if (!extRolePermMap.containsKey(roleFunc.getCode())) {
351 String checkType = roleFunc.getCode().contains("menu") ? "menu" : "url";
352 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, roleFunc.getCode(),
354 extRolePerms = new ExternalAccessRolePerms(extPerms,
355 app.getNameSpace() + "." + updateExtRole.getName().replaceAll(" ", "_"));
356 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
357 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
358 logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
359 ResponseEntity<String> addResponse = template.exchange(
360 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
362 HttpMethod.POST, entity, String.class);
363 if (addResponse.getStatusCode().value() != 201) {
365 logger.debug(EELFLoggerDelegate.debugLogger,
366 "updateRoleInExternalSystem: Connected to External Auth system but something went wrong! due to {} and statuscode: {}",
367 addResponse.getStatusCode().getReasonPhrase(),
368 addResponse.getStatusCode().value());
371 logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: Finished adding permissions to roles in External Auth system and status code: {} ", addResponse.getStatusCode().value());
378 // It seems like role exists in local DB but not in External Access system
379 addRole(updateExtRole, app.getUebKey());
380 List<RoleFunction> roleFunctionListUpdate = convertSetToListOfRoleFunctions(updateExtRole);
382 if (!roleFunctionListUpdate.isEmpty()) {
383 addRoleFunctionsInExternalSystem(updateExtRole, mapper, app);
391 * It adds functions to the role in external auth system
393 * @param updateExtRole
394 * @param addPermsMapper
396 * @return true if success else false
399 private boolean addRoleFunctionsInExternalSystem(Role updateExtRole, ObjectMapper addPermsMapper, EPApp app)
401 boolean response = false;
402 ExternalAccessRolePerms extAddRolePerms = null;
403 ExternalAccessPerms extAddPerms = null;
404 List<RoleFunction> roleFunctionListAdd = convertSetToListOfRoleFunctions(updateExtRole);
405 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
406 for (RoleFunction roleFunc : roleFunctionListAdd) {
407 String checkType = roleFunc.getCode().contains("menu") ? "menu" : "url";
408 extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, roleFunc.getCode(), "*");
409 extAddRolePerms = new ExternalAccessRolePerms(extAddPerms,
410 app.getNameSpace() + "." + updateExtRole.getName().replaceAll(" ", "_"));
411 String updateRolePerms = addPermsMapper.writeValueAsString(extAddRolePerms);
412 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
413 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
414 ResponseEntity<String> addResponse = template.exchange(
415 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
416 HttpMethod.POST, entity, String.class);
417 if (addResponse.getStatusCode().value() != 201) {
419 logger.debug(EELFLoggerDelegate.debugLogger,
420 "addRoleFunctionsInExternalSystem: While adding permission to the role in External Auth system something went wrong! due to {} and statuscode: {}",
421 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
424 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system and status code: {} ", addResponse.getStatusCode().value());
432 * It converts list of functions in updateExtRole parameter to the RoleFunction object
434 * @param updateExtRole
435 * @return list of functions
437 @SuppressWarnings("unchecked")
438 private List<RoleFunction> convertSetToListOfRoleFunctions(Role updateExtRole) {
439 Set<RoleFunction> roleFunctionSetList = updateExtRole.getRoleFunctions();
440 List<RoleFunction> roleFunctionList = new ArrayList<>();
441 ObjectMapper roleFuncMapper = new ObjectMapper();
442 Iterator<RoleFunction> itetaror = roleFunctionSetList.iterator();
443 while (itetaror.hasNext()) {
444 Object nextValue = itetaror.next();
445 RoleFunction roleFunction = roleFuncMapper.convertValue(nextValue, RoleFunction.class);
446 roleFunctionList.add(roleFunction);
448 return roleFunctionList.stream().distinct().collect(Collectors.toList());
452 * It delete permissions/functions in the external auth system
460 private void removePermForRole(ExternalAccessPerms perm, ObjectMapper permMapper, String name, HttpHeaders headers)
462 ExternalAccessRolePerms extAccessRolePerms = new ExternalAccessRolePerms(perm, name);
463 String permDetails = permMapper.writeValueAsString(extAccessRolePerms);
464 HttpEntity<String> deleteEntity = new HttpEntity<>(permDetails, headers);
465 logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
466 ResponseEntity<String> deletePermResponse = template
467 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/"
468 + name + "/perm", HttpMethod.DELETE, deleteEntity, String.class);
469 if (deletePermResponse.getStatusCode().value() != 200) {
470 throw new Exception(deletePermResponse.getBody());
472 logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: Finished deleting permission to role in External Auth system and status code: {}",
473 deletePermResponse.getStatusCode().value());
477 * It will create new role in the External Auth System
481 * @return true if successfully added in the system else false
483 * If fails to add role in the system
485 private boolean addNewRoleInExternalSystem(List<EPRole> newRole, EPApp app) throws Exception {
486 boolean response = false;
487 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
488 ObjectMapper mapper = new ObjectMapper();
489 String addNewRole = "";
490 ExternalAccessRole extRole = new ExternalAccessRole();
491 String addDesc = null;
492 Map<String, String> extSystemJsonMapper = new LinkedHashMap<>();
493 extSystemJsonMapper.put(ID, String.valueOf(newRole.get(0).getId()));
494 extSystemJsonMapper.put(ROLE_NAME, String.valueOf(newRole.get(0).getName()));
495 extSystemJsonMapper.put(ACTIVE, String.valueOf(newRole.get(0).getActive()));
496 extSystemJsonMapper.put(PRIORITY, String.valueOf(newRole.get(0).getPriority()));
497 extSystemJsonMapper.put(APP_ID, String.valueOf(newRole.get(0).getAppId()));
498 extSystemJsonMapper.put(APP_ROLE_ID, String.valueOf(newRole.get(0).getAppRoleId()));
499 addDesc = mapper.writeValueAsString(extSystemJsonMapper);
500 extRole.setName(app.getNameSpace() + "." + newRole.get(0).getName().replaceAll(" ", "_"));
501 extRole.setDescription(addDesc);
502 addNewRole = mapper.writeValueAsString(extRole);
503 HttpEntity<String> deleteEntity = new HttpEntity<>(addNewRole, headers);
504 logger.debug(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
505 ResponseEntity<String> addNewRoleInExternalSystem = template.exchange(
506 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
507 HttpMethod.POST, deleteEntity, String.class);
508 if (addNewRoleInExternalSystem.getStatusCode().value() != 201) {
509 throw new Exception(addNewRoleInExternalSystem.getBody());
511 logger.debug(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: Finished adding into External Auth system and status code: {}",
512 addNewRoleInExternalSystem.getStatusCode().value());
520 * It updates existing role in the External Auth System
523 * It Contains role information
525 * @return string which is formatted to match with the external auth system
526 * @throws JsonProcessingException
528 @SuppressWarnings("unchecked")
529 private String updateExistingRoleInExternalSystem(Role addRole, EPApp app) throws JsonProcessingException {
530 ObjectMapper mapper = new ObjectMapper();
531 String addNewRole = "";
532 ExternalAccessRole extRole = new ExternalAccessRole();
533 List<EPRole> role = null;
534 String addDesc = null;
535 Map<String, String> extSystemUpdateRole = new LinkedHashMap<>();
536 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
537 role = dataAccessService.getList(EPRole.class, WHERE_ROLE_ID_EQUALS + addRole.getId() + " and app_id is null", null, null);
539 role = dataAccessService.getList(EPRole.class, " where app_role_id = " + addRole.getId() + " and app_id ="+app.getId(), null, null);
541 extSystemUpdateRole.put(ID, String.valueOf(role.get(0).getId()));
542 extSystemUpdateRole.put(ROLE_NAME, String.valueOf(addRole.getName()));
543 extSystemUpdateRole.put(ACTIVE, String.valueOf(role.get(0).getActive()));
544 extSystemUpdateRole.put(PRIORITY, String.valueOf(role.get(0).getPriority()));
545 extSystemUpdateRole.put(APP_ID, String.valueOf(role.get(0).getAppId()));
546 extSystemUpdateRole.put(APP_ROLE_ID, String.valueOf(role.get(0).getAppRoleId()));
547 addDesc = mapper.writeValueAsString(extSystemUpdateRole);
548 extRole.setName(app.getNameSpace() + "." + addRole.getName().replaceAll(" ", "_"));
549 extRole.setDescription(addDesc);
550 addNewRole = mapper.writeValueAsString(extRole);
555 * It create a role in the external auth system and then in our local
559 * @return true else false
562 @SuppressWarnings("unchecked")
564 private boolean addRoleInEcompDB(Role addRoleInDB, EPApp app) throws Exception {
565 boolean result = false;
566 List<EPRole> applicationRoles = null;
567 EPRole epRole = null;
568 Set<RoleFunction> roleFunctionList = addRoleInDB.getRoleFunctions();
569 List<RoleFunction> roleFunctionListNew = new ArrayList<>();
570 ObjectMapper mapper = new ObjectMapper();
571 Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
572 while (itetaror.hasNext()) {
573 Object nextValue = itetaror.next();
574 RoleFunction roleFunction = mapper.convertValue(nextValue, RoleFunction.class);
575 roleFunctionListNew.add(roleFunction);
577 List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct().collect(Collectors.toList());
579 if (addRoleInDB.getId() == null) { // check if it is new role
580 checkIfRoleExitsInExternalSystem(addRoleInDB, app);
581 EPRole epRoleNew = new EPRole();
582 epRoleNew.setActive(addRoleInDB.getActive());
583 epRoleNew.setName(addRoleInDB.getName());
584 epRoleNew.setPriority(addRoleInDB.getPriority());
585 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
586 epRoleNew.setAppId(null);
588 epRoleNew.setAppId(app.getId());
590 dataAccessService.saveDomainObject(epRoleNew, null);
591 List<EPRole> getRoleCreated = null;
592 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
593 List<EPRole> roleCreated = dataAccessService.getList(EPRole.class,
594 WHERE_ROLE_NAME_EQUALS + addRoleInDB.getName() + "' and app_id = " + app.getId(), null,
596 EPRole epUpdateRole = roleCreated.get(0);
597 epUpdateRole.setAppRoleId(epUpdateRole.getId());
598 dataAccessService.saveDomainObject(epUpdateRole, null);
599 getRoleCreated = dataAccessService.getList(EPRole.class,
600 WHERE_ROLE_NAME_EQUALS + addRoleInDB.getName() + "' and app_id = " + app.getId(), null,
603 getRoleCreated = dataAccessService.getList(EPRole.class,
604 WHERE_ROLE_NAME_EQUALS + addRoleInDB.getName() + "' and app_id is null", null, null);
606 // Add role in External Auth system
607 result = addNewRoleInExternalSystem(getRoleCreated, app);
608 } else { // if role already exists then update it
609 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
610 applicationRoles = dataAccessService.getList(EPRole.class,
611 " where app_id is null " + " and role_id = " + addRoleInDB.getId(), null, null);
613 applicationRoles = dataAccessService.getList(EPRole.class,
614 WHERE_APP_ID_EQUALS + app.getId() + " and app_role_id = " + addRoleInDB.getId(), null, null);
616 if (applicationRoles.isEmpty()) {
617 applicationRoles = dataAccessService.getList(EPRole.class,
618 WHERE_APP_ID_EQUALS + app.getId() + " and role_name = '" + addRoleInDB.getName() + "'", null,
621 updateRoleInExternalSystem(addRoleInDB, app);
622 deleteRoleFunction(app, applicationRoles);
623 if (!applicationRoles.isEmpty()) {
624 epRole = applicationRoles.get(0);
625 epRole.setName(addRoleInDB.getName());
626 epRole.setPriority(addRoleInDB.getPriority());
627 epRole.setActive(addRoleInDB.getActive());
628 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
629 epRole.setAppId(null);
630 epRole.setAppRoleId(null);
631 } else if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)
632 && applicationRoles.get(0).getAppRoleId() == null) {
633 epRole.setAppRoleId(epRole.getId());
635 dataAccessService.saveDomainObject(epRole, null);
638 saveRoleFunction(listWithoutDuplicates, app, applicationRoles);
641 } catch (Exception e) {
642 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInEcompDB is failed", e);
643 throw new Exception(e.getMessage());
650 * It validates whether role exists in external auth system
657 private void checkIfRoleExitsInExternalSystem(Role checkRole, EPApp app) throws Exception {
658 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
659 String roleName = app.getNameSpace() + "." + checkRole.getName().replaceAll(" ", "_");
660 HttpEntity<String> checkRoleEntity = new HttpEntity<>(headers);
661 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRoleExitsInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
662 ResponseEntity<String> checkRoleInExternalSystem = template
663 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
664 + roleName, HttpMethod.GET, checkRoleEntity, String.class);
665 if (!checkRoleInExternalSystem.getBody().equals(IS_EMPTY_JSON_STRING)) {
666 logger.debug("checkIfRoleExitsInExternalSystem: Role already exists in external system {} and status code: {} ", checkRoleInExternalSystem.getBody(), checkRoleInExternalSystem.getStatusCode().value());
667 throw new Exception("Role already exists in external system");
672 * It saves list of functions to the role in portal
674 * @param roleFunctionListNew
676 * @param applicationRoles
679 @SuppressWarnings("unchecked")
680 private void saveRoleFunction(List<RoleFunction> roleFunctionListNew, EPApp app, List<EPRole> applicationRoles)
682 for (RoleFunction roleFunc : roleFunctionListNew) {
683 EPAppRoleFunction appRoleFunc = new EPAppRoleFunction();
684 appRoleFunc.setAppId(app.getId());
685 appRoleFunc.setRoleId(applicationRoles.get(0).getId());
686 // query to check if function code is different for safe operation
687 List<CentralRoleFunction> roleFunction = dataAccessService.getList(CentralRoleFunction.class,
688 WHERE_APP_ID_EQUALS+ app.getId()+FUNCTION_CD_LIKE_CLAUSE + roleFunc.getCode() + "'", null, null);
689 appRoleFunc.setCode(roleFunction.get(0).getCode());
690 dataAccessService.saveDomainObject(appRoleFunc, null);
695 * It deletes all EPAppRoleFunction records in the portal
700 @SuppressWarnings("unchecked")
701 private void deleteRoleFunction(EPApp app, List<EPRole> role) {
702 List<EPAppRoleFunction> appRoleFunctionList = dataAccessService.getList(EPAppRoleFunction.class,
703 WHERE_APP_ID_EQUALS + app.getId() + " and role_id = " + role.get(0).getId(), null, null);
704 if (!appRoleFunctionList.isEmpty()) {
705 for (EPAppRoleFunction approleFunction : appRoleFunctionList) {
706 dataAccessService.deleteDomainObject(approleFunction, null);
712 @SuppressWarnings("unchecked")
713 public List<EPUser> getUser(String loginId){
714 return (List<EPUser>) dataAccessService.getList(EPUser.class,
715 " where org_user_id = '" + loginId + "'", null, null);
719 public String getUserWithRoles(String loginId, String uebkey) throws Exception {
720 final Map<String, String> params = new HashMap<>();
721 List<EPUser> userList = null;
722 CentralUser cenUser = null;
724 String result = null;
726 params.put("orgUserIdValue", loginId);
727 List<EPApp> appList = getApp(uebkey);
728 if (!appList.isEmpty()) {
729 app = appList.get(0);
730 userList = getUser(loginId);
731 if (!userList.isEmpty()) {
732 EPUser user = userList.get(0);
733 ObjectMapper mapper = new ObjectMapper();
734 Set<EPUserApp> userAppSet = user.getEPUserApps();
735 cenUser = createEPUser(user, userAppSet, app);
736 result = mapper.writeValueAsString(cenUser);
737 } else if (userList.isEmpty()) {
738 throw new Exception("User not found");
741 throw new Exception("Application not found");
743 } catch (Exception e) {
744 logger.error(EELFLoggerDelegate.errorLogger, "getUser: failed", e);
745 throw new Exception(e.getMessage());
751 public List<CentralRole> getRolesForApp(String uebkey) throws Exception {
752 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Entering into getRolesForApp");
753 List<CentralRole> roleList = new ArrayList<>();
754 final Map<String, Long> params = new HashMap<>();
756 List<EPApp> app = getApp(uebkey);
757 List<EPRole> appRolesList = getAppRoles(app.get(0).getId());
758 createCentralRoleObject(app, appRolesList, roleList, params);
759 } catch (Exception e) {
760 throw new Exception("getRolesForApp Failed", e);
762 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Finished getRolesForApp");
766 @SuppressWarnings("unchecked")
768 public List<CentralRoleFunction> getRoleFuncList(String uebkey) throws Exception {
769 EPApp app = getApp(uebkey).get(0);
770 List<CentralRoleFunction> finalRoleList = new ArrayList<>();
771 final Map<String, Long> params = new HashMap<>();
772 params.put(APP_ID, app.getId());
773 // Sync all functions from external system into Ecomp portal DB
774 logger.debug(EELFLoggerDelegate.debugLogger, "getRoleFuncList: Entering into syncRoleFunctionFromExternalAccessSystem");
775 syncRoleFunctionFromExternalAccessSystem(app);
776 logger.debug(EELFLoggerDelegate.debugLogger, "getRoleFuncList: Finished syncRoleFunctionFromExternalAccessSystem");
777 List<CentralRoleFunction> getRoleFuncList = dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null);
778 for(CentralRoleFunction roleFuncItem : getRoleFuncList ){
779 if(roleFuncItem.getCode().contains(FUNCTION_PIPE)){
781 int count = StringUtils.countMatches(roleFuncItem.getCode(), FUNCTION_PIPE);
783 code = roleFuncItem.getCode().substring(
784 roleFuncItem.getCode().indexOf(FUNCTION_PIPE) + 1,
785 roleFuncItem.getCode().lastIndexOf(FUNCTION_PIPE));
787 code = roleFuncItem.getCode()
788 .substring(roleFuncItem.getCode().lastIndexOf(FUNCTION_PIPE) + 1);
790 roleFuncItem.setCode(code);
791 finalRoleList.add(roleFuncItem);
793 finalRoleList.add(roleFuncItem);
796 return finalRoleList;
800 * It returns user detail information which is deep copy of EPUser.class object
808 @SuppressWarnings("unchecked")
809 private CentralUser createEPUser(EPUser userInfo, Set<EPUserApp> userAppSet, EPApp app) throws Exception {
811 final Map<String, Long> params = new HashMap<>();
812 CentralUser userAppList = new CentralUser();
813 CentralUser user1 = null;
815 userAppList.userApps = new TreeSet<CentralUserApp>();
816 for (EPUserApp userApp : userAppSet) {
817 if (userApp.getRole().getActive()) {
818 EPApp epApp = userApp.getApp();
819 String globalRole = userApp.getRole().getName().toLowerCase();
820 if (((epApp.getId().equals(app.getId()))
821 && (!userApp.getRole().getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)))
822 || ((epApp.getId().equals(PortalConstants.PORTAL_APP_ID))
823 && (globalRole.toLowerCase().startsWith("global_")))) {
824 CentralUserApp cua = new CentralUserApp();
826 CentralApp cenApp = new CentralApp(1L, epApp.getCreated(), epApp.getModified(),
827 epApp.getCreatedId(), epApp.getModifiedId(), epApp.getRowNum(), epApp.getName(),
828 epApp.getImageUrl(), epApp.getDescription(), epApp.getNotes(), epApp.getUrl(),
829 epApp.getAlternateUrl(), epApp.getAppRestEndpoint(), epApp.getMlAppName(),
830 epApp.getMlAppAdminId(), String.valueOf(epApp.getMotsId()), epApp.getAppPassword(),
831 String.valueOf(epApp.getOpen()), String.valueOf(epApp.getEnabled()),
832 epApp.getThumbnail(), epApp.getUsername(), epApp.getUebKey(), epApp.getUebSecret(),
833 epApp.getUebTopicName());
835 params.put("roleId", userApp.getRole().getId());
836 params.put(APP_ID, userApp.getApp().getId());
837 List<CentralRoleFunction> appRoleFunctionList = dataAccessService
838 .executeNamedQuery("getAppRoleFunctionList", params, null);
839 SortedSet<CentralRoleFunction> roleFunctionSet = new TreeSet<>();
840 for (CentralRoleFunction roleFunc : appRoleFunctionList) {
841 String functionCode = "";
842 if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
843 int count = StringUtils.countMatches(roleFunc.getCode(), FUNCTION_PIPE);
844 String finalFunctionCodeVal;
846 finalFunctionCodeVal = roleFunc.getCode().substring(
847 roleFunc.getCode().indexOf(FUNCTION_PIPE) + 1,
848 roleFunc.getCode().lastIndexOf(FUNCTION_PIPE));
850 finalFunctionCodeVal = roleFunc.getCode()
851 .substring(roleFunc.getCode().lastIndexOf(FUNCTION_PIPE) + 1);
853 functionCode = finalFunctionCodeVal;
855 functionCode = roleFunc.getCode();
857 CentralRoleFunction cenRoleFunc = new CentralRoleFunction(roleFunc.getId(), functionCode,
858 roleFunc.getName(), null, null);
859 roleFunctionSet.add(cenRoleFunc);
861 Long userRoleId = null;
862 if (globalRole.toLowerCase().startsWith("global_")
863 && epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) {
864 userRoleId = userApp.getRole().getId();
866 userRoleId = userApp.getRole().getAppRoleId();
868 CentralRole cenRole = new CentralRole(userRoleId, userApp.getRole().getCreated(),
869 userApp.getRole().getModified(), userApp.getRole().getCreatedId(),
870 userApp.getRole().getModifiedId(), userApp.getRole().getRowNum(),
871 userApp.getRole().getName(), userApp.getRole().getActive(),
872 userApp.getRole().getPriority(), roleFunctionSet, null, null);
873 cua.setRole(cenRole);
875 userAppList.userApps.add(cua);
880 user1 = new CentralUser(null, userInfo.getCreated(), userInfo.getModified(), userInfo.getCreatedId(),
881 userInfo.getModifiedId(), userInfo.getRowNum(), userInfo.getOrgId(), userInfo.getManagerId(),
882 userInfo.getFirstName(), userInfo.getMiddleInitial(), userInfo.getLastName(), userInfo.getPhone(),
883 userInfo.getFax(), userInfo.getCellular(), userInfo.getEmail(), userInfo.getAddressId(),
884 userInfo.getAlertMethodCd(), userInfo.getHrid(), userInfo.getOrgUserId(), userInfo.getOrgCode(),
885 userInfo.getAddress1(), userInfo.getAddress2(), userInfo.getCity(), userInfo.getState(),
886 userInfo.getZipCode(), userInfo.getCountry(), userInfo.getOrgManagerUserId(),
887 userInfo.getLocationClli(), userInfo.getBusinessCountryCode(), userInfo.getBusinessCountryName(),
888 userInfo.getBusinessUnit(), userInfo.getBusinessUnitName(), userInfo.getDepartment(),
889 userInfo.getDepartmentName(), userInfo.getCompanyCode(), userInfo.getCompany(),
890 userInfo.getZipCodeSuffix(), userInfo.getJobTitle(), userInfo.getCommandChain(),
891 userInfo.getSiloStatus(), userInfo.getCostCenter(), userInfo.getFinancialLocCode(),
892 userInfo.getLoginId(), userInfo.getLoginPwd(), userInfo.getLastLoginDate(), userInfo.getActive(),
893 userInfo.getInternal(), userInfo.getSelectedProfileId(), userInfo.getTimeZoneId(),
894 userInfo.isOnline(), userInfo.getChatId(), userAppList.userApps, null);
895 } catch (Exception e) {
896 logger.error(EELFLoggerDelegate.errorLogger, "createEPUser: createEPUser failed", e);
897 throw new Exception(e.getMessage());
903 @SuppressWarnings("unchecked")
905 public CentralRole getRoleInfo(Long roleId, String uebkey) throws Exception {
906 final Map<String, Long> params = new HashMap<>();
907 List<CentralRole> roleList = new ArrayList<>();
908 CentralRole cenRole = new CentralRole();
909 List<EPRole> roleInfo = null;
910 List<EPApp> app = null;
912 app = getApp(uebkey);
914 throw new Exception("Application not found");
916 String filter = null;
917 if (app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
918 filter = WHERE_ROLE_ID_EQUALS + roleId + " and app_id is null ";
920 filter = " where app_role_id = " + roleId + " and app_id = " + app.get(0).getId();
923 roleInfo = dataAccessService.getList(EPRole.class, filter, null, null);
924 roleList = createCentralRoleObject(app, roleInfo, roleList, params);
925 if (roleList.isEmpty()) {
929 } catch (Exception e) {
930 logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo: failed", e);
931 throw new Exception(e.getMessage());
934 return roleList.get(0);
939 * It returns list of app roles along with role functions and which went through deep copy
947 @SuppressWarnings("unchecked")
948 private List<CentralRole> createCentralRoleObject(List<EPApp> app, List<EPRole> roleInfo,
949 List<CentralRole> roleList, Map<String, Long> params) {
950 for (EPRole role : roleInfo) {
951 params.put("roleId", role.getId());
952 params.put(APP_ID, app.get(0).getId());
953 List<CentralRoleFunction> cenRoleFuncList = dataAccessService.executeNamedQuery("getAppRoleFunctionList",
955 SortedSet<CentralRoleFunction> roleFunctionSet = new TreeSet<>();
956 for (CentralRoleFunction roleFunc : cenRoleFuncList) {
957 String functionCode = "";
958 if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
959 int count = StringUtils.countMatches(roleFunc.getCode(), FUNCTION_PIPE);
960 String finalFunctionCodeVal;
962 finalFunctionCodeVal = roleFunc.getCode().substring(
963 roleFunc.getCode().indexOf(FUNCTION_PIPE) + 1,
964 roleFunc.getCode().lastIndexOf(FUNCTION_PIPE));
966 finalFunctionCodeVal = roleFunc.getCode()
967 .substring(roleFunc.getCode().lastIndexOf(FUNCTION_PIPE) + 1);
968 functionCode = finalFunctionCodeVal;
970 functionCode = roleFunc.getCode();
972 CentralRoleFunction cenRoleFunc = new CentralRoleFunction(role.getId(), functionCode,
973 roleFunc.getName(), null, null);
974 roleFunctionSet.add(cenRoleFunc);
976 SortedSet<CentralRole> childRoles = new TreeSet<>();
977 CentralRole cenRole = null;
978 if (role.getAppRoleId() == null) {
979 cenRole = new CentralRole(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
980 role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
981 roleFunctionSet, childRoles, null);
983 cenRole = new CentralRole(role.getAppRoleId(), role.getCreated(), role.getModified(),
984 role.getCreatedId(), role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(),
985 role.getPriority(), roleFunctionSet, childRoles, null);
987 roleList.add(cenRole);
992 @SuppressWarnings("unchecked")
994 public CentralRoleFunction getRoleFunction(String functionCode, String uebkey) throws Exception {
995 CentralRoleFunction roleFunc = null;
996 EPApp app = getApp(uebkey).get(0);
997 List<CentralRoleFunction> getRoleFuncList = null;
998 final Map<String, String> params = new HashMap<>();
1000 params.put("functionCode", functionCode);
1001 params.put(APP_ID, String.valueOf(app.getId()));
1002 getRoleFuncList = dataAccessService.executeNamedQuery("getRoleFunction", params, null);
1003 if (getRoleFuncList.isEmpty()) {
1006 String functionCodeFormat = getRoleFuncList.get(0).getCode();
1007 if(functionCodeFormat.contains(FUNCTION_PIPE)){
1008 String newfunctionCodeFormat = functionCodeFormat.substring(functionCodeFormat.lastIndexOf(FUNCTION_PIPE)+1);
1009 roleFunc = new CentralRoleFunction(getRoleFuncList.get(0).getId(), newfunctionCodeFormat, getRoleFuncList.get(0).getName(), getRoleFuncList.get(0).getAppId(), getRoleFuncList.get(0).getEditUrl());
1011 roleFunc = new CentralRoleFunction(getRoleFuncList.get(0).getId(), functionCodeFormat, getRoleFuncList.get(0).getName(), getRoleFuncList.get(0).getAppId(), getRoleFuncList.get(0).getEditUrl());
1014 } catch (Exception e) {
1015 logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction: failed", e);
1016 throw new Exception("getRoleFunction failed", e);
1022 public boolean saveCentralRoleFunction(CentralRoleFunction domainCentralRoleFunction, EPApp app) throws Exception {
1023 boolean saveOrUpdateFunction = false;
1025 addRoleFunctionInExternalSystem(domainCentralRoleFunction, app);
1026 dataAccessService.saveDomainObject(domainCentralRoleFunction, null);
1027 saveOrUpdateFunction = true;
1028 } catch (Exception e) {
1029 logger.error(EELFLoggerDelegate.errorLogger, "saveCentralRoleFunction: failed", e);
1030 saveOrUpdateFunction = false;
1032 return saveOrUpdateFunction;
1036 * It creates application permission in external auth system
1038 * @param domainCentralRoleFunction
1042 @SuppressWarnings("unchecked")
1043 private void addRoleFunctionInExternalSystem(CentralRoleFunction domainCentralRoleFunction, EPApp app)
1045 ObjectMapper mapper = new ObjectMapper();
1046 ExternalAccessPerms extPerms = new ExternalAccessPerms();
1047 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1048 List<CentralRoleFunction> appRoleFunc = dataAccessService.getList(CentralRoleFunction.class,
1049 WHERE_APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + domainCentralRoleFunction.getCode() + "'", null, null);
1050 String roleFuncName = null;
1051 if (!appRoleFunc.isEmpty()) {
1052 roleFuncName = appRoleFunc.get(0).getCode();
1054 roleFuncName = domainCentralRoleFunction.getCode();
1056 String checkType = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url";
1057 HttpEntity<String> getSinglePermEntity = new HttpEntity<>(headers);
1058 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} ", CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1059 ResponseEntity<String> getResponse = template.exchange(
1060 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perms/"
1061 + app.getNameSpace() + "." + checkType + "/" + roleFuncName + "/*",
1062 HttpMethod.GET, getSinglePermEntity, String.class);
1063 if (getResponse.getStatusCode().value() != 200) {
1064 EPLogUtil.logExternalAuthAccessAlarm(logger, getResponse.getStatusCode());
1065 throw new Exception(getResponse.getBody());
1067 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished GET permission from External Auth system and response: {} ", getResponse.getBody());
1068 String res = getResponse.getBody();
1069 if (res.equals(IS_EMPTY_JSON_STRING)) {
1071 extPerms.setAction("*");
1072 extPerms.setInstance(domainCentralRoleFunction.getCode());
1073 extPerms.setType(app.getNameSpace() + "." + checkType);
1074 extPerms.setDescription(domainCentralRoleFunction.getName());
1075 String updateRole = mapper.writeValueAsString(extPerms);
1076 HttpEntity<String> entity = new HttpEntity<>(updateRole, headers);
1077 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1078 ResponseEntity<String> addPermResponse= template.exchange(
1079 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
1080 HttpMethod.POST, entity, String.class);
1081 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished adding permission in and status code: {} ", addPermResponse.getStatusCode().value());
1082 } catch(HttpClientErrorException e){
1083 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to add function in external central auth system", e);
1084 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1085 }catch (Exception e) {
1086 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionInExternalSystem: Failed to add fucntion in external central auth system",
1091 extPerms.setAction("*");
1092 extPerms.setInstance(domainCentralRoleFunction.getCode());
1093 extPerms.setType(app.getNameSpace() + "." + checkType);
1094 extPerms.setDescription(domainCentralRoleFunction.getName());
1095 String updateRole = mapper.writeValueAsString(extPerms);
1096 HttpEntity<String> entity = new HttpEntity<>(updateRole, headers);
1097 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1098 ResponseEntity<String> updatePermResponse = template.exchange(
1099 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
1100 HttpMethod.PUT, entity, String.class);
1101 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished updating permission in External Auth system and response: {} ", updatePermResponse.getBody());
1102 } catch(HttpClientErrorException e){
1103 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to add function in external central auth system", e);
1104 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1105 } catch (Exception e) {
1106 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionInExternalSystem: Failed to update function in external central auth system",
1114 public boolean deleteCentralRoleFunction(String code, EPApp app) {
1115 boolean deleteFunctionResponse = false;
1117 final Map<String, String> params = new HashMap<>();
1118 params.put("functionCode", code);
1119 params.put(APP_ID, String.valueOf(app.getId()));
1120 CentralRoleFunction domainCentralRoleFunction = (CentralRoleFunction) dataAccessService
1121 .executeNamedQuery("getRoleFunction", params, null).get(0);
1122 deleteRoleFunctionInExternalSystem(domainCentralRoleFunction, app);
1123 // Delete role function dependency records
1124 deleteAppRoleFunctions(code, app);
1125 dataAccessService.deleteDomainObject(domainCentralRoleFunction, null);
1126 deleteFunctionResponse = true;
1127 } catch (Exception e) {
1128 logger.error(EELFLoggerDelegate.errorLogger, "deleteCentralRoleFunction: failed", e);
1130 return deleteFunctionResponse;
1134 * It deletes app function record in portal
1139 private void deleteAppRoleFunctions(String code, EPApp app) {
1140 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
1141 APP_ID_EQUALS + app.getId() + FUNCTION_CD_LIKE_CLAUSE + code + "'", null);
1146 * It deletes permission in the external auth system
1148 * @param domainCentralRoleFunction
1152 private void deleteRoleFunctionInExternalSystem(CentralRoleFunction domainCentralRoleFunction, EPApp app)
1155 ObjectMapper mapper = new ObjectMapper();
1156 ExternalAccessPerms extPerms = new ExternalAccessPerms();
1157 String instanceValue = "";
1158 if(domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)){
1159 instanceValue = domainCentralRoleFunction.getCode().substring(domainCentralRoleFunction.getCode().lastIndexOf(FUNCTION_PIPE)+1);
1161 instanceValue = domainCentralRoleFunction.getCode();
1163 String checkType = instanceValue.contains("menu") ? "menu" : "url";
1164 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1165 extPerms.setAction("*");
1166 extPerms.setInstance(domainCentralRoleFunction.getCode());
1167 extPerms.setType(app.getNameSpace() + "." + checkType);
1168 extPerms.setDescription(domainCentralRoleFunction.getName());
1169 String updateRole = mapper.writeValueAsString(extPerms);
1170 HttpEntity<String> entity = new HttpEntity<>(updateRole, headers);
1171 logger.debug(EELFLoggerDelegate.debugLogger,"deleteRoleFunctionInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1172 ResponseEntity<String> delPermResponse = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1173 + "perm?force=true", HttpMethod.DELETE, entity, String.class);
1174 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleFunctionInExternalSystem: Finished deleting permission in External Auth system and status code: {} ", delPermResponse.getStatusCode().value());
1175 } catch(HttpClientErrorException e){
1176 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to delete functions in External System", e);
1177 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1178 } catch (Exception e) {
1179 if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
1180 logger.debug(EELFLoggerDelegate.debugLogger,
1181 " deleteRoleFunctionInExternalSystem: It seems like function is already deleted in external central auth system but exists in local DB",
1184 logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleFunctionInExternalSystem: Failed to delete functions in External System", e);
1190 public boolean saveRoleForApplication(Role saveRole, String uebkey) throws Exception {
1191 boolean addRoleResponse = false;
1193 EPApp app = getApp(uebkey).get(0);
1194 addRoleInEcompDB(saveRole, app);
1195 addRoleResponse = true;
1196 } catch (Exception e) {
1197 logger.error(EELFLoggerDelegate.errorLogger, "saveRoleForApplication failed", e);
1199 return addRoleResponse;
1202 @SuppressWarnings("unchecked")
1204 public boolean deleteRoleForApplication(String deleteRole, String uebkey) throws Exception {
1205 Session localSession = sessionFactory.openSession();
1206 Transaction transaction = null;
1207 boolean result = false;
1209 transaction = localSession.beginTransaction();
1211 List<EPRole> epRoleList = null;
1212 ResponseEntity<String> deleteResponse = null;
1213 EPApp app = getApp(uebkey).get(0);
1214 if (app.getId() == 1) {
1215 epRoleList = dataAccessService.getList(EPRole.class,
1216 " where app_id is null " + "and role_name = '" + deleteRole + "'", null, null);
1218 epRoleList = dataAccessService.getList(EPRole.class,
1219 WHERE_APP_ID_EQUALS + app.getId() + " and role_name = '" + deleteRole + "'", null, null);
1221 // Delete app role functions before deleting role
1222 deleteRoleFunction(app, epRoleList);
1223 if (app.getId() == 1) {
1224 // Delete fn_user_ role
1225 dataAccessService.deleteDomainObjects(EPUserApp.class,
1226 APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
1228 deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId());
1230 // Delete Role in External System
1231 String deleteRoleKey = "{\"name\":\"" + app.getNameSpace() + "."
1232 + epRoleList.get(0).getName().replaceAll(" ", "_") + "\"}";
1233 deleteResponse = deleteRoleInExternalSystem(deleteRoleKey);
1234 if (deleteResponse.getStatusCode().value() != 200 || deleteResponse.getStatusCode().value() != 404) {
1235 EPLogUtil.logExternalAuthAccessAlarm(logger, deleteResponse.getStatusCode());
1236 logger.error(EELFLoggerDelegate.errorLogger,
1237 "deleteRoleForApplication: Failed to delete role in external auth system! due to {} ",
1238 deleteResponse.getBody());
1240 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: about to commit the transaction");
1241 transaction.commit();
1242 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: committed the transaction");
1243 dataAccessService.deleteDomainObject(epRoleList.get(0), null);
1245 } catch (Exception e) {
1246 logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleForApplication: failed", e);
1249 localSession.close();
1256 * It deletes application user role in external auth system
1263 private void deleteUserRoleInExternalSystem(EPRole role, EPApp app, String LoginId) throws Exception {
1264 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1265 HttpEntity<String> entity = new HttpEntity<>(headers);
1266 logger.debug(EELFLoggerDelegate.debugLogger,"deleteUserRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1267 ResponseEntity<String> getResponse = template
1269 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
1272 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
1273 + "/" + app.getNameSpace() + "." + role.getName().replaceAll(" ", "_"),
1274 HttpMethod.GET, entity, String.class);
1275 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: Finished GET user roles from External Auth system and response: {} ", getResponse.getBody());
1276 if (getResponse.getStatusCode().value() != 200) {
1277 throw new Exception(getResponse.getBody());
1279 String res = getResponse.getBody();
1280 if (!res.equals(IS_EMPTY_JSON_STRING)) {
1281 HttpEntity<String> userRoleentity = new HttpEntity<>(headers);
1282 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1283 ResponseEntity<String> deleteResponse = template
1285 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1286 + "userRole/" + LoginId
1288 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
1289 + "/" + app.getNameSpace() + "." + role.getName().replaceAll(" ", "_"),
1290 HttpMethod.DELETE, userRoleentity, String.class);
1291 if (deleteResponse.getStatusCode().value() != 200) {
1292 throw new Exception("Failed to delete user role");
1294 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: Finished deleting user role in External Auth system and status code: {} ", deleteResponse.getStatusCode().value());
1298 @SuppressWarnings("unchecked")
1300 public List<CentralRole> getActiveRoles(String uebkey) throws Exception {
1301 List<CentralRole> roleList = new ArrayList<>();
1303 List<EPApp> app = getApp(uebkey);
1304 final Map<String, Long> params = new HashMap<>();
1307 if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
1308 appId = app.get(0).getId();
1310 List<EPRole> epRole = dataAccessService.getList(EPRole.class,
1311 WHERE_APP_ID_EQUALS + appId + " and active_yn = 'Y'", null, null);
1312 roleList = createCentralRoleObject(app, epRole, roleList, params);
1313 } catch (Exception e) {
1314 logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles: failed", e);
1315 throw new Exception(e.getMessage());
1321 @SuppressWarnings("unchecked")
1323 public boolean deleteDependencyRoleRecord(Long roleId, String uebkey, String LoginId) throws Exception {
1324 boolean result = false;
1325 Session localSession = sessionFactory.openSession();
1326 Transaction transaction = null;
1329 transaction = localSession.beginTransaction();
1330 List<EPRole> epRoleList = null;
1331 app = getApp(uebkey).get(0);
1332 epRoleList = dataAccessService.getList(EPRole.class,
1333 WHERE_APP_ID_EQUALS + app.getId() + " and app_role_id = " + roleId, null, null);
1334 if (epRoleList.isEmpty()) {
1335 epRoleList = dataAccessService.getList(EPRole.class,
1336 WHERE_APP_ID_EQUALS + app.getId() + " and role_id = " + roleId, null, null);
1338 // Delete User Role in External System before deleting role
1339 deleteUserRoleInExternalSystem(epRoleList.get(0), app, LoginId);
1340 // Delete user app roles
1341 dataAccessService.deleteDomainObjects(EPUserApp.class,
1342 APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
1344 deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId());
1345 logger.debug(EELFLoggerDelegate.debugLogger, "deleteDependencyRoleRecord: about to commit the transaction");
1346 transaction.commit();
1347 logger.debug(EELFLoggerDelegate.debugLogger, "deleteDependencyRoleRecord: committed the transaction");
1349 } catch(HttpClientErrorException e){
1350 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to deleteRoleDependeciesRecord", e);
1351 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1352 } catch (Exception e) {
1353 EcompPortalUtils.rollbackTransaction(transaction, "deleteDependencyRoleRecord: rollback, exception = " + e);
1354 logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
1357 localSession.close();
1363 @SuppressWarnings("unchecked")
1365 public void syncRoleFunctionFromExternalAccessSystem(EPApp app) {
1367 ResponseEntity<String> response = null;
1368 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1369 HttpEntity<String> entity = new HttpEntity<>(headers);
1370 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1372 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1373 + "perms/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
1375 String res = response.getBody();
1376 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Finished GET permissions from External Auth system and response: {} ", response.getBody());
1377 JSONObject jsonObj = new JSONObject(res);
1378 JSONArray extPerms = jsonObj.getJSONArray("perm");
1379 for (int i = 0; i < extPerms.length(); i++) {
1380 if (extPerms.getJSONObject(i).getString("type").equals(app.getNameSpace() + ".access")) {
1385 ExternalAccessPermsDetail permDetails = null;
1386 List<ExternalAccessPermsDetail> permsDetailList = new ArrayList<>();
1387 for (int i = 0; i < extPerms.length(); i++) {
1388 String description = null;
1389 if(extPerms.getJSONObject(i).has("description")){
1390 description = extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
1392 description = extPerms.getJSONObject(i).getString("instance");
1394 if (extPerms.getJSONObject(i).has("roles")) {
1395 ObjectMapper rolesListMapper = new ObjectMapper();
1396 JSONArray resRoles = extPerms.getJSONObject(i).getJSONArray("roles");
1397 List<String> list = rolesListMapper.readValue(resRoles.toString(),
1398 TypeFactory.defaultInstance().constructCollectionType(List.class, String.class));
1399 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
1400 extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
1401 + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
1402 + extPerms.getJSONObject(i).getString("action"),
1403 extPerms.getJSONObject(i).getString("action"), list, description);
1404 permsDetailList.add(permDetails);
1406 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
1407 extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
1408 + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
1409 + extPerms.getJSONObject(i).getString("action"),
1410 extPerms.getJSONObject(i).getString("action"), description);
1411 permsDetailList.add(permDetails);
1415 final Map<String, Long> params = new HashMap<>();
1416 final Map<String, CentralRoleFunction> roleFuncMap = new HashMap<>();
1417 params.put(APP_ID, app.getId());
1418 List<CentralRoleFunction> appFunctions = dataAccessService.executeNamedQuery("getAllRoleFunctions", params,
1420 if (!appFunctions.isEmpty()) {
1421 for (CentralRoleFunction roleFunc : appFunctions) {
1422 roleFuncMap.put(roleFunc.getCode(), roleFunc);
1425 // delete all application role functions
1426 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, APP_ID_EQUALS + app.getId(), null);
1427 // Add if new functions and app role functions were added in external auth system
1428 for (ExternalAccessPermsDetail permsDetail : permsDetailList) {
1429 String code = permsDetail.getInstance();
1430 CentralRoleFunction getFunctionCodeKey = roleFuncMap.get(permsDetail.getInstance());
1431 if (null == getFunctionCodeKey) {
1432 String finalFunctionCodeVal = "";
1433 if (permsDetail.getInstance().contains(FUNCTION_PIPE)) {
1434 int count = StringUtils.countMatches(permsDetail.getInstance(), FUNCTION_PIPE);
1436 finalFunctionCodeVal = permsDetail.getInstance().substring(
1437 permsDetail.getInstance().indexOf(FUNCTION_PIPE) + 1,
1438 permsDetail.getInstance().lastIndexOf(FUNCTION_PIPE));
1440 finalFunctionCodeVal = permsDetail.getInstance()
1441 .substring(permsDetail.getInstance().lastIndexOf(FUNCTION_PIPE) + 1);
1443 finalFunctionCodeVal = permsDetail.getInstance();
1445 CentralRoleFunction checkIfCodeStillExits = roleFuncMap.get(finalFunctionCodeVal);
1446 if (null == checkIfCodeStillExits) {
1447 logger.debug(EELFLoggerDelegate.debugLogger,
1448 "syncRoleFunctionFromExternalAccessSystem: Adding function: {} ", code);
1449 addFunctionInEcompDB(app, permsDetail, code);
1450 logger.debug(EELFLoggerDelegate.debugLogger,
1451 "syncRoleFunctionFromExternalAccessSystem: Finished adding function: {} ", code);
1455 List<EPRole> epRolesList = null;
1456 List<String> roles = permsDetail.getRoles();
1457 if (roles != null) {
1458 for (String roleList : roles) {
1459 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1460 epRolesList = dataAccessService.getList(EPRole.class,
1461 " where app_id is null " + " and role_name = '"
1462 + roleList.substring(app.getNameSpace().length() + 1).replaceAll("_", " ")
1466 epRolesList = dataAccessService.getList(EPRole.class,
1467 WHERE_APP_ID_EQUALS + app.getId() + " and role_name = '"
1468 + roleList.substring(app.getNameSpace().length() + 1).replaceAll("_", " ")
1472 if (epRolesList.isEmpty()) {
1473 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1474 epRolesList = dataAccessService.getList(EPRole.class,
1475 " where app_id is null " + " and role_name = '"
1476 + roleList.substring(app.getNameSpace().length() + 1) + "'",
1479 epRolesList = dataAccessService.getList(EPRole.class,
1480 WHERE_APP_ID_EQUALS + app.getId() + " and role_name = '"
1481 + roleList.substring(app.getNameSpace().length() + 1) + "'",
1484 // Adding new role thats does not exits in Local but exists in external access system
1485 if (epRolesList.isEmpty()) {
1486 Role role = addRoleInDBIfDoesNotExists(app, roleList.substring(app.getNameSpace().length() + 1));
1487 addIfRoleDescriptionNotExitsInExtSystem(role, app);
1488 epRolesList = dataAccessService.getList(EPRole.class,
1489 WHERE_APP_ID_EQUALS + app.getId() + " and role_name = '"
1490 + role.getName() + "'",
1494 // save all application role functions
1495 if (!epRolesList.isEmpty()) {
1497 List<CentralRoleFunction> roleFunctionList = null;
1498 String functionCode = "";
1499 if (permsDetail.getInstance().contains(FUNCTION_PIPE)) {
1500 int count = StringUtils.countMatches(permsDetail.getInstance(), FUNCTION_PIPE);
1501 String finalFunctionCodeVal;
1503 finalFunctionCodeVal = permsDetail.getInstance().substring(
1504 permsDetail.getInstance().indexOf(FUNCTION_PIPE) + 1,
1505 permsDetail.getInstance().lastIndexOf(FUNCTION_PIPE));
1507 finalFunctionCodeVal = permsDetail.getInstance()
1508 .substring(permsDetail.getInstance().lastIndexOf(FUNCTION_PIPE) + 1);
1510 functionCode = finalFunctionCodeVal;
1512 roleFunctionList = dataAccessService.getList(CentralRoleFunction.class,
1513 " where app_id = " + app.getId() + AND_FUNCTION_CD_EQUALS + functionCode + "'",
1515 if (roleFunctionList.isEmpty()) {
1516 roleFunctionList = dataAccessService.getList(CentralRoleFunction.class,
1517 " where app_id = " + app.getId() + AND_FUNCTION_CD_EQUALS + code + "'",
1520 if (!roleFunctionList.isEmpty()) {
1521 EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
1522 addAppRoleFunc.setAppId(app.getId());
1523 addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
1524 addAppRoleFunc.setRoleId(epRolesList.get(0).getId());
1525 dataAccessService.saveDomainObject(addAppRoleFunc, null);
1527 } catch (Exception e) {
1528 logger.error(EELFLoggerDelegate.errorLogger,
1529 "syncRoleFunctionFromExternalAccessSystem: Failed to save app role function ",
1536 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Finished syncRoleFunctionFromExternalAccessSystem");
1537 } catch (Exception e) {
1538 logger.error(EELFLoggerDelegate.errorLogger, "syncRoleFunctionFromExternalAccessSystem: Failed syncRoleFunctionFromExternalAccessSystem", e);
1545 * Add function into local DB
1548 * @param permsDetail
1551 private void addFunctionInEcompDB(EPApp app, ExternalAccessPermsDetail permsDetail, String code) {
1553 CentralRoleFunction addFunction = new CentralRoleFunction();
1554 addFunction.setAppId(app.getId());
1555 addFunction.setCode(code);
1556 addFunction.setName(permsDetail.getDescription());
1557 dataAccessService.saveDomainObject(addFunction, null);
1558 } catch(Exception e){
1559 logger.error(EELFLoggerDelegate.errorLogger, "addFunctionInEcompDB: Failed to add function", e);
1565 * It updates description of a role in external auth system
1571 private void addIfRoleDescriptionNotExitsInExtSystem(Role role, EPApp app) throws Exception {
1572 String addRoleNew = updateExistingRoleInExternalSystem(role, app);
1573 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1575 HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
1577 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
1578 HttpMethod.PUT, entity, String.class);
1579 } catch (HttpClientErrorException e) {
1580 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addIfRoleDescriptionNotExitsInExtSystem",
1582 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1583 } catch (Exception e) {
1584 logger.error(EELFLoggerDelegate.errorLogger, "addIfRoleDescriptionNotExitsInExtSystem: Failed",
1591 * While sync functions form external auth system if new role found we should add in local and return Role.class object
1597 @SuppressWarnings("unchecked")
1598 private Role addRoleInDBIfDoesNotExists(EPApp app, String role) {
1599 Role setNewRole = new Role();
1600 EPRole epRoleNew = new EPRole();
1602 epRoleNew.setActive(true);
1603 epRoleNew.setName(role);
1604 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1605 epRoleNew.setAppId(null);
1607 epRoleNew.setAppId(app.getId());
1609 dataAccessService.saveDomainObject(epRoleNew, null);
1610 List<EPRole> getRoleCreated = null;
1611 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1612 List<EPRole> roleCreated = dataAccessService.getList(EPRole.class,
1613 WHERE_ROLE_NAME_EQUALS + role + "' and app_id = " + app.getId(), null, null);
1614 EPRole epUpdateRole = roleCreated.get(0);
1615 epUpdateRole.setAppRoleId(epUpdateRole.getId());
1616 dataAccessService.saveDomainObject(epUpdateRole, null);
1617 getRoleCreated = dataAccessService.getList(EPRole.class,
1618 WHERE_ROLE_NAME_EQUALS + role + "' and app_id = " + app.getId(), null, null);
1620 getRoleCreated = dataAccessService.getList(EPRole.class,
1621 WHERE_ROLE_NAME_EQUALS + role + "' and app_id is null", null, null);
1623 EPRole roleObject = getRoleCreated.get(0);
1624 setNewRole.setId(roleObject.getId());
1625 setNewRole.setName(roleObject.getName());
1626 setNewRole.setActive(roleObject.getActive());
1627 setNewRole.setPriority(roleObject.getPriority());
1628 } catch (Exception e) {
1629 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInDBIfDoesNotExists: Failed", e);
1635 @SuppressWarnings("unchecked")
1636 public Integer bulkUploadFunctions(String uebkey) throws Exception {
1637 EPApp app = getApp(uebkey).get(0);
1638 List<RoleFunction> roleFuncList = null;
1639 roleFuncList = dataAccessService.getList(RoleFunction.class, null);
1640 CentralRoleFunction cenRoleFunc = null;
1641 Integer functionsAdded = 0;
1643 for (RoleFunction roleFunc : roleFuncList) {
1644 cenRoleFunc = new CentralRoleFunction(roleFunc.getCode(), roleFunc.getName());
1645 addRoleFunctionInExternalSystem(cenRoleFunc, app);
1648 } catch(HttpClientErrorException e){
1649 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadFunctions failed", e);
1650 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1651 } catch (Exception e) {
1652 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions: failed", e.getMessage(), e);
1654 return functionsAdded;
1658 public Integer bulkUploadRoles(String uebkey) throws Exception {
1659 List<EPApp> app = getApp(uebkey);
1660 List<EPRole> roles = getAppRoles(app.get(0).getId());
1661 List<CentralRole> cenRoleList = new ArrayList<>();
1662 final Map<String, Long> params = new HashMap<>();
1663 Integer rolesListAdded = 0;
1665 cenRoleList = createCentralRoleObject(app, roles, cenRoleList, params);
1666 ObjectMapper mapper = new ObjectMapper();
1667 mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
1668 String roleList = mapper.writeValueAsString(cenRoleList);
1669 List<Role> roleObjectList = mapper.readValue(roleList,
1670 TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
1671 for (Role role : roleObjectList) {
1672 addRoleInExternalSystem(role, app.get(0));
1675 } catch (Exception e) {
1676 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles: failed", e);
1677 throw new Exception(e.getMessage());
1679 return rolesListAdded;
1683 * It creating new role in external auth system while doing bulk upload
1689 private void addRoleInExternalSystem(Role role, EPApp app) throws Exception {
1690 String addRoleNew = updateExistingRoleInExternalSystem(role, app);
1691 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1693 HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
1695 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
1696 HttpMethod.POST, entity, String.class);
1697 } catch(HttpClientErrorException e){
1698 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addRoleInExternalSystem", e);
1699 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1700 } catch (Exception e) {
1701 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
1702 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInExternalSystem: Role already exits but does not break functionality", e);
1704 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInExternalSystem: Failed to addRoleInExternalSystem", e.getMessage());
1710 @SuppressWarnings("unchecked")
1711 public Integer bulkUploadRolesFunctions(String uebkey) throws Exception {
1712 EPApp app = getApp(uebkey).get(0);
1713 List<EPRole> roles = getAppRoles(app.getId());
1714 final Map<String, Long> params = new HashMap<>();
1715 Integer roleFunctions = 0;
1717 for (EPRole role : roles) {
1718 params.put("roleId", role.getId());
1719 List<BulkUploadRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("uploadAllRoleFunctions",
1721 if (!appRoleFunc.isEmpty()) {
1722 for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
1723 addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
1728 } catch(HttpClientErrorException e){
1729 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
1730 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1731 } catch (Exception e) {
1732 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
1734 return roleFunctions;
1738 * Its adding a role function while doing bulk upload
1740 * @param addRoleFunc
1744 private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, EPRole role, EPApp app) {
1745 String checkType = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
1746 ExternalAccessRolePerms extRolePerms = null;
1747 ExternalAccessPerms extPerms = null;
1748 ObjectMapper mapper = new ObjectMapper();
1750 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1752 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, addRoleFunc.getFunctionCd(), "*",
1753 addRoleFunc.getFunctionName());
1754 extRolePerms = new ExternalAccessRolePerms(extPerms,
1755 app.getNameSpace() + "." + role.getName().replaceAll(" ", "_"));
1756 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
1757 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
1759 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
1760 HttpMethod.POST, entity, String.class);
1761 } catch (Exception e) {
1762 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
1763 logger.error(EELFLoggerDelegate.errorLogger,
1764 "addRoleFunctionsInExternalSystem: RoleFunction already exits but does not break functionality", e);
1766 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionsInExternalSystem: Failed to addRoleFunctionsInExternalSystem",
1773 public void bulkUploadPartnerFunctions(String uebkey, List<RoleFunction> roleFunctionsList) throws Exception {
1774 EPApp app = getApp(uebkey).get(0);
1775 CentralRoleFunction cenRoleFunc = null;
1776 for (RoleFunction roleFunction : roleFunctionsList) {
1777 cenRoleFunc = new CentralRoleFunction(roleFunction.getCode(), roleFunction.getName());
1778 addRoleFunctionInExternalSystem(cenRoleFunc, app);
1783 public void bulkUploadPartnerRoles(String uebkey, List<Role> roleList) throws Exception {
1784 EPApp app = getApp(uebkey).get(0);
1785 for (Role role : roleList) {
1786 addRoleInExternalSystem(role, app);
1790 @SuppressWarnings("unchecked")
1792 public void bulkUploadPartnerRoleFunctions(String uebkey, List<Role> roleList) throws Exception {
1793 EPApp app = getApp(uebkey).get(0);
1794 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1795 for (Role role : roleList) {
1797 Set<RoleFunction> roleFunctionList = role.getRoleFunctions();
1798 List<RoleFunction> roleFunctionListNew = new ArrayList<>();
1799 ObjectMapper roleFunctionsMapper = new ObjectMapper();
1800 Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
1801 while (itetaror.hasNext()) {
1802 Object nextValue = itetaror.next();
1803 RoleFunction roleFunction = roleFunctionsMapper.convertValue(nextValue, RoleFunction.class);
1804 roleFunctionListNew.add(roleFunction);
1806 List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct()
1807 .collect(Collectors.toList());
1808 for (RoleFunction roleFunction : listWithoutDuplicates) {
1809 String checkType = roleFunction.getCode().contains("menu") ? "menu" : "url";
1810 ExternalAccessRolePerms extRolePerms = null;
1811 ExternalAccessPerms extPerms = null;
1812 ObjectMapper mapper = new ObjectMapper();
1813 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, roleFunction.getCode(),
1815 extRolePerms = new ExternalAccessRolePerms(extPerms,
1816 app.getNameSpace() + "." + role.getName().replaceAll(" ", "_"));
1817 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
1818 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
1819 template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1820 + "role/perm", HttpMethod.PUT, entity, String.class);
1822 } catch (Exception e) {
1823 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
1824 logger.error(EELFLoggerDelegate.errorLogger,
1825 "bulkUploadPartnerRoleFunctions: RoleFunction already exits but does not break functionality");
1827 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerRoleFunctions: Failed to addRoleFunctionsInExternalSystem",
1836 @SuppressWarnings("unchecked")
1838 public void syncApplicationRolesWithEcompDB(EPApp app) {
1840 ResponseEntity<String> response = null;
1841 List<EPRole> finalRoleList = new ArrayList<>();
1842 ExternalRoleDescription ApplicationRole = new ExternalRoleDescription();
1843 ExternalAccessPerms externalAccessPerms = null;
1844 List<String> functionCodelist = new ArrayList<>();
1845 List<ExternalRoleDetails> externalRoleDetailsList = new ArrayList<>();
1846 ObjectMapper mapper = new ObjectMapper();
1847 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1848 HttpEntity<String> entity = new HttpEntity<>(headers);
1849 logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: {} ",
1850 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1852 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1853 + "roles/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
1854 String res = response.getBody();
1855 logger.debug(EELFLoggerDelegate.debugLogger,
1856 "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
1858 JSONObject jsonObj = new JSONObject(res);
1859 JSONArray extRole = jsonObj.getJSONArray("role");
1860 for (int i = 0; i < extRole.length(); i++) {
1861 if (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ADMIN)
1862 || extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + OWNER)
1863 || (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ACCOUNT_ADMINISTRATOR)
1864 && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
1869 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, APP_ID_EQUALS + app.getId(), null);
1870 for (int i = 0; i < extRole.length(); i++) {
1871 ExternalRoleDetails externalRoleDetail = new ExternalRoleDetails();
1872 EPAppRoleFunction ePAppRoleFunction = new EPAppRoleFunction();
1873 JSONObject Role = (JSONObject) extRole.get(i);
1874 if (!extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
1875 ApplicationRole.setActive("true");
1876 ApplicationRole.setAppId(IS_NULL_STRING);
1877 ApplicationRole.setPriority(IS_NULL_STRING);
1878 ApplicationRole.setAppRoleId(IS_NULL_STRING);
1879 String roleName = extRole.getJSONObject(i).getString(ROLE_NAME);
1880 ApplicationRole.setName(roleName.substring(app.getNameSpace().length() + 1));
1882 String desc = extRole.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
1883 ApplicationRole = mapper.readValue(desc, ExternalRoleDescription.class);
1886 SortedSet<ExternalAccessPerms> externalAccessPermsOfRole = new TreeSet<>();
1887 if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_PERMS)) {
1888 JSONArray extPerm = (JSONArray) Role.get(EXTERNAL_AUTH_PERMS);
1889 for (int j = 0; j < extPerm.length(); j++) {
1890 JSONObject perms = extPerm.getJSONObject(j);
1891 externalAccessPerms = new ExternalAccessPerms(perms.getString("type"),
1892 perms.getString("instance"), perms.getString("action"));
1893 ePAppRoleFunction.setCode(externalAccessPerms.getInstance());
1894 functionCodelist.add(ePAppRoleFunction.getCode());
1895 externalAccessPermsOfRole.add(externalAccessPerms);
1899 if (ApplicationRole.getActive().equals(IS_NULL_STRING)) {
1900 externalRoleDetail.setActive(false);
1902 externalRoleDetail.setActive(Boolean.parseBoolean(ApplicationRole.getActive()));
1904 externalRoleDetail.setName(ApplicationRole.getName());
1906 if (ApplicationRole.getAppId().equals(IS_NULL_STRING) && app.getId() == 1) {
1907 externalRoleDetail.setAppId(null);
1908 } else if (ApplicationRole.getAppId().equals(IS_NULL_STRING)) {
1909 externalRoleDetail.setAppId(app.getId());
1911 externalRoleDetail.setAppId(Long.parseLong(ApplicationRole.getAppId()));
1914 if (ApplicationRole.getPriority().equals(IS_NULL_STRING)) {
1915 externalRoleDetail.setPriority(null);
1917 externalRoleDetail.setPriority(Integer.parseInt(ApplicationRole.getPriority()));
1920 if (ApplicationRole.getAppRoleId().equals(IS_NULL_STRING) && app.getId() == 1) {
1921 externalRoleDetail.setAppRoleId(null);
1924 if (!externalAccessPermsOfRole.isEmpty()) {
1925 // Adding functions to roles
1926 for (ExternalAccessPerms externalpermission : externalAccessPermsOfRole) {
1928 logger.debug(EELFLoggerDelegate.debugLogger,
1929 "SyncApplicationRolesWithEcompDB: Adding function to the role: {}",
1930 externalpermission.getInstance());
1931 List<CentralRoleFunction> roleFunction = null;
1932 roleFunction = dataAccessService.getList(
1933 CentralRoleFunction.class, " where function_cd = '"
1934 + externalpermission.getInstance() + "' and " + APP_ID_EQUALS + app.getId(),
1936 if (roleFunction.isEmpty()) {
1937 String funcCode = externalpermission.getType()
1938 .substring(app.getNameSpace().length() + 1) + FUNCTION_PIPE
1939 + externalAccessPerms.getInstance();
1940 roleFunction = dataAccessService.getList(CentralRoleFunction.class,
1941 " where function_cd = '" + funcCode + "' and " + APP_ID_EQUALS + app.getId(), null,
1944 if(!roleFunction.isEmpty()){
1945 EPAppRoleFunction apRoleFunction = new EPAppRoleFunction();
1946 apRoleFunction.setAppId(app.getId());
1947 apRoleFunction.setRoleId(Long.parseLong(ApplicationRole.getId()));
1948 apRoleFunction.setCode(roleFunction.get(0).getCode());
1949 dataAccessService.saveDomainObject(apRoleFunction, null);
1951 } catch (Exception e) {
1952 logger.error(EELFLoggerDelegate.errorLogger,
1953 "SyncApplicationRolesWithEcompDB: Failed to add role function", e);
1957 externalRoleDetailsList.add(externalRoleDetail);
1959 for (ExternalRoleDetails externalRole : externalRoleDetailsList) {
1960 EPRole ecompRole = convertExternalRoleDetailstoEpRole(externalRole);
1961 finalRoleList.add(ecompRole);
1964 List<EPRole> applicationRolesList = new ArrayList<>();
1965 applicationRolesList = getAppRoles(app.getId());
1966 List<String> applicationRoleIdList = new ArrayList<>();
1967 for (EPRole applicationRole : applicationRolesList) {
1968 applicationRoleIdList.add(applicationRole.getName());
1971 List<EPRole> roleListToBeAddInEcompDB = new ArrayList<>();
1972 for (EPRole aafRole : finalRoleList) {
1973 if (!applicationRoleIdList.contains(aafRole.getName())) {
1974 roleListToBeAddInEcompDB.add(aafRole);
1978 // Check if roles exits in external Access system and make it inactive
1979 final Map<String, EPRole> checkRolesInactive = new HashMap<>();
1980 for (EPRole extrole : finalRoleList) {
1981 checkRolesInactive.put(extrole.getName(), extrole);
1983 for (EPRole role : applicationRolesList) {
1985 final Map<String, String> extRoleParams = new HashMap<>();
1986 List<EPRole> roleList = null;
1987 extRoleParams.put("appRoleName", role.getName());
1988 if (!checkRolesInactive.containsKey(role.getName())) {
1989 if (app.getId() == 1) {
1990 roleList = dataAccessService.executeNamedQuery("getPortalAppRoles", extRoleParams, null);
1992 extRoleParams.put(APP_ID, app.getId().toString());
1993 roleList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", extRoleParams, null);
1995 EPRole updateRoleInactive = roleList.get(0);
1996 updateRoleInactive.setActive(false);
1997 dataAccessService.saveDomainObject(updateRoleInactive, null);
1999 } catch (Exception e) {
2000 logger.error(EELFLoggerDelegate.errorLogger,
2001 "syncApplicationRolesWithEcompDB: Failed to de-activate role ", e);
2005 // It checks properties in the external auth system app role description and updates role in local
2006 for (EPRole roleItem : finalRoleList) {
2007 final Map<String, String> roleParams = new HashMap<>();
2008 List<EPRole> currentList = null;
2009 roleParams.put("appRoleName", roleItem.getName());
2010 if (app.getId() == 1) {
2011 currentList = dataAccessService.executeNamedQuery("getPortalAppRoles", roleParams, null);
2013 roleParams.put(APP_ID, app.getId().toString());
2014 currentList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", roleParams, null);
2017 if (!currentList.isEmpty()) {
2019 Boolean aafRoleActive;
2020 Boolean localRoleActive;
2022 aafRoleActive = Boolean.valueOf(roleItem.getActive());
2023 localRoleActive = Boolean.valueOf(currentList.get(0).getActive());
2024 result = aafRoleActive.equals(localRoleActive);
2025 EPRole updateRole = currentList.get(0);
2028 updateRole.setActive(roleItem.getActive());
2029 dataAccessService.saveDomainObject(updateRole, null);
2031 if (roleItem.getPriority() != null
2032 && !currentList.get(0).getPriority().equals(roleItem.getPriority())) {
2033 updateRole.setPriority(roleItem.getPriority());
2034 dataAccessService.saveDomainObject(updateRole, null);
2036 } catch (Exception e) {
2037 logger.error(EELFLoggerDelegate.errorLogger,
2038 "syncApplicationRolesWithEcompDB: Failed to update role ", e);
2043 EPRole roleToBeAddedInEcompDB = new EPRole();
2044 for (int i = 0; i < roleListToBeAddInEcompDB.size(); i++) {
2046 roleToBeAddedInEcompDB = roleListToBeAddInEcompDB.get(i);
2047 if (app.getId() == 1) {
2048 roleToBeAddedInEcompDB.setAppRoleId(null);
2050 dataAccessService.saveDomainObject(roleToBeAddedInEcompDB, null);
2051 List<EPRole> getRoleCreatedInSync = null;
2052 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2053 getRoleCreatedInSync = dataAccessService.getList(EPRole.class,
2054 WHERE_ROLE_NAME_EQUALS + roleToBeAddedInEcompDB.getName() + "' and app_id = "+app.getId(), null, null);
2055 EPRole epUpdateRole = getRoleCreatedInSync.get(0);
2056 epUpdateRole.setAppRoleId(epUpdateRole.getId());
2057 dataAccessService.saveDomainObject(epUpdateRole, null);
2059 List<EPRole> roleList = new ArrayList<>();
2060 final Map<String, String> params = new HashMap<>();
2062 params.put("appRoleName", roleToBeAddedInEcompDB.getName());
2063 if (app.getId() == 1) {
2064 roleList = dataAccessService.executeNamedQuery("getPortalAppRoles", params, null);
2066 params.put(APP_ID, app.getId().toString());
2067 roleList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", params, null);
2069 EPRole role = roleList.get(0);
2070 Role aaFrole = new Role();
2071 aaFrole.setId(role.getId());
2072 aaFrole.setActive(role.getActive());
2073 aaFrole.setPriority(role.getPriority());
2074 aaFrole.setName(role.getName());
2075 updateRoleInExternalSystem(aaFrole, app);
2076 } catch (Exception e) {
2077 logger.error(EELFLoggerDelegate.errorLogger,
2078 "SyncApplicationRolesWithEcompDB: Failed to add or update role in external auth system", e);
2081 logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: Finished");
2082 } catch (HttpClientErrorException e) {
2083 logger.error(EELFLoggerDelegate.errorLogger, "Failed to SyncApplicationRolesWithEcompDB", e);
2084 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2085 } catch (Exception e) {
2086 logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed ", e);
2092 * It converts from ExternalRoleDetails.class object to EPRole.class object
2094 * @param externalRoleDetails
2095 * @return EPRole object
2097 private EPRole convertExternalRoleDetailstoEpRole(ExternalRoleDetails externalRoleDetails) {
2098 EPRole role = new EPRole();
2099 role.setActive(externalRoleDetails.isActive());
2100 role.setAppId(externalRoleDetails.getAppId());
2101 role.setAppRoleId(externalRoleDetails.getAppRoleId());
2102 role.setName(externalRoleDetails.getName());
2103 role.setPriority(externalRoleDetails.getPriority());
2107 @SuppressWarnings("unchecked")
2109 public Integer bulkUploadUserRoles(String uebkey) throws Exception {
2110 EPApp app = getApp(uebkey).get(0);
2111 final Map<String, String> params = new HashMap<>();
2112 params.put("uebKey", app.getUebKey());
2113 List<BulkUploadUserRoles> userRolesList = null;
2114 Integer userRolesAdded = 0;
2115 if (app.getCentralAuth()) {
2116 userRolesList = dataAccessService.executeNamedQuery("getBulkUserRoles", params, null);
2117 for (BulkUploadUserRoles userRolesUpload : userRolesList) {
2118 addUserRoleInExternalSystem(userRolesUpload);
2122 return userRolesAdded;
2126 * Its adding a user role in external auth system while doing bulk upload
2128 * @param userRolesUpload
2130 private void addUserRoleInExternalSystem(BulkUploadUserRoles userRolesUpload) {
2133 ObjectMapper mapper = new ObjectMapper();
2134 if (EPCommonSystemProperties
2135 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
2136 name = userRolesUpload.getOrgUserId()
2137 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
2139 ExternalAccessUser extUser = new ExternalAccessUser(name,
2140 userRolesUpload.getAppNameSpace() + "." + userRolesUpload.getRoleName().replaceAll(" ", "_"));
2141 String userRole = mapper.writeValueAsString(extUser);
2142 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2143 HttpEntity<String> entity = new HttpEntity<>(userRole, headers);
2145 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
2146 HttpMethod.POST, entity, String.class);
2147 } catch(HttpClientErrorException e){
2148 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addUserRoleInExternalSystem", e);
2149 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2150 } catch (Exception e) {
2151 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2152 logger.error(EELFLoggerDelegate.errorLogger, "addUserRoleInExternalSystem: UserRole already exits but does not break functionality");
2154 logger.error(EELFLoggerDelegate.errorLogger, "addUserRoleInExternalSystem: Failed to addUserRoleInExternalSystem", e.getMessage());
2160 public void deleteRoleDependencyRecords(Session localSession, Long roleId, Long appId) throws Exception {
2165 //It should delete only when it portal's roleId
2166 if(appId.equals(PortalConstants.PORTAL_APP_ID)){
2167 // Delete from fn_role_function
2168 sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
2169 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2170 query = localSession.createSQLQuery(sql);
2171 query.executeUpdate();
2173 // Delete from fn_role_composite
2174 sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId;
2175 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2176 query = localSession.createSQLQuery(sql);
2177 query.executeUpdate();
2180 // Delete from ep_app_role_function
2181 sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId;
2182 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2183 query = localSession.createSQLQuery(sql);
2184 query.executeUpdate();
2186 // Delete from ep_role_notification
2187 sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
2188 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2189 query = localSession.createSQLQuery(sql);
2190 query.executeUpdate();
2192 // Delete from fn_user_pseudo_role
2193 sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
2194 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2195 query = localSession.createSQLQuery(sql);
2196 query.executeUpdate();
2198 // Delete form EP_WIDGET_CATALOG_ROLE
2199 sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId;
2200 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2201 query = localSession.createSQLQuery(sql);
2202 query.executeUpdate();
2204 // Delete form EP_WIDGET_CATALOG_ROLE
2205 sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId;
2206 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2207 query = localSession.createSQLQuery(sql);
2208 query.executeUpdate();
2210 // Delete form fn_menu_functional_roles
2211 sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
2212 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2213 query = localSession.createSQLQuery(sql);
2214 query.executeUpdate();
2216 } catch (Exception e) {
2217 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e);
2218 throw new Exception("delete Failed" + e.getMessage());
2223 @SuppressWarnings("unchecked")
2225 public List<String> getMenuFunctionsList(String uebkey) throws Exception {
2226 List<String> appMenuFunctionsList = null;
2228 EPApp app = getApp(uebkey).get(0);
2229 final Map<String, Long> appParams = new HashMap<>();
2230 appParams.put(APP_ID, app.getId());
2231 appMenuFunctionsList = dataAccessService.executeNamedQuery("getMenuFunctions", appParams, null);
2232 } catch (Exception e) {
2233 logger.error(EELFLoggerDelegate.errorLogger, "getMenuFunctionsList: Failed", e);
2234 return appMenuFunctionsList;
2236 return appMenuFunctionsList;
2239 @SuppressWarnings({ "unchecked"})
2241 public List<EcompUser> getAllAppUsers(String uebkey) throws Exception {
2242 List<String> usersList = new ArrayList<>();
2243 List<EcompUser> usersfinalList = new ArrayList<>();
2245 EPApp app = getApp(uebkey).get(0);
2246 final Map<String, Long> appParams = new HashMap<>();
2247 appParams.put("appId", app.getId());
2248 List<EcompUserRoles> userList = (List<EcompUserRoles>) dataAccessService
2249 .executeNamedQuery("ApplicationUserRoles", appParams, null);
2250 for (EcompUserRoles ecompUserRole : userList) {
2251 boolean found = false;
2252 Set<EcompRole> roles = null;
2253 for (EcompUser user : usersfinalList) {
2254 if (user.getOrgUserId().equals(ecompUserRole.getOrgUserId())) {
2255 EcompRole ecompRole = new EcompRole();
2256 ecompRole.setId(ecompUserRole.getRoleId());
2257 ecompRole.setName(ecompUserRole.getRoleName());
2258 roles = user.getRoles();
2259 roles.add(ecompRole);
2260 user.setRoles(roles);
2267 EcompUser epUser = new EcompUser();
2268 epUser.setOrgId(ecompUserRole.getOrgId());
2269 epUser.setManagerId(ecompUserRole.getManagerId());
2270 epUser.setFirstName(ecompUserRole.getFirstName());
2271 epUser.setLastName(ecompUserRole.getLastName());
2272 epUser.setPhone(ecompUserRole.getPhone());
2273 epUser.setEmail(ecompUserRole.getEmail());
2274 epUser.setOrgUserId(ecompUserRole.getOrgUserId());
2275 epUser.setOrgCode(ecompUserRole.getOrgCode());
2276 epUser.setOrgManagerUserId(ecompUserRole.getOrgManagerUserId());
2277 epUser.setJobTitle(ecompUserRole.getJobTitle());
2278 epUser.setLoginId(ecompUserRole.getLoginId());
2279 epUser.setActive(true);
2280 roles = new HashSet<>();
2281 EcompRole ecompRole = new EcompRole();
2282 ecompRole.setId(ecompUserRole.getRoleId());
2283 ecompRole.setName(ecompUserRole.getRoleName());
2284 roles.add(ecompRole);
2285 epUser.setRoles(roles);
2286 usersfinalList.add(epUser);
2289 ObjectMapper mapper = new ObjectMapper();
2291 for (EcompUser u1 : usersfinalList) {
2292 String str = mapper.writeValueAsString(u1);
2295 } catch (Exception e) {
2296 logger.error(EELFLoggerDelegate.errorLogger, "getAllUsers failed", e);
2299 return usersfinalList;