+ private Role fnRoleToRole(final FnRole role) {
+ return Role.builder().name(role.getRoleName()).active(role.getActiveYn()).priority(role.getPriority())
+ .roleFunctions(role.getFnRoleFunctions()).childRoles(role.getChildRoles()).parentRoles(role.getParentRoles())
+ .build();
+ }
+
+ @SuppressWarnings("unchecked")
+ public List<RoleInAppForUser> getAppRolesForUser(Long appId, String orgUserId, Boolean extRequestValue, Long userId) {
+ List<RoleInAppForUser> rolesInAppForUser = null;
+ FnApp app = fnAppService.getById(appId);
+ logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - app = {}", app);
+ try {
+ // for onap portal app, no need to make a remote call
+ List<Role> roleList = new ArrayList<>();
+ if (!PortalConstants.PORTAL_APP_ID.equals(appId)) {
+ if (app.getAuthCentral()) {
+ List<CentralV2Role> cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey());
+ for (CentralV2Role cenRole : cenRoleList) {
+ Role role = new Role();
+ role.setActive(cenRole.isActive());
+ role.setId(cenRole.getId());
+ role.setName(cenRole.getName());
+ role.setPriority(cenRole.getPriority());
+ roleList.add(role);
+ }
+ } else {
+ Optional<FnUser> user = fnUserService.getUser(userId);
+ if (user.isPresent()){
+ roleList = user.get().getFnRoles().stream().map(this::fnRoleToRole).collect(Collectors.toList());
+ }
+ }
+ List<Role> activeRoleList = new ArrayList<>();
+ for (Role role : roleList) {
+ if (role.isActive()) {
+ if (role.getId() != 1) { // prevent portal admin from being added
+ activeRoleList.add(role);
+ } else if (extRequestValue) {
+ activeRoleList.add(role);
+ }
+ }
+
+ }
+ FnUser localUser = getUserFromApp(Long.toString(userId), app, applicationsRestClientService);
+ // If localUser does not exists return roles
+ Set<FnRole> roleSet = null;
+ FnRole[] roleSetList = null;
+ if (localUser != null) {
+ roleSet = localUser.getAppEPRoles(app);
+ roleSetList = roleSet.toArray(new FnRole[0]);
+ }
+ rolesInAppForUser = fnUserRoleService
+ .constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue);
+ return rolesInAppForUser;
+ }
+
+ EcompRole[] appRoles = null;
+ boolean checkIfUserIsApplicationAccAdmin = false;
+ List<EcompRole> roles = new ArrayList<>();
+ if (app.getAuthCentral()) {
+ List<FnRole> applicationRoles = fnRoleService.retrieveActiveRolesOfApplication(app.getId());
+ FnApp application = fnAppService.getById(appId);
+ checkIfUserIsApplicationAccAdmin = isAccountAdminOfApplication(userId,
+ application);
+
+ List<FnRole> roleSetWithFunctioncds = new ArrayList<>();
+ for (FnRole role : applicationRoles) {
+ List<EpAppFunction> cenRoleFuncList = epAppFunctionService.getAppRoleFunctionList(role.getId(), app.getId());
+ for (EpAppFunction roleFunc : cenRoleFuncList) {
+
+ String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getFunctionCd());
+ functionCode = EPUserUtils.decodeFunctionCode(functionCode);
+ String type = externalAccessRolesService.getFunctionCodeType(roleFunc.getFunctionCd());
+ String action = externalAccessRolesService.getFunctionCodeAction(roleFunc.getFunctionCd());
+ String name = roleFunc.getFunctionName();
+
+ FnFunction function = new FnFunction();
+ function.setAction(action);
+ function.setType(type);
+ function.setCode(functionCode);
+ function.setName(name);
+ role.getFnRoleFunctions().add(new FnRoleFunction(role, function));
+
+ }
+ roleSetWithFunctioncds.add(role);
+
+
+ }
+
+ for (FnRole role1 : roleSetWithFunctioncds) {
+ EcompRole ecompRole = new EcompRole();
+ ecompRole.setId(role1.getId());
+ ecompRole.setName(role1.getRoleName());
+ ecompRole.setRoleFunctions(role1.getRoleFunctions());
+ roles.add(ecompRole);
+
+ }
+ if (checkIfUserIsApplicationAccAdmin) {
+ appRoles = roles.toArray(new EcompRole[roles.size()]);
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "In getAppRolesForUser() If Logged in user checkIfUserisApplicationAccAdmin- appRoles = {}", appRoles);
+ } else if (isRoleAdmin(userId) && !checkIfUserIsApplicationAccAdmin) {
+ List<EcompRole> roleAdminAppRoles = new ArrayList<>();
+ List<String> roleAdminAppRolesNames = new ArrayList<>();
+ String QUERY =
+ "select distinct fr.role_name as roleName from fn_user_role fu, ep_app_role_function ep, ep_app_function ea, fn_role fr"
+ + " where fu.role_id = ep.role_id"
+ + " and fu.app_id = ep.app_id"
+ + " and fu.user_id = :userId"
+ + " and fu.role_id = fr.role_id and fr.active_yn='Y'"
+ + " and ea.function_cd = ep.function_cd and ea.function_cd like 'approver|%'"
+ + " and exists"
+ + " ("
+ + " select fa.app_id from fn_user fu, fn_user_role ur, fn_app fa where fu.user_id =:userId and fu.user_id = ur.user_id"
+ + " and ur.app_id = fa.app_id and fa.enabled = 'Y')";
+ List<Tuple> tuples = entityManager.createNativeQuery(QUERY, Tuple.class)
+ .setParameter("userId", userId)
+ .getResultList();
+ List<String> getUserApproverRoles = tuples.stream().map(tuple -> (String) tuple.get("roleName"))
+ .collect(Collectors.toList());
+
+ List<EcompRole> userapproverRolesList = new ArrayList<>();
+ for (String str : getUserApproverRoles) {
+ EcompRole epRole = roles.stream().filter(x -> str.equals(x.getName())).findAny().orElse(null);
+ if (epRole != null) {
+ userapproverRolesList.add(epRole);
+ }
+ }
+ for (EcompRole role : userapproverRolesList) {
+
+ List<RoleFunction> roleFunList = new ArrayList<>(role.getRoleFunctions());
+ boolean checkIfFunctionsExits = roleFunList.stream()
+ .anyMatch(roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
+ if (checkIfFunctionsExits) {
+ roleAdminAppRoles.add(role);
+ List<RoleFunction> filteredList = roleFunList.stream()
+ .filter(x -> "Approver".equalsIgnoreCase(x.getType())).collect(Collectors.toList());
+ roleAdminAppRolesNames.addAll(filteredList.stream().map(RoleFunction::getCode)
+ .collect(Collectors.toList()));
+ }
+ }
+ for (String name : roleAdminAppRolesNames) {
+ roles.stream().filter(x -> name.equals(x.getName())).findAny().ifPresent(roleAdminAppRoles::add);
+
+ }
+ appRoles = roleAdminAppRoles.toArray(new EcompRole[0]);
+
+ }
+ } else {
+ appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
+ }
+ // Test this error case, for generating an internal ONAP Portal
+ // error
+ // EcompRole[] appRoles = null;
+ // If there is an exception in the rest client api, then null will
+ // be returned.
+ if (appRoles != null) {
+ if (!app.getAuthCentral()) {
+ syncAppRoles(appId, appRoles);
+ }
+ EcompRole[] userAppRoles = null;
+ try {
+ try {
+ if (app.getAuthCentral()) {
+ List<FnUser> actualUser = fnUserService.getUserWithOrgUserId(Long.toString(userId));
+ List<EPUserAppCurrentRoles> userAppsRolesList = entityManager
+ .createNamedQuery("EPUserAppCurrentRoles")
+ .setParameter("appId", app.getId())
+ .setParameter("userId", actualUser.get(0).getId())
+ .getResultList();
+ List<EcompRole> setUserRoles = new ArrayList<>();
+ for (EPUserAppCurrentRoles role : userAppsRolesList) {
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "In getAppRolesForUser() - userAppsRolesList get userRolename = {}", role.getRoleName());
+ EcompRole ecompRole = new EcompRole();
+ ecompRole.setId(role.getRoleId());
+ ecompRole.setName(role.getRoleName());
+ setUserRoles.add(ecompRole);
+ }
+
+ boolean checkIfUserisAccAdmin = setUserRoles.stream()
+ .anyMatch(ecompRole -> ecompRole.getId() == 999L);
+
+ if (!checkIfUserisAccAdmin) {
+ List<EcompRole> appRolesList = Arrays.asList(appRoles);
+ Set<EcompRole> finalUserAppRolesList = new HashSet<>();
+
+ List<String> roleNames = new ArrayList<>();
+ for (EcompRole role : setUserRoles) {
+ EcompRole epRole = appRolesList.stream()
+ .filter(x -> role.getName().equals(x.getName())).findAny().orElse(null);
+ List<RoleFunction> roleFunList = new ArrayList<>();
+
+ if (epRole != null) {
+ if (epRole.getRoleFunctions().size() > 0) {
+ roleFunList.addAll(epRole.getRoleFunctions());
+ }
+ boolean checkIfFunctionsExits = roleFunList.stream().anyMatch(
+ roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
+ if (checkIfFunctionsExits) {
+ finalUserAppRolesList.add(role);
+ List<RoleFunction> filteredList = roleFunList.stream()
+ .filter(x -> "Approver".equalsIgnoreCase(x.getType()))
+ .collect(Collectors.toList());
+ roleNames = filteredList.stream().map(RoleFunction::getCode)
+ .collect(Collectors.toList());
+ } else {
+ roleNames.add(epRole.getName());
+ }
+ }
+ for (String name : roleNames) {
+ EcompRole ecompRole = appRolesList.stream()
+ .filter(x -> name.equals(x.getName())).findAny().orElse(null);
+ if (ecompRole != null) {
+ finalUserAppRolesList.add(ecompRole);
+ }
+ }
+ }
+ for (String name : roleNames) {
+ boolean checkIfFunctionsExits = userAppsRolesList.stream().anyMatch(
+ role -> role.getRoleName().equalsIgnoreCase(name));
+ if (checkIfFunctionsExits) {
+ appRolesList.stream().filter(x -> name.equals(x.getName()))
+ .findAny().ifPresent(setUserRoles::add);
+ }
+ }
+ userAppRoles = setUserRoles.toArray(new EcompRole[0]);
+ }
+ } else {
+ userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
+ String.format("/user/%s/roles", userId));
+ }
+ } catch (HTTPException e) {
+ // Some apps are returning 400 if user is not found.
+ if (e.getResponseCode() == 400) {
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "getAppRolesForUser caught exception with response code 400; continuing", e);
+ } else {
+ // Other response code, let it come thru.
+ throw e;
+ }
+ }
+ if (userAppRoles == null) {
+ if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
+ EcompPortalUtils.setExternalAppResponseCode(200);
+ String message = String.format(
+ "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
+ + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
+ + "Overriding to 200 until framework SDK returns a useful response.",
+ Long.toString(appId), userId);
+ logger.warn(EELFLoggerDelegate.applicationLogger, message);
+ }
+ }
+
+ HashMap<Long, EcompRole> appRolesActiveMap = hashMapFromEcompRoles(appRoles);
+ ArrayList<EcompRole> activeRoles = new ArrayList<>();
+ if (userAppRoles != null) {
+ for (EcompRole userAppRole : userAppRoles) {
+ if (appRolesActiveMap.containsKey(userAppRole.getId())) {
+ EcompRole role = new EcompRole();
+ role.setId(userAppRole.getId());
+ role.setName(userAppRole.getName());
+ activeRoles.add(role);
+ }
+ }
+ }
+ EcompRole[] userAppRolesActive = activeRoles.toArray(new EcompRole[0]);
+
+ boolean checkIfUserisRoleAdmin = isRoleAdmin(userId) && !checkIfUserIsApplicationAccAdmin;
+
+ // If the remote application isn't down we MUST sync user
+ // roles here in case we have this user here!
+ syncUserRoles(Long.toString(userId), appId, userAppRolesActive, extRequestValue, null, checkIfUserisRoleAdmin,
+ appRoles);
+ } catch (Exception e) {
+ // TODO: we may need to check if user exists, maybe remote
+ // app is down.
+ String message = String.format(
+ "getAppRolesForUser: user %s does not exist in remote application %s", userId,
+ Long.toString(appId));
+ logger.error(EELFLoggerDelegate.errorLogger, message, e);
+ userAppRoles = new EcompRole[0];
+ }
+ rolesInAppForUser = fnUserRoleService.constructRolesInAppForUserGet(appRoles, userAppRoles);
+ }
+ } catch (Exception e) {
+ String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
+ Long.toString(appId));
+ logger.error(EELFLoggerDelegate.errorLogger, message, e);
+ }
+ return rolesInAppForUser;
+ }
+
+ private void syncAppRoles(Long appId, EcompRole[] appRoles) throws Exception {
+ logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId);
+ HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles);
+ try {
+ List<FnRole> currentAppRoles = fnRoleService.retrieveAppRolesByAppId(appId);
+
+ List<FnRole> obsoleteRoles = new ArrayList<>();
+ for (FnRole oldAppRole : currentAppRoles) {
+ if (oldAppRole.getAppRoleId() != null) {
+ EcompRole role;
+ role = newRolesMap.get(oldAppRole.getAppRoleId());
+ if (role != null) {
+ if (!(role.getName() == null || oldAppRole.getRoleName().equals(role.getName()))) {
+ oldAppRole.setRoleName(role.getName());
+ }
+ oldAppRole.setActiveYn(true);
+ newRolesMap.remove(oldAppRole.getAppRoleId());
+ } else {
+ obsoleteRoles.add(oldAppRole);
+ }
+ } else {
+ obsoleteRoles.add(oldAppRole);
+ }
+ }
+ Collection<EcompRole> newRolesToAdd = newRolesMap.values();
+ if (obsoleteRoles.size() > 0) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: we have obsolete roles to delete");
+ for (FnRole role : obsoleteRoles) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: obsolete role: " + role.toString());
+ Long roleId = role.getId();
+ List<FnUserRole> userRoles = fnUserRoleService.retrieveByAppIdAndRoleId(appId, roleId);
+
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "syncAppRoles: number of userRoles to delete: " + userRoles.size());
+ for (FnUserRole userRole : userRoles) {
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "syncAppRoles: about to delete userRole: " + userRole.toString());
+ fnUserRoleService.deleteById(userRole.getId());
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "syncAppRoles: finished deleting userRole: " + userRole.toString());
+ }
+ List<FnMenuFunctionalRoles> funcMenuRoles = fnMenuFunctionalRolesService.retrieveByroleId(roleId);
+ int numMenuRoles = funcMenuRoles.size();
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "syncAppRoles: number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles);
+ for (FnMenuFunctionalRoles funcMenuRole : funcMenuRoles) {
+ Long menuId = funcMenuRole.getMenuId().getMenuId();
+ // If this is the only role for this menu item, then the
+ // app and roles will be gone,
+ // so must null out the url too, to be consistent
+ List<FnMenuFunctionalRoles> funcMenuRoles2 = fnMenuFunctionalRolesService.retrieveByMenuId(menuId);
+ int numMenuRoles2 = funcMenuRoles2.size();
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "syncAppRoles: number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2);
+ fnMenuFunctionalRolesService.delete(funcMenuRole);
+
+ if (numMenuRoles2 == 1) {
+ // If this is the only role for this menu item, then
+ // the app and roles will be gone,
+ // so must null out the url too, to be consistent
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url");
+ List<FnMenuFunctional> funcMenuItems = fnMenuFunctionalService.retrieveByMenuId(menuId);
+ if (funcMenuItems.size() > 0) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item");
+ FnMenuFunctional funcMenuItem = funcMenuItems.get(0);
+ funcMenuItem.setUrl("");
+ }
+ }
+ }
+ boolean isPortalRequest = true;
+ deleteRoleDependencyRecords(roleId, appId, isPortalRequest);
+ logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to delete the role: " + role.toString());
+ fnRoleService.delete(role);
+ logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: deleted the role");
+ }
+ }
+ for (EcompRole role : newRolesToAdd) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to add missing role: " + role.toString());
+ FnRole newRole = new FnRole();
+ // Attention! All roles from remote application supposed to be
+ // active!
+ newRole.setActiveYn(true);
+ newRole.setRoleName(role.getName());
+ newRole.setAppId(appId);
+ newRole.setAppRoleId(role.getId());
+ fnRoleService.saveOne(newRole);
+ }
+ logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to commit the transaction");
+ logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: committed the transaction");
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "syncAppRoles failed", e);
+ EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
+ throw new Exception(e);
+ }
+ }
+
+ private void deleteRoleDependencyRecords(Long roleId, Long appId, boolean isPortalRequest)
+ throws Exception {
+ Session localSession = entityManager.unwrap(Session.class);
+ try {
+ String sql;
+ Query query;
+ // It should delete only when it portal's roleId
+ if (appId.equals(PortalConstants.PORTAL_APP_ID)) {
+ // Delete from fn_role_function
+ sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
+ logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
+ query = localSession.createSQLQuery(sql);
+ query.executeUpdate();
+ // Delete from fn_role_composite
+ sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId;
+ logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
+ query = localSession.createSQLQuery(sql);
+ query.executeUpdate();
+ }
+ // Delete from ep_app_role_function
+ sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId;
+ logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
+ query = localSession.createSQLQuery(sql);
+ query.executeUpdate();
+ // Delete from ep_role_notification
+ sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
+ logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
+ query = localSession.createSQLQuery(sql);
+ query.executeUpdate();
+ // Delete from fn_user_pseudo_role
+ sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
+ logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
+ query = localSession.createSQLQuery(sql);
+ query.executeUpdate();
+ // Delete form EP_WIDGET_CATALOG_ROLE
+ sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId;
+ logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
+ query = localSession.createSQLQuery(sql);
+ query.executeUpdate();
+ // Delete form EP_WIDGET_CATALOG_ROLE
+ sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId;
+ logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
+ query = localSession.createSQLQuery(sql);
+ query.executeUpdate();
+ if (!isPortalRequest) {
+ // Delete form fn_menu_functional_roles
+ sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
+ logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
+ query = localSession.createSQLQuery(sql);
+ query.executeUpdate();
+ }
+ } catch (Exception e) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e);
+ throw new DeleteDomainObjectFailedException("delete Failed" + e.getMessage());
+ }
+ }
+