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 :name where app.id=:appId :roleActive and userId=:userId")
295 .setParameter("name",EPUserApp.class.getName())
296 .setParameter("appId",appId)
297 .setParameter("roleActive",roleActive)
298 .setParameter("userId",client.getId())
301 if ("DELETE".equals(reqType)) {
302 for (EPUserApp userAppRoleList : userRoles) {
303 userAppParams.put("roleName", String.valueOf(userAppRoleList.getRole().getName()));
304 userAppParams.put("appId", String.valueOf(appId));
305 appParams.put("appRoleName", userAppRoleList.getRole().getName());
306 @SuppressWarnings("unchecked")
307 List<EPRole> rolesList = (!userAppRoleList.getRole().getName().equals(PortalConstants.ADMIN_ROLE)) ? (List<EPRole>) dataAccessService.executeNamedQuery("getAppRoles", userAppParams, null) : (List<EPRole>) dataAccessService.executeNamedQuery("getPortalAppRoles", appParams, null);
308 if(rolesList.size() > 0 || !rolesList.isEmpty()){
309 checkIfRoleInactive(rolesList.get(0));
314 for (EPUserApp userRole : userRoles) {
315 if (!userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && userRole.getRoleId() != PortalConstants.SYS_ADMIN_ROLE_ID && !extRequestValue){
316 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
318 else if (extRequestValue && ("PUT".equals(reqType) || "POST".equals(reqType) || "DELETE".equals(reqType))){
319 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
321 else if (extRequestValue && !userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)){
322 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
325 Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values();
326 if (newRolesToAdd.size() > 0) {
327 EPApp app = (EPApp) localSession.get(EPApp.class, appId);
329 HashMap<Long, EPRole> rolesMap = new HashMap<Long, EPRole>();
330 if (appId.equals(PortalConstants.PORTAL_APP_ID)) { // local app
331 String appIdValue = "";
332 if(!extRequestValue){
333 appIdValue = "and id != " + PortalConstants.SYS_ADMIN_ROLE_ID;
335 @SuppressWarnings("unchecked")
336 List<EPRole> roles = localSession
337 .createQuery("from " + EPRole.class.getName() + " where appId is null " + appIdValue).list();
338 for (EPRole role : roles) {
340 rolesMap.put(role.getId(), role);
342 } else { // remote app
343 @SuppressWarnings("unchecked")
344 List<EPRole> roles = localSession
345 .createQuery("from :name where appId=:appId")
346 .setParameter("name",EPRole.class.getName())
347 .setParameter("appId",appId)
349 for (EPRole role : roles) {
350 if (!extRequestValue && app.getCentralAuth()) {
351 rolesMap.put(role.getId(), role);
353 rolesMap.put(role.getAppRoleId(), role);
359 for (EcompRole userRole : newRolesToAdd) {
360 EPUserApp userApp = new EPUserApp();
361 if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName().equals(PortalConstants.ADMIN_ROLE)) {
362 role = (EPRole) localSession.get(EPRole.class, new Long(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
363 userApp.setRole(role);
364 } else if ((userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) && !extRequestValue){
366 }else if((userRole.getId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)) && app.getId().equals(PortalConstants.PORTAL_APP_ID) && !extRequestValue){
370 userApp.setRole(rolesMap.get(userRole.getId()));
373 userApp.setUserId(client.getId());
375 localSession.save(userApp);
376 localSession.flush();
379 if (appId == PortalConstants.PORTAL_APP_ID) {
381 * for local app -- hack - always make sure fn_role
382 * table's app_id is null and not 1 for primary app in
383 * this case being onap portal app; reason: hibernate
384 * is rightly setting this to 1 while persisting to
385 * fn_role as per the mapping but SDK role management
386 * code expects the app_id to be null as there is no
387 * concept of App_id in SDK
389 localSession.flush();
390 SQLQuery sqlQuery = localSession
391 .createSQLQuery("update fn_role set app_id = null where app_id = 1 ");
392 sqlQuery.executeUpdate();
397 transaction.commit();
398 } catch (Exception e) {
399 logger.error(EELFLoggerDelegate.errorLogger, "syncUserRoles failed", e);
400 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
401 EcompPortalUtils.rollbackTransaction(transaction,
402 "Exception occurred in syncUserRoles, Details: " + e.toString());
403 if("DELETE".equals(reqType)){
404 throw new SyncUserRolesException(e.getMessage());
407 if(localSession != null)
408 localSession.close();
413 * Called when getting the list of roles for the user
416 * @param userAppRoles
417 * @return List<RoleInAppForUser>
419 protected List<RoleInAppForUser> constructRolesInAppForUserGet(EcompRole[] appRoles, EcompRole[] userAppRoles) {
420 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
422 Set<Long> userAppRolesMap = new HashSet<Long>();
423 if (userAppRoles != null) {
424 for (EcompRole ecompRole : userAppRoles) {
425 userAppRolesMap.add(ecompRole.getId());
428 logger.error(EELFLoggerDelegate.errorLogger,
429 "constructRolesInAppForUserGet has received userAppRoles list empty");
432 if (appRoles != null) {
433 for (EcompRole ecompRole : appRoles) {
434 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
435 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
436 rolesInAppForUser.add(roleForUser);
439 logger.error(EELFLoggerDelegate.errorLogger, "constructRolesInAppForUser has received appRoles list empty");
441 return rolesInAppForUser;
445 * Called when getting the list of roles for the user
448 * @param userAppRoles
449 * @param extRequestValue
450 * set to false if request is from users page otherwise true
451 * @return List<RoleInAppForUser>
453 protected List<RoleInAppForUser> constructRolesInAppForUserGet(List<Role> appRoles, EPRole[] userAppRoles, Boolean extRequestValue) {
454 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
456 Set<Long> userAppRolesMap = new HashSet<Long>();
457 if (userAppRoles != null) {
458 for (EPRole ecompRole : userAppRoles) {
459 userAppRolesMap.add(ecompRole.getId());
461 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - userAppRolesMap = {}", userAppRolesMap);
464 logger.error(EELFLoggerDelegate.errorLogger,
465 "constructRolesInAppForUserGet has received userAppRoles list empty.");
468 if (appRoles != null) {
470 for (Role ecompRole : appRoles) {
471 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - appRoles not null = {}", ecompRole);
473 if (ecompRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && !extRequestValue)
475 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
476 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
477 rolesInAppForUser.add(roleForUser);
478 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - rolesInAppForUser = {}", rolesInAppForUser);
482 logger.error(EELFLoggerDelegate.errorLogger,
483 "constructRolesInAppForUser has received appRoles list empty.");
485 return rolesInAppForUser;
490 * copies of methods in GetAppsWithUserRoleState
492 * @param sessionFactory
497 protected void syncAppRoles(SessionFactory sessionFactory, Long appId, EcompRole[] appRoles) throws Exception {
498 logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId);
499 HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles);
500 Session localSession = null;
501 Transaction transaction = null;
504 localSession = sessionFactory.openSession();
505 transaction = localSession.beginTransaction();
506 // Attention! All roles from remote application supposed to be
509 @SuppressWarnings("unchecked")
510 List<EPRole> currentAppRoles = localSession.createQuery("from :name where appId = :appId")
511 .setParameter("name",EPRole.class.getName())
512 .setParameter("appId",appId)
515 List<EPRole> obsoleteRoles = new ArrayList<EPRole>();
516 for (int i = 0; i < currentAppRoles.size(); i++) {
517 EPRole oldAppRole = currentAppRoles.get(i);
518 if (oldAppRole.getAppRoleId() != null) {
519 EcompRole role = null;
520 role = newRolesMap.get(oldAppRole.getAppRoleId());
522 if (!(role.getName() == null || oldAppRole.getName().equals(role.getName()))) {
523 oldAppRole.setName(role.getName());
524 localSession.update(oldAppRole);
526 oldAppRole.setActive(true);
527 newRolesMap.remove(oldAppRole.getAppRoleId());
529 obsoleteRoles.add(oldAppRole);
532 obsoleteRoles.add(oldAppRole);
535 Collection<EcompRole> newRolesToAdd = newRolesMap.values();
536 if (obsoleteRoles.size() > 0) {
537 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: we have obsolete roles to delete");
538 for (EPRole role : obsoleteRoles) {
539 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: obsolete role: " + role.toString());
540 Long roleId = role.getId();
541 // delete obsolete roles here
542 // Must delete all records with foreign key constraints on
544 // fn_user_role, fn_role_composite, fn_role_function,
545 // fn_user_pseudo_role, fn_menu_functional_roles.
546 // And for fn_menu_functional, if no other roles for that
547 // menu item, remove the url.
549 // Delete from fn_user_role
550 @SuppressWarnings("unchecked")
551 List<EPUserApp> userRoles = localSession.createQuery(
552 "from :name where app.id=:appId and role_id=:roleId")
553 .setParameter("name",EPUserApp.class.getName())
554 .setParameter("appId",appId)
555 .setParameter("roleId",roleId)
558 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: number of userRoles to delete: " + userRoles.size());
559 for (EPUserApp userRole : userRoles) {
560 logger.debug(EELFLoggerDelegate.debugLogger,
561 "syncAppRoles: about to delete userRole: " + userRole.toString());
562 localSession.delete(userRole);
563 logger.debug(EELFLoggerDelegate.debugLogger,
564 "syncAppRoles: finished deleting userRole: " + userRole.toString());
567 // Delete from fn_menu_functional_roles
568 @SuppressWarnings("unchecked")
569 List<FunctionalMenuRole> funcMenuRoles = localSession
570 .createQuery("from :name where roleId=:roleId")
571 .setParameter("name",FunctionalMenuRole.class.getName())
572 .setParameter("roleId",roleId)
574 int numMenuRoles = funcMenuRoles.size();
575 logger.debug(EELFLoggerDelegate.debugLogger,
576 "syncAppRoles: number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles);
577 for (FunctionalMenuRole funcMenuRole : funcMenuRoles) {
578 Long menuId = funcMenuRole.menuId;
579 // If this is the only role for this menu item, then the
580 // app and roles will be gone,
581 // so must null out the url too, to be consistent
582 @SuppressWarnings("unchecked")
583 List<FunctionalMenuRole> funcMenuRoles2 = localSession
584 .createQuery("from :name where menuId=:menuId")
585 .setParameter("name",FunctionalMenuRole.class.getName())
586 .setParameter("menuId",menuId)
588 int numMenuRoles2 = funcMenuRoles2.size();
589 logger.debug(EELFLoggerDelegate.debugLogger,
590 "syncAppRoles: number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2);
591 localSession.delete(funcMenuRole);
592 if (numMenuRoles2 == 1) {
593 // If this is the only role for this menu item, then
594 // the app and roles will be gone,
595 // so must null out the url too, to be consistent
596 logger.debug(EELFLoggerDelegate.debugLogger,
597 "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url");
598 @SuppressWarnings("unchecked")
599 List<FunctionalMenuItem> funcMenuItems = localSession
601 "from " + FunctionalMenuItem.class.getName() + " where menuId=" + menuId)
603 if (funcMenuItems.size() > 0) {
604 logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item");
605 FunctionalMenuItem funcMenuItem = funcMenuItems.get(0);
606 funcMenuItem.url = "";
607 localSession.update(funcMenuItem);
611 boolean isPortalRequest = true;
612 externalAccessRolesService.deleteRoleDependencyRecords(localSession, roleId, appId, isPortalRequest);
613 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to delete the role: " + role.toString());
614 localSession.delete(role);
615 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: deleted the role");
618 for (EcompRole role : newRolesToAdd) {
619 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to add missing role: " + role.toString());
620 EPRole newRole = new EPRole();
621 // Attention! All roles from remote application supposed to be
623 newRole.setActive(true);
624 newRole.setName(role.getName());
625 newRole.setAppId(appId);
626 newRole.setAppRoleId(role.getId());
627 localSession.save(newRole);
629 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to commit the transaction");
630 transaction.commit();
631 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: committed the transaction");
632 } catch (Exception e) {
633 logger.error(EELFLoggerDelegate.errorLogger, "syncAppRoles failed", e);
634 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
635 EcompPortalUtils.rollbackTransaction(transaction,
636 "Exception occurred in syncAppRoles, Details: " + e.toString());
637 throw new Exception(e);
639 localSession.close();
648 * Called when updating the list of roles for the user
652 * @param userRolesInRemoteApp
653 * @return RolesInAppForUser
655 protected RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId,
656 Set<EcompRole> userRolesInRemoteApp) {
657 RolesInAppForUser result;
658 result = new RolesInAppForUser();
659 result.appId = appId;
660 result.orgUserId = userId;
662 for (EcompRole role : userRolesInRemoteApp) {
663 RoleInAppForUser roleInAppForUser = new RoleInAppForUser();
664 roleInAppForUser.roleId = role.getId();
665 roleInAppForUser.roleName = role.getName();
666 roleInAppForUser.isApplied = new Boolean(true);
667 result.roles.add(roleInAppForUser);
674 * @param roleInAppForUserList
677 protected boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) {
678 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
679 if (roleInAppForUser.isApplied.booleanValue()) {
687 * Builds JSON and posts it to a remote application to update user roles.
689 * @param roleInAppForUserList
691 * @param applicationsRestClientService
694 * @return Set of roles as sent; NOT the response from the app.
695 * @throws JsonProcessingException
696 * @throws HTTPException
698 protected Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
699 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId,boolean systemUser)
700 throws JsonProcessingException, HTTPException {
701 Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList);
702 Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList);
703 String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote);
704 EPApp externalApp = null;
705 SystemType type = SystemType.APPLICATION;
706 externalApp = appsCacheService.getApp(appId);
707 String appBaseUri = null;
708 Set<RemoteRoleV1> updatedUserRolesinRemoteV1 = new TreeSet<>();
709 if (externalApp != null) {
710 appBaseUri = (type == SystemType.APPLICATION) ? externalApp.getAppRestEndpoint() : "";
712 if(appBaseUri != null && appBaseUri.endsWith("/api")){
713 for(EcompRole eprole :updatedUserRolesinRemote)
715 RemoteRoleV1 role = new RemoteRoleV1();
716 role.setId(eprole.getId());
717 role.setName(eprole.getName());
718 updatedUserRolesinRemoteV1.add(role);
720 userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemoteV1);
722 applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString,
723 String.format("/user/%s/roles", userId));
724 // TODO: We should add code that verifies that the post operation did
725 // succeed. Because the SDK may still return 200 OK with an html page
726 // even when it fails!
727 return updateUserRolesInEcomp;
732 * @param roleInAppForUserList
733 * @return Set<EcompRole>
735 protected Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) {
736 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
737 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
738 if (roleInAppForUser.isApplied) {
739 EcompRole ecompRole = new EcompRole();
740 ecompRole.setId(roleInAppForUser.roleId);
741 ecompRole.setName(roleInAppForUser.roleName);
742 existingUserRoles.add(ecompRole);
745 return existingUserRoles;
749 * Constructs user app roles excluding Account Administrator role
751 * @param roleInAppForUserList
753 * List of roles with Role name, Role Id
755 protected Set<EcompRole> constructUsersRemoteAppRoles(List<RoleInAppForUser> roleInAppForUserList) {
756 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
757 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
758 if (roleInAppForUser.isApplied && !roleInAppForUser.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
759 EcompRole ecompRole = new EcompRole();
760 ecompRole.setId(roleInAppForUser.roleId);
761 ecompRole.setName(roleInAppForUser.roleName);
762 existingUserRoles.add(ecompRole);
765 return existingUserRoles;
769 * This is for a single app
771 * @param rolesInAppForUser
772 * @param externalSystemRequest
773 * set to false if requests from Users page otherwise true
774 * @return true on success, false otherwise
776 protected boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser, boolean externalSystemRequest, String reqType,boolean isSystemUser) throws Exception {
777 boolean result = false;
778 String userId = rolesInAppForUser.orgUserId;
779 Long appId = rolesInAppForUser.appId;
780 synchronized (syncRests) {
781 if (rolesInAppForUser != null) {
782 createLocalUserIfNecessary(userId, isSystemUser);
785 if (rolesInAppForUser != null) {
786 EcompRole[] userAppRoles = new EcompRole[rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size()];
787 for (int i = 0; i < rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size(); i++) {
788 RoleInAppForUser roleInAppForUser = rolesInAppForUser.roles.get(i);
789 EcompRole role = new EcompRole();
790 role.setId(roleInAppForUser.roleId);
791 role.setName(roleInAppForUser.roleName);
792 userAppRoles[i] = role;
795 syncUserRoles(sessionFactory, userId, appId, userAppRoles, externalSystemRequest, reqType);
797 } catch (Exception e) {
798 logger.error(EELFLoggerDelegate.errorLogger,
799 "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for orgUserId " + userId, e);
800 if("DELETE".equals(reqType)){
801 throw new Exception(e.getMessage());
813 * @return UserApplicationRoles
815 protected UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) {
816 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
817 userWithRemoteAppRoles.setAppId(appId);
818 userWithRemoteAppRoles.setOrgUserId(remoteUser.getOrgUserId());
819 userWithRemoteAppRoles.setFirstName(remoteUser.getFirstName());
820 userWithRemoteAppRoles.setLastName(remoteUser.getLastName());
821 userWithRemoteAppRoles.setRoles(remoteUser.getRoles());
822 return userWithRemoteAppRoles;
828 * @see org.onap.portalapp.portal.service.UserRolesService#
829 * importRolesFromRemoteApplication(java.lang.Long)
831 public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException {
832 EPRole[] appRolesFull = applicationsRestClientService.get(EPRole[].class, appId, "/rolesFull");
833 List<EPRole> rolesList = Arrays.asList(appRolesFull);
834 for (EPRole externalAppRole : rolesList) {
836 // Try to find an existing extern role for the app in the local
837 // onap DB. If so, then use its id to update the existing external
838 // application role record.
839 Long externAppId = externalAppRole.getId();
840 EPRole existingAppRole = epRoleService.getRole(appId, externAppId);
841 if (existingAppRole != null) {
842 logger.debug(EELFLoggerDelegate.debugLogger,
843 String.format("ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.",
844 appId, externAppId));
847 // persistExternalRoleInEcompDb(externalAppRole, appId,
855 * It adds new user for remote application
857 * @param roleInAppForUserList
858 * @param remoteAppUser
862 * @param searchService
863 * @param applicationsRestClientService
867 private EPUser addRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app,
868 ObjectMapper mapper, SearchService searchService,
869 ApplicationsRestClientService applicationsRestClientService) throws Exception {
870 EPUser addRemoteUser = null;
871 if (remoteUserShouldBeCreated(roleInAppForUserList)) {
872 createNewUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper,
873 isAppUpgradeVersion(app));
875 return addRemoteUser;
878 private EPUser pushRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app,
879 ObjectMapper mapper, SearchService searchService,
880 ApplicationsRestClientService applicationsRestClientService,boolean appRoleIdUsed) throws Exception {
881 EPUser addRemoteUser = null;
882 // if (remoteUserShouldBeCreated(roleInAppForUserList)) {
883 pushUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper,
884 isAppUpgradeVersion(app), roleInAppForUserList, appRoleIdUsed);
886 return addRemoteUser;
889 @SuppressWarnings("unchecked")
890 protected void pushUserOnRemoteApp(String userId, EPApp app,
891 ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
892 ObjectMapper mapper, boolean postOpenSource, List<RoleInAppForUser> roleInAppForUserList,boolean appRoleIdUsed) throws Exception {
894 EPUser client = null;
895 client = searchService.searchUserByUserId(userId);
897 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
898 if (client == null) {
899 String msg = "cannot create user " + userId + ", because he/she cannot be found in directory.";
900 logger.error(EELFLoggerDelegate.errorLogger, msg);
901 // throw new Exception(msg);
902 final Map<String, String> loginIdParams = new HashMap<>();
903 loginIdParams.put("orgUserIdValue", userId);
904 List<EPUser> userList = new ArrayList<>();
905 userList = dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null);
906 if (userList.size() > 0) {
907 logger.debug(EELFLoggerDelegate.debugLogger,
908 userList.get(0).getOrgUserId() + " User was found in Portal");
909 client = userList.get(0);
910 SortedSet<EPUserApp> userApps = new TreeSet<>();
911 client.setEPUserApps(userApps);
912 client.setSystemUser(false);
914 logger.error(EELFLoggerDelegate.errorLogger, "user cannot be found be in directory or in portal");
915 throw new Exception(msg);
920 client.setLoginId(userId);
921 client.setActive(true);
922 client.setOrgUserId(userId);
925 roleInAppForUserList.removeIf(role -> role.isApplied.equals(false));
926 SortedSet<Role> roles = new TreeSet<>();
928 List<EPRole> getAppRoles = externalAccessRolesService.getAppRoles(app.getId());
929 List<EPApp> appList = new ArrayList<>();
931 List<CentralV2Role> roleList = new ArrayList<>();
932 Map<String, Long> params = new HashMap<>();
934 List<EPRole> userRoles = new ArrayList<>();
936 for (RoleInAppForUser roleInappForUser : roleInAppForUserList) {
937 EPRole role = new EPRole();
938 role.setId(roleInappForUser.getRoleId());
939 role.setName(roleInappForUser.getRoleName());
944 List<EPRole> userAppRoles = new ArrayList<>();
945 for (EPRole role : userRoles) {
946 EPRole appRole = getAppRoles.stream()
947 .filter(applicationRole -> role.getId().equals(applicationRole.getAppRoleId())).findAny()
949 EPRole epRole = new EPRole();
950 if (appRole != null) {
951 epRole.setId(appRole.getId());
952 epRole.setName(appRole.getName());
954 userAppRoles.add(epRole);
956 userRoles = new ArrayList<>();
957 userRoles.addAll(userAppRoles);
959 roleList = externalAccessRolesService.createCentralRoleObject(appList, userRoles, roleList, params);
961 for (CentralV2Role epRole : roleList) {
962 Role role = new Role();
963 EPRole appRole = getAppRoles.stream()
964 .filter(applicationRole -> epRole.getId().equals(applicationRole.getId())).findAny().orElse(null);
965 if (appRole != null){
966 role.setId(appRole.getAppRoleId());
967 role.setName(epRole.getName());
968 role.setRoleFunctions(epRole.getRoleFunctions());
972 client.setRoles(roles);
973 String userInString = null;
974 userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
975 logger.debug(EELFLoggerDelegate.debugLogger,
976 "about to post a client to remote application, users json = " + userInString);
977 applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user/%s", userId));
981 * It checks whether the remote user exists or not
982 * if exits returns user object else null
986 * @param applicationsRestClientService
988 * @throws HTTPException
990 private EPUser checkIfRemoteUserExits(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService) throws HTTPException{
991 EPUser checkRemoteUser = null;
993 checkRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
994 } catch (HTTPException e) {
995 // Some apps are returning 400 if user is not found.
996 if (e.getResponseCode() == 400) {
997 logger.debug(EELFLoggerDelegate.debugLogger,
998 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing",
1000 } else if(e.getResponseCode() == 404) {
1001 logger.debug(EELFLoggerDelegate.debugLogger,
1002 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 404; continuing",
1005 // Other response code, let it come thru.
1009 return checkRemoteUser;
1016 * @see org.onap.portalapp.portal.service.UserRolesService#
1017 * setAppWithUserRoleStateForUser(org.onap.portalapp.portal.domain.
1018 * EPUser, org.onap.portalapp.portal.transport.AppWithRolesForUser)
1020 public ExternalRequestFieldsValidator setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser) {
1021 boolean result = false;
1022 boolean epRequestValue = false;
1024 String reqMessage = "";
1025 if (newAppRolesForUser != null && newAppRolesForUser.getOrgUserId() != null) {
1026 userId = newAppRolesForUser.getOrgUserId().trim();
1028 Long appId = newAppRolesForUser.getAppId();
1029 List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.getAppRoles();
1030 if (userId.length() > 0 ) {
1031 ObjectMapper mapper = new ObjectMapper();
1032 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1035 EPApp app = appsService.getApp(appId);
1036 applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
1038 boolean systemUser = newAppRolesForUser.isSystemUser();
1039 if ((app.getCentralAuth() || app.getId().equals(PortalConstants.PORTAL_APP_ID)) && systemUser) {
1041 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1042 applicationsRestClientService, appId, userId);
1043 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1044 userRolesInLocalApp);
1045 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1046 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1047 // Apply changes in external Access system
1048 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList,
1049 epRequestValue, systemUser);
1051 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal",
1054 }else if (!app.getCentralAuth() && systemUser)
1056 throw new Exception("For non-centralized application we cannot add systemUser");
1058 else{ // if centralized app
1059 if (app.getCentralAuth()) {
1060 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1061 pushRemoteUser(roleInAppForUserList, userId, app, mapper, searchService,
1062 applicationsRestClientService,false);
1065 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1066 applicationsRestClientService, appId, userId);
1067 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1068 userRolesInLocalApp);
1069 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1070 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1071 // Apply changes in external Access system
1072 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList,
1073 epRequestValue,false);
1075 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal", systemUser);
1077 // In case if portal is not centralized then follow existing approach
1078 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1079 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1080 applicationsRestClientService, appId, userId);
1081 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1082 userRolesInLocalApp);
1083 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal",false);
1084 } else{// remote app
1085 EPUser remoteAppUser = null;
1086 if(!app.getCentralAuth() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1088 remoteAppUser = checkIfRemoteUserExits(userId, app, applicationsRestClientService);
1090 if (remoteAppUser == null) {
1091 remoteAppUser = addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService, applicationsRestClientService);
1093 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
1094 applicationsRestClientService, appId, userId,systemUser);
1095 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1096 userRolesInRemoteApp);
1097 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null,false);
1099 // If no roles remain, request app to set user inactive.
1100 if (userRolesInRemoteApp.size() == 0) {
1101 logger.debug(EELFLoggerDelegate.debugLogger,
1102 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
1104 //remoteAppUser.setActive(false);
1105 postUserToRemoteApp(userId, user, app, applicationsRestClientService);
1110 } catch (Exception 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);
1117 String message = String.format(
1118 "Failed to create user or update user roles for User %s, AppId %s",
1119 userId, Long.toString(appId));
1120 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1122 reqMessage = e.getMessage();
1129 return new ExternalRequestFieldsValidator(result, reqMessage);
1133 * It adds user roles in External system and also make data consistent in both local and in External System
1135 * @param app details
1137 * @param roleInAppUser Contains list of active roles
1139 @SuppressWarnings("unchecked")
1140 private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser, boolean isPortalRequest,boolean isSystemUser) throws Exception
1143 // check if user exists
1144 final Map<String, String> userParams = new HashMap<>();
1145 userParams.put("orgUserIdValue", orgUserId);
1146 List<EPUser> userInfo = checkIfUserExists(userParams);
1147 if (userInfo.isEmpty()) {
1148 createLocalUserIfNecessary(orgUserId, isSystemUser);
1151 if (EPCommonSystemProperties
1152 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN) && !isSystemUser) {
1154 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
1158 ObjectMapper mapper = new ObjectMapper();
1159 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1160 HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
1161 ResponseEntity<String> getResponse = externalAccessRolesService.getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
1162 List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
1163 String res = getResponse.getBody();
1164 JSONObject jsonObj = null;
1165 JSONArray extRoles = null;
1166 if (!res.equals("{}")) {
1167 jsonObj = new JSONObject(res);
1168 extRoles = jsonObj.getJSONArray("role");
1170 ExternalAccessUserRoleDetail userRoleDetail = null;
1171 if (extRoles != null) {
1172 for (int i = 0; i < extRoles.length(); i++) {
1173 if (extRoles.getJSONObject(i).getString("name").startsWith(app.getNameSpace() + ".")
1174 && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".admin")
1175 && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".owner")) {
1176 if (extRoles.getJSONObject(i).has("description")) {
1177 ExternalRoleDescription desc = new ExternalRoleDescription(extRoles.getJSONObject(i).getString("description"));
1178 userRoleDetail = new ExternalAccessUserRoleDetail(
1179 extRoles.getJSONObject(i).getString("name"), desc);
1180 userRoleDetailList.add(userRoleDetail);
1182 userRoleDetail = new ExternalAccessUserRoleDetail(
1183 extRoles.getJSONObject(i).getString("name"), null);
1184 userRoleDetailList.add(userRoleDetail);
1191 List<ExternalAccessUserRoleDetail> userRoleListMatchingInExtAuthAndLocal = CheckIfRoleAreMatchingInUserRoleDetailList(userRoleDetailList,app);
1193 // If request coming from portal not from external role approval system then we have to check if user already
1194 // have account admin or system admin as GUI will not send these roles
1195 if (!isPortalRequest) {
1196 final Map<String, String> loginIdParams = new HashMap<>();
1197 loginIdParams.put("orgUserIdValue", orgUserId);
1198 EPUser user = (EPUser) dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null).get(0);
1199 final Map<String, Long> params = new HashMap<>();
1200 params.put("appId", app.getId());
1201 params.put("userId", user.getId());
1202 List<EcompUserAppRoles> userAppList = dataAccessService.executeNamedQuery("getUserAppExistingRoles",
1204 if (!roleInAppUser.isEmpty()) {
1205 for (EcompUserAppRoles userApp : userAppList) {
1206 if (userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)
1207 || userApp.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
1208 RoleInAppForUser addSpecialRole = new RoleInAppForUser();
1209 addSpecialRole.setIsApplied(true);
1210 addSpecialRole.setRoleId(userApp.getRoleId());
1211 addSpecialRole.setRoleName(userApp.getRoleName());
1212 roleInAppUser.add(addSpecialRole);
1217 List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct()
1218 .collect(Collectors.toList());
1219 final Map<String, RoleInAppForUser> currentUserRolesToUpdate = new HashMap<>();
1220 for (RoleInAppForUser roleInAppUserNew : roleInAppUserNonDupls) {
1221 currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), roleInAppUserNew);
1223 final Map<String, ExternalAccessUserRoleDetail> currentUserRolesInExternalSystem = new HashMap<>();
1224 for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleListMatchingInExtAuthAndLocal) {
1225 currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole);
1227 // Check if user roles does not exists in local but still there in External Central Auth System delete them all
1228 for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
1229 if (!(currentUserRolesToUpdate
1230 .containsKey(userRole.getName().substring(app.getNameSpace().length() + 1)))) {
1231 HttpEntity<String> entity = new HttpEntity<>(headers);
1232 logger.debug(EELFLoggerDelegate.debugLogger,
1233 "updateUserRolesInExternalSystem: Connecting to external system to DELETE user role {}",
1234 userRole.getName());
1235 ResponseEntity<String> deleteResponse = template.exchange(
1236 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1237 + "userRole/" + name + "/" + userRole.getName(),
1238 HttpMethod.DELETE, entity, String.class);
1239 logger.debug(EELFLoggerDelegate.debugLogger,
1240 "updateUserRolesInExternalSystem: Finished DELETE operation in external system for user role {} and the response is {}",
1241 userRole.getName(), deleteResponse.getBody());
1244 // Check if user roles does not exists in External Central Auth System add them all
1245 for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) {
1246 if (!(currentUserRolesInExternalSystem
1247 .containsKey(app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")))) {
1248 ExternalAccessUser extUser = new ExternalAccessUser(name,
1249 app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1250 String formattedUserRole = mapper.writeValueAsString(extUser);
1251 HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers);
1252 logger.debug(EELFLoggerDelegate.debugLogger, "updateUserRolesInExternalSystem: Connecting to external system for user {} and POST {}",
1253 name , addUserRole.getRoleName());
1254 ResponseEntity<String> addResponse = template
1255 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1256 + "userRole", HttpMethod.POST, entity, String.class);
1257 logger.debug(EELFLoggerDelegate.debugLogger,
1258 "updateUserRolesInExternalSystem: Finished adding user role in external system {} and added user role {}",
1259 addResponse.getBody(), addUserRole.getRoleName());
1260 if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 404) {
1261 logger.debug(EELFLoggerDelegate.debugLogger,
1262 "Finished POST operation in external system but unable to save user role", addResponse.getBody(),
1263 addUserRole.getRoleName());
1264 throw new Exception(addResponse.getBody());
1268 } catch (HttpClientErrorException e) {
1269 logger.error(EELFLoggerDelegate.errorLogger,
1270 "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}",
1272 if (e.getStatusCode() == HttpStatus.FORBIDDEN) {
1273 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid systemUser", orgUserId);
1274 throw new HttpClientErrorException(HttpStatus.FORBIDDEN, "Please enter the valid systemUser");
1276 if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
1277 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid role");
1278 throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "Please enter the valid role");
1280 EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
1284 catch (Exception e) {
1285 logger.error(EELFLoggerDelegate.errorLogger, "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}", app.getId(), e);
1286 EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
1292 private List<ExternalAccessUserRoleDetail> CheckIfRoleAreMatchingInUserRoleDetailList(
1293 List<ExternalAccessUserRoleDetail> userRoleDetailList, EPApp app) {
1294 Map<String, EPRole> epRoleList = externalAccessRolesService.getAppRoleNamesWithUnderscoreMap(app);
1295 //Add Account Admin role for partner app to prevent conflict
1296 if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1297 EPRole role = new EPRole();
1298 role.setName(PortalConstants.ADMIN_ROLE.replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1299 epRoleList.put(role.getName(), role);
1301 userRoleDetailList.removeIf(userRoleDetail -> !epRoleList.containsKey(userRoleDetail.getName().substring(app.getNameSpace().length()+1)));
1302 return userRoleDetailList;
1309 * @param applicationsRestClientService
1310 * @param searchService
1314 protected void createNewUserOnRemoteApp(String userId, EPApp app,
1315 ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
1316 ObjectMapper mapper, boolean postOpenSource) throws Exception {
1319 EPUser client = searchService.searchUserByUserId(userId);
1321 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1323 if (client == null) {
1324 String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook.";
1325 logger.error(EELFLoggerDelegate.errorLogger, msg);
1326 throw new Exception(msg);
1329 client.setLoginId(userId);
1330 client.setActive(true);
1332 String userInString = null;
1333 userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
1334 logger.debug(EELFLoggerDelegate.debugLogger,
1335 "about to post new client to remote application, users json = " + userInString);
1336 applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user", userId));
1340 @SuppressWarnings("unchecked")
1341 protected void applyChangesToAppRolesRequest(Long appId, Long userId, String updateStatus, EPUserAppRolesRequest epUserAppRolesRequest) {
1342 final Map<String, Long> epRequestParams = new HashMap<>();
1344 EPUserAppRolesRequest epAppRolesRequestData = epUserAppRolesRequest;
1345 epAppRolesRequestData.setUpdatedDate(new Date());
1346 epAppRolesRequestData.setRequestStatus(updateStatus);
1347 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1348 addiotonalUpdateParam.put("userId", userId);
1349 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1350 epRequestParams.put("reqId", epUserAppRolesRequest.getId());
1351 List<EPUserAppRolesRequestDetail> epUserAppRolessDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1352 epUserAppRolessDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1353 epRequestParams, null);
1354 if (epUserAppRolessDetailList.size() > 0) {
1355 for (EPUserAppRolesRequestDetail epRequestUpdateData : epUserAppRolessDetailList) {
1356 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateData;
1357 epAppRoleDetailData.setReqType(updateStatus);
1358 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1359 HashMap<String, Long> updateDetailsParam = new HashMap<String, Long>();
1360 addiotonalUpdateParam.put("reqId", epUserAppRolesRequest.getId());
1361 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParam);
1364 logger.debug(EELFLoggerDelegate.debugLogger, "The request is set to complete");
1366 } catch (Exception e) {
1367 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToAppRolesRequest failed", e);
1371 @SuppressWarnings("unchecked")
1372 public void applyChangesToUserAppRolesForMyLoginsRequest(EPUser user, Long appId) {
1373 final Map<String, Long> params = new HashMap<>();
1374 final Map<String, Long> epDetailParams = new HashMap<>();
1375 List<EPUserAppRolesRequest> epRequestIdVal = new ArrayList<EPUserAppRolesRequest>();
1376 params.put("appId", appId);
1377 params.put("userId", user.getId());
1379 epRequestIdVal = (List<EPUserAppRolesRequest>) dataAccessService
1380 .executeNamedQuery("userAppRolesRequestList", params, null);
1381 if (epRequestIdVal.size() > 0) {
1382 EPUserAppRolesRequest epAppRolesRequestData = epRequestIdVal.get(0);
1383 epAppRolesRequestData.setUpdatedDate(new Date());
1384 epAppRolesRequestData.setRequestStatus("O");
1385 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1386 addiotonalUpdateParam.put("userId", user.getId());
1387 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1388 epDetailParams.put("reqId", epAppRolesRequestData.getId());
1389 List<EPUserAppRolesRequestDetail> epUserAppRolesDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1390 epUserAppRolesDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1391 epDetailParams, null);
1392 if (epUserAppRolesDetailList.size() > 0) {
1393 for (EPUserAppRolesRequestDetail epRequestUpdateList : epUserAppRolesDetailList) {
1394 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateList;
1395 epAppRoleDetailData.setReqType("O");
1396 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1397 HashMap<String, Long> updateDetailsParams = new HashMap<String, Long>();
1398 addiotonalUpdateParam.put("reqId", epAppRolesRequestData.getId());
1399 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParams);
1401 logger.debug(EELFLoggerDelegate.debugLogger, "User App roles request from User Page is overridden");
1405 } catch (Exception e) {
1406 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e);
1411 * Pushes specified user details to the specified remote app.
1414 * OrgUserId identifying user at remote app in REST endpoint path
1416 * User details to be pushed
1419 * @param applicationsRestClientService
1420 * @throws HTTPException
1422 protected void postUserToRemoteApp(String userId, EPUser user, EPApp app,
1423 ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
1425 getUser(userId, app, applicationsRestClientService);
1430 * It returns user details for single org user id
1434 * if user exists it returns list of user details otherwise empty value
1436 @SuppressWarnings("unchecked")
1437 private List<EPUser> checkIfUserExists(Map<String, String> userParams){
1438 return (List<EPUser>)dataAccessService.executeNamedQuery("epUserAppId", userParams, null);
1442 * It checks whether the new user is valid or not otherwise throws exception
1447 * Checks if user is valid and returns message otherwise throws exception
1450 private String validateNewUser(String orgUserId, EPApp app) throws Exception {
1451 EPUser epUser = searchService.searchUserByUserId(orgUserId);
1452 if (epUser == null) {
1453 throw new Exception("User does not exist");
1454 } else if (!epUser.getOrgUserId().equals(orgUserId)) {
1455 throw new Exception("User does not exist");
1456 } else if (app == null) {
1457 throw new Exception("Application does not exist");
1459 return "Saved Successfully";
1463 * Checks if the fields exists or not
1466 * contains user information
1470 * throws exception if the field is not valid
1472 private void validateExternalRequestFields(List<EPUser> userList, EPApp app) throws Exception{
1473 if (userList.size() == 0 || userList.isEmpty() ) {
1474 throw new Exception("User does not exist");
1475 } else if(app == null) {
1476 throw new Exception("Application does not exist");
1477 } else if(!app.getEnabled() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1478 throw new Exception(app.getMlAppName()+" application is unavailable");
1482 @SuppressWarnings("unchecked")
1483 public ExternalRequestFieldsValidator setExternalRequestUserAppRole(ExternalSystemUser newAppRolesForUser, String reqType) {
1484 boolean result = false;
1485 boolean externalSystemRequest = true;
1486 final Map<String, Long> params = new HashMap<>();
1487 final Map<String, String> userParams = new HashMap<>();
1488 List<EPUser> userInfo = null;
1490 List<EPUserAppRolesRequest> epRequestId = null;
1491 String orgUserId = "";
1492 String updateStatus = "";
1493 String reqMessage = "";
1495 if (newAppRolesForUser != null && newAppRolesForUser.getLoginId() != null) {
1496 orgUserId = newAppRolesForUser.getLoginId().trim();
1498 String appName = newAppRolesForUser.getApplicationName();
1499 String logMessage = ("DELETE").equals(reqType) ? "Deleting": "Assigning/Updating" ;
1500 if (orgUserId.length() > 0) {
1501 ObjectMapper mapper = new ObjectMapper();
1502 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1503 int epRequestIdSize = 0;
1505 app = appsService.getAppDetail(appName);
1506 userParams.put("orgUserIdValue", orgUserId);
1507 userInfo = checkIfUserExists(userParams);
1508 reqMessage = "Updated Successfully";
1509 if (!reqType.equals("DELETE") && (userInfo.size() == 0 || userInfo.isEmpty())) {
1510 reqMessage = validateNewUser(orgUserId, app);
1512 if (userInfo.size() != 0 || !userInfo.isEmpty()) {
1513 validateExternalRequestFields(userInfo, app);
1514 user = userInfo.get(0);
1515 params.put("appId", app.getId());
1516 params.put("userId", user.getId());
1517 epRequestId = (List<EPUserAppRolesRequest>) dataAccessService
1518 .executeNamedQuery("userAppRolesRequestList", params, null);
1519 epRequestIdSize = epRequestId.size();
1522 //If Non-Centralized app make sure you sync app roles before assigning to user
1523 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !app.getCentralAuth()) {
1524 logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Starting GET roles for app {}",app.getId());
1525 EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, app.getId(), "/roles");
1526 logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Finshed GET roles for app {} and payload {}",app.getId(), appRoles);
1527 if (appRoles.length > 0) {
1528 syncAppRoles(sessionFactory, app.getId(), appRoles);
1531 List<RoleInAppForUser> roleInAppForUserList = roleInAppForUserList(newAppRolesForUser.getRoles(),
1532 app.getId(), app.getMlAppName());
1533 List<EcompUserAppRoles> userRoleList = null;
1534 if(!userInfo.isEmpty()){
1535 final Map<String, Long> appParams = new HashMap<>();
1536 appParams.put("userId", user.getId());
1537 appParams.put("appId", app.getId());
1538 userRoleList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", appParams, null);
1540 // Check if list contains just account admin role
1541 boolean checkIfAdminRoleExists = false;
1542 if (reqType.equals("DELETE") && userRoleList!=null) {
1543 checkIfAdminRoleExists = userRoleList.stream()
1544 .anyMatch(userRole -> userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1546 checkIfAdminRoleExists = roleInAppForUserList.stream()
1547 .anyMatch(roleList -> roleList.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1549 // if Centralized app
1550 if (app.getCentralAuth()) {
1551 // We should add If user does not exist in remote application
1553 // If adding just account admin role dont make remote application user call or
1554 // if request has only single non admin role then make remote call
1555 if (!(app.getId().equals(PortalConstants.PORTAL_APP_ID) && reqType.equals("DELETE"))
1556 && ((checkIfAdminRoleExists && roleInAppForUserList.size() > 1)
1557 || (!checkIfAdminRoleExists && roleInAppForUserList.size() >= 1))) {
1558 // check if admin role exist then delete
1559 List<RoleInAppForUser> remoteUserRoles = roleInAppForUserList.stream()
1560 .collect(Collectors.toList());
1561 remoteUserRoles.removeIf(role -> {
1562 return (role.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1564 String orgUserIdNewOrExist = (userInfo.size() != 0 || !userInfo.isEmpty()) ? user.getOrgUserId() : orgUserId;
1565 pushRemoteUser(remoteUserRoles, orgUserIdNewOrExist , app, mapper, searchService,
1566 applicationsRestClientService,true);
1568 } catch (Exception e) {
1569 reqMessage = e.getMessage();
1570 logger.error(EELFLoggerDelegate.errorLogger, "setExternalRequestUserAppRole: Failed to added remote user", e);
1571 throw new Exception(reqMessage);
1573 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1574 applicationsRestClientService, app.getId(), orgUserId);
1575 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1576 userRolesInLocalApp);
1577 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1578 if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1579 // Apply changes in external Access system
1580 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, externalSystemRequest,false);
1582 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
1583 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1584 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,false);
1586 // If local application is not centralized
1587 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1588 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1589 applicationsRestClientService, app.getId(), orgUserId);
1590 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1591 userRolesInLocalApp);
1592 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,false);
1593 } else {// remote app
1594 // If adding just account admin role don't do remote application user call
1595 if (!((roleInAppForUserList.size() == 1 || reqType.equals("DELETE")) && checkIfAdminRoleExists)) {
1596 EPUser remoteAppUser = null;
1597 remoteAppUser = checkIfRemoteUserExits(orgUserId, app, applicationsRestClientService);
1598 if (remoteAppUser == null) {
1599 addRemoteUser(roleInAppForUserList, orgUserId, app, mapper, searchService,
1600 applicationsRestClientService);
1601 reqMessage = "Saved Successfully";
1604 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
1605 applicationsRestClientService, app.getId(), orgUserId,false);
1607 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1608 userRolesInRemoteApp);
1609 logger.info(EELFLoggerDelegate.debugLogger,
1610 "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
1611 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1612 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1614 // If no roles remain, request app to set user inactive.
1616 * if (userRolesInRemoteApp.size() == 0) {
1617 * logger.debug(EELFLoggerDelegate.debugLogger,
1618 * "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive"
1619 * , app, orgUserId); //TODO Need to fix the logged in user is not set to
1620 * inactive remoteAppUser.setActive(false); postUserToRemoteApp(orgUserId, user,
1621 * app, applicationsRestClientService); }
1625 // Here we are adding only we have single account admin in roleInAppForUserList and this should not add in remote
1626 if(!(reqType.equals("DELETE")) && userInfo.isEmpty()){
1627 reqMessage = "Saved Successfully";
1629 Set<EcompRole> userRolesInRemoteApp = constructUsersEcompRoles(roleInAppForUserList);
1631 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1632 userRolesInRemoteApp);
1633 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}",
1634 logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1635 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1639 reqMessage = "Failed to save the user app role(s)";
1641 if (epRequestIdSize > 0 && !userInfo.isEmpty()) {
1643 applyChangesToAppRolesRequest(app.getId(), user.getId(), updateStatus, epRequestId.get(0));
1646 } catch (Exception e) {
1647 String message = String.format("setExternalRequestUserAppRole: Failed to create user or update user roles for User %s, AppId %s",
1648 orgUserId, appName);
1649 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1651 reqMessage = e.getMessage();
1652 if(epRequestIdSize > 0 && userInfo!=null && !userInfo.isEmpty()){
1654 applyChangesToAppRolesRequest(app.getId(), user.getId(),
1655 updateStatus, epRequestId.get(0));
1660 return new ExternalRequestFieldsValidator(result, reqMessage);
1665 * @param roleInAppForUserList
1667 * @param applicationsRestClientService
1670 * @return Set<EcompRole>
1671 * @throws JsonProcessingException
1672 * @throws HTTPException
1674 private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
1675 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
1676 throws JsonProcessingException, HTTPException {
1677 Set<EcompRole> updatedUserRoles = constructUsersEcompRoles(roleInAppForUserList);
1678 return updatedUserRoles;
1682 * It constructs and returns list of user app roles when the external API role approval system calls
1685 * @param roleInAppForUserList
1687 * @return list of user app roles
1689 * throws exceptions if role id does not exits
1691 private List<RoleInAppForUser> roleInAppForUserList(List<ExternalSystemRoleApproval> roleInAppForUserList,
1692 Long appId, String appName) throws Exception {
1693 List<RoleInAppForUser> existingUserRoles = new ArrayList<RoleInAppForUser>();
1694 EPRole existingAppRole = null;
1695 for (ExternalSystemRoleApproval roleInAppForUser : roleInAppForUserList) {
1696 RoleInAppForUser ecompRole = new RoleInAppForUser();
1697 existingAppRole = epRoleService.getAppRole(roleInAppForUser.getRoleName(), appId);
1698 if (existingAppRole == null) {
1699 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1700 roleInAppForUserList);
1701 throw new Exception("'" +roleInAppForUser.getRoleName() + "'" +" role does not exist for " + appName + " application");
1703 if (!existingAppRole.getActive()) {
1704 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1705 roleInAppForUserList);
1706 throw new Exception(roleInAppForUser.getRoleName() + " role is unavailable for "+ appName + " application");
1708 ecompRole.roleId = (appId == 1 || roleInAppForUser.getRoleName().equals(PortalConstants.ADMIN_ROLE)) ? existingAppRole.getId() : existingAppRole.getAppRoleId();
1709 ecompRole.roleName = roleInAppForUser.getRoleName();
1710 ecompRole.isApplied = true;
1711 existingUserRoles.add(ecompRole);
1714 return existingUserRoles;
1723 * @param applicationsRestClientService
1725 * @throws HTTPException
1727 protected EPUser getUserFromApp(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1728 throws HTTPException {
1730 if (app.getId() == PortalConstants.PORTAL_APP_ID) {
1731 // Map<String,String> params = new HashMap<String,String>();
1732 // params.put("sbcid",userId);
1733 @SuppressWarnings("unchecked")
1734 List<EPUser> userList = (List<EPUser>) dataAccessService
1735 .executeQuery("from EPUser where orgUserId='" + userId + "'", null);
1736 if (userList != null && !userList.isEmpty())
1737 return userList.get(0);
1743 return getUser(userId, app, applicationsRestClientService);
1746 protected EPUser getUser(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1747 throws HTTPException {
1748 return applicationsRestClientService.get(EPUser.class, app.getId(), String.format("/user/%s", userId), true);
1752 protected boolean isAppUpgradeVersion(EPApp app){
1757 public ExternalSystemAccess getExternalRequestAccess(){
1758 ExternalSystemAccess res = null;
1760 res = new ExternalSystemAccess(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE,
1761 Boolean.parseBoolean(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE)));
1762 } catch (Exception e) {
1763 logger.error(EELFLoggerDelegate.errorLogger, "getExternalRequestAccess failed" + e.getMessage());
1771 * @see org.onap.portalapp.portal.service.UserRolesService#
1772 * getAppRolesForUser(java.lang.Long, java.lang.String)
1774 @SuppressWarnings("unchecked")
1775 public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId, Boolean extRequestValue,EPUser user) {
1776 List<RoleInAppForUser> rolesInAppForUser = null;
1777 EPApp app = appsService.getApp(appId);
1778 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - app = {}", app);
1780 // for onap portal app, no need to make a remote call
1781 List<Role> roleList = new ArrayList<>();
1782 if (appId == PortalConstants.PORTAL_APP_ID) {
1783 if(app.getCentralAuth()){
1784 List<CentralV2Role> cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey());
1785 for(CentralV2Role cenRole : cenRoleList){
1786 Role role = new Role();
1787 role.setActive(cenRole.getActive());
1788 role.setId(cenRole.getId());
1789 role.setName(cenRole.getName());
1790 role.setPriority(cenRole.getPriority());
1794 roleList = roleService.getAvailableRoles(userId);
1796 List<Role> activeRoleList = new ArrayList<Role>();
1797 for(Role role: roleList) {
1798 if(role.getActive()) {
1799 if(role.getId() != 1){ // prevent portal admin from being added
1800 activeRoleList.add(role);
1801 } else if(extRequestValue){
1802 activeRoleList.add(role);
1807 EPUser localUser = getUserFromApp(userId, app, applicationsRestClientService);
1808 // If localUser does not exists return roles
1809 Set<EPRole> roleSet = null;
1810 EPRole[] roleSetList = null;
1811 if(localUser != null){
1812 roleSet = localUser.getAppEPRoles(app);
1813 roleSetList = roleSet.toArray(new EPRole[0]);
1815 rolesInAppForUser = constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue);
1816 return rolesInAppForUser;
1819 EcompRole[] appRoles = null;
1820 List<EcompRole> roles = new ArrayList<>();
1821 if (app.getCentralAuth()) {
1822 final Map<String, Long> appParams = new HashMap<>();
1823 appParams.put("appId", app.getId());
1824 List<EPRole> applicationRoles = dataAccessService.executeNamedQuery("getActiveRolesOfApplication",
1827 EPApp application = appService.getApp(appId);
1828 boolean checkIfUserisApplicationAccAdmin = adminRolesService.isAccountAdminOfApplication(user,
1831 List<EPRole> rolesetwithfunctioncds = new ArrayList<EPRole>();
1832 for (EPRole role : applicationRoles) {
1833 Map<String, Long> params = new HashMap<>();
1834 params.put("roleId", role.getId());
1835 params.put(APP_ID, app.getId());
1836 List<CentralV2RoleFunction> cenRoleFuncList = dataAccessService
1837 .executeNamedQuery("getAppRoleFunctionList", params, null);
1839 // SortedSet<CentralV2RoleFunction> roleFunctionSet =
1841 SortedSet<RoleFunction> roleFunctionSet = new TreeSet<>();
1842 for (CentralV2RoleFunction roleFunc : cenRoleFuncList) {
1844 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1845 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
1846 String type = externalAccessRolesService.getFunctionCodeType(roleFunc.getCode());
1847 String action = externalAccessRolesService.getFunctionCodeAction(roleFunc.getCode());
1848 String name = roleFunc.getName();
1850 RoleFunction function = new RoleFunction();
1851 function.setAction(action);
1852 function.setType(type);
1853 function.setCode(functionCode);
1854 function.setName(name);
1855 roleFunctionSet.add(function);
1856 role.setRoleFunctions(roleFunctionSet);
1859 rolesetwithfunctioncds.add(role);
1864 for (EPRole role1 : rolesetwithfunctioncds) {
1865 EcompRole ecompRole = new EcompRole();
1866 ecompRole.setId(role1.getId());
1867 ecompRole.setName(role1.getName());
1868 ecompRole.setRoleFunctions(role1.getRoleFunctions());
1869 roles.add(ecompRole);
1872 if (checkIfUserisApplicationAccAdmin) {
1873 appRoles = roles.toArray(new EcompRole[roles.size()]);
1874 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() If Logged in user checkIfUserisApplicationAccAdmin- appRoles = {}", appRoles);
1875 } else if (adminRolesService.isRoleAdmin(user) && !checkIfUserisApplicationAccAdmin) {
1876 List<EcompRole> roleAdminAppRoles = new ArrayList<>();
1877 List<String> roleAdminAppRolesNames = new ArrayList<>();
1878 final Map<String, Long> userParams = new HashMap<>();
1879 userParams.put("userId", user.getId());
1880 List<String> getUserApproverRoles = dataAccessService.executeNamedQuery("getUserApproverRoles", userParams, null);
1882 List<EcompRole> userapproverRolesList = new ArrayList<>();
1883 for (String str : getUserApproverRoles) {
1884 EcompRole epRole = roles.stream().filter(x -> str.equals(x.getName())).findAny().orElse(null);
1886 userapproverRolesList.add(epRole);
1888 // roles.removeAll(userapproverRolesList);
1889 for (EcompRole role : userapproverRolesList) {
1891 List<RoleFunction> roleFunList = new ArrayList<>();
1892 roleFunList.addAll(role.getRoleFunctions());
1893 boolean checkIfFunctionsExits = roleFunList.stream()
1894 .anyMatch(roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
1895 if (checkIfFunctionsExits) {
1896 roleAdminAppRoles.add(role);
1897 List<RoleFunction> filteredList = roleFunList.stream()
1898 .filter(x -> "Approver".equalsIgnoreCase(x.getType())).collect(Collectors.toList());
1899 roleAdminAppRolesNames.addAll(filteredList.stream().map(RoleFunction::getCode)
1900 .collect(Collectors.toList()));
1901 // roleAdminAppRolesNames = filteredList.stream().map(RoleFunction::getCode)
1902 // .collect(Collectors.toList());
1905 for (String name : roleAdminAppRolesNames) {
1906 EcompRole ecompRole = roles.stream().filter(x -> name.equals(x.getName())).findAny()
1908 if (ecompRole != null)
1909 roleAdminAppRoles.add(ecompRole);
1912 appRoles = roleAdminAppRoles.toArray(new EcompRole[roleAdminAppRoles.size()]);
1916 appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
1918 // Test this error case, for generating an internal ONAP Portal
1920 // EcompRole[] appRoles = null;
1921 // If there is an exception in the rest client api, then null will
1923 if (appRoles != null) {
1924 if(!app.getCentralAuth()) {
1925 syncAppRoles(sessionFactory, appId, appRoles);
1927 EcompRole[] userAppRoles = null;
1931 if(app.getCentralAuth()){
1932 final Map<String, String> params = new HashMap<>();
1933 final Map<String, Long> userParams = new HashMap<>();
1934 params.put("orgUserIdValue", userId);
1935 List<EPUser> actualUser = dataAccessService.executeNamedQuery("epUserAppId", params, null);
1936 userParams.put("appId", app.getId());
1937 userParams.put("userId", actualUser.get(0).getId());
1938 List<EPUserAppCurrentRoles> userAppsRolesList = dataAccessService.executeNamedQuery("getUserAppCurrentRoles", userParams, null);
1940 List<EcompRole> setUserRoles = new ArrayList<>();
1941 for(EPUserAppCurrentRoles role : userAppsRolesList){
1942 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - userAppsRolesList get userRolename = {}", role.getRoleName());
1943 EcompRole ecompRole = new EcompRole();
1944 ecompRole.setId(role.getRoleId());
1945 ecompRole.setName(role.getRoleName());
1946 setUserRoles.add(ecompRole);
1949 boolean checkIfUserisAccAdmin = setUserRoles.stream()
1950 .anyMatch(ecompRole -> ecompRole.getId() == 999L);
1952 if (!checkIfUserisAccAdmin) {
1953 List<EcompRole> userApplicationRolesList = setUserRoles;
1954 List<EcompRole> appRolesList = Arrays.asList(appRoles);
1955 Set<EcompRole> finalUserAppRolesList = new HashSet<>();
1957 List<String> roleNames = new ArrayList<>();
1958 for (EcompRole role : userApplicationRolesList) {
1959 EcompRole epRole = appRolesList.stream()
1960 .filter(x -> role.getName().equals(x.getName())).findAny().orElse(null);
1961 List<RoleFunction> roleFunList = new ArrayList<>();
1962 if(epRole.getRoleFunctions().size()>0)
1963 roleFunList.addAll(epRole.getRoleFunctions());
1964 boolean checkIfFunctionsExits = roleFunList.stream().anyMatch(
1965 roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
1966 if (checkIfFunctionsExits) {
1967 finalUserAppRolesList.add(role);
1968 List<RoleFunction> filteredList = roleFunList.stream()
1969 .filter(x -> "Approver".equalsIgnoreCase(x.getType()))
1970 .collect(Collectors.toList());
1971 roleNames = filteredList.stream().map(RoleFunction::getCode)
1972 .collect(Collectors.toList());
1975 for (String name : roleNames) {
1976 EcompRole ecompRole = appRolesList.stream()
1977 .filter(x -> name.equals(x.getName())).findAny().orElse(null);
1978 if (ecompRole != null)
1979 finalUserAppRolesList.add(ecompRole);
1984 for (String name : roleNames) {
1986 boolean checkIfFunctionsExits = userAppsRolesList.stream().anyMatch(
1987 role -> role.getRoleName().equalsIgnoreCase(name));
1988 if(checkIfFunctionsExits)
1990 EcompRole epRole = appRolesList.stream().filter(x -> name.equals(x.getName()))
1991 .findAny().orElse(null);
1993 setUserRoles.add(epRole);
1997 userAppRoles = setUserRoles.toArray(new EcompRole[setUserRoles.size()]);
2000 userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
2001 String.format("/user/%s/roles", userId));
2003 } catch (HTTPException e) {
2004 // Some apps are returning 400 if user is not found.
2005 if (e.getResponseCode() == 400) {
2006 logger.debug(EELFLoggerDelegate.debugLogger,
2007 "getAppRolesForUser caught exception with response code 400; continuing", e);
2009 // Other response code, let it come thru.
2013 if (userAppRoles == null) {
2014 if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
2015 EcompPortalUtils.setExternalAppResponseCode(200);
2016 String message = String.format(
2017 "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
2018 + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
2019 + "Overriding to 200 until framework SDK returns a useful response.",
2020 Long.toString(appId), userId);
2021 logger.warn(EELFLoggerDelegate.applicationLogger, message);
2025 HashMap<Long, EcompRole> appRolesActiveMap =hashMapFromEcompRoles(appRoles);
2026 ArrayList<EcompRole> activeRoles = new ArrayList<EcompRole>();
2027 if(userAppRoles != null){
2028 for (int i = 0; i < userAppRoles.length; i++) {
2029 if (appRolesActiveMap.containsKey(userAppRoles[i].getId())) {
2030 EcompRole role = new EcompRole();
2031 role.setId(userAppRoles[i].getId());
2032 role.setName(userAppRoles[i].getName());
2033 activeRoles.add(role);
2037 EcompRole[] userAppRolesActive = activeRoles.toArray(new EcompRole[activeRoles.size()]);
2039 // If the remote application isn't down we MUST sync user
2040 // roles here in case we have this user here!
2041 syncUserRoles(sessionFactory, userId, appId, userAppRolesActive, extRequestValue, null);
2042 } catch (Exception e) {
2043 // TODO: we may need to check if user exists, maybe remote
2045 String message = String.format(
2046 "getAppRolesForUser: user %s does not exist in remote application %s", userId,
2047 Long.toString(appId));
2048 logger.error(EELFLoggerDelegate.errorLogger, message, e);
2049 userAppRoles = new EcompRole[0];
2051 rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
2053 } catch (Exception e) {
2054 String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
2055 Long.toString(appId));
2056 logger.error(EELFLoggerDelegate.errorLogger, message, e);
2058 return rolesInAppForUser;
2061 private boolean postUserRolesToMylogins(AppWithRolesForUser userAppRolesData,
2062 ApplicationsRestClientService applicationsRestClientService, Long appId, Long userId)
2063 throws JsonProcessingException, HTTPException {
2064 boolean result = false;
2065 ObjectMapper mapper = new ObjectMapper();
2066 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
2067 String userRolesAsString = mapper.writeValueAsString(userAppRolesData);
2068 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, as the endpoint is not defined yet from the Mylogins");
2069 applicationsRestClientService.post(AppWithRolesForUser.class, appId, userRolesAsString, String.format("/user/%s/myLoginroles", userId));
2073 @SuppressWarnings("unchecked")
2074 public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser userAppRolesData, EPUser user) {
2075 FieldsValidator fieldsValidator = new FieldsValidator();
2076 final Map<String, Long> params = new HashMap<>();
2077 List<EPUserAppRoles> appRole= null;
2079 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, still the endpoint is yet to be defined");
2080 boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService,
2081 userAppRolesData.getAppId(), user.getId());
2082 logger.debug(EELFLoggerDelegate.debugLogger,"putUserAppRolesRequest: result {}", result);
2084 params.put("appId", userAppRolesData.getAppId());
2085 EPUserAppRolesRequest epAppRolesRequestData = new EPUserAppRolesRequest();
2086 epAppRolesRequestData.setCreatedDate(new Date());
2087 epAppRolesRequestData.setUpdatedDate(new Date());
2088 epAppRolesRequestData.setUserId(user.getId());
2089 epAppRolesRequestData.setAppId(userAppRolesData.getAppId());
2090 epAppRolesRequestData.setRequestStatus("P");
2091 List<RoleInAppForUser> appRoleIdList = userAppRolesData.getAppRoles();
2092 Set<EPUserAppRolesRequestDetail> appRoleDetails = new LinkedHashSet<EPUserAppRolesRequestDetail>();
2093 dataAccessService.saveDomainObject(epAppRolesRequestData, null);
2094 for (RoleInAppForUser userAppRoles : appRoleIdList) {
2095 Boolean isAppliedVal = userAppRoles.isApplied;
2096 params.put("appRoleId", userAppRoles.roleId);
2098 appRole = (List<EPUserAppRoles>) dataAccessService.executeNamedQuery("appRoles", params, null);
2099 if (!appRole.isEmpty()) {
2100 EPUserAppRolesRequestDetail epAppRoleDetail = new EPUserAppRolesRequestDetail();
2101 epAppRoleDetail.setReqRoleId(appRole.get(0).getRoleId());
2102 epAppRoleDetail.setReqType("P");
2103 epAppRoleDetail.setEpRequestIdData(epAppRolesRequestData);
2104 dataAccessService.saveDomainObject(epAppRoleDetail, null);
2108 epAppRolesRequestData.setEpRequestIdDetail(appRoleDetails);
2109 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
2111 } catch (Exception e) {
2112 logger.error(EELFLoggerDelegate.errorLogger, "putUserAppRolesRequest failed", e);
2113 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
2115 return fieldsValidator;
2118 public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(EPUser userid, String appName) {
2119 Map<String, String> params = new HashMap<>();
2120 params.put("userid", userid.getId().toString());
2121 //params.put("appid", appid);
2122 params.put("appName", appName);
2124 @SuppressWarnings("unchecked")
2125 List<EPUserAppCatalogRoles> userAppRoles = (List<EPUserAppCatalogRoles>) dataAccessService
2126 .executeNamedQuery("userAppCatalogRoles", params, null);
2127 return userAppRoles;
2130 public String updateRemoteUserProfile(String orgUserId, Long appId) {
2131 ObjectMapper mapper = new ObjectMapper();
2132 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
2133 EPUser client = searchService.searchUserByUserId(orgUserId);
2134 EPUser newUser = new EPUser();
2135 newUser.setActive(client.getActive());
2136 newUser.setFirstName(client.getFirstName());
2137 newUser.setLastName(client.getLastName());
2138 newUser.setLoginId(client.getLoginId());
2139 newUser.setLoginPwd(client.getLoginPwd());
2140 newUser.setMiddleInitial(client.getMiddleInitial());
2141 newUser.setEmail(client.getEmail());
2142 newUser.setOrgUserId(client.getLoginId());
2144 String userAsString = mapper.writeValueAsString(newUser);
2145 List<EPApp> appList = appsService.getUserRemoteApps(client.getId().toString());
2146 // applicationsRestClientService.post(EPUser.class, appId,
2147 // userAsString, String.format("/user", orgUserId));
2148 for (EPApp eachApp : appList) {
2150 applicationsRestClientService.post(EPUser.class, eachApp.getId(), userAsString,
2151 String.format("/user/%s", orgUserId));
2152 } catch (Exception e) {
2153 logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId()
2154 + " in remote app. appId = " + eachApp.getId());
2157 } catch (Exception e) {
2158 logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
2169 * @see org.onap.portalapp.portal.service.UserRolesService#
2170 * getCachedAppRolesForUser(java.lang.Long, java.lang.Long)
2172 @SuppressWarnings("deprecation")
2173 public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId) {
2174 // Find the records for this user-app combo, if any
2175 String filter = " where user_id = " + Long.toString(userId) + " and app_id = " + Long.toString(appId);
2176 @SuppressWarnings("unchecked")
2177 List<EPUserApp> roleList = dataAccessService.getList(EPUserApp.class, filter, null, null);
2178 logger.debug(EELFLoggerDelegate.debugLogger, "getCachedAppRolesForUser: list size is {}", roleList.size());
2183 * It retrieves and returns list of user app roles for local and remote applications based app id
2186 * @return list of user app roles
2187 * @throws HTTPException
2189 public List<UserApplicationRoles> getUsersFromAppEndpoint(Long appId) throws HTTPException {
2190 ArrayList<UserApplicationRoles> userApplicationRoles = new ArrayList<UserApplicationRoles>();
2192 EPApp app = appsService.getApp(appId);
2193 //If local or centralized application
2194 if (appId == PortalConstants.PORTAL_APP_ID || app.getCentralAuth()) {
2195 @SuppressWarnings("unchecked")
2196 List<EPUser> userList = (List<EPUser>) dataAccessService.executeNamedQuery("getActiveUsers", null, null);
2197 for (EPUser user : userList) {
2198 UserApplicationRoles userWithAppRoles = convertToUserApplicationRoles(appId, user, app);
2199 if (userWithAppRoles.getRoles() != null && userWithAppRoles.getRoles().size() > 0)
2200 userApplicationRoles.add(userWithAppRoles);
2206 RemoteUserWithRoles[] remoteUsers = null;
2207 String remoteUsersString = applicationsRestClientService.getIncomingJsonString(appId, "/users");
2209 remoteUsers = doGetUsers(isAppUpgradeVersion(app), remoteUsersString);
2211 userApplicationRoles = new ArrayList<UserApplicationRoles>();
2212 for (RemoteUserWithRoles remoteUser : remoteUsers) {
2213 UserApplicationRoles userWithRemoteAppRoles = convertToUserApplicationRoles(appId, remoteUser);
2214 if (userWithRemoteAppRoles.getRoles() != null && userWithRemoteAppRoles.getRoles().size() > 0) {
2215 userApplicationRoles.add(userWithRemoteAppRoles);
2217 logger.debug(EELFLoggerDelegate.debugLogger,
2218 "User " + userWithRemoteAppRoles.getOrgUserId() + " doesn't have any roles assigned to any app.");
2223 return userApplicationRoles;
2230 * @param appgetUsersFromAppEndpoint
2233 private UserApplicationRoles convertToUserApplicationRoles(Long appId, EPUser user, EPApp app) {
2234 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
2235 userWithRemoteAppRoles.setAppId(appId);
2236 userWithRemoteAppRoles.setOrgUserId(user.getOrgUserId());
2237 userWithRemoteAppRoles.setFirstName(user.getFirstName());
2238 userWithRemoteAppRoles.setLastName(user.getLastName());
2239 userWithRemoteAppRoles.setRoles(convertToRemoteRoleList(user, app));
2240 return userWithRemoteAppRoles;
2249 @SuppressWarnings("unchecked")
2250 private List<RemoteRole> convertToRemoteRoleList(EPUser user, EPApp app) {
2251 List<RemoteRole> roleList = new ArrayList<RemoteRole>();
2252 SortedSet<EPRole> roleSet = user.getAppEPRoles(app);
2253 for (EPRole role : roleSet) {
2254 logger.debug(EELFLoggerDelegate.debugLogger, "In convertToRemoteRoleList() - for user {}, found Name {}", user.getOrgUserId(), role.getName());
2255 RemoteRole rRole = new RemoteRole();
2256 rRole.setId(role.getId());
2257 rRole.setName(role.getName());
2258 roleList.add(rRole);
2261 //Get the active roles of user for that application using query
2262 List<EPRole> userEpRoleList = new ArrayList<>();
2263 final Map<String, Long> params = new HashMap<>();
2264 params.put("appId", app.getId());
2265 params.put("userId", user.getId());
2266 userEpRoleList = dataAccessService.executeNamedQuery("getUserRoleOnUserIdAndAppId", params, null);
2268 for (EPRole remoteUserRoleList : userEpRoleList) {
2270 RemoteRole remoteRoleListId = roleList.stream().filter(x -> remoteUserRoleList.getId().equals(x.getId()))
2271 .findAny().orElse(null);
2272 if (remoteRoleListId == null) {
2273 logger.debug(EELFLoggerDelegate.debugLogger,
2274 "Adding the role to the rolelist () - for user {}, found Name {}", user.getOrgUserId(),
2276 remoteUserRoleList.getName());
2277 RemoteRole role = new RemoteRole();
2278 role.setId(remoteUserRoleList.getId());
2279 role.setName(remoteUserRoleList.getName());
2286 logger.debug(EELFLoggerDelegate.debugLogger, "rolelist size of the USER() - for user {}, found RoleListSize {}", user.getOrgUserId(), roleList.size());
2294 public RemoteUserWithRoles[] doGetUsers(boolean postOpenSource, String remoteUsersString) {
2296 ObjectMapper mapper = new ObjectMapper();
2298 return mapper.readValue(remoteUsersString, RemoteUserWithRoles[].class);
2299 } catch (IOException e) {
2300 logger.error(EELFLoggerDelegate.errorLogger,
2301 "doGetUsers : Failed : Unexpected property in incoming JSON",
2303 logger.error(EELFLoggerDelegate.errorLogger,
2304 "doGetUsers : Incoming JSON that caused it --> " + remoteUsersString);
2307 return new RemoteUserWithRoles[0];
2310 @SuppressWarnings("unchecked")
2311 public List<EPUserApp> getEPUserAppList(Long appId, Long userId, Long roleId) {
2312 List<EPUserApp> userRoleList = new ArrayList<EPUserApp>();
2313 final Map<String, Long> params = new HashMap<>();
2314 params.put("appId", appId);
2315 params.put("userId", userId);
2316 params.put("roleId", roleId);
2317 userRoleList = dataAccessService.executeNamedQuery("getUserRoleOnUserIdAndRoleIdAndAppId", params, null);
2318 return userRoleList;
2322 /*public static void main(String[] args) {
2323 List<EcompRole> str1 = new ArrayList<String>();
2329 List<String> str2 = new ArrayList<String>();
2333 List<EcompRole> userApplicationRolesList = setUserRoles;
2334 List<EcompRole> appRolesList = Arrays.asList(appRoles);