2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
8 * Unless otherwise specified, all software contained herein is licensed
9 * under the Apache License, Version 2.0 (the "License");
10 * you may not use this software except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * Unless otherwise specified, all documentation contained herein is licensed
22 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23 * you may not use this documentation except in compliance with the License.
24 * You may obtain a copy of the License at
26 * https://creativecommons.org/licenses/by/4.0/
28 * Unless required by applicable law or agreed to in writing, documentation
29 * distributed under the License is distributed on an "AS IS" BASIS,
30 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31 * See the License for the specific language governing permissions and
32 * limitations under the License.
34 * ============LICENSE_END============================================
39 package org.onap.portalapp.portal.service;
41 import java.io.IOException;
42 import java.util.ArrayList;
43 import java.util.Arrays;
44 import java.util.Collection;
45 import java.util.Date;
46 import java.util.HashMap;
47 import java.util.HashSet;
48 import java.util.LinkedHashSet;
49 import java.util.List;
52 import java.util.SortedSet;
53 import java.util.TreeSet;
54 import java.util.stream.Collectors;
56 import javax.servlet.http.HttpServletResponse;
58 import org.apache.commons.lang.StringUtils;
59 import org.apache.cxf.transport.http.HTTPException;
60 import org.hibernate.SQLQuery;
61 import org.hibernate.Session;
62 import org.hibernate.SessionFactory;
63 import org.hibernate.Transaction;
64 import org.json.JSONArray;
65 import org.json.JSONObject;
66 import org.onap.portalapp.externalsystemapproval.model.ExternalSystemRoleApproval;
67 import org.onap.portalapp.externalsystemapproval.model.ExternalSystemUser;
68 import org.onap.portalapp.portal.domain.CentralV2RoleFunction;
69 import org.onap.portalapp.portal.domain.EPApp;
70 import org.onap.portalapp.portal.domain.EPRole;
71 import org.onap.portalapp.portal.domain.EPUser;
72 import org.onap.portalapp.portal.domain.EPUserApp;
73 import org.onap.portalapp.portal.domain.EPUserAppCatalogRoles;
74 import org.onap.portalapp.portal.domain.EPUserAppRoles;
75 import org.onap.portalapp.portal.domain.EPUserAppRolesRequest;
76 import org.onap.portalapp.portal.domain.EPUserAppRolesRequestDetail;
77 import org.onap.portalapp.portal.domain.ExternalSystemAccess;
78 import org.onap.portalapp.portal.exceptions.SyncUserRolesException;
79 import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
80 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
81 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
82 import org.onap.portalapp.portal.transport.AppWithRolesForUser;
83 import org.onap.portalapp.portal.transport.CentralV2Role;
84 import org.onap.portalapp.portal.transport.EPUserAppCurrentRoles;
85 import org.onap.portalapp.portal.transport.EcompUserAppRoles;
86 import org.onap.portalapp.portal.transport.ExternalAccessUser;
87 import org.onap.portalapp.portal.transport.ExternalAccessUserRoleDetail;
88 import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator;
89 import org.onap.portalapp.portal.transport.ExternalRoleDescription;
90 import org.onap.portalapp.portal.transport.FieldsValidator;
91 import org.onap.portalapp.portal.transport.FunctionalMenuItem;
92 import org.onap.portalapp.portal.transport.FunctionalMenuRole;
93 import org.onap.portalapp.portal.transport.RemoteRole;
94 import org.onap.portalapp.portal.transport.RemoteRoleV1;
95 import org.onap.portalapp.portal.transport.RemoteUserWithRoles;
96 import org.onap.portalapp.portal.transport.RoleInAppForUser;
97 import org.onap.portalapp.portal.transport.RolesInAppForUser;
98 import org.onap.portalapp.portal.transport.UserApplicationRoles;
99 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
100 import org.onap.portalapp.portal.utils.EcompPortalUtils;
101 import org.onap.portalapp.portal.utils.PortalConstants;
102 import org.onap.portalapp.util.EPUserUtils;
103 import org.onap.portalapp.util.SystemType;
104 import org.onap.portalsdk.core.domain.Role;
105 import org.onap.portalsdk.core.domain.RoleFunction;
106 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
107 import org.onap.portalsdk.core.restful.domain.EcompRole;
108 import org.onap.portalsdk.core.service.DataAccessService;
109 import org.onap.portalsdk.core.service.RoleService;
110 import org.onap.portalsdk.core.util.SystemProperties;
111 import org.springframework.beans.factory.annotation.Autowired;
112 import org.springframework.http.HttpEntity;
113 import org.springframework.http.HttpHeaders;
114 import org.springframework.http.HttpMethod;
115 import org.springframework.http.HttpStatus;
116 import org.springframework.http.ResponseEntity;
117 import org.springframework.web.client.HttpClientErrorException;
118 import org.springframework.web.client.RestTemplate;
120 import com.fasterxml.jackson.core.JsonProcessingException;
121 import com.fasterxml.jackson.databind.DeserializationFeature;
122 import com.fasterxml.jackson.databind.ObjectMapper;
125 public class UserRolesCommonServiceImpl {
127 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesCommonServiceImpl.class);
129 private static final Object syncRests = new Object();
131 private static final String APP_ID = "appId";
134 private DataAccessService dataAccessService;
136 private SessionFactory sessionFactory;
138 private SearchService searchService;
140 private EPAppService appsService;
142 private ApplicationsRestClientService applicationsRestClientService;
144 private EPRoleService epRoleService;
146 private RoleService roleService;
148 private AdminRolesService adminRolesService;
150 private EPAppService appService;
152 private ExternalAccessRolesService externalAccessRolesService;
155 private AppsCacheService appsCacheService;
157 RestTemplate template = new RestTemplate();
162 * @return HashMap<Long, EcompRole>
164 private static HashMap<Long, EcompRole> hashMapFromEcompRoles(EcompRole[] ecompRoles) {
165 HashMap<Long, EcompRole> result = new HashMap<Long, EcompRole>();
166 if (ecompRoles != null) {
167 for (int i = 0; i < ecompRoles.length; i++) {
168 if (ecompRoles[i].getId() != null) {
169 result.put(ecompRoles[i].getId(), ecompRoles[i]);
180 protected void createLocalUserIfNecessary(String userId,boolean isSystemUser) {
181 if (StringUtils.isEmpty(userId)) {
182 logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty userId!");
185 Session localSession = null;
186 Transaction transaction = null;
188 localSession = sessionFactory.openSession();
189 transaction = localSession.beginTransaction();
190 @SuppressWarnings("unchecked")
191 List<EPUser> userList = localSession
192 .createQuery("from :name where orgUserId=:userId")
193 .setParameter("name",EPUser.class.getName())
194 .setParameter("userId",userId)
196 if (userList.size() == 0) {
197 EPUser client = null;
199 client = searchService.searchUserByUserId(userId);
201 client = new EPUser();
202 client.setOrgUserId(userId);
203 client.setSystemUser(true);
204 client.setFirstName(userId.substring(0,userId.indexOf("@")));
206 if (client == null) {
207 String msg = "createLocalUserIfNecessary: cannot create user " + userId
208 + ", because not found in phonebook";
209 logger.error(EELFLoggerDelegate.errorLogger, msg);
211 client.setLoginId(userId);
212 client.setActive(true);
213 localSession.save(client);
216 transaction.commit();
217 } catch (Exception e) {
218 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
219 EcompPortalUtils.rollbackTransaction(transaction, "searchOrCreateUser rollback, exception = " + e);
221 EcompPortalUtils.closeLocalSession(localSession, "searchOrCreateUser");
226 * This method return nothing and remove roles before adding any roles for an app
229 * @param localSession
230 * @param userAppRoles
231 * @param newUserAppRolesMap
233 private static void syncUserRolesExtension(EPUserApp userRole, Long appId, Session localSession, EcompRole[] userAppRoles, HashMap<Long, EcompRole> newUserAppRolesMap) {
235 Long userAppRoleId = 0L;
236 if (appId == PortalConstants.PORTAL_APP_ID) { // local app
237 userAppRoleId = userRole.getRoleId();
238 } else { // remote app
239 userAppRoleId = userRole.getAppRoleId();
242 if (!newUserAppRolesMap.containsKey(userAppRoleId)) {
243 localSession.delete(userRole);
245 newUserAppRolesMap.remove(userAppRoleId);
250 * Checks whether the role is inactive
254 * if role is inactive, throws exception
256 private void checkIfRoleInactive(EPRole epRole) throws Exception{
257 if(!epRole.getActive()){
258 throw new Exception(epRole.getName()+ " role is unavailable");
264 * @param sessionFactory
267 * @param userAppRoles
268 * @param extRequestValue
269 * set to false if request is from users page otherwise true
272 protected void syncUserRoles(SessionFactory sessionFactory, String userId, Long appId,
273 EcompRole[] userAppRoles, Boolean extRequestValue, String reqType) throws Exception {
274 Session localSession = null;
275 Transaction transaction = null;
276 String roleActive = null;
277 final Map<String, String> userAppParams = new HashMap<>();
278 final Map<String, String> appParams = new HashMap<>();
279 HashMap<Long, EcompRole> newUserAppRolesMap = hashMapFromEcompRoles(userAppRoles);
282 localSession = sessionFactory.openSession();
283 transaction = localSession.beginTransaction();
284 @SuppressWarnings("unchecked")
285 List<EPUser> userList = localSession
286 .createQuery("from :name where orgUserId=:userId")
287 .setParameter("name",EPUser.class.getName())
288 .setParameter("userId",userId)
290 if (userList.size() > 0) {
291 EPUser client = userList.get(0);
292 roleActive = ("DELETE".equals(reqType)) ? "" : " and role.active = 'Y'";
293 @SuppressWarnings("unchecked")
294 List<EPUserApp> userRoles = localSession.createQuery("from " + EPUserApp.class.getName()
295 + " where app.id=" + appId + roleActive + " and userId=" + client.getId()).list();
297 if ("DELETE".equals(reqType)) {
298 for (EPUserApp userAppRoleList : userRoles) {
299 userAppParams.put("roleName", String.valueOf(userAppRoleList.getRole().getName()));
300 userAppParams.put("appId", String.valueOf(appId));
301 appParams.put("appRoleName", userAppRoleList.getRole().getName());
302 @SuppressWarnings("unchecked")
303 List<EPRole> rolesList = (!userAppRoleList.getRole().getName().equals(PortalConstants.ADMIN_ROLE)) ? (List<EPRole>) dataAccessService.executeNamedQuery("getAppRoles", userAppParams, null) : (List<EPRole>) dataAccessService.executeNamedQuery("getPortalAppRoles", appParams, null);
304 if(rolesList.size() > 0 || !rolesList.isEmpty()){
305 checkIfRoleInactive(rolesList.get(0));
310 for (EPUserApp userRole : userRoles) {
311 if (!userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && userRole.getRoleId() != PortalConstants.SYS_ADMIN_ROLE_ID && !extRequestValue){
312 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
314 else if (extRequestValue && ("PUT".equals(reqType) || "POST".equals(reqType) || "DELETE".equals(reqType))){
315 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
317 else if (extRequestValue && !userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)){
318 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
321 Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values();
322 if (newRolesToAdd.size() > 0) {
323 EPApp app = (EPApp) localSession.get(EPApp.class, appId);
325 HashMap<Long, EPRole> rolesMap = new HashMap<Long, EPRole>();
326 if (appId.equals(PortalConstants.PORTAL_APP_ID)) { // local app
327 String appIdValue = "";
328 if(!extRequestValue){
329 appIdValue = "and id != " + PortalConstants.SYS_ADMIN_ROLE_ID;
331 @SuppressWarnings("unchecked")
332 List<EPRole> roles = localSession
333 .createQuery("from " + EPRole.class.getName() + " where appId is null " + appIdValue).list();
334 for (EPRole role : roles) {
336 rolesMap.put(role.getId(), role);
338 } else { // remote app
339 @SuppressWarnings("unchecked")
340 List<EPRole> roles = localSession
341 .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list();
342 for (EPRole role : roles) {
343 if (!extRequestValue && app.getCentralAuth()) {
344 rolesMap.put(role.getId(), role);
346 rolesMap.put(role.getAppRoleId(), role);
352 for (EcompRole userRole : newRolesToAdd) {
353 EPUserApp userApp = new EPUserApp();
354 if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName().equals(PortalConstants.ADMIN_ROLE)) {
355 role = (EPRole) localSession.get(EPRole.class, new Long(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
356 userApp.setRole(role);
357 } else if ((userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) && !extRequestValue){
359 }else if((userRole.getId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)) && app.getId().equals(PortalConstants.PORTAL_APP_ID) && !extRequestValue){
363 userApp.setRole(rolesMap.get(userRole.getId()));
366 userApp.setUserId(client.getId());
368 localSession.save(userApp);
369 localSession.flush();
372 if (appId == PortalConstants.PORTAL_APP_ID) {
374 * for local app -- hack - always make sure fn_role
375 * table's app_id is null and not 1 for primary app in
376 * this case being onap portal app; reason: hibernate
377 * is rightly setting this to 1 while persisting to
378 * fn_role as per the mapping but SDK role management
379 * code expects the app_id to be null as there is no
380 * concept of App_id in SDK
382 localSession.flush();
383 SQLQuery sqlQuery = localSession
384 .createSQLQuery("update fn_role set app_id = null where app_id = 1 ");
385 sqlQuery.executeUpdate();
390 transaction.commit();
391 } catch (Exception e) {
392 logger.error(EELFLoggerDelegate.errorLogger, "syncUserRoles failed", e);
393 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
394 EcompPortalUtils.rollbackTransaction(transaction,
395 "Exception occurred in syncUserRoles, Details: " + e.toString());
396 if("DELETE".equals(reqType)){
397 throw new SyncUserRolesException(e.getMessage());
400 if(localSession != null)
401 localSession.close();
406 * Called when getting the list of roles for the user
409 * @param userAppRoles
410 * @return List<RoleInAppForUser>
412 protected List<RoleInAppForUser> constructRolesInAppForUserGet(EcompRole[] appRoles, EcompRole[] userAppRoles) {
413 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
415 Set<Long> userAppRolesMap = new HashSet<Long>();
416 if (userAppRoles != null) {
417 for (EcompRole ecompRole : userAppRoles) {
418 userAppRolesMap.add(ecompRole.getId());
421 logger.error(EELFLoggerDelegate.errorLogger,
422 "constructRolesInAppForUserGet has received userAppRoles list empty");
425 if (appRoles != null) {
426 for (EcompRole ecompRole : appRoles) {
427 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
428 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
429 rolesInAppForUser.add(roleForUser);
432 logger.error(EELFLoggerDelegate.errorLogger, "constructRolesInAppForUser has received appRoles list empty");
434 return rolesInAppForUser;
438 * Called when getting the list of roles for the user
441 * @param userAppRoles
442 * @param extRequestValue
443 * set to false if request is from users page otherwise true
444 * @return List<RoleInAppForUser>
446 protected List<RoleInAppForUser> constructRolesInAppForUserGet(List<Role> appRoles, EPRole[] userAppRoles, Boolean extRequestValue) {
447 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
449 Set<Long> userAppRolesMap = new HashSet<Long>();
450 if (userAppRoles != null) {
451 for (EPRole ecompRole : userAppRoles) {
452 userAppRolesMap.add(ecompRole.getId());
454 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - userAppRolesMap = {}", userAppRolesMap);
457 logger.error(EELFLoggerDelegate.errorLogger,
458 "constructRolesInAppForUserGet has received userAppRoles list empty.");
461 if (appRoles != null) {
463 for (Role ecompRole : appRoles) {
464 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - appRoles not null = {}", ecompRole);
466 if (ecompRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && !extRequestValue)
468 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
469 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
470 rolesInAppForUser.add(roleForUser);
471 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - rolesInAppForUser = {}", rolesInAppForUser);
475 logger.error(EELFLoggerDelegate.errorLogger,
476 "constructRolesInAppForUser has received appRoles list empty.");
478 return rolesInAppForUser;
483 * copies of methods in GetAppsWithUserRoleState
485 * @param sessionFactory
490 protected void syncAppRoles(SessionFactory sessionFactory, Long appId, EcompRole[] appRoles) throws Exception {
491 logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId);
492 HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles);
493 Session localSession = null;
494 Transaction transaction = null;
497 localSession = sessionFactory.openSession();
498 transaction = localSession.beginTransaction();
499 // Attention! All roles from remote application supposed to be
502 @SuppressWarnings("unchecked")
503 List<EPRole> currentAppRoles = localSession.createQuery("from :name where appId = :appId")
504 .setParameter("name",EPRole.class.getName())
505 .setParameter("appId",appId)
508 List<EPRole> obsoleteRoles = new ArrayList<EPRole>();
509 for (int i = 0; i < currentAppRoles.size(); i++) {
510 EPRole oldAppRole = currentAppRoles.get(i);
511 if (oldAppRole.getAppRoleId() != null) {
512 EcompRole role = null;
513 role = newRolesMap.get(oldAppRole.getAppRoleId());
515 if (!(role.getName() == null || oldAppRole.getName().equals(role.getName()))) {
516 oldAppRole.setName(role.getName());
517 localSession.update(oldAppRole);
519 oldAppRole.setActive(true);
520 newRolesMap.remove(oldAppRole.getAppRoleId());
522 obsoleteRoles.add(oldAppRole);
525 obsoleteRoles.add(oldAppRole);
528 Collection<EcompRole> newRolesToAdd = newRolesMap.values();
529 if (obsoleteRoles.size() > 0) {
530 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: we have obsolete roles to delete");
531 for (EPRole role : obsoleteRoles) {
532 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: obsolete role: " + role.toString());
533 Long roleId = role.getId();
534 // delete obsolete roles here
535 // Must delete all records with foreign key constraints on
537 // fn_user_role, fn_role_composite, fn_role_function,
538 // fn_user_pseudo_role, fn_menu_functional_roles.
539 // And for fn_menu_functional, if no other roles for that
540 // menu item, remove the url.
542 // Delete from fn_user_role
543 @SuppressWarnings("unchecked")
544 List<EPUserApp> userRoles = localSession.createQuery(
545 "from :name where app.id=:appId and role_id=:roleId")
546 .setParameter("name",EPUserApp.class.getName())
547 .setParameter("appId",appId)
548 .setParameter("roleId",roleId)
551 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: number of userRoles to delete: " + userRoles.size());
552 for (EPUserApp userRole : userRoles) {
553 logger.debug(EELFLoggerDelegate.debugLogger,
554 "syncAppRoles: about to delete userRole: " + userRole.toString());
555 localSession.delete(userRole);
556 logger.debug(EELFLoggerDelegate.debugLogger,
557 "syncAppRoles: finished deleting userRole: " + userRole.toString());
560 // Delete from fn_menu_functional_roles
561 @SuppressWarnings("unchecked")
562 List<FunctionalMenuRole> funcMenuRoles = localSession
563 .createQuery("from :name where roleId=:roleId")
564 .setParameter("name",FunctionalMenuRole.class.getName())
565 .setParameter("roleId",roleId)
567 int numMenuRoles = funcMenuRoles.size();
568 logger.debug(EELFLoggerDelegate.debugLogger,
569 "syncAppRoles: number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles);
570 for (FunctionalMenuRole funcMenuRole : funcMenuRoles) {
571 Long menuId = funcMenuRole.menuId;
572 // If this is the only role for this menu item, then the
573 // app and roles will be gone,
574 // so must null out the url too, to be consistent
575 @SuppressWarnings("unchecked")
576 List<FunctionalMenuRole> funcMenuRoles2 = localSession
577 .createQuery("from :name where menuId=:menuId")
578 .setParameter("name",FunctionalMenuRole.class.getName())
579 .setParameter("menuId",menuId)
581 int numMenuRoles2 = funcMenuRoles2.size();
582 logger.debug(EELFLoggerDelegate.debugLogger,
583 "syncAppRoles: number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2);
584 localSession.delete(funcMenuRole);
585 if (numMenuRoles2 == 1) {
586 // If this is the only role for this menu item, then
587 // the app and roles will be gone,
588 // so must null out the url too, to be consistent
589 logger.debug(EELFLoggerDelegate.debugLogger,
590 "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url");
591 @SuppressWarnings("unchecked")
592 List<FunctionalMenuItem> funcMenuItems = localSession
593 .createQuery("from :name where menuId=:menuId")
594 .setParameter("name",FunctionalMenuItem.class.getName())
595 .setParameter("menuId",menuId)
597 if (funcMenuItems.size() > 0) {
598 logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item");
599 FunctionalMenuItem funcMenuItem = funcMenuItems.get(0);
600 funcMenuItem.url = "";
601 localSession.update(funcMenuItem);
605 boolean isPortalRequest = true;
606 externalAccessRolesService.deleteRoleDependencyRecords(localSession, roleId, appId, isPortalRequest);
607 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to delete the role: " + role.toString());
608 localSession.delete(role);
609 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: deleted the role");
612 for (EcompRole role : newRolesToAdd) {
613 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to add missing role: " + role.toString());
614 EPRole newRole = new EPRole();
615 // Attention! All roles from remote application supposed to be
617 newRole.setActive(true);
618 newRole.setName(role.getName());
619 newRole.setAppId(appId);
620 newRole.setAppRoleId(role.getId());
621 localSession.save(newRole);
623 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to commit the transaction");
624 transaction.commit();
625 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: committed the transaction");
626 } catch (Exception e) {
627 logger.error(EELFLoggerDelegate.errorLogger, "syncAppRoles failed", e);
628 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
629 EcompPortalUtils.rollbackTransaction(transaction,
630 "Exception occurred in syncAppRoles, Details: " + e.toString());
631 throw new Exception(e);
633 localSession.close();
642 * Called when updating the list of roles for the user
646 * @param userRolesInRemoteApp
647 * @return RolesInAppForUser
649 protected RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId,
650 Set<EcompRole> userRolesInRemoteApp) {
651 RolesInAppForUser result;
652 result = new RolesInAppForUser();
653 result.appId = appId;
654 result.orgUserId = userId;
656 for (EcompRole role : userRolesInRemoteApp) {
657 RoleInAppForUser roleInAppForUser = new RoleInAppForUser();
658 roleInAppForUser.roleId = role.getId();
659 roleInAppForUser.roleName = role.getName();
660 roleInAppForUser.isApplied = new Boolean(true);
661 result.roles.add(roleInAppForUser);
668 * @param roleInAppForUserList
671 protected boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) {
672 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
673 if (roleInAppForUser.isApplied.booleanValue()) {
681 * Builds JSON and posts it to a remote application to update user roles.
683 * @param roleInAppForUserList
685 * @param applicationsRestClientService
688 * @return Set of roles as sent; NOT the response from the app.
689 * @throws JsonProcessingException
690 * @throws HTTPException
692 protected Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
693 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId,boolean systemUser)
694 throws JsonProcessingException, HTTPException {
695 Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList);
696 Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList);
697 String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote);
698 EPApp externalApp = null;
699 SystemType type = SystemType.APPLICATION;
700 externalApp = appsCacheService.getApp(appId);
701 String appBaseUri = null;
702 Set<RemoteRoleV1> updatedUserRolesinRemoteV1 = new TreeSet<>();
703 if (externalApp != null) {
704 appBaseUri = (type == SystemType.APPLICATION) ? externalApp.getAppRestEndpoint() : "";
706 if(appBaseUri != null && appBaseUri.endsWith("/api")){
707 for(EcompRole eprole :updatedUserRolesinRemote)
709 RemoteRoleV1 role = new RemoteRoleV1();
710 role.setId(eprole.getId());
711 role.setName(eprole.getName());
712 updatedUserRolesinRemoteV1.add(role);
714 userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemoteV1);
716 applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString,
717 String.format("/user/%s/roles", userId));
718 // TODO: We should add code that verifies that the post operation did
719 // succeed. Because the SDK may still return 200 OK with an html page
720 // even when it fails!
721 return updateUserRolesInEcomp;
726 * @param roleInAppForUserList
727 * @return Set<EcompRole>
729 protected Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) {
730 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
731 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
732 if (roleInAppForUser.isApplied) {
733 EcompRole ecompRole = new EcompRole();
734 ecompRole.setId(roleInAppForUser.roleId);
735 ecompRole.setName(roleInAppForUser.roleName);
736 existingUserRoles.add(ecompRole);
739 return existingUserRoles;
743 * Constructs user app roles excluding Account Administrator role
745 * @param roleInAppForUserList
747 * List of roles with Role name, Role Id
749 protected Set<EcompRole> constructUsersRemoteAppRoles(List<RoleInAppForUser> roleInAppForUserList) {
750 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
751 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
752 if (roleInAppForUser.isApplied && !roleInAppForUser.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
753 EcompRole ecompRole = new EcompRole();
754 ecompRole.setId(roleInAppForUser.roleId);
755 ecompRole.setName(roleInAppForUser.roleName);
756 existingUserRoles.add(ecompRole);
759 return existingUserRoles;
763 * This is for a single app
765 * @param rolesInAppForUser
766 * @param externalSystemRequest
767 * set to false if requests from Users page otherwise true
768 * @return true on success, false otherwise
770 protected boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser, boolean externalSystemRequest, String reqType,boolean isSystemUser) throws Exception {
771 boolean result = false;
772 String userId = rolesInAppForUser.orgUserId;
773 Long appId = rolesInAppForUser.appId;
774 synchronized (syncRests) {
775 if (rolesInAppForUser != null) {
776 createLocalUserIfNecessary(userId, isSystemUser);
779 if (rolesInAppForUser != null) {
780 EcompRole[] userAppRoles = new EcompRole[rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size()];
781 for (int i = 0; i < rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size(); i++) {
782 RoleInAppForUser roleInAppForUser = rolesInAppForUser.roles.get(i);
783 EcompRole role = new EcompRole();
784 role.setId(roleInAppForUser.roleId);
785 role.setName(roleInAppForUser.roleName);
786 userAppRoles[i] = role;
789 syncUserRoles(sessionFactory, userId, appId, userAppRoles, externalSystemRequest, reqType);
791 } catch (Exception e) {
792 logger.error(EELFLoggerDelegate.errorLogger,
793 "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for orgUserId " + userId, e);
794 if("DELETE".equals(reqType)){
795 throw new Exception(e.getMessage());
807 * @return UserApplicationRoles
809 protected UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) {
810 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
811 userWithRemoteAppRoles.setAppId(appId);
812 userWithRemoteAppRoles.setOrgUserId(remoteUser.getOrgUserId());
813 userWithRemoteAppRoles.setFirstName(remoteUser.getFirstName());
814 userWithRemoteAppRoles.setLastName(remoteUser.getLastName());
815 userWithRemoteAppRoles.setRoles(remoteUser.getRoles());
816 return userWithRemoteAppRoles;
822 * @see org.onap.portalapp.portal.service.UserRolesService#
823 * importRolesFromRemoteApplication(java.lang.Long)
825 public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException {
826 EPRole[] appRolesFull = applicationsRestClientService.get(EPRole[].class, appId, "/rolesFull");
827 List<EPRole> rolesList = Arrays.asList(appRolesFull);
828 for (EPRole externalAppRole : rolesList) {
830 // Try to find an existing extern role for the app in the local
831 // onap DB. If so, then use its id to update the existing external
832 // application role record.
833 Long externAppId = externalAppRole.getId();
834 EPRole existingAppRole = epRoleService.getRole(appId, externAppId);
835 if (existingAppRole != null) {
836 logger.debug(EELFLoggerDelegate.debugLogger,
837 String.format("ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.",
838 appId, externAppId));
841 // persistExternalRoleInEcompDb(externalAppRole, appId,
849 * It adds new user for remote application
851 * @param roleInAppForUserList
852 * @param remoteAppUser
856 * @param searchService
857 * @param applicationsRestClientService
861 private EPUser addRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app,
862 ObjectMapper mapper, SearchService searchService,
863 ApplicationsRestClientService applicationsRestClientService) throws Exception {
864 EPUser addRemoteUser = null;
865 if (remoteUserShouldBeCreated(roleInAppForUserList)) {
866 createNewUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper,
867 isAppUpgradeVersion(app));
869 return addRemoteUser;
872 private EPUser pushRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app,
873 ObjectMapper mapper, SearchService searchService,
874 ApplicationsRestClientService applicationsRestClientService,boolean appRoleIdUsed) throws Exception {
875 EPUser addRemoteUser = null;
876 // if (remoteUserShouldBeCreated(roleInAppForUserList)) {
877 pushUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper,
878 isAppUpgradeVersion(app), roleInAppForUserList, appRoleIdUsed);
880 return addRemoteUser;
883 @SuppressWarnings("unchecked")
884 protected void pushUserOnRemoteApp(String userId, EPApp app,
885 ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
886 ObjectMapper mapper, boolean postOpenSource, List<RoleInAppForUser> roleInAppForUserList,boolean appRoleIdUsed) throws Exception {
888 EPUser client = null;
889 client = searchService.searchUserByUserId(userId);
891 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
892 if (client == null) {
893 String msg = "cannot create user " + userId + ", because he/she cannot be found in directory.";
894 logger.error(EELFLoggerDelegate.errorLogger, msg);
895 // throw new Exception(msg);
896 final Map<String, String> loginIdParams = new HashMap<>();
897 loginIdParams.put("orgUserIdValue", userId);
898 List<EPUser> userList = new ArrayList<>();
899 userList = dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null);
900 if (userList.size() > 0) {
901 logger.debug(EELFLoggerDelegate.debugLogger,
902 userList.get(0).getOrgUserId() + " User was found in Portal");
903 client = userList.get(0);
904 SortedSet<EPUserApp> userApps = new TreeSet<>();
905 client.setEPUserApps(userApps);
906 client.setSystemUser(false);
908 logger.error(EELFLoggerDelegate.errorLogger, "user cannot be found be in directory or in portal");
909 throw new Exception(msg);
914 client.setLoginId(userId);
915 client.setActive(true);
916 client.setOrgUserId(userId);
919 roleInAppForUserList.removeIf(role -> role.isApplied.equals(false));
920 SortedSet<Role> roles = new TreeSet<>();
922 List<EPRole> getAppRoles = externalAccessRolesService.getAppRoles(app.getId());
923 List<EPApp> appList = new ArrayList<>();
925 List<CentralV2Role> roleList = new ArrayList<>();
926 Map<String, Long> params = new HashMap<>();
928 List<EPRole> userRoles = new ArrayList<>();
930 for (RoleInAppForUser roleInappForUser : roleInAppForUserList) {
931 EPRole role = new EPRole();
932 role.setId(roleInappForUser.getRoleId());
933 role.setName(roleInappForUser.getRoleName());
938 List<EPRole> userAppRoles = new ArrayList<>();
939 for (EPRole role : userRoles) {
940 EPRole appRole = getAppRoles.stream()
941 .filter(applicationRole -> role.getId().equals(applicationRole.getAppRoleId())).findAny()
943 EPRole epRole = new EPRole();
944 if (appRole != null) {
945 epRole.setId(appRole.getId());
946 epRole.setName(appRole.getName());
948 userAppRoles.add(epRole);
950 userRoles = new ArrayList<>();
951 userRoles.addAll(userAppRoles);
953 roleList = externalAccessRolesService.createCentralRoleObject(appList, userRoles, roleList, params);
955 for (CentralV2Role epRole : roleList) {
956 Role role = new Role();
957 EPRole appRole = getAppRoles.stream()
958 .filter(applicationRole -> epRole.getId().equals(applicationRole.getId())).findAny().orElse(null);
959 if (appRole != null){
960 role.setId(appRole.getAppRoleId());
961 role.setName(epRole.getName());
962 role.setRoleFunctions(epRole.getRoleFunctions());
966 client.setRoles(roles);
967 String userInString = null;
968 userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
969 logger.debug(EELFLoggerDelegate.debugLogger,
970 "about to post a client to remote application, users json = " + userInString);
971 applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user/%s", userId));
975 * It checks whether the remote user exists or not
976 * if exits returns user object else null
980 * @param applicationsRestClientService
982 * @throws HTTPException
984 private EPUser checkIfRemoteUserExits(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService) throws HTTPException{
985 EPUser checkRemoteUser = null;
987 checkRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
988 } catch (HTTPException e) {
989 // Some apps are returning 400 if user is not found.
990 if (e.getResponseCode() == 400) {
991 logger.debug(EELFLoggerDelegate.debugLogger,
992 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing",
994 } else if(e.getResponseCode() == 404) {
995 logger.debug(EELFLoggerDelegate.debugLogger,
996 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 404; continuing",
999 // Other response code, let it come thru.
1003 return checkRemoteUser;
1010 * @see org.onap.portalapp.portal.service.UserRolesService#
1011 * setAppWithUserRoleStateForUser(org.onap.portalapp.portal.domain.
1012 * EPUser, org.onap.portalapp.portal.transport.AppWithRolesForUser)
1014 public ExternalRequestFieldsValidator setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser) {
1015 boolean result = false;
1016 boolean epRequestValue = false;
1018 String reqMessage = "";
1019 if (newAppRolesForUser != null && newAppRolesForUser.getOrgUserId() != null) {
1020 userId = newAppRolesForUser.getOrgUserId().trim();
1022 Long appId = newAppRolesForUser.getAppId();
1023 List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.getAppRoles();
1024 if (userId.length() > 0 ) {
1025 ObjectMapper mapper = new ObjectMapper();
1026 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1029 EPApp app = appsService.getApp(appId);
1030 applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
1032 boolean systemUser = newAppRolesForUser.isSystemUser();
1033 if ((app.getCentralAuth() || app.getId().equals(PortalConstants.PORTAL_APP_ID)) && systemUser) {
1035 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1036 applicationsRestClientService, appId, userId);
1037 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1038 userRolesInLocalApp);
1039 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1040 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1041 // Apply changes in external Access system
1042 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList,
1043 epRequestValue, systemUser);
1045 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal",
1048 }else if (!app.getCentralAuth() && systemUser)
1050 throw new Exception("For non-centralized application we cannot add systemUser");
1052 else{ // if centralized app
1053 if (app.getCentralAuth()) {
1054 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1055 pushRemoteUser(roleInAppForUserList, userId, app, mapper, searchService,
1056 applicationsRestClientService,false);
1059 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1060 applicationsRestClientService, appId, userId);
1061 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1062 userRolesInLocalApp);
1063 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1064 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1065 // Apply changes in external Access system
1066 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList,
1067 epRequestValue,false);
1069 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal", systemUser);
1071 // In case if portal is not centralized then follow existing approach
1072 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1073 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1074 applicationsRestClientService, appId, userId);
1075 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1076 userRolesInLocalApp);
1077 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal",false);
1078 } else{// remote app
1079 EPUser remoteAppUser = null;
1080 if(!app.getCentralAuth() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1082 remoteAppUser = checkIfRemoteUserExits(userId, app, applicationsRestClientService);
1084 if (remoteAppUser == null) {
1085 remoteAppUser = addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService, applicationsRestClientService);
1087 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
1088 applicationsRestClientService, appId, userId,systemUser);
1089 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1090 userRolesInRemoteApp);
1091 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null,false);
1093 // If no roles remain, request app to set user inactive.
1094 if (userRolesInRemoteApp.size() == 0) {
1095 logger.debug(EELFLoggerDelegate.debugLogger,
1096 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
1098 //remoteAppUser.setActive(false);
1099 postUserToRemoteApp(userId, user, app, applicationsRestClientService);
1104 } catch (Exception e) {
1105 /*String message = String.format(
1106 "Failed to create user or update user roles for User %s, AppId %s",
1107 userId, Long.toString(appId));
1108 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1111 String message = String.format(
1112 "Failed to create user or update user roles for User %s, AppId %s",
1113 userId, Long.toString(appId));
1114 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1116 reqMessage = e.getMessage();
1123 return new ExternalRequestFieldsValidator(result, reqMessage);
1127 * It adds user roles in External system and also make data consistent in both local and in External System
1129 * @param app details
1131 * @param roleInAppUser Contains list of active roles
1133 @SuppressWarnings("unchecked")
1134 private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser, boolean isPortalRequest,boolean isSystemUser) throws Exception
1137 // check if user exists
1138 final Map<String, String> userParams = new HashMap<>();
1139 userParams.put("orgUserIdValue", orgUserId);
1140 List<EPUser> userInfo = checkIfUserExists(userParams);
1141 if (userInfo.isEmpty()) {
1142 createLocalUserIfNecessary(orgUserId, isSystemUser);
1145 if (EPCommonSystemProperties
1146 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN) && !isSystemUser) {
1148 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
1152 ObjectMapper mapper = new ObjectMapper();
1153 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1154 HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
1155 ResponseEntity<String> getResponse = externalAccessRolesService.getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
1156 List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
1157 String res = getResponse.getBody();
1158 JSONObject jsonObj = null;
1159 JSONArray extRoles = null;
1160 if (!res.equals("{}")) {
1161 jsonObj = new JSONObject(res);
1162 extRoles = jsonObj.getJSONArray("role");
1164 ExternalAccessUserRoleDetail userRoleDetail = null;
1165 if (extRoles != null) {
1166 for (int i = 0; i < extRoles.length(); i++) {
1167 if (extRoles.getJSONObject(i).getString("name").startsWith(app.getNameSpace() + ".")
1168 && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".admin")
1169 && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".owner")) {
1170 if (extRoles.getJSONObject(i).has("description")) {
1171 ExternalRoleDescription desc = new ExternalRoleDescription(extRoles.getJSONObject(i).getString("description"));
1172 userRoleDetail = new ExternalAccessUserRoleDetail(
1173 extRoles.getJSONObject(i).getString("name"), desc);
1174 userRoleDetailList.add(userRoleDetail);
1176 userRoleDetail = new ExternalAccessUserRoleDetail(
1177 extRoles.getJSONObject(i).getString("name"), null);
1178 userRoleDetailList.add(userRoleDetail);
1185 List<ExternalAccessUserRoleDetail> userRoleListMatchingInExtAuthAndLocal = CheckIfRoleAreMatchingInUserRoleDetailList(userRoleDetailList,app);
1187 // If request coming from portal not from external role approval system then we have to check if user already
1188 // have account admin or system admin as GUI will not send these roles
1189 if (!isPortalRequest) {
1190 final Map<String, String> loginIdParams = new HashMap<>();
1191 loginIdParams.put("orgUserIdValue", orgUserId);
1192 EPUser user = (EPUser) dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null).get(0);
1193 final Map<String, Long> params = new HashMap<>();
1194 params.put("appId", app.getId());
1195 params.put("userId", user.getId());
1196 List<EcompUserAppRoles> userAppList = dataAccessService.executeNamedQuery("getUserAppExistingRoles",
1198 if (!roleInAppUser.isEmpty()) {
1199 for (EcompUserAppRoles userApp : userAppList) {
1200 if (userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)
1201 || userApp.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
1202 RoleInAppForUser addSpecialRole = new RoleInAppForUser();
1203 addSpecialRole.setIsApplied(true);
1204 addSpecialRole.setRoleId(userApp.getRoleId());
1205 addSpecialRole.setRoleName(userApp.getRoleName());
1206 roleInAppUser.add(addSpecialRole);
1211 List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct()
1212 .collect(Collectors.toList());
1213 final Map<String, RoleInAppForUser> currentUserRolesToUpdate = new HashMap<>();
1214 for (RoleInAppForUser roleInAppUserNew : roleInAppUserNonDupls) {
1215 currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), roleInAppUserNew);
1217 final Map<String, ExternalAccessUserRoleDetail> currentUserRolesInExternalSystem = new HashMap<>();
1218 for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleListMatchingInExtAuthAndLocal) {
1219 currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole);
1221 // Check if user roles does not exists in local but still there in External Central Auth System delete them all
1222 for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
1223 if (!(currentUserRolesToUpdate
1224 .containsKey(userRole.getName().substring(app.getNameSpace().length() + 1)))) {
1225 HttpEntity<String> entity = new HttpEntity<>(headers);
1226 logger.debug(EELFLoggerDelegate.debugLogger,
1227 "updateUserRolesInExternalSystem: Connecting to external system to DELETE user role {}",
1228 userRole.getName());
1229 ResponseEntity<String> deleteResponse = template.exchange(
1230 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1231 + "userRole/" + name + "/" + userRole.getName(),
1232 HttpMethod.DELETE, entity, String.class);
1233 logger.debug(EELFLoggerDelegate.debugLogger,
1234 "updateUserRolesInExternalSystem: Finished DELETE operation in external system for user role {} and the response is {}",
1235 userRole.getName(), deleteResponse.getBody());
1238 // Check if user roles does not exists in External Central Auth System add them all
1239 for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) {
1240 if (!(currentUserRolesInExternalSystem
1241 .containsKey(app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")))) {
1242 ExternalAccessUser extUser = new ExternalAccessUser(name,
1243 app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1244 String formattedUserRole = mapper.writeValueAsString(extUser);
1245 HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers);
1246 logger.debug(EELFLoggerDelegate.debugLogger, "updateUserRolesInExternalSystem: Connecting to external system for user {} and POST {}",
1247 name , addUserRole.getRoleName());
1248 ResponseEntity<String> addResponse = template
1249 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1250 + "userRole", HttpMethod.POST, entity, String.class);
1251 logger.debug(EELFLoggerDelegate.debugLogger,
1252 "updateUserRolesInExternalSystem: Finished adding user role in external system {} and added user role {}",
1253 addResponse.getBody(), addUserRole.getRoleName());
1254 if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 404) {
1255 logger.debug(EELFLoggerDelegate.debugLogger,
1256 "Finished POST operation in external system but unable to save user role", addResponse.getBody(),
1257 addUserRole.getRoleName());
1258 throw new Exception(addResponse.getBody());
1262 } catch (HttpClientErrorException e) {
1263 logger.error(EELFLoggerDelegate.errorLogger,
1264 "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}",
1266 if (e.getStatusCode() == HttpStatus.FORBIDDEN) {
1267 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid systemUser", orgUserId);
1268 throw new HttpClientErrorException(HttpStatus.FORBIDDEN, "Please enter the valid systemUser");
1270 if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
1271 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid role");
1272 throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "Please enter the valid role");
1274 EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
1278 catch (Exception e) {
1279 logger.error(EELFLoggerDelegate.errorLogger, "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}", app.getId(), e);
1280 EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
1286 private List<ExternalAccessUserRoleDetail> CheckIfRoleAreMatchingInUserRoleDetailList(
1287 List<ExternalAccessUserRoleDetail> userRoleDetailList, EPApp app) {
1288 Map<String, EPRole> epRoleList = externalAccessRolesService.getAppRoleNamesWithUnderscoreMap(app);
1289 //Add Account Admin role for partner app to prevent conflict
1290 if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1291 EPRole role = new EPRole();
1292 role.setName(PortalConstants.ADMIN_ROLE.replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1293 epRoleList.put(role.getName(), role);
1295 userRoleDetailList.removeIf(userRoleDetail -> !epRoleList.containsKey(userRoleDetail.getName().substring(app.getNameSpace().length()+1)));
1296 return userRoleDetailList;
1303 * @param applicationsRestClientService
1304 * @param searchService
1308 protected void createNewUserOnRemoteApp(String userId, EPApp app,
1309 ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
1310 ObjectMapper mapper, boolean postOpenSource) throws Exception {
1313 EPUser client = searchService.searchUserByUserId(userId);
1315 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1317 if (client == null) {
1318 String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook.";
1319 logger.error(EELFLoggerDelegate.errorLogger, msg);
1320 throw new Exception(msg);
1323 client.setLoginId(userId);
1324 client.setActive(true);
1326 String userInString = null;
1327 userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
1328 logger.debug(EELFLoggerDelegate.debugLogger,
1329 "about to post new client to remote application, users json = " + userInString);
1330 applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user", userId));
1334 @SuppressWarnings("unchecked")
1335 protected void applyChangesToAppRolesRequest(Long appId, Long userId, String updateStatus, EPUserAppRolesRequest epUserAppRolesRequest) {
1336 final Map<String, Long> epRequestParams = new HashMap<>();
1338 EPUserAppRolesRequest epAppRolesRequestData = epUserAppRolesRequest;
1339 epAppRolesRequestData.setUpdatedDate(new Date());
1340 epAppRolesRequestData.setRequestStatus(updateStatus);
1341 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1342 addiotonalUpdateParam.put("userId", userId);
1343 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1344 epRequestParams.put("reqId", epUserAppRolesRequest.getId());
1345 List<EPUserAppRolesRequestDetail> epUserAppRolessDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1346 epUserAppRolessDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1347 epRequestParams, null);
1348 if (epUserAppRolessDetailList.size() > 0) {
1349 for (EPUserAppRolesRequestDetail epRequestUpdateData : epUserAppRolessDetailList) {
1350 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateData;
1351 epAppRoleDetailData.setReqType(updateStatus);
1352 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1353 HashMap<String, Long> updateDetailsParam = new HashMap<String, Long>();
1354 addiotonalUpdateParam.put("reqId", epUserAppRolesRequest.getId());
1355 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParam);
1358 logger.debug(EELFLoggerDelegate.debugLogger, "The request is set to complete");
1360 } catch (Exception e) {
1361 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToAppRolesRequest failed", e);
1365 @SuppressWarnings("unchecked")
1366 public void applyChangesToUserAppRolesForMyLoginsRequest(EPUser user, Long appId) {
1367 final Map<String, Long> params = new HashMap<>();
1368 final Map<String, Long> epDetailParams = new HashMap<>();
1369 List<EPUserAppRolesRequest> epRequestIdVal = new ArrayList<EPUserAppRolesRequest>();
1370 params.put("appId", appId);
1371 params.put("userId", user.getId());
1373 epRequestIdVal = (List<EPUserAppRolesRequest>) dataAccessService
1374 .executeNamedQuery("userAppRolesRequestList", params, null);
1375 if (epRequestIdVal.size() > 0) {
1376 EPUserAppRolesRequest epAppRolesRequestData = epRequestIdVal.get(0);
1377 epAppRolesRequestData.setUpdatedDate(new Date());
1378 epAppRolesRequestData.setRequestStatus("O");
1379 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1380 addiotonalUpdateParam.put("userId", user.getId());
1381 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1382 epDetailParams.put("reqId", epAppRolesRequestData.getId());
1383 List<EPUserAppRolesRequestDetail> epUserAppRolesDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1384 epUserAppRolesDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1385 epDetailParams, null);
1386 if (epUserAppRolesDetailList.size() > 0) {
1387 for (EPUserAppRolesRequestDetail epRequestUpdateList : epUserAppRolesDetailList) {
1388 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateList;
1389 epAppRoleDetailData.setReqType("O");
1390 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1391 HashMap<String, Long> updateDetailsParams = new HashMap<String, Long>();
1392 addiotonalUpdateParam.put("reqId", epAppRolesRequestData.getId());
1393 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParams);
1395 logger.debug(EELFLoggerDelegate.debugLogger, "User App roles request from User Page is overridden");
1399 } catch (Exception e) {
1400 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e);
1405 * Pushes specified user details to the specified remote app.
1408 * OrgUserId identifying user at remote app in REST endpoint path
1410 * User details to be pushed
1413 * @param applicationsRestClientService
1414 * @throws HTTPException
1416 protected void postUserToRemoteApp(String userId, EPUser user, EPApp app,
1417 ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
1419 getUser(userId, app, applicationsRestClientService);
1424 * It returns user details for single org user id
1428 * if user exists it returns list of user details otherwise empty value
1430 @SuppressWarnings("unchecked")
1431 private List<EPUser> checkIfUserExists(Map<String, String> userParams){
1432 return (List<EPUser>)dataAccessService.executeNamedQuery("epUserAppId", userParams, null);
1436 * It checks whether the new user is valid or not otherwise throws exception
1441 * Checks if user is valid and returns message otherwise throws exception
1444 private String validateNewUser(String orgUserId, EPApp app) throws Exception {
1445 EPUser epUser = searchService.searchUserByUserId(orgUserId);
1446 if (epUser == null) {
1447 throw new Exception("User does not exist");
1448 } else if (!epUser.getOrgUserId().equals(orgUserId)) {
1449 throw new Exception("User does not exist");
1450 } else if (app == null) {
1451 throw new Exception("Application does not exist");
1453 return "Saved Successfully";
1457 * Checks if the fields exists or not
1460 * contains user information
1464 * throws exception if the field is not valid
1466 private void validateExternalRequestFields(List<EPUser> userList, EPApp app) throws Exception{
1467 if (userList.size() == 0 || userList.isEmpty() ) {
1468 throw new Exception("User does not exist");
1469 } else if(app == null) {
1470 throw new Exception("Application does not exist");
1471 } else if(!app.getEnabled() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1472 throw new Exception(app.getMlAppName()+" application is unavailable");
1476 @SuppressWarnings("unchecked")
1477 public ExternalRequestFieldsValidator setExternalRequestUserAppRole(ExternalSystemUser newAppRolesForUser, String reqType) {
1478 boolean result = false;
1479 boolean externalSystemRequest = true;
1480 final Map<String, Long> params = new HashMap<>();
1481 final Map<String, String> userParams = new HashMap<>();
1482 List<EPUser> userInfo = null;
1484 List<EPUserAppRolesRequest> epRequestId = null;
1485 String orgUserId = "";
1486 String updateStatus = "";
1487 String reqMessage = "";
1489 if (newAppRolesForUser != null && newAppRolesForUser.getLoginId() != null) {
1490 orgUserId = newAppRolesForUser.getLoginId().trim();
1492 String appName = newAppRolesForUser.getApplicationName();
1493 String logMessage = ("DELETE").equals(reqType) ? "Deleting": "Assigning/Updating" ;
1494 if (orgUserId.length() > 0) {
1495 ObjectMapper mapper = new ObjectMapper();
1496 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1497 int epRequestIdSize = 0;
1499 app = appsService.getAppDetail(appName);
1500 userParams.put("orgUserIdValue", orgUserId);
1501 userInfo = checkIfUserExists(userParams);
1502 reqMessage = "Updated Successfully";
1503 if (!reqType.equals("DELETE") && (userInfo.size() == 0 || userInfo.isEmpty())) {
1504 reqMessage = validateNewUser(orgUserId, app);
1506 if (userInfo.size() != 0 || !userInfo.isEmpty()) {
1507 validateExternalRequestFields(userInfo, app);
1508 user = userInfo.get(0);
1509 params.put("appId", app.getId());
1510 params.put("userId", user.getId());
1511 epRequestId = (List<EPUserAppRolesRequest>) dataAccessService
1512 .executeNamedQuery("userAppRolesRequestList", params, null);
1513 epRequestIdSize = epRequestId.size();
1516 //If Non-Centralized app make sure you sync app roles before assigning to user
1517 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !app.getCentralAuth()) {
1518 logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Starting GET roles for app {}",app.getId());
1519 EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, app.getId(), "/roles");
1520 logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Finshed GET roles for app {} and payload {}",app.getId(), appRoles);
1521 if (appRoles.length > 0) {
1522 syncAppRoles(sessionFactory, app.getId(), appRoles);
1525 List<RoleInAppForUser> roleInAppForUserList = roleInAppForUserList(newAppRolesForUser.getRoles(),
1526 app.getId(), app.getMlAppName());
1527 List<EcompUserAppRoles> userRoleList = null;
1528 if(!userInfo.isEmpty()){
1529 final Map<String, Long> appParams = new HashMap<>();
1530 appParams.put("userId", user.getId());
1531 appParams.put("appId", app.getId());
1532 userRoleList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", appParams, null);
1534 // Check if list contains just account admin role
1535 boolean checkIfAdminRoleExists = false;
1536 if (reqType.equals("DELETE") && userRoleList!=null) {
1537 checkIfAdminRoleExists = userRoleList.stream()
1538 .anyMatch(userRole -> userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1540 checkIfAdminRoleExists = roleInAppForUserList.stream()
1541 .anyMatch(roleList -> roleList.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1543 // if Centralized app
1544 if (app.getCentralAuth()) {
1545 // We should add If user does not exist in remote application
1547 // If adding just account admin role dont make remote application user call or
1548 // if request has only single non admin role then make remote call
1549 if (!(app.getId().equals(PortalConstants.PORTAL_APP_ID) && reqType.equals("DELETE"))
1550 && ((checkIfAdminRoleExists && roleInAppForUserList.size() > 1)
1551 || (!checkIfAdminRoleExists && roleInAppForUserList.size() >= 1))) {
1552 // check if admin role exist then delete
1553 List<RoleInAppForUser> remoteUserRoles = roleInAppForUserList.stream()
1554 .collect(Collectors.toList());
1555 remoteUserRoles.removeIf(role -> {
1556 return (role.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1558 String orgUserIdNewOrExist = (userInfo.size() != 0 || !userInfo.isEmpty()) ? user.getOrgUserId() : orgUserId;
1559 pushRemoteUser(remoteUserRoles, orgUserIdNewOrExist , app, mapper, searchService,
1560 applicationsRestClientService,true);
1562 } catch (Exception e) {
1563 reqMessage = e.getMessage();
1564 logger.error(EELFLoggerDelegate.errorLogger, "setExternalRequestUserAppRole: Failed to added remote user", e);
1565 throw new Exception(reqMessage);
1567 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1568 applicationsRestClientService, app.getId(), orgUserId);
1569 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1570 userRolesInLocalApp);
1571 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1572 if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1573 // Apply changes in external Access system
1574 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, externalSystemRequest,false);
1576 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
1577 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1578 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,false);
1580 // If local application is not centralized
1581 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1582 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1583 applicationsRestClientService, app.getId(), orgUserId);
1584 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1585 userRolesInLocalApp);
1586 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,false);
1587 } else {// remote app
1588 // If adding just account admin role don't do remote application user call
1589 if (!((roleInAppForUserList.size() == 1 || reqType.equals("DELETE")) && checkIfAdminRoleExists)) {
1590 EPUser remoteAppUser = null;
1591 remoteAppUser = checkIfRemoteUserExits(orgUserId, app, applicationsRestClientService);
1592 if (remoteAppUser == null) {
1593 addRemoteUser(roleInAppForUserList, orgUserId, app, mapper, searchService,
1594 applicationsRestClientService);
1595 reqMessage = "Saved Successfully";
1598 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
1599 applicationsRestClientService, app.getId(), orgUserId,false);
1601 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1602 userRolesInRemoteApp);
1603 logger.info(EELFLoggerDelegate.debugLogger,
1604 "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
1605 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1606 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1608 // If no roles remain, request app to set user inactive.
1610 * if (userRolesInRemoteApp.size() == 0) {
1611 * logger.debug(EELFLoggerDelegate.debugLogger,
1612 * "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive"
1613 * , app, orgUserId); //TODO Need to fix the logged in user is not set to
1614 * inactive remoteAppUser.setActive(false); postUserToRemoteApp(orgUserId, user,
1615 * app, applicationsRestClientService); }
1619 // Here we are adding only we have single account admin in roleInAppForUserList and this should not add in remote
1620 if(!(reqType.equals("DELETE")) && userInfo.isEmpty()){
1621 reqMessage = "Saved Successfully";
1623 Set<EcompRole> userRolesInRemoteApp = constructUsersEcompRoles(roleInAppForUserList);
1625 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1626 userRolesInRemoteApp);
1627 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}",
1628 logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1629 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1633 reqMessage = "Failed to save the user app role(s)";
1635 if (epRequestIdSize > 0 && !userInfo.isEmpty()) {
1637 applyChangesToAppRolesRequest(app.getId(), user.getId(), updateStatus, epRequestId.get(0));
1640 } catch (Exception e) {
1641 String message = String.format("setExternalRequestUserAppRole: Failed to create user or update user roles for User %s, AppId %s",
1642 orgUserId, appName);
1643 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1645 reqMessage = e.getMessage();
1646 if(epRequestIdSize > 0 && userInfo!=null && !userInfo.isEmpty()){
1648 applyChangesToAppRolesRequest(app.getId(), user.getId(),
1649 updateStatus, epRequestId.get(0));
1654 return new ExternalRequestFieldsValidator(result, reqMessage);
1659 * @param roleInAppForUserList
1661 * @param applicationsRestClientService
1664 * @return Set<EcompRole>
1665 * @throws JsonProcessingException
1666 * @throws HTTPException
1668 private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
1669 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
1670 throws JsonProcessingException, HTTPException {
1671 Set<EcompRole> updatedUserRoles = constructUsersEcompRoles(roleInAppForUserList);
1672 return updatedUserRoles;
1676 * It constructs and returns list of user app roles when the external API role approval system calls
1679 * @param roleInAppForUserList
1681 * @return list of user app roles
1683 * throws exceptions if role id does not exits
1685 private List<RoleInAppForUser> roleInAppForUserList(List<ExternalSystemRoleApproval> roleInAppForUserList,
1686 Long appId, String appName) throws Exception {
1687 List<RoleInAppForUser> existingUserRoles = new ArrayList<RoleInAppForUser>();
1688 EPRole existingAppRole = null;
1689 for (ExternalSystemRoleApproval roleInAppForUser : roleInAppForUserList) {
1690 RoleInAppForUser ecompRole = new RoleInAppForUser();
1691 existingAppRole = epRoleService.getAppRole(roleInAppForUser.getRoleName(), appId);
1692 if (existingAppRole == null) {
1693 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1694 roleInAppForUserList);
1695 throw new Exception("'" +roleInAppForUser.getRoleName() + "'" +" role does not exist for " + appName + " application");
1697 if (!existingAppRole.getActive()) {
1698 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1699 roleInAppForUserList);
1700 throw new Exception(roleInAppForUser.getRoleName() + " role is unavailable for "+ appName + " application");
1702 ecompRole.roleId = (appId == 1 || roleInAppForUser.getRoleName().equals(PortalConstants.ADMIN_ROLE)) ? existingAppRole.getId() : existingAppRole.getAppRoleId();
1703 ecompRole.roleName = roleInAppForUser.getRoleName();
1704 ecompRole.isApplied = true;
1705 existingUserRoles.add(ecompRole);
1708 return existingUserRoles;
1717 * @param applicationsRestClientService
1719 * @throws HTTPException
1721 protected EPUser getUserFromApp(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1722 throws HTTPException {
1724 if (app.getId() == PortalConstants.PORTAL_APP_ID) {
1725 // Map<String,String> params = new HashMap<String,String>();
1726 // params.put("sbcid",userId);
1727 @SuppressWarnings("unchecked")
1728 List<EPUser> userList = (List<EPUser>) dataAccessService
1729 .executeQuery("from EPUser where orgUserId='" + userId + "'", null);
1730 if (userList != null && !userList.isEmpty())
1731 return userList.get(0);
1737 return getUser(userId, app, applicationsRestClientService);
1740 protected EPUser getUser(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1741 throws HTTPException {
1742 return applicationsRestClientService.get(EPUser.class, app.getId(), String.format("/user/%s", userId), true);
1746 protected boolean isAppUpgradeVersion(EPApp app){
1751 public ExternalSystemAccess getExternalRequestAccess(){
1752 ExternalSystemAccess res = null;
1754 res = new ExternalSystemAccess(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE,
1755 Boolean.parseBoolean(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE)));
1756 } catch (Exception e) {
1757 logger.error(EELFLoggerDelegate.errorLogger, "getExternalRequestAccess failed" + e.getMessage());
1765 * @see org.onap.portalapp.portal.service.UserRolesService#
1766 * getAppRolesForUser(java.lang.Long, java.lang.String)
1768 @SuppressWarnings("unchecked")
1769 public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId, Boolean extRequestValue,EPUser user) {
1770 List<RoleInAppForUser> rolesInAppForUser = null;
1771 EPApp app = appsService.getApp(appId);
1772 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - app = {}", app);
1774 // for onap portal app, no need to make a remote call
1775 List<Role> roleList = new ArrayList<>();
1776 if (appId == PortalConstants.PORTAL_APP_ID) {
1777 if(app.getCentralAuth()){
1778 List<CentralV2Role> cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey());
1779 for(CentralV2Role cenRole : cenRoleList){
1780 Role role = new Role();
1781 role.setActive(cenRole.getActive());
1782 role.setId(cenRole.getId());
1783 role.setName(cenRole.getName());
1784 role.setPriority(cenRole.getPriority());
1788 roleList = roleService.getAvailableRoles(userId);
1790 List<Role> activeRoleList = new ArrayList<Role>();
1791 for(Role role: roleList) {
1792 if(role.getActive()) {
1793 if(role.getId() != 1){ // prevent portal admin from being added
1794 activeRoleList.add(role);
1795 } else if(extRequestValue){
1796 activeRoleList.add(role);
1801 EPUser localUser = getUserFromApp(userId, app, applicationsRestClientService);
1802 // If localUser does not exists return roles
1803 Set<EPRole> roleSet = null;
1804 EPRole[] roleSetList = null;
1805 if(localUser != null){
1806 roleSet = localUser.getAppEPRoles(app);
1807 roleSetList = roleSet.toArray(new EPRole[0]);
1809 rolesInAppForUser = constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue);
1810 return rolesInAppForUser;
1813 EcompRole[] appRoles = null;
1814 List<EcompRole> roles = new ArrayList<>();
1815 if (app.getCentralAuth()) {
1816 final Map<String, Long> appParams = new HashMap<>();
1817 appParams.put("appId", app.getId());
1818 List<EPRole> applicationRoles = dataAccessService.executeNamedQuery("getActiveRolesOfApplication",
1821 EPApp application = appService.getApp(appId);
1822 boolean checkIfUserisApplicationAccAdmin = adminRolesService.isAccountAdminOfApplication(user,
1825 List<EPRole> rolesetwithfunctioncds = new ArrayList<EPRole>();
1826 for (EPRole role : applicationRoles) {
1827 Map<String, Long> params = new HashMap<>();
1828 params.put("roleId", role.getId());
1829 params.put(APP_ID, app.getId());
1830 List<CentralV2RoleFunction> cenRoleFuncList = dataAccessService
1831 .executeNamedQuery("getAppRoleFunctionList", params, null);
1833 // SortedSet<CentralV2RoleFunction> roleFunctionSet =
1835 SortedSet<RoleFunction> roleFunctionSet = new TreeSet<>();
1836 for (CentralV2RoleFunction roleFunc : cenRoleFuncList) {
1838 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1839 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
1840 String type = externalAccessRolesService.getFunctionCodeType(roleFunc.getCode());
1841 String action = externalAccessRolesService.getFunctionCodeAction(roleFunc.getCode());
1842 String name = roleFunc.getName();
1844 RoleFunction function = new RoleFunction();
1845 function.setAction(action);
1846 function.setType(type);
1847 function.setCode(functionCode);
1848 function.setName(name);
1849 roleFunctionSet.add(function);
1850 role.setRoleFunctions(roleFunctionSet);
1853 rolesetwithfunctioncds.add(role);
1858 for (EPRole role1 : rolesetwithfunctioncds) {
1859 EcompRole ecompRole = new EcompRole();
1860 ecompRole.setId(role1.getId());
1861 ecompRole.setName(role1.getName());
1862 ecompRole.setRoleFunctions(role1.getRoleFunctions());
1863 roles.add(ecompRole);
1866 if (checkIfUserisApplicationAccAdmin) {
1867 appRoles = roles.toArray(new EcompRole[roles.size()]);
1868 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() If Logged in user checkIfUserisApplicationAccAdmin- appRoles = {}", appRoles);
1869 } else if (adminRolesService.isRoleAdmin(user) && !checkIfUserisApplicationAccAdmin) {
1870 List<EcompRole> roleAdminAppRoles = new ArrayList<>();
1871 List<String> roleAdminAppRolesNames = new ArrayList<>();
1872 final Map<String, Long> userParams = new HashMap<>();
1873 userParams.put("userId", user.getId());
1874 List<String> getUserApproverRoles = dataAccessService.executeNamedQuery("getUserApproverRoles", userParams, null);
1876 List<EcompRole> userapproverRolesList = new ArrayList<>();
1877 for (String str : getUserApproverRoles) {
1878 EcompRole epRole = roles.stream().filter(x -> str.equals(x.getName())).findAny().orElse(null);
1880 userapproverRolesList.add(epRole);
1882 // roles.removeAll(userapproverRolesList);
1883 for (EcompRole role : userapproverRolesList) {
1885 List<RoleFunction> roleFunList = new ArrayList<>();
1886 roleFunList.addAll(role.getRoleFunctions());
1887 boolean checkIfFunctionsExits = roleFunList.stream()
1888 .anyMatch(roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
1889 if (checkIfFunctionsExits) {
1890 roleAdminAppRoles.add(role);
1891 List<RoleFunction> filteredList = roleFunList.stream()
1892 .filter(x -> "Approver".equalsIgnoreCase(x.getType())).collect(Collectors.toList());
1893 roleAdminAppRolesNames.addAll(filteredList.stream().map(RoleFunction::getCode)
1894 .collect(Collectors.toList()));
1895 // roleAdminAppRolesNames = filteredList.stream().map(RoleFunction::getCode)
1896 // .collect(Collectors.toList());
1899 for (String name : roleAdminAppRolesNames) {
1900 EcompRole ecompRole = roles.stream().filter(x -> name.equals(x.getName())).findAny()
1902 if (ecompRole != null)
1903 roleAdminAppRoles.add(ecompRole);
1906 appRoles = roleAdminAppRoles.toArray(new EcompRole[roleAdminAppRoles.size()]);
1910 appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
1912 // Test this error case, for generating an internal ONAP Portal
1914 // EcompRole[] appRoles = null;
1915 // If there is an exception in the rest client api, then null will
1917 if (appRoles != null) {
1918 if(!app.getCentralAuth()) {
1919 syncAppRoles(sessionFactory, appId, appRoles);
1921 EcompRole[] userAppRoles = null;
1925 if(app.getCentralAuth()){
1926 final Map<String, String> params = new HashMap<>();
1927 final Map<String, Long> userParams = new HashMap<>();
1928 params.put("orgUserIdValue", userId);
1929 List<EPUser> actualUser = dataAccessService.executeNamedQuery("epUserAppId", params, null);
1930 userParams.put("appId", app.getId());
1931 userParams.put("userId", actualUser.get(0).getId());
1932 List<EPUserAppCurrentRoles> userAppsRolesList = dataAccessService.executeNamedQuery("getUserAppCurrentRoles", userParams, null);
1934 List<EcompRole> setUserRoles = new ArrayList<>();
1935 for(EPUserAppCurrentRoles role : userAppsRolesList){
1936 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - userAppsRolesList get userRolename = {}", role.getRoleName());
1937 EcompRole ecompRole = new EcompRole();
1938 ecompRole.setId(role.getRoleId());
1939 ecompRole.setName(role.getRoleName());
1940 setUserRoles.add(ecompRole);
1943 boolean checkIfUserisAccAdmin = setUserRoles.stream()
1944 .anyMatch(ecompRole -> ecompRole.getId() == 999L);
1946 if (!checkIfUserisAccAdmin) {
1947 List<EcompRole> userApplicationRolesList = setUserRoles;
1948 List<EcompRole> appRolesList = Arrays.asList(appRoles);
1949 Set<EcompRole> finalUserAppRolesList = new HashSet<>();
1951 List<String> roleNames = new ArrayList<>();
1952 for (EcompRole role : userApplicationRolesList) {
1953 EcompRole epRole = appRolesList.stream()
1954 .filter(x -> role.getName().equals(x.getName())).findAny().orElse(null);
1955 List<RoleFunction> roleFunList = new ArrayList<>();
1956 if(epRole.getRoleFunctions().size()>0)
1957 roleFunList.addAll(epRole.getRoleFunctions());
1958 boolean checkIfFunctionsExits = roleFunList.stream().anyMatch(
1959 roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
1960 if (checkIfFunctionsExits) {
1961 finalUserAppRolesList.add(role);
1962 List<RoleFunction> filteredList = roleFunList.stream()
1963 .filter(x -> "Approver".equalsIgnoreCase(x.getType()))
1964 .collect(Collectors.toList());
1965 roleNames = filteredList.stream().map(RoleFunction::getCode)
1966 .collect(Collectors.toList());
1969 for (String name : roleNames) {
1970 EcompRole ecompRole = appRolesList.stream()
1971 .filter(x -> name.equals(x.getName())).findAny().orElse(null);
1972 if (ecompRole != null)
1973 finalUserAppRolesList.add(ecompRole);
1978 for (String name : roleNames) {
1980 boolean checkIfFunctionsExits = userAppsRolesList.stream().anyMatch(
1981 role -> role.getRoleName().equalsIgnoreCase(name));
1982 if(checkIfFunctionsExits)
1984 EcompRole epRole = appRolesList.stream().filter(x -> name.equals(x.getName()))
1985 .findAny().orElse(null);
1987 setUserRoles.add(epRole);
1991 userAppRoles = setUserRoles.toArray(new EcompRole[setUserRoles.size()]);
1994 userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
1995 String.format("/user/%s/roles", userId));
1997 } catch (HTTPException e) {
1998 // Some apps are returning 400 if user is not found.
1999 if (e.getResponseCode() == 400) {
2000 logger.debug(EELFLoggerDelegate.debugLogger,
2001 "getAppRolesForUser caught exception with response code 400; continuing", e);
2003 // Other response code, let it come thru.
2007 if (userAppRoles == null) {
2008 if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
2009 EcompPortalUtils.setExternalAppResponseCode(200);
2010 String message = String.format(
2011 "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
2012 + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
2013 + "Overriding to 200 until framework SDK returns a useful response.",
2014 Long.toString(appId), userId);
2015 logger.warn(EELFLoggerDelegate.applicationLogger, message);
2019 HashMap<Long, EcompRole> appRolesActiveMap =hashMapFromEcompRoles(appRoles);
2020 ArrayList<EcompRole> activeRoles = new ArrayList<EcompRole>();
2021 if(userAppRoles != null){
2022 for (int i = 0; i < userAppRoles.length; i++) {
2023 if (appRolesActiveMap.containsKey(userAppRoles[i].getId())) {
2024 EcompRole role = new EcompRole();
2025 role.setId(userAppRoles[i].getId());
2026 role.setName(userAppRoles[i].getName());
2027 activeRoles.add(role);
2031 EcompRole[] userAppRolesActive = activeRoles.toArray(new EcompRole[activeRoles.size()]);
2033 // If the remote application isn't down we MUST sync user
2034 // roles here in case we have this user here!
2035 syncUserRoles(sessionFactory, userId, appId, userAppRolesActive, extRequestValue, null);
2036 } catch (Exception e) {
2037 // TODO: we may need to check if user exists, maybe remote
2039 String message = String.format(
2040 "getAppRolesForUser: user %s does not exist in remote application %s", userId,
2041 Long.toString(appId));
2042 logger.error(EELFLoggerDelegate.errorLogger, message, e);
2043 userAppRoles = new EcompRole[0];
2045 rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
2047 } catch (Exception e) {
2048 String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
2049 Long.toString(appId));
2050 logger.error(EELFLoggerDelegate.errorLogger, message, e);
2052 return rolesInAppForUser;
2055 private boolean postUserRolesToMylogins(AppWithRolesForUser userAppRolesData,
2056 ApplicationsRestClientService applicationsRestClientService, Long appId, Long userId)
2057 throws JsonProcessingException, HTTPException {
2058 boolean result = false;
2059 ObjectMapper mapper = new ObjectMapper();
2060 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
2061 String userRolesAsString = mapper.writeValueAsString(userAppRolesData);
2062 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, as the endpoint is not defined yet from the Mylogins");
2063 applicationsRestClientService.post(AppWithRolesForUser.class, appId, userRolesAsString, String.format("/user/%s/myLoginroles", userId));
2067 @SuppressWarnings("unchecked")
2068 public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser userAppRolesData, EPUser user) {
2069 FieldsValidator fieldsValidator = new FieldsValidator();
2070 final Map<String, Long> params = new HashMap<>();
2071 List<EPUserAppRoles> appRole= null;
2073 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, still the endpoint is yet to be defined");
2074 boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService,
2075 userAppRolesData.getAppId(), user.getId());
2076 logger.debug(EELFLoggerDelegate.debugLogger,"putUserAppRolesRequest: result {}", result);
2078 params.put("appId", userAppRolesData.getAppId());
2079 EPUserAppRolesRequest epAppRolesRequestData = new EPUserAppRolesRequest();
2080 epAppRolesRequestData.setCreatedDate(new Date());
2081 epAppRolesRequestData.setUpdatedDate(new Date());
2082 epAppRolesRequestData.setUserId(user.getId());
2083 epAppRolesRequestData.setAppId(userAppRolesData.getAppId());
2084 epAppRolesRequestData.setRequestStatus("P");
2085 List<RoleInAppForUser> appRoleIdList = userAppRolesData.getAppRoles();
2086 Set<EPUserAppRolesRequestDetail> appRoleDetails = new LinkedHashSet<EPUserAppRolesRequestDetail>();
2087 dataAccessService.saveDomainObject(epAppRolesRequestData, null);
2088 for (RoleInAppForUser userAppRoles : appRoleIdList) {
2089 Boolean isAppliedVal = userAppRoles.isApplied;
2090 params.put("appRoleId", userAppRoles.roleId);
2092 appRole = (List<EPUserAppRoles>) dataAccessService.executeNamedQuery("appRoles", params, null);
2093 if (!appRole.isEmpty()) {
2094 EPUserAppRolesRequestDetail epAppRoleDetail = new EPUserAppRolesRequestDetail();
2095 epAppRoleDetail.setReqRoleId(appRole.get(0).getRoleId());
2096 epAppRoleDetail.setReqType("P");
2097 epAppRoleDetail.setEpRequestIdData(epAppRolesRequestData);
2098 dataAccessService.saveDomainObject(epAppRoleDetail, null);
2102 epAppRolesRequestData.setEpRequestIdDetail(appRoleDetails);
2103 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
2105 } catch (Exception e) {
2106 logger.error(EELFLoggerDelegate.errorLogger, "putUserAppRolesRequest failed", e);
2107 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
2109 return fieldsValidator;
2112 public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(EPUser userid, String appName) {
2113 Map<String, String> params = new HashMap<>();
2114 params.put("userid", userid.getId().toString());
2115 //params.put("appid", appid);
2116 params.put("appName", appName);
2118 @SuppressWarnings("unchecked")
2119 List<EPUserAppCatalogRoles> userAppRoles = (List<EPUserAppCatalogRoles>) dataAccessService
2120 .executeNamedQuery("userAppCatalogRoles", params, null);
2121 return userAppRoles;
2124 public String updateRemoteUserProfile(String orgUserId, Long appId) {
2125 ObjectMapper mapper = new ObjectMapper();
2126 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
2127 EPUser client = searchService.searchUserByUserId(orgUserId);
2128 EPUser newUser = new EPUser();
2129 newUser.setActive(client.getActive());
2130 newUser.setFirstName(client.getFirstName());
2131 newUser.setLastName(client.getLastName());
2132 newUser.setLoginId(client.getLoginId());
2133 newUser.setLoginPwd(client.getLoginPwd());
2134 newUser.setMiddleInitial(client.getMiddleInitial());
2135 newUser.setEmail(client.getEmail());
2136 newUser.setOrgUserId(client.getLoginId());
2138 String userAsString = mapper.writeValueAsString(newUser);
2139 List<EPApp> appList = appsService.getUserRemoteApps(client.getId().toString());
2140 // applicationsRestClientService.post(EPUser.class, appId,
2141 // userAsString, String.format("/user", orgUserId));
2142 for (EPApp eachApp : appList) {
2144 applicationsRestClientService.post(EPUser.class, eachApp.getId(), userAsString,
2145 String.format("/user/%s", orgUserId));
2146 } catch (Exception e) {
2147 logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId()
2148 + " in remote app. appId = " + eachApp.getId());
2151 } catch (Exception e) {
2152 logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
2163 * @see org.onap.portalapp.portal.service.UserRolesService#
2164 * getCachedAppRolesForUser(java.lang.Long, java.lang.Long)
2166 @SuppressWarnings("deprecation")
2167 public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId) {
2168 // Find the records for this user-app combo, if any
2169 String filter = " where user_id = " + Long.toString(userId) + " and app_id = " + Long.toString(appId);
2170 @SuppressWarnings("unchecked")
2171 List<EPUserApp> roleList = dataAccessService.getList(EPUserApp.class, filter, null, null);
2172 logger.debug(EELFLoggerDelegate.debugLogger, "getCachedAppRolesForUser: list size is {}", roleList.size());
2177 * It retrieves and returns list of user app roles for local and remote applications based app id
2180 * @return list of user app roles
2181 * @throws HTTPException
2183 public List<UserApplicationRoles> getUsersFromAppEndpoint(Long appId) throws HTTPException {
2184 ArrayList<UserApplicationRoles> userApplicationRoles = new ArrayList<UserApplicationRoles>();
2186 EPApp app = appsService.getApp(appId);
2187 //If local or centralized application
2188 if (appId == PortalConstants.PORTAL_APP_ID || app.getCentralAuth()) {
2189 @SuppressWarnings("unchecked")
2190 List<EPUser> userList = (List<EPUser>) dataAccessService.executeNamedQuery("getActiveUsers", null, null);
2191 for (EPUser user : userList) {
2192 UserApplicationRoles userWithAppRoles = convertToUserApplicationRoles(appId, user, app);
2193 if (userWithAppRoles.getRoles() != null && userWithAppRoles.getRoles().size() > 0)
2194 userApplicationRoles.add(userWithAppRoles);
2200 RemoteUserWithRoles[] remoteUsers = null;
2201 String remoteUsersString = applicationsRestClientService.getIncomingJsonString(appId, "/users");
2203 remoteUsers = doGetUsers(isAppUpgradeVersion(app), remoteUsersString);
2205 userApplicationRoles = new ArrayList<UserApplicationRoles>();
2206 for (RemoteUserWithRoles remoteUser : remoteUsers) {
2207 UserApplicationRoles userWithRemoteAppRoles = convertToUserApplicationRoles(appId, remoteUser);
2208 if (userWithRemoteAppRoles.getRoles() != null && userWithRemoteAppRoles.getRoles().size() > 0) {
2209 userApplicationRoles.add(userWithRemoteAppRoles);
2211 logger.debug(EELFLoggerDelegate.debugLogger,
2212 "User " + userWithRemoteAppRoles.getOrgUserId() + " doesn't have any roles assigned to any app.");
2217 return userApplicationRoles;
2224 * @param appgetUsersFromAppEndpoint
2227 private UserApplicationRoles convertToUserApplicationRoles(Long appId, EPUser user, EPApp app) {
2228 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
2229 userWithRemoteAppRoles.setAppId(appId);
2230 userWithRemoteAppRoles.setOrgUserId(user.getOrgUserId());
2231 userWithRemoteAppRoles.setFirstName(user.getFirstName());
2232 userWithRemoteAppRoles.setLastName(user.getLastName());
2233 userWithRemoteAppRoles.setRoles(convertToRemoteRoleList(user, app));
2234 return userWithRemoteAppRoles;
2243 @SuppressWarnings("unchecked")
2244 private List<RemoteRole> convertToRemoteRoleList(EPUser user, EPApp app) {
2245 List<RemoteRole> roleList = new ArrayList<RemoteRole>();
2246 SortedSet<EPRole> roleSet = user.getAppEPRoles(app);
2247 for (EPRole role : roleSet) {
2248 logger.debug(EELFLoggerDelegate.debugLogger, "In convertToRemoteRoleList() - for user {}, found Name {}", user.getOrgUserId(), role.getName());
2249 RemoteRole rRole = new RemoteRole();
2250 rRole.setId(role.getId());
2251 rRole.setName(role.getName());
2252 roleList.add(rRole);
2255 //Get the active roles of user for that application using query
2256 List<EPRole> userEpRoleList = new ArrayList<>();
2257 final Map<String, Long> params = new HashMap<>();
2258 params.put("appId", app.getId());
2259 params.put("userId", user.getId());
2260 userEpRoleList = dataAccessService.executeNamedQuery("getUserRoleOnUserIdAndAppId", params, null);
2262 for (EPRole remoteUserRoleList : userEpRoleList) {
2264 RemoteRole remoteRoleListId = roleList.stream().filter(x -> remoteUserRoleList.getId().equals(x.getId()))
2265 .findAny().orElse(null);
2266 if (remoteRoleListId == null) {
2267 logger.debug(EELFLoggerDelegate.debugLogger,
2268 "Adding the role to the rolelist () - for user {}, found Name {}", user.getOrgUserId(),
2270 remoteUserRoleList.getName());
2271 RemoteRole role = new RemoteRole();
2272 role.setId(remoteUserRoleList.getId());
2273 role.setName(remoteUserRoleList.getName());
2280 logger.debug(EELFLoggerDelegate.debugLogger, "rolelist size of the USER() - for user {}, found RoleListSize {}", user.getOrgUserId(), roleList.size());
2288 public RemoteUserWithRoles[] doGetUsers(boolean postOpenSource, String remoteUsersString) {
2290 ObjectMapper mapper = new ObjectMapper();
2292 return mapper.readValue(remoteUsersString, RemoteUserWithRoles[].class);
2293 } catch (IOException e) {
2294 logger.error(EELFLoggerDelegate.errorLogger,
2295 "doGetUsers : Failed : Unexpected property in incoming JSON",
2297 logger.error(EELFLoggerDelegate.errorLogger,
2298 "doGetUsers : Incoming JSON that caused it --> " + remoteUsersString);
2301 return new RemoteUserWithRoles[0];
2304 @SuppressWarnings("unchecked")
2305 public List<EPUserApp> getEPUserAppList(Long appId, Long userId, Long roleId) {
2306 List<EPUserApp> userRoleList = new ArrayList<EPUserApp>();
2307 final Map<String, Long> params = new HashMap<>();
2308 params.put("appId", appId);
2309 params.put("userId", userId);
2310 params.put("roleId", roleId);
2311 userRoleList = dataAccessService.executeNamedQuery("getUserRoleOnUserIdAndRoleIdAndAppId", params, null);
2312 return userRoleList;
2316 /*public static void main(String[] args) {
2317 List<EcompRole> str1 = new ArrayList<String>();
2323 List<String> str2 = new ArrayList<String>();
2327 List<EcompRole> userApplicationRolesList = setUserRoles;
2328 List<EcompRole> appRolesList = Arrays.asList(appRoles);