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 " + EPUser.class.getName() + " where orgUserId='" + userId + "'").list();
287 if (userList.size() > 0) {
288 EPUser client = userList.get(0);
289 roleActive = ("DELETE".equals(reqType)) ? "" : " and role.active = 'Y'";
290 @SuppressWarnings("unchecked")
291 List<EPUserApp> userRoles = localSession.createQuery("from " + EPUserApp.class.getName()
292 + " where app.id=" + appId + roleActive + " and userId=" + client.getId()).list();
294 if ("DELETE".equals(reqType)) {
295 for (EPUserApp userAppRoleList : userRoles) {
296 userAppParams.put("roleName", String.valueOf(userAppRoleList.getRole().getName()));
297 userAppParams.put("appId", String.valueOf(appId));
298 appParams.put("appRoleName", userAppRoleList.getRole().getName());
299 @SuppressWarnings("unchecked")
300 List<EPRole> rolesList = (!userAppRoleList.getRole().getName().equals(PortalConstants.ADMIN_ROLE)) ? (List<EPRole>) dataAccessService.executeNamedQuery("getAppRoles", userAppParams, null) : (List<EPRole>) dataAccessService.executeNamedQuery("getPortalAppRoles", appParams, null);
301 if(rolesList.size() > 0 || !rolesList.isEmpty()){
302 checkIfRoleInactive(rolesList.get(0));
307 for (EPUserApp userRole : userRoles) {
308 if (!userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && userRole.getRoleId() != PortalConstants.SYS_ADMIN_ROLE_ID && !extRequestValue){
309 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
311 else if (extRequestValue && ("PUT".equals(reqType) || "POST".equals(reqType) || "DELETE".equals(reqType))){
312 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
314 else if (extRequestValue && !userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)){
315 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
318 Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values();
319 if (newRolesToAdd.size() > 0) {
320 EPApp app = (EPApp) localSession.get(EPApp.class, appId);
322 HashMap<Long, EPRole> rolesMap = new HashMap<Long, EPRole>();
323 if (appId.equals(PortalConstants.PORTAL_APP_ID)) { // local app
324 String appIdValue = "";
325 if(!extRequestValue){
326 appIdValue = "and id != " + PortalConstants.SYS_ADMIN_ROLE_ID;
328 @SuppressWarnings("unchecked")
329 List<EPRole> roles = localSession
330 .createQuery("from " + EPRole.class.getName() + " where appId is null " + appIdValue).list();
331 for (EPRole role : roles) {
333 rolesMap.put(role.getId(), role);
335 } else { // remote app
336 @SuppressWarnings("unchecked")
337 List<EPRole> roles = localSession
338 .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list();
339 for (EPRole role : roles) {
340 if (!extRequestValue && app.getCentralAuth()) {
341 rolesMap.put(role.getId(), role);
343 rolesMap.put(role.getAppRoleId(), role);
349 for (EcompRole userRole : newRolesToAdd) {
350 EPUserApp userApp = new EPUserApp();
351 if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName().equals(PortalConstants.ADMIN_ROLE)) {
352 role = (EPRole) localSession.get(EPRole.class, new Long(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
353 userApp.setRole(role);
354 } else if ((userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) && !extRequestValue){
356 }else if((userRole.getId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)) && app.getId().equals(PortalConstants.PORTAL_APP_ID) && !extRequestValue){
360 userApp.setRole(rolesMap.get(userRole.getId()));
363 userApp.setUserId(client.getId());
365 localSession.save(userApp);
366 localSession.flush();
369 if (appId == PortalConstants.PORTAL_APP_ID) {
371 * for local app -- hack - always make sure fn_role
372 * table's app_id is null and not 1 for primary app in
373 * this case being onap portal app; reason: hibernate
374 * is rightly setting this to 1 while persisting to
375 * fn_role as per the mapping but SDK role management
376 * code expects the app_id to be null as there is no
377 * concept of App_id in SDK
379 localSession.flush();
380 SQLQuery sqlQuery = localSession
381 .createSQLQuery("update fn_role set app_id = null where app_id = 1 ");
382 sqlQuery.executeUpdate();
387 transaction.commit();
388 } catch (Exception e) {
389 logger.error(EELFLoggerDelegate.errorLogger, "syncUserRoles failed", e);
390 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
391 EcompPortalUtils.rollbackTransaction(transaction,
392 "Exception occurred in syncUserRoles, Details: " + e.toString());
393 if("DELETE".equals(reqType)){
394 throw new SyncUserRolesException(e.getMessage());
397 if(localSession != null)
398 localSession.close();
403 * Called when getting the list of roles for the user
406 * @param userAppRoles
407 * @return List<RoleInAppForUser>
409 protected List<RoleInAppForUser> constructRolesInAppForUserGet(EcompRole[] appRoles, EcompRole[] userAppRoles) {
410 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
412 Set<Long> userAppRolesMap = new HashSet<Long>();
413 if (userAppRoles != null) {
414 for (EcompRole ecompRole : userAppRoles) {
415 userAppRolesMap.add(ecompRole.getId());
418 logger.error(EELFLoggerDelegate.errorLogger,
419 "constructRolesInAppForUserGet has received userAppRoles list empty");
422 if (appRoles != null) {
423 for (EcompRole ecompRole : appRoles) {
424 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
425 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
426 rolesInAppForUser.add(roleForUser);
429 logger.error(EELFLoggerDelegate.errorLogger, "constructRolesInAppForUser has received appRoles list empty");
431 return rolesInAppForUser;
435 * Called when getting the list of roles for the user
438 * @param userAppRoles
439 * @param extRequestValue
440 * set to false if request is from users page otherwise true
441 * @return List<RoleInAppForUser>
443 protected List<RoleInAppForUser> constructRolesInAppForUserGet(List<Role> appRoles, EPRole[] userAppRoles, Boolean extRequestValue) {
444 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
446 Set<Long> userAppRolesMap = new HashSet<Long>();
447 if (userAppRoles != null) {
448 for (EPRole ecompRole : userAppRoles) {
449 userAppRolesMap.add(ecompRole.getId());
451 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - userAppRolesMap = {}", userAppRolesMap);
454 logger.error(EELFLoggerDelegate.errorLogger,
455 "constructRolesInAppForUserGet has received userAppRoles list empty.");
458 if (appRoles != null) {
460 for (Role ecompRole : appRoles) {
461 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - appRoles not null = {}", ecompRole);
463 if (ecompRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && !extRequestValue)
465 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
466 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
467 rolesInAppForUser.add(roleForUser);
468 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - rolesInAppForUser = {}", rolesInAppForUser);
472 logger.error(EELFLoggerDelegate.errorLogger,
473 "constructRolesInAppForUser has received appRoles list empty.");
475 return rolesInAppForUser;
480 * copies of methods in GetAppsWithUserRoleState
482 * @param sessionFactory
487 protected void syncAppRoles(SessionFactory sessionFactory, Long appId, EcompRole[] appRoles) throws Exception {
488 logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId);
489 HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles);
490 Session localSession = null;
491 Transaction transaction = null;
494 localSession = sessionFactory.openSession();
495 transaction = localSession.beginTransaction();
496 // Attention! All roles from remote application supposed to be
499 @SuppressWarnings("unchecked")
500 List<EPRole> currentAppRoles = localSession.createQuery("from :name where appId = :appId")
501 .setParameter("name",EPRole.class.getName())
502 .setParameter("appId",appId)
505 List<EPRole> obsoleteRoles = new ArrayList<EPRole>();
506 for (int i = 0; i < currentAppRoles.size(); i++) {
507 EPRole oldAppRole = currentAppRoles.get(i);
508 if (oldAppRole.getAppRoleId() != null) {
509 EcompRole role = null;
510 role = newRolesMap.get(oldAppRole.getAppRoleId());
512 if (!(role.getName() == null || oldAppRole.getName().equals(role.getName()))) {
513 oldAppRole.setName(role.getName());
514 localSession.update(oldAppRole);
516 oldAppRole.setActive(true);
517 newRolesMap.remove(oldAppRole.getAppRoleId());
519 obsoleteRoles.add(oldAppRole);
522 obsoleteRoles.add(oldAppRole);
525 Collection<EcompRole> newRolesToAdd = newRolesMap.values();
526 if (obsoleteRoles.size() > 0) {
527 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: we have obsolete roles to delete");
528 for (EPRole role : obsoleteRoles) {
529 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: obsolete role: " + role.toString());
530 Long roleId = role.getId();
531 // delete obsolete roles here
532 // Must delete all records with foreign key constraints on
534 // fn_user_role, fn_role_composite, fn_role_function,
535 // fn_user_pseudo_role, fn_menu_functional_roles.
536 // And for fn_menu_functional, if no other roles for that
537 // menu item, remove the url.
539 // Delete from fn_user_role
540 @SuppressWarnings("unchecked")
541 List<EPUserApp> userRoles = localSession.createQuery(
542 "from :name where app.id=:appId and role_id=:roleId")
543 .setParameter("name",EPUserApp.class.getName())
544 .setParameter("appId",appId)
545 .setParameter("roleId",roleId)
548 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: number of userRoles to delete: " + userRoles.size());
549 for (EPUserApp userRole : userRoles) {
550 logger.debug(EELFLoggerDelegate.debugLogger,
551 "syncAppRoles: about to delete userRole: " + userRole.toString());
552 localSession.delete(userRole);
553 logger.debug(EELFLoggerDelegate.debugLogger,
554 "syncAppRoles: finished deleting userRole: " + userRole.toString());
557 // Delete from fn_menu_functional_roles
558 @SuppressWarnings("unchecked")
559 List<FunctionalMenuRole> funcMenuRoles = localSession
560 .createQuery("from " + FunctionalMenuRole.class.getName() + " where roleId=" + roleId)
562 int numMenuRoles = funcMenuRoles.size();
563 logger.debug(EELFLoggerDelegate.debugLogger,
564 "syncAppRoles: number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles);
565 for (FunctionalMenuRole funcMenuRole : funcMenuRoles) {
566 Long menuId = funcMenuRole.menuId;
567 // If this is the only role for this menu item, then the
568 // app and roles will be gone,
569 // so must null out the url too, to be consistent
570 @SuppressWarnings("unchecked")
571 List<FunctionalMenuRole> funcMenuRoles2 = localSession
572 .createQuery("from " + FunctionalMenuRole.class.getName() + " where menuId=" + menuId)
574 int numMenuRoles2 = funcMenuRoles2.size();
575 logger.debug(EELFLoggerDelegate.debugLogger,
576 "syncAppRoles: number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2);
577 localSession.delete(funcMenuRole);
578 if (numMenuRoles2 == 1) {
579 // If this is the only role for this menu item, then
580 // the app and roles will be gone,
581 // so must null out the url too, to be consistent
582 logger.debug(EELFLoggerDelegate.debugLogger,
583 "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url");
584 @SuppressWarnings("unchecked")
585 List<FunctionalMenuItem> funcMenuItems = localSession
587 "from " + FunctionalMenuItem.class.getName() + " where menuId=" + menuId)
589 if (funcMenuItems.size() > 0) {
590 logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item");
591 FunctionalMenuItem funcMenuItem = funcMenuItems.get(0);
592 funcMenuItem.url = "";
593 localSession.update(funcMenuItem);
597 boolean isPortalRequest = true;
598 externalAccessRolesService.deleteRoleDependencyRecords(localSession, roleId, appId, isPortalRequest);
599 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to delete the role: " + role.toString());
600 localSession.delete(role);
601 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: deleted the role");
604 for (EcompRole role : newRolesToAdd) {
605 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to add missing role: " + role.toString());
606 EPRole newRole = new EPRole();
607 // Attention! All roles from remote application supposed to be
609 newRole.setActive(true);
610 newRole.setName(role.getName());
611 newRole.setAppId(appId);
612 newRole.setAppRoleId(role.getId());
613 localSession.save(newRole);
615 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to commit the transaction");
616 transaction.commit();
617 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: committed the transaction");
618 } catch (Exception e) {
619 logger.error(EELFLoggerDelegate.errorLogger, "syncAppRoles failed", e);
620 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
621 EcompPortalUtils.rollbackTransaction(transaction,
622 "Exception occurred in syncAppRoles, Details: " + e.toString());
623 throw new Exception(e);
625 localSession.close();
634 * Called when updating the list of roles for the user
638 * @param userRolesInRemoteApp
639 * @return RolesInAppForUser
641 protected RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId,
642 Set<EcompRole> userRolesInRemoteApp) {
643 RolesInAppForUser result;
644 result = new RolesInAppForUser();
645 result.appId = appId;
646 result.orgUserId = userId;
648 for (EcompRole role : userRolesInRemoteApp) {
649 RoleInAppForUser roleInAppForUser = new RoleInAppForUser();
650 roleInAppForUser.roleId = role.getId();
651 roleInAppForUser.roleName = role.getName();
652 roleInAppForUser.isApplied = new Boolean(true);
653 result.roles.add(roleInAppForUser);
660 * @param roleInAppForUserList
663 protected boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) {
664 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
665 if (roleInAppForUser.isApplied.booleanValue()) {
673 * Builds JSON and posts it to a remote application to update user roles.
675 * @param roleInAppForUserList
677 * @param applicationsRestClientService
680 * @return Set of roles as sent; NOT the response from the app.
681 * @throws JsonProcessingException
682 * @throws HTTPException
684 protected Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
685 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId,boolean systemUser)
686 throws JsonProcessingException, HTTPException {
687 Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList);
688 Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList);
689 String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote);
690 EPApp externalApp = null;
691 SystemType type = SystemType.APPLICATION;
692 externalApp = appsCacheService.getApp(appId);
693 String appBaseUri = null;
694 Set<RemoteRoleV1> updatedUserRolesinRemoteV1 = new TreeSet<>();
695 if (externalApp != null) {
696 appBaseUri = (type == SystemType.APPLICATION) ? externalApp.getAppRestEndpoint() : "";
698 if(appBaseUri != null && appBaseUri.endsWith("/api")){
699 for(EcompRole eprole :updatedUserRolesinRemote)
701 RemoteRoleV1 role = new RemoteRoleV1();
702 role.setId(eprole.getId());
703 role.setName(eprole.getName());
704 updatedUserRolesinRemoteV1.add(role);
706 userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemoteV1);
708 applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString,
709 String.format("/user/%s/roles", userId));
710 // TODO: We should add code that verifies that the post operation did
711 // succeed. Because the SDK may still return 200 OK with an html page
712 // even when it fails!
713 return updateUserRolesInEcomp;
718 * @param roleInAppForUserList
719 * @return Set<EcompRole>
721 protected Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) {
722 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
723 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
724 if (roleInAppForUser.isApplied) {
725 EcompRole ecompRole = new EcompRole();
726 ecompRole.setId(roleInAppForUser.roleId);
727 ecompRole.setName(roleInAppForUser.roleName);
728 existingUserRoles.add(ecompRole);
731 return existingUserRoles;
735 * Constructs user app roles excluding Account Administrator role
737 * @param roleInAppForUserList
739 * List of roles with Role name, Role Id
741 protected Set<EcompRole> constructUsersRemoteAppRoles(List<RoleInAppForUser> roleInAppForUserList) {
742 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
743 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
744 if (roleInAppForUser.isApplied && !roleInAppForUser.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
745 EcompRole ecompRole = new EcompRole();
746 ecompRole.setId(roleInAppForUser.roleId);
747 ecompRole.setName(roleInAppForUser.roleName);
748 existingUserRoles.add(ecompRole);
751 return existingUserRoles;
755 * This is for a single app
757 * @param rolesInAppForUser
758 * @param externalSystemRequest
759 * set to false if requests from Users page otherwise true
760 * @return true on success, false otherwise
762 protected boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser, boolean externalSystemRequest, String reqType,boolean isSystemUser) throws Exception {
763 boolean result = false;
764 String userId = rolesInAppForUser.orgUserId;
765 Long appId = rolesInAppForUser.appId;
766 synchronized (syncRests) {
767 if (rolesInAppForUser != null) {
768 createLocalUserIfNecessary(userId, isSystemUser);
771 if (rolesInAppForUser != null) {
772 EcompRole[] userAppRoles = new EcompRole[rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size()];
773 for (int i = 0; i < rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size(); i++) {
774 RoleInAppForUser roleInAppForUser = rolesInAppForUser.roles.get(i);
775 EcompRole role = new EcompRole();
776 role.setId(roleInAppForUser.roleId);
777 role.setName(roleInAppForUser.roleName);
778 userAppRoles[i] = role;
781 syncUserRoles(sessionFactory, userId, appId, userAppRoles, externalSystemRequest, reqType);
783 } catch (Exception e) {
784 logger.error(EELFLoggerDelegate.errorLogger,
785 "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for orgUserId " + userId, e);
786 if("DELETE".equals(reqType)){
787 throw new Exception(e.getMessage());
799 * @return UserApplicationRoles
801 protected UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) {
802 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
803 userWithRemoteAppRoles.setAppId(appId);
804 userWithRemoteAppRoles.setOrgUserId(remoteUser.getOrgUserId());
805 userWithRemoteAppRoles.setFirstName(remoteUser.getFirstName());
806 userWithRemoteAppRoles.setLastName(remoteUser.getLastName());
807 userWithRemoteAppRoles.setRoles(remoteUser.getRoles());
808 return userWithRemoteAppRoles;
814 * @see org.onap.portalapp.portal.service.UserRolesService#
815 * importRolesFromRemoteApplication(java.lang.Long)
817 public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException {
818 EPRole[] appRolesFull = applicationsRestClientService.get(EPRole[].class, appId, "/rolesFull");
819 List<EPRole> rolesList = Arrays.asList(appRolesFull);
820 for (EPRole externalAppRole : rolesList) {
822 // Try to find an existing extern role for the app in the local
823 // onap DB. If so, then use its id to update the existing external
824 // application role record.
825 Long externAppId = externalAppRole.getId();
826 EPRole existingAppRole = epRoleService.getRole(appId, externAppId);
827 if (existingAppRole != null) {
828 logger.debug(EELFLoggerDelegate.debugLogger,
829 String.format("ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.",
830 appId, externAppId));
833 // persistExternalRoleInEcompDb(externalAppRole, appId,
841 * It adds new user for remote application
843 * @param roleInAppForUserList
844 * @param remoteAppUser
848 * @param searchService
849 * @param applicationsRestClientService
853 private EPUser addRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app,
854 ObjectMapper mapper, SearchService searchService,
855 ApplicationsRestClientService applicationsRestClientService) throws Exception {
856 EPUser addRemoteUser = null;
857 if (remoteUserShouldBeCreated(roleInAppForUserList)) {
858 createNewUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper,
859 isAppUpgradeVersion(app));
861 return addRemoteUser;
864 private EPUser pushRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app,
865 ObjectMapper mapper, SearchService searchService,
866 ApplicationsRestClientService applicationsRestClientService,boolean appRoleIdUsed) throws Exception {
867 EPUser addRemoteUser = null;
868 // if (remoteUserShouldBeCreated(roleInAppForUserList)) {
869 pushUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper,
870 isAppUpgradeVersion(app), roleInAppForUserList, appRoleIdUsed);
872 return addRemoteUser;
875 @SuppressWarnings("unchecked")
876 protected void pushUserOnRemoteApp(String userId, EPApp app,
877 ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
878 ObjectMapper mapper, boolean postOpenSource, List<RoleInAppForUser> roleInAppForUserList,boolean appRoleIdUsed) throws Exception {
880 EPUser client = null;
881 client = searchService.searchUserByUserId(userId);
883 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
884 if (client == null) {
885 String msg = "cannot create user " + userId + ", because he/she cannot be found in directory.";
886 logger.error(EELFLoggerDelegate.errorLogger, msg);
887 // throw new Exception(msg);
888 final Map<String, String> loginIdParams = new HashMap<>();
889 loginIdParams.put("orgUserIdValue", userId);
890 List<EPUser> userList = new ArrayList<>();
891 userList = dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null);
892 if (userList.size() > 0) {
893 logger.debug(EELFLoggerDelegate.debugLogger,
894 userList.get(0).getOrgUserId() + " User was found in Portal");
895 client = userList.get(0);
896 SortedSet<EPUserApp> userApps = new TreeSet<>();
897 client.setEPUserApps(userApps);
898 client.setSystemUser(false);
900 logger.error(EELFLoggerDelegate.errorLogger, "user cannot be found be in directory or in portal");
901 throw new Exception(msg);
906 client.setLoginId(userId);
907 client.setActive(true);
908 client.setOrgUserId(userId);
911 roleInAppForUserList.removeIf(role -> role.isApplied.equals(false));
912 SortedSet<Role> roles = new TreeSet<>();
914 List<EPRole> getAppRoles = externalAccessRolesService.getAppRoles(app.getId());
915 List<EPApp> appList = new ArrayList<>();
917 List<CentralV2Role> roleList = new ArrayList<>();
918 Map<String, Long> params = new HashMap<>();
920 List<EPRole> userRoles = new ArrayList<>();
922 for (RoleInAppForUser roleInappForUser : roleInAppForUserList) {
923 EPRole role = new EPRole();
924 role.setId(roleInappForUser.getRoleId());
925 role.setName(roleInappForUser.getRoleName());
930 List<EPRole> userAppRoles = new ArrayList<>();
931 for (EPRole role : userRoles) {
932 EPRole appRole = getAppRoles.stream()
933 .filter(applicationRole -> role.getId().equals(applicationRole.getAppRoleId())).findAny()
935 EPRole epRole = new EPRole();
936 if (appRole != null) {
937 epRole.setId(appRole.getId());
938 epRole.setName(appRole.getName());
940 userAppRoles.add(epRole);
942 userRoles = new ArrayList<>();
943 userRoles.addAll(userAppRoles);
945 roleList = externalAccessRolesService.createCentralRoleObject(appList, userRoles, roleList, params);
947 for (CentralV2Role epRole : roleList) {
948 Role role = new Role();
949 EPRole appRole = getAppRoles.stream()
950 .filter(applicationRole -> epRole.getId().equals(applicationRole.getId())).findAny().orElse(null);
951 if (appRole != null){
952 role.setId(appRole.getAppRoleId());
953 role.setName(epRole.getName());
954 role.setRoleFunctions(epRole.getRoleFunctions());
958 client.setRoles(roles);
959 String userInString = null;
960 userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
961 logger.debug(EELFLoggerDelegate.debugLogger,
962 "about to post a client to remote application, users json = " + userInString);
963 applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user/%s", userId));
967 * It checks whether the remote user exists or not
968 * if exits returns user object else null
972 * @param applicationsRestClientService
974 * @throws HTTPException
976 private EPUser checkIfRemoteUserExits(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService) throws HTTPException{
977 EPUser checkRemoteUser = null;
979 checkRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
980 } catch (HTTPException e) {
981 // Some apps are returning 400 if user is not found.
982 if (e.getResponseCode() == 400) {
983 logger.debug(EELFLoggerDelegate.debugLogger,
984 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing",
986 } else if(e.getResponseCode() == 404) {
987 logger.debug(EELFLoggerDelegate.debugLogger,
988 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 404; continuing",
991 // Other response code, let it come thru.
995 return checkRemoteUser;
1002 * @see org.onap.portalapp.portal.service.UserRolesService#
1003 * setAppWithUserRoleStateForUser(org.onap.portalapp.portal.domain.
1004 * EPUser, org.onap.portalapp.portal.transport.AppWithRolesForUser)
1006 public ExternalRequestFieldsValidator setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser) {
1007 boolean result = false;
1008 boolean epRequestValue = false;
1010 String reqMessage = "";
1011 if (newAppRolesForUser != null && newAppRolesForUser.getOrgUserId() != null) {
1012 userId = newAppRolesForUser.getOrgUserId().trim();
1014 Long appId = newAppRolesForUser.getAppId();
1015 List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.getAppRoles();
1016 if (userId.length() > 0 ) {
1017 ObjectMapper mapper = new ObjectMapper();
1018 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1021 EPApp app = appsService.getApp(appId);
1022 applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
1024 boolean systemUser = newAppRolesForUser.isSystemUser();
1025 if ((app.getCentralAuth() || app.getId().equals(PortalConstants.PORTAL_APP_ID)) && systemUser) {
1027 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1028 applicationsRestClientService, appId, userId);
1029 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1030 userRolesInLocalApp);
1031 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1032 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1033 // Apply changes in external Access system
1034 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList,
1035 epRequestValue, systemUser);
1037 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal",
1040 }else if (!app.getCentralAuth() && systemUser)
1042 throw new Exception("For non-centralized application we cannot add systemUser");
1044 else{ // if centralized app
1045 if (app.getCentralAuth()) {
1046 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1047 pushRemoteUser(roleInAppForUserList, userId, app, mapper, searchService,
1048 applicationsRestClientService,false);
1051 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1052 applicationsRestClientService, appId, userId);
1053 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1054 userRolesInLocalApp);
1055 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1056 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1057 // Apply changes in external Access system
1058 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList,
1059 epRequestValue,false);
1061 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal", systemUser);
1063 // In case if portal is not centralized then follow existing approach
1064 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1065 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1066 applicationsRestClientService, appId, userId);
1067 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1068 userRolesInLocalApp);
1069 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal",false);
1070 } else{// remote app
1071 EPUser remoteAppUser = null;
1072 if(!app.getCentralAuth() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1074 remoteAppUser = checkIfRemoteUserExits(userId, app, applicationsRestClientService);
1076 if (remoteAppUser == null) {
1077 remoteAppUser = addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService, applicationsRestClientService);
1079 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
1080 applicationsRestClientService, appId, userId,systemUser);
1081 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1082 userRolesInRemoteApp);
1083 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null,false);
1085 // If no roles remain, request app to set user inactive.
1086 if (userRolesInRemoteApp.size() == 0) {
1087 logger.debug(EELFLoggerDelegate.debugLogger,
1088 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
1090 //remoteAppUser.setActive(false);
1091 postUserToRemoteApp(userId, user, app, applicationsRestClientService);
1096 } catch (Exception e) {
1097 /*String message = String.format(
1098 "Failed to create user or update user roles for User %s, AppId %s",
1099 userId, Long.toString(appId));
1100 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1103 String message = String.format(
1104 "Failed to create user or update user roles for User %s, AppId %s",
1105 userId, Long.toString(appId));
1106 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1108 reqMessage = e.getMessage();
1115 return new ExternalRequestFieldsValidator(result, reqMessage);
1119 * It adds user roles in External system and also make data consistent in both local and in External System
1121 * @param app details
1123 * @param roleInAppUser Contains list of active roles
1125 @SuppressWarnings("unchecked")
1126 private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser, boolean isPortalRequest,boolean isSystemUser) throws Exception
1129 // check if user exists
1130 final Map<String, String> userParams = new HashMap<>();
1131 userParams.put("orgUserIdValue", orgUserId);
1132 List<EPUser> userInfo = checkIfUserExists(userParams);
1133 if (userInfo.isEmpty()) {
1134 createLocalUserIfNecessary(orgUserId, isSystemUser);
1137 if (EPCommonSystemProperties
1138 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN) && !isSystemUser) {
1140 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
1144 ObjectMapper mapper = new ObjectMapper();
1145 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1146 HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
1147 ResponseEntity<String> getResponse = externalAccessRolesService.getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
1148 List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
1149 String res = getResponse.getBody();
1150 JSONObject jsonObj = null;
1151 JSONArray extRoles = null;
1152 if (!res.equals("{}")) {
1153 jsonObj = new JSONObject(res);
1154 extRoles = jsonObj.getJSONArray("role");
1156 ExternalAccessUserRoleDetail userRoleDetail = null;
1157 if (extRoles != null) {
1158 for (int i = 0; i < extRoles.length(); i++) {
1159 if (extRoles.getJSONObject(i).getString("name").startsWith(app.getNameSpace() + ".")
1160 && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".admin")
1161 && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".owner")) {
1162 if (extRoles.getJSONObject(i).has("description")) {
1163 ExternalRoleDescription desc = new ExternalRoleDescription(extRoles.getJSONObject(i).getString("description"));
1164 userRoleDetail = new ExternalAccessUserRoleDetail(
1165 extRoles.getJSONObject(i).getString("name"), desc);
1166 userRoleDetailList.add(userRoleDetail);
1168 userRoleDetail = new ExternalAccessUserRoleDetail(
1169 extRoles.getJSONObject(i).getString("name"), null);
1170 userRoleDetailList.add(userRoleDetail);
1177 List<ExternalAccessUserRoleDetail> userRoleListMatchingInExtAuthAndLocal = CheckIfRoleAreMatchingInUserRoleDetailList(userRoleDetailList,app);
1179 // If request coming from portal not from external role approval system then we have to check if user already
1180 // have account admin or system admin as GUI will not send these roles
1181 if (!isPortalRequest) {
1182 final Map<String, String> loginIdParams = new HashMap<>();
1183 loginIdParams.put("orgUserIdValue", orgUserId);
1184 EPUser user = (EPUser) dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null).get(0);
1185 final Map<String, Long> params = new HashMap<>();
1186 params.put("appId", app.getId());
1187 params.put("userId", user.getId());
1188 List<EcompUserAppRoles> userAppList = dataAccessService.executeNamedQuery("getUserAppExistingRoles",
1190 if (!roleInAppUser.isEmpty()) {
1191 for (EcompUserAppRoles userApp : userAppList) {
1192 if (userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)
1193 || userApp.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
1194 RoleInAppForUser addSpecialRole = new RoleInAppForUser();
1195 addSpecialRole.setIsApplied(true);
1196 addSpecialRole.setRoleId(userApp.getRoleId());
1197 addSpecialRole.setRoleName(userApp.getRoleName());
1198 roleInAppUser.add(addSpecialRole);
1203 List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct()
1204 .collect(Collectors.toList());
1205 final Map<String, RoleInAppForUser> currentUserRolesToUpdate = new HashMap<>();
1206 for (RoleInAppForUser roleInAppUserNew : roleInAppUserNonDupls) {
1207 currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), roleInAppUserNew);
1209 final Map<String, ExternalAccessUserRoleDetail> currentUserRolesInExternalSystem = new HashMap<>();
1210 for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleListMatchingInExtAuthAndLocal) {
1211 currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole);
1213 // Check if user roles does not exists in local but still there in External Central Auth System delete them all
1214 for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
1215 if (!(currentUserRolesToUpdate
1216 .containsKey(userRole.getName().substring(app.getNameSpace().length() + 1)))) {
1217 HttpEntity<String> entity = new HttpEntity<>(headers);
1218 logger.debug(EELFLoggerDelegate.debugLogger,
1219 "updateUserRolesInExternalSystem: Connecting to external system to DELETE user role {}",
1220 userRole.getName());
1221 ResponseEntity<String> deleteResponse = template.exchange(
1222 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1223 + "userRole/" + name + "/" + userRole.getName(),
1224 HttpMethod.DELETE, entity, String.class);
1225 logger.debug(EELFLoggerDelegate.debugLogger,
1226 "updateUserRolesInExternalSystem: Finished DELETE operation in external system for user role {} and the response is {}",
1227 userRole.getName(), deleteResponse.getBody());
1230 // Check if user roles does not exists in External Central Auth System add them all
1231 for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) {
1232 if (!(currentUserRolesInExternalSystem
1233 .containsKey(app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")))) {
1234 ExternalAccessUser extUser = new ExternalAccessUser(name,
1235 app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1236 String formattedUserRole = mapper.writeValueAsString(extUser);
1237 HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers);
1238 logger.debug(EELFLoggerDelegate.debugLogger, "updateUserRolesInExternalSystem: Connecting to external system for user {} and POST {}",
1239 name , addUserRole.getRoleName());
1240 ResponseEntity<String> addResponse = template
1241 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1242 + "userRole", HttpMethod.POST, entity, String.class);
1243 logger.debug(EELFLoggerDelegate.debugLogger,
1244 "updateUserRolesInExternalSystem: Finished adding user role in external system {} and added user role {}",
1245 addResponse.getBody(), addUserRole.getRoleName());
1246 if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 404) {
1247 logger.debug(EELFLoggerDelegate.debugLogger,
1248 "Finished POST operation in external system but unable to save user role", addResponse.getBody(),
1249 addUserRole.getRoleName());
1250 throw new Exception(addResponse.getBody());
1254 } catch (HttpClientErrorException e) {
1255 logger.error(EELFLoggerDelegate.errorLogger,
1256 "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}",
1258 if (e.getStatusCode() == HttpStatus.FORBIDDEN) {
1259 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid systemUser", orgUserId);
1260 throw new HttpClientErrorException(HttpStatus.FORBIDDEN, "Please enter the valid systemUser");
1262 if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
1263 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid role");
1264 throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "Please enter the valid role");
1266 EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
1270 catch (Exception e) {
1271 logger.error(EELFLoggerDelegate.errorLogger, "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}", app.getId(), e);
1272 EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
1278 private List<ExternalAccessUserRoleDetail> CheckIfRoleAreMatchingInUserRoleDetailList(
1279 List<ExternalAccessUserRoleDetail> userRoleDetailList, EPApp app) {
1280 Map<String, EPRole> epRoleList = externalAccessRolesService.getAppRoleNamesWithUnderscoreMap(app);
1281 //Add Account Admin role for partner app to prevent conflict
1282 if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1283 EPRole role = new EPRole();
1284 role.setName(PortalConstants.ADMIN_ROLE.replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1285 epRoleList.put(role.getName(), role);
1287 userRoleDetailList.removeIf(userRoleDetail -> !epRoleList.containsKey(userRoleDetail.getName().substring(app.getNameSpace().length()+1)));
1288 return userRoleDetailList;
1295 * @param applicationsRestClientService
1296 * @param searchService
1300 protected void createNewUserOnRemoteApp(String userId, EPApp app,
1301 ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
1302 ObjectMapper mapper, boolean postOpenSource) throws Exception {
1305 EPUser client = searchService.searchUserByUserId(userId);
1307 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1309 if (client == null) {
1310 String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook.";
1311 logger.error(EELFLoggerDelegate.errorLogger, msg);
1312 throw new Exception(msg);
1315 client.setLoginId(userId);
1316 client.setActive(true);
1318 String userInString = null;
1319 userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
1320 logger.debug(EELFLoggerDelegate.debugLogger,
1321 "about to post new client to remote application, users json = " + userInString);
1322 applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user", userId));
1326 @SuppressWarnings("unchecked")
1327 protected void applyChangesToAppRolesRequest(Long appId, Long userId, String updateStatus, EPUserAppRolesRequest epUserAppRolesRequest) {
1328 final Map<String, Long> epRequestParams = new HashMap<>();
1330 EPUserAppRolesRequest epAppRolesRequestData = epUserAppRolesRequest;
1331 epAppRolesRequestData.setUpdatedDate(new Date());
1332 epAppRolesRequestData.setRequestStatus(updateStatus);
1333 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1334 addiotonalUpdateParam.put("userId", userId);
1335 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1336 epRequestParams.put("reqId", epUserAppRolesRequest.getId());
1337 List<EPUserAppRolesRequestDetail> epUserAppRolessDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1338 epUserAppRolessDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1339 epRequestParams, null);
1340 if (epUserAppRolessDetailList.size() > 0) {
1341 for (EPUserAppRolesRequestDetail epRequestUpdateData : epUserAppRolessDetailList) {
1342 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateData;
1343 epAppRoleDetailData.setReqType(updateStatus);
1344 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1345 HashMap<String, Long> updateDetailsParam = new HashMap<String, Long>();
1346 addiotonalUpdateParam.put("reqId", epUserAppRolesRequest.getId());
1347 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParam);
1350 logger.debug(EELFLoggerDelegate.debugLogger, "The request is set to complete");
1352 } catch (Exception e) {
1353 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToAppRolesRequest failed", e);
1357 @SuppressWarnings("unchecked")
1358 public void applyChangesToUserAppRolesForMyLoginsRequest(EPUser user, Long appId) {
1359 final Map<String, Long> params = new HashMap<>();
1360 final Map<String, Long> epDetailParams = new HashMap<>();
1361 List<EPUserAppRolesRequest> epRequestIdVal = new ArrayList<EPUserAppRolesRequest>();
1362 params.put("appId", appId);
1363 params.put("userId", user.getId());
1365 epRequestIdVal = (List<EPUserAppRolesRequest>) dataAccessService
1366 .executeNamedQuery("userAppRolesRequestList", params, null);
1367 if (epRequestIdVal.size() > 0) {
1368 EPUserAppRolesRequest epAppRolesRequestData = epRequestIdVal.get(0);
1369 epAppRolesRequestData.setUpdatedDate(new Date());
1370 epAppRolesRequestData.setRequestStatus("O");
1371 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1372 addiotonalUpdateParam.put("userId", user.getId());
1373 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1374 epDetailParams.put("reqId", epAppRolesRequestData.getId());
1375 List<EPUserAppRolesRequestDetail> epUserAppRolesDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1376 epUserAppRolesDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1377 epDetailParams, null);
1378 if (epUserAppRolesDetailList.size() > 0) {
1379 for (EPUserAppRolesRequestDetail epRequestUpdateList : epUserAppRolesDetailList) {
1380 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateList;
1381 epAppRoleDetailData.setReqType("O");
1382 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1383 HashMap<String, Long> updateDetailsParams = new HashMap<String, Long>();
1384 addiotonalUpdateParam.put("reqId", epAppRolesRequestData.getId());
1385 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParams);
1387 logger.debug(EELFLoggerDelegate.debugLogger, "User App roles request from User Page is overridden");
1391 } catch (Exception e) {
1392 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e);
1397 * Pushes specified user details to the specified remote app.
1400 * OrgUserId identifying user at remote app in REST endpoint path
1402 * User details to be pushed
1405 * @param applicationsRestClientService
1406 * @throws HTTPException
1408 protected void postUserToRemoteApp(String userId, EPUser user, EPApp app,
1409 ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
1411 getUser(userId, app, applicationsRestClientService);
1416 * It returns user details for single org user id
1420 * if user exists it returns list of user details otherwise empty value
1422 @SuppressWarnings("unchecked")
1423 private List<EPUser> checkIfUserExists(Map<String, String> userParams){
1424 return (List<EPUser>)dataAccessService.executeNamedQuery("epUserAppId", userParams, null);
1428 * It checks whether the new user is valid or not otherwise throws exception
1433 * Checks if user is valid and returns message otherwise throws exception
1436 private String validateNewUser(String orgUserId, EPApp app) throws Exception {
1437 EPUser epUser = searchService.searchUserByUserId(orgUserId);
1438 if (epUser == null) {
1439 throw new Exception("User does not exist");
1440 } else if (!epUser.getOrgUserId().equals(orgUserId)) {
1441 throw new Exception("User does not exist");
1442 } else if (app == null) {
1443 throw new Exception("Application does not exist");
1445 return "Saved Successfully";
1449 * Checks if the fields exists or not
1452 * contains user information
1456 * throws exception if the field is not valid
1458 private void validateExternalRequestFields(List<EPUser> userList, EPApp app) throws Exception{
1459 if (userList.size() == 0 || userList.isEmpty() ) {
1460 throw new Exception("User does not exist");
1461 } else if(app == null) {
1462 throw new Exception("Application does not exist");
1463 } else if(!app.getEnabled() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1464 throw new Exception(app.getMlAppName()+" application is unavailable");
1468 @SuppressWarnings("unchecked")
1469 public ExternalRequestFieldsValidator setExternalRequestUserAppRole(ExternalSystemUser newAppRolesForUser, String reqType) {
1470 boolean result = false;
1471 boolean externalSystemRequest = true;
1472 final Map<String, Long> params = new HashMap<>();
1473 final Map<String, String> userParams = new HashMap<>();
1474 List<EPUser> userInfo = null;
1476 List<EPUserAppRolesRequest> epRequestId = null;
1477 String orgUserId = "";
1478 String updateStatus = "";
1479 String reqMessage = "";
1481 if (newAppRolesForUser != null && newAppRolesForUser.getLoginId() != null) {
1482 orgUserId = newAppRolesForUser.getLoginId().trim();
1484 String appName = newAppRolesForUser.getApplicationName();
1485 String logMessage = ("DELETE").equals(reqType) ? "Deleting": "Assigning/Updating" ;
1486 if (orgUserId.length() > 0) {
1487 ObjectMapper mapper = new ObjectMapper();
1488 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1489 int epRequestIdSize = 0;
1491 app = appsService.getAppDetail(appName);
1492 userParams.put("orgUserIdValue", orgUserId);
1493 userInfo = checkIfUserExists(userParams);
1494 reqMessage = "Updated Successfully";
1495 if (!reqType.equals("DELETE") && (userInfo.size() == 0 || userInfo.isEmpty())) {
1496 reqMessage = validateNewUser(orgUserId, app);
1498 if (userInfo.size() != 0 || !userInfo.isEmpty()) {
1499 validateExternalRequestFields(userInfo, app);
1500 user = userInfo.get(0);
1501 params.put("appId", app.getId());
1502 params.put("userId", user.getId());
1503 epRequestId = (List<EPUserAppRolesRequest>) dataAccessService
1504 .executeNamedQuery("userAppRolesRequestList", params, null);
1505 epRequestIdSize = epRequestId.size();
1508 //If Non-Centralized app make sure you sync app roles before assigning to user
1509 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !app.getCentralAuth()) {
1510 logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Starting GET roles for app {}",app.getId());
1511 EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, app.getId(), "/roles");
1512 logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Finshed GET roles for app {} and payload {}",app.getId(), appRoles);
1513 if (appRoles.length > 0) {
1514 syncAppRoles(sessionFactory, app.getId(), appRoles);
1517 List<RoleInAppForUser> roleInAppForUserList = roleInAppForUserList(newAppRolesForUser.getRoles(),
1518 app.getId(), app.getMlAppName());
1519 List<EcompUserAppRoles> userRoleList = null;
1520 if(!userInfo.isEmpty()){
1521 final Map<String, Long> appParams = new HashMap<>();
1522 appParams.put("userId", user.getId());
1523 appParams.put("appId", app.getId());
1524 userRoleList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", appParams, null);
1526 // Check if list contains just account admin role
1527 boolean checkIfAdminRoleExists = false;
1528 if (reqType.equals("DELETE") && userRoleList!=null) {
1529 checkIfAdminRoleExists = userRoleList.stream()
1530 .anyMatch(userRole -> userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1532 checkIfAdminRoleExists = roleInAppForUserList.stream()
1533 .anyMatch(roleList -> roleList.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1535 // if Centralized app
1536 if (app.getCentralAuth()) {
1537 // We should add If user does not exist in remote application
1539 // If adding just account admin role dont make remote application user call or
1540 // if request has only single non admin role then make remote call
1541 if (!(app.getId().equals(PortalConstants.PORTAL_APP_ID) && reqType.equals("DELETE"))
1542 && ((checkIfAdminRoleExists && roleInAppForUserList.size() > 1)
1543 || (!checkIfAdminRoleExists && roleInAppForUserList.size() >= 1))) {
1544 // check if admin role exist then delete
1545 List<RoleInAppForUser> remoteUserRoles = roleInAppForUserList.stream()
1546 .collect(Collectors.toList());
1547 remoteUserRoles.removeIf(role -> {
1548 return (role.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1550 String orgUserIdNewOrExist = (userInfo.size() != 0 || !userInfo.isEmpty()) ? user.getOrgUserId() : orgUserId;
1551 pushRemoteUser(remoteUserRoles, orgUserIdNewOrExist , app, mapper, searchService,
1552 applicationsRestClientService,true);
1554 } catch (Exception e) {
1555 reqMessage = e.getMessage();
1556 logger.error(EELFLoggerDelegate.errorLogger, "setExternalRequestUserAppRole: Failed to added remote user", e);
1557 throw new Exception(reqMessage);
1559 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1560 applicationsRestClientService, app.getId(), orgUserId);
1561 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1562 userRolesInLocalApp);
1563 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1564 if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1565 // Apply changes in external Access system
1566 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, externalSystemRequest,false);
1568 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
1569 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1570 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,false);
1572 // If local application is not centralized
1573 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1574 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1575 applicationsRestClientService, app.getId(), orgUserId);
1576 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1577 userRolesInLocalApp);
1578 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,false);
1579 } else {// remote app
1580 // If adding just account admin role don't do remote application user call
1581 if (!((roleInAppForUserList.size() == 1 || reqType.equals("DELETE")) && checkIfAdminRoleExists)) {
1582 EPUser remoteAppUser = null;
1583 remoteAppUser = checkIfRemoteUserExits(orgUserId, app, applicationsRestClientService);
1584 if (remoteAppUser == null) {
1585 addRemoteUser(roleInAppForUserList, orgUserId, app, mapper, searchService,
1586 applicationsRestClientService);
1587 reqMessage = "Saved Successfully";
1590 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
1591 applicationsRestClientService, app.getId(), orgUserId,false);
1593 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1594 userRolesInRemoteApp);
1595 logger.info(EELFLoggerDelegate.debugLogger,
1596 "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
1597 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1598 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1600 // If no roles remain, request app to set user inactive.
1602 * if (userRolesInRemoteApp.size() == 0) {
1603 * logger.debug(EELFLoggerDelegate.debugLogger,
1604 * "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive"
1605 * , app, orgUserId); //TODO Need to fix the logged in user is not set to
1606 * inactive remoteAppUser.setActive(false); postUserToRemoteApp(orgUserId, user,
1607 * app, applicationsRestClientService); }
1611 // Here we are adding only we have single account admin in roleInAppForUserList and this should not add in remote
1612 if(!(reqType.equals("DELETE")) && userInfo.isEmpty()){
1613 reqMessage = "Saved Successfully";
1615 Set<EcompRole> userRolesInRemoteApp = constructUsersEcompRoles(roleInAppForUserList);
1617 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1618 userRolesInRemoteApp);
1619 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}",
1620 logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1621 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1625 reqMessage = "Failed to save the user app role(s)";
1627 if (epRequestIdSize > 0 && !userInfo.isEmpty()) {
1629 applyChangesToAppRolesRequest(app.getId(), user.getId(), updateStatus, epRequestId.get(0));
1632 } catch (Exception e) {
1633 String message = String.format("setExternalRequestUserAppRole: Failed to create user or update user roles for User %s, AppId %s",
1634 orgUserId, appName);
1635 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1637 reqMessage = e.getMessage();
1638 if(epRequestIdSize > 0 && userInfo!=null && !userInfo.isEmpty()){
1640 applyChangesToAppRolesRequest(app.getId(), user.getId(),
1641 updateStatus, epRequestId.get(0));
1646 return new ExternalRequestFieldsValidator(result, reqMessage);
1651 * @param roleInAppForUserList
1653 * @param applicationsRestClientService
1656 * @return Set<EcompRole>
1657 * @throws JsonProcessingException
1658 * @throws HTTPException
1660 private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
1661 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
1662 throws JsonProcessingException, HTTPException {
1663 Set<EcompRole> updatedUserRoles = constructUsersEcompRoles(roleInAppForUserList);
1664 return updatedUserRoles;
1668 * It constructs and returns list of user app roles when the external API role approval system calls
1671 * @param roleInAppForUserList
1673 * @return list of user app roles
1675 * throws exceptions if role id does not exits
1677 private List<RoleInAppForUser> roleInAppForUserList(List<ExternalSystemRoleApproval> roleInAppForUserList,
1678 Long appId, String appName) throws Exception {
1679 List<RoleInAppForUser> existingUserRoles = new ArrayList<RoleInAppForUser>();
1680 EPRole existingAppRole = null;
1681 for (ExternalSystemRoleApproval roleInAppForUser : roleInAppForUserList) {
1682 RoleInAppForUser ecompRole = new RoleInAppForUser();
1683 existingAppRole = epRoleService.getAppRole(roleInAppForUser.getRoleName(), appId);
1684 if (existingAppRole == null) {
1685 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1686 roleInAppForUserList);
1687 throw new Exception("'" +roleInAppForUser.getRoleName() + "'" +" role does not exist for " + appName + " application");
1689 if (!existingAppRole.getActive()) {
1690 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1691 roleInAppForUserList);
1692 throw new Exception(roleInAppForUser.getRoleName() + " role is unavailable for "+ appName + " application");
1694 ecompRole.roleId = (appId == 1 || roleInAppForUser.getRoleName().equals(PortalConstants.ADMIN_ROLE)) ? existingAppRole.getId() : existingAppRole.getAppRoleId();
1695 ecompRole.roleName = roleInAppForUser.getRoleName();
1696 ecompRole.isApplied = true;
1697 existingUserRoles.add(ecompRole);
1700 return existingUserRoles;
1709 * @param applicationsRestClientService
1711 * @throws HTTPException
1713 protected EPUser getUserFromApp(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1714 throws HTTPException {
1716 if (app.getId() == PortalConstants.PORTAL_APP_ID) {
1717 // Map<String,String> params = new HashMap<String,String>();
1718 // params.put("sbcid",userId);
1719 @SuppressWarnings("unchecked")
1720 List<EPUser> userList = (List<EPUser>) dataAccessService
1721 .executeQuery("from EPUser where orgUserId='" + userId + "'", null);
1722 if (userList != null && !userList.isEmpty())
1723 return userList.get(0);
1729 return getUser(userId, app, applicationsRestClientService);
1732 protected EPUser getUser(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1733 throws HTTPException {
1734 return applicationsRestClientService.get(EPUser.class, app.getId(), String.format("/user/%s", userId), true);
1738 protected boolean isAppUpgradeVersion(EPApp app){
1743 public ExternalSystemAccess getExternalRequestAccess(){
1744 ExternalSystemAccess res = null;
1746 res = new ExternalSystemAccess(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE,
1747 Boolean.parseBoolean(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE)));
1748 } catch (Exception e) {
1749 logger.error(EELFLoggerDelegate.errorLogger, "getExternalRequestAccess failed" + e.getMessage());
1757 * @see org.onap.portalapp.portal.service.UserRolesService#
1758 * getAppRolesForUser(java.lang.Long, java.lang.String)
1760 @SuppressWarnings("unchecked")
1761 public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId, Boolean extRequestValue,EPUser user) {
1762 List<RoleInAppForUser> rolesInAppForUser = null;
1763 EPApp app = appsService.getApp(appId);
1764 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - app = {}", app);
1766 // for onap portal app, no need to make a remote call
1767 List<Role> roleList = new ArrayList<>();
1768 if (appId == PortalConstants.PORTAL_APP_ID) {
1769 if(app.getCentralAuth()){
1770 List<CentralV2Role> cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey());
1771 for(CentralV2Role cenRole : cenRoleList){
1772 Role role = new Role();
1773 role.setActive(cenRole.getActive());
1774 role.setId(cenRole.getId());
1775 role.setName(cenRole.getName());
1776 role.setPriority(cenRole.getPriority());
1780 roleList = roleService.getAvailableRoles(userId);
1782 List<Role> activeRoleList = new ArrayList<Role>();
1783 for(Role role: roleList) {
1784 if(role.getActive()) {
1785 if(role.getId() != 1){ // prevent portal admin from being added
1786 activeRoleList.add(role);
1787 } else if(extRequestValue){
1788 activeRoleList.add(role);
1793 EPUser localUser = getUserFromApp(userId, app, applicationsRestClientService);
1794 // If localUser does not exists return roles
1795 Set<EPRole> roleSet = null;
1796 EPRole[] roleSetList = null;
1797 if(localUser != null){
1798 roleSet = localUser.getAppEPRoles(app);
1799 roleSetList = roleSet.toArray(new EPRole[0]);
1801 rolesInAppForUser = constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue);
1802 return rolesInAppForUser;
1805 EcompRole[] appRoles = null;
1806 List<EcompRole> roles = new ArrayList<>();
1807 if (app.getCentralAuth()) {
1808 final Map<String, Long> appParams = new HashMap<>();
1809 appParams.put("appId", app.getId());
1810 List<EPRole> applicationRoles = dataAccessService.executeNamedQuery("getActiveRolesOfApplication",
1813 EPApp application = appService.getApp(appId);
1814 boolean checkIfUserisApplicationAccAdmin = adminRolesService.isAccountAdminOfApplication(user,
1817 List<EPRole> rolesetwithfunctioncds = new ArrayList<EPRole>();
1818 for (EPRole role : applicationRoles) {
1819 Map<String, Long> params = new HashMap<>();
1820 params.put("roleId", role.getId());
1821 params.put(APP_ID, app.getId());
1822 List<CentralV2RoleFunction> cenRoleFuncList = dataAccessService
1823 .executeNamedQuery("getAppRoleFunctionList", params, null);
1825 // SortedSet<CentralV2RoleFunction> roleFunctionSet =
1827 SortedSet<RoleFunction> roleFunctionSet = new TreeSet<>();
1828 for (CentralV2RoleFunction roleFunc : cenRoleFuncList) {
1830 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1831 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
1832 String type = externalAccessRolesService.getFunctionCodeType(roleFunc.getCode());
1833 String action = externalAccessRolesService.getFunctionCodeAction(roleFunc.getCode());
1834 String name = roleFunc.getName();
1836 RoleFunction function = new RoleFunction();
1837 function.setAction(action);
1838 function.setType(type);
1839 function.setCode(functionCode);
1840 function.setName(name);
1841 roleFunctionSet.add(function);
1842 role.setRoleFunctions(roleFunctionSet);
1845 rolesetwithfunctioncds.add(role);
1850 for (EPRole role1 : rolesetwithfunctioncds) {
1851 EcompRole ecompRole = new EcompRole();
1852 ecompRole.setId(role1.getId());
1853 ecompRole.setName(role1.getName());
1854 ecompRole.setRoleFunctions(role1.getRoleFunctions());
1855 roles.add(ecompRole);
1858 if (checkIfUserisApplicationAccAdmin) {
1859 appRoles = roles.toArray(new EcompRole[roles.size()]);
1860 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() If Logged in user checkIfUserisApplicationAccAdmin- appRoles = {}", appRoles);
1861 } else if (adminRolesService.isRoleAdmin(user) && !checkIfUserisApplicationAccAdmin) {
1862 List<EcompRole> roleAdminAppRoles = new ArrayList<>();
1863 List<String> roleAdminAppRolesNames = new ArrayList<>();
1864 final Map<String, Long> userParams = new HashMap<>();
1865 userParams.put("userId", user.getId());
1866 List<String> getUserApproverRoles = dataAccessService.executeNamedQuery("getUserApproverRoles", userParams, null);
1868 List<EcompRole> userapproverRolesList = new ArrayList<>();
1869 for (String str : getUserApproverRoles) {
1870 EcompRole epRole = roles.stream().filter(x -> str.equals(x.getName())).findAny().orElse(null);
1872 userapproverRolesList.add(epRole);
1874 // roles.removeAll(userapproverRolesList);
1875 for (EcompRole role : userapproverRolesList) {
1877 List<RoleFunction> roleFunList = new ArrayList<>();
1878 roleFunList.addAll(role.getRoleFunctions());
1879 boolean checkIfFunctionsExits = roleFunList.stream()
1880 .anyMatch(roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
1881 if (checkIfFunctionsExits) {
1882 roleAdminAppRoles.add(role);
1883 List<RoleFunction> filteredList = roleFunList.stream()
1884 .filter(x -> "Approver".equalsIgnoreCase(x.getType())).collect(Collectors.toList());
1885 roleAdminAppRolesNames.addAll(filteredList.stream().map(RoleFunction::getCode)
1886 .collect(Collectors.toList()));
1887 // roleAdminAppRolesNames = filteredList.stream().map(RoleFunction::getCode)
1888 // .collect(Collectors.toList());
1891 for (String name : roleAdminAppRolesNames) {
1892 EcompRole ecompRole = roles.stream().filter(x -> name.equals(x.getName())).findAny()
1894 if (ecompRole != null)
1895 roleAdminAppRoles.add(ecompRole);
1898 appRoles = roleAdminAppRoles.toArray(new EcompRole[roleAdminAppRoles.size()]);
1902 appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
1904 // Test this error case, for generating an internal ONAP Portal
1906 // EcompRole[] appRoles = null;
1907 // If there is an exception in the rest client api, then null will
1909 if (appRoles != null) {
1910 if(!app.getCentralAuth()) {
1911 syncAppRoles(sessionFactory, appId, appRoles);
1913 EcompRole[] userAppRoles = null;
1917 if(app.getCentralAuth()){
1918 final Map<String, String> params = new HashMap<>();
1919 final Map<String, Long> userParams = new HashMap<>();
1920 params.put("orgUserIdValue", userId);
1921 List<EPUser> actualUser = dataAccessService.executeNamedQuery("epUserAppId", params, null);
1922 userParams.put("appId", app.getId());
1923 userParams.put("userId", actualUser.get(0).getId());
1924 List<EPUserAppCurrentRoles> userAppsRolesList = dataAccessService.executeNamedQuery("getUserAppCurrentRoles", userParams, null);
1926 List<EcompRole> setUserRoles = new ArrayList<>();
1927 for(EPUserAppCurrentRoles role : userAppsRolesList){
1928 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - userAppsRolesList get userRolename = {}", role.getRoleName());
1929 EcompRole ecompRole = new EcompRole();
1930 ecompRole.setId(role.getRoleId());
1931 ecompRole.setName(role.getRoleName());
1932 setUserRoles.add(ecompRole);
1935 boolean checkIfUserisAccAdmin = setUserRoles.stream()
1936 .anyMatch(ecompRole -> ecompRole.getId() == 999L);
1938 if (!checkIfUserisAccAdmin) {
1939 List<EcompRole> userApplicationRolesList = setUserRoles;
1940 List<EcompRole> appRolesList = Arrays.asList(appRoles);
1941 Set<EcompRole> finalUserAppRolesList = new HashSet<>();
1943 List<String> roleNames = new ArrayList<>();
1944 for (EcompRole role : userApplicationRolesList) {
1945 EcompRole epRole = appRolesList.stream()
1946 .filter(x -> role.getName().equals(x.getName())).findAny().orElse(null);
1947 List<RoleFunction> roleFunList = new ArrayList<>();
1948 if(epRole.getRoleFunctions().size()>0)
1949 roleFunList.addAll(epRole.getRoleFunctions());
1950 boolean checkIfFunctionsExits = roleFunList.stream().anyMatch(
1951 roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
1952 if (checkIfFunctionsExits) {
1953 finalUserAppRolesList.add(role);
1954 List<RoleFunction> filteredList = roleFunList.stream()
1955 .filter(x -> "Approver".equalsIgnoreCase(x.getType()))
1956 .collect(Collectors.toList());
1957 roleNames = filteredList.stream().map(RoleFunction::getCode)
1958 .collect(Collectors.toList());
1961 for (String name : roleNames) {
1962 EcompRole ecompRole = appRolesList.stream()
1963 .filter(x -> name.equals(x.getName())).findAny().orElse(null);
1964 if (ecompRole != null)
1965 finalUserAppRolesList.add(ecompRole);
1970 for (String name : roleNames) {
1972 boolean checkIfFunctionsExits = userAppsRolesList.stream().anyMatch(
1973 role -> role.getRoleName().equalsIgnoreCase(name));
1974 if(checkIfFunctionsExits)
1976 EcompRole epRole = appRolesList.stream().filter(x -> name.equals(x.getName()))
1977 .findAny().orElse(null);
1979 setUserRoles.add(epRole);
1983 userAppRoles = setUserRoles.toArray(new EcompRole[setUserRoles.size()]);
1986 userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
1987 String.format("/user/%s/roles", userId));
1989 } catch (HTTPException e) {
1990 // Some apps are returning 400 if user is not found.
1991 if (e.getResponseCode() == 400) {
1992 logger.debug(EELFLoggerDelegate.debugLogger,
1993 "getAppRolesForUser caught exception with response code 400; continuing", e);
1995 // Other response code, let it come thru.
1999 if (userAppRoles == null) {
2000 if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
2001 EcompPortalUtils.setExternalAppResponseCode(200);
2002 String message = String.format(
2003 "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
2004 + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
2005 + "Overriding to 200 until framework SDK returns a useful response.",
2006 Long.toString(appId), userId);
2007 logger.warn(EELFLoggerDelegate.applicationLogger, message);
2011 HashMap<Long, EcompRole> appRolesActiveMap =hashMapFromEcompRoles(appRoles);
2012 ArrayList<EcompRole> activeRoles = new ArrayList<EcompRole>();
2013 if(userAppRoles != null){
2014 for (int i = 0; i < userAppRoles.length; i++) {
2015 if (appRolesActiveMap.containsKey(userAppRoles[i].getId())) {
2016 EcompRole role = new EcompRole();
2017 role.setId(userAppRoles[i].getId());
2018 role.setName(userAppRoles[i].getName());
2019 activeRoles.add(role);
2023 EcompRole[] userAppRolesActive = activeRoles.toArray(new EcompRole[activeRoles.size()]);
2025 // If the remote application isn't down we MUST sync user
2026 // roles here in case we have this user here!
2027 syncUserRoles(sessionFactory, userId, appId, userAppRolesActive, extRequestValue, null);
2028 } catch (Exception e) {
2029 // TODO: we may need to check if user exists, maybe remote
2031 String message = String.format(
2032 "getAppRolesForUser: user %s does not exist in remote application %s", userId,
2033 Long.toString(appId));
2034 logger.error(EELFLoggerDelegate.errorLogger, message, e);
2035 userAppRoles = new EcompRole[0];
2037 rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
2039 } catch (Exception e) {
2040 String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
2041 Long.toString(appId));
2042 logger.error(EELFLoggerDelegate.errorLogger, message, e);
2044 return rolesInAppForUser;
2047 private boolean postUserRolesToMylogins(AppWithRolesForUser userAppRolesData,
2048 ApplicationsRestClientService applicationsRestClientService, Long appId, Long userId)
2049 throws JsonProcessingException, HTTPException {
2050 boolean result = false;
2051 ObjectMapper mapper = new ObjectMapper();
2052 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
2053 String userRolesAsString = mapper.writeValueAsString(userAppRolesData);
2054 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, as the endpoint is not defined yet from the Mylogins");
2055 applicationsRestClientService.post(AppWithRolesForUser.class, appId, userRolesAsString, String.format("/user/%s/myLoginroles", userId));
2059 @SuppressWarnings("unchecked")
2060 public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser userAppRolesData, EPUser user) {
2061 FieldsValidator fieldsValidator = new FieldsValidator();
2062 final Map<String, Long> params = new HashMap<>();
2063 List<EPUserAppRoles> appRole= null;
2065 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, still the endpoint is yet to be defined");
2066 boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService,
2067 userAppRolesData.getAppId(), user.getId());
2068 logger.debug(EELFLoggerDelegate.debugLogger,"putUserAppRolesRequest: result {}", result);
2070 params.put("appId", userAppRolesData.getAppId());
2071 EPUserAppRolesRequest epAppRolesRequestData = new EPUserAppRolesRequest();
2072 epAppRolesRequestData.setCreatedDate(new Date());
2073 epAppRolesRequestData.setUpdatedDate(new Date());
2074 epAppRolesRequestData.setUserId(user.getId());
2075 epAppRolesRequestData.setAppId(userAppRolesData.getAppId());
2076 epAppRolesRequestData.setRequestStatus("P");
2077 List<RoleInAppForUser> appRoleIdList = userAppRolesData.getAppRoles();
2078 Set<EPUserAppRolesRequestDetail> appRoleDetails = new LinkedHashSet<EPUserAppRolesRequestDetail>();
2079 dataAccessService.saveDomainObject(epAppRolesRequestData, null);
2080 for (RoleInAppForUser userAppRoles : appRoleIdList) {
2081 Boolean isAppliedVal = userAppRoles.isApplied;
2082 params.put("appRoleId", userAppRoles.roleId);
2084 appRole = (List<EPUserAppRoles>) dataAccessService.executeNamedQuery("appRoles", params, null);
2085 if (!appRole.isEmpty()) {
2086 EPUserAppRolesRequestDetail epAppRoleDetail = new EPUserAppRolesRequestDetail();
2087 epAppRoleDetail.setReqRoleId(appRole.get(0).getRoleId());
2088 epAppRoleDetail.setReqType("P");
2089 epAppRoleDetail.setEpRequestIdData(epAppRolesRequestData);
2090 dataAccessService.saveDomainObject(epAppRoleDetail, null);
2094 epAppRolesRequestData.setEpRequestIdDetail(appRoleDetails);
2095 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
2097 } catch (Exception e) {
2098 logger.error(EELFLoggerDelegate.errorLogger, "putUserAppRolesRequest failed", e);
2099 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
2101 return fieldsValidator;
2104 public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(EPUser userid, String appName) {
2105 Map<String, String> params = new HashMap<>();
2106 params.put("userid", userid.getId().toString());
2107 //params.put("appid", appid);
2108 params.put("appName", appName);
2110 @SuppressWarnings("unchecked")
2111 List<EPUserAppCatalogRoles> userAppRoles = (List<EPUserAppCatalogRoles>) dataAccessService
2112 .executeNamedQuery("userAppCatalogRoles", params, null);
2113 return userAppRoles;
2116 public String updateRemoteUserProfile(String orgUserId, Long appId) {
2117 ObjectMapper mapper = new ObjectMapper();
2118 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
2119 EPUser client = searchService.searchUserByUserId(orgUserId);
2120 EPUser newUser = new EPUser();
2121 newUser.setActive(client.getActive());
2122 newUser.setFirstName(client.getFirstName());
2123 newUser.setLastName(client.getLastName());
2124 newUser.setLoginId(client.getLoginId());
2125 newUser.setLoginPwd(client.getLoginPwd());
2126 newUser.setMiddleInitial(client.getMiddleInitial());
2127 newUser.setEmail(client.getEmail());
2128 newUser.setOrgUserId(client.getLoginId());
2130 String userAsString = mapper.writeValueAsString(newUser);
2131 List<EPApp> appList = appsService.getUserRemoteApps(client.getId().toString());
2132 // applicationsRestClientService.post(EPUser.class, appId,
2133 // userAsString, String.format("/user", orgUserId));
2134 for (EPApp eachApp : appList) {
2136 applicationsRestClientService.post(EPUser.class, eachApp.getId(), userAsString,
2137 String.format("/user/%s", orgUserId));
2138 } catch (Exception e) {
2139 logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId()
2140 + " in remote app. appId = " + eachApp.getId());
2143 } catch (Exception e) {
2144 logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
2155 * @see org.onap.portalapp.portal.service.UserRolesService#
2156 * getCachedAppRolesForUser(java.lang.Long, java.lang.Long)
2158 @SuppressWarnings("deprecation")
2159 public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId) {
2160 // Find the records for this user-app combo, if any
2161 String filter = " where user_id = " + Long.toString(userId) + " and app_id = " + Long.toString(appId);
2162 @SuppressWarnings("unchecked")
2163 List<EPUserApp> roleList = dataAccessService.getList(EPUserApp.class, filter, null, null);
2164 logger.debug(EELFLoggerDelegate.debugLogger, "getCachedAppRolesForUser: list size is {}", roleList.size());
2169 * It retrieves and returns list of user app roles for local and remote applications based app id
2172 * @return list of user app roles
2173 * @throws HTTPException
2175 public List<UserApplicationRoles> getUsersFromAppEndpoint(Long appId) throws HTTPException {
2176 ArrayList<UserApplicationRoles> userApplicationRoles = new ArrayList<UserApplicationRoles>();
2178 EPApp app = appsService.getApp(appId);
2179 //If local or centralized application
2180 if (appId == PortalConstants.PORTAL_APP_ID || app.getCentralAuth()) {
2181 @SuppressWarnings("unchecked")
2182 List<EPUser> userList = (List<EPUser>) dataAccessService.executeNamedQuery("getActiveUsers", null, null);
2183 for (EPUser user : userList) {
2184 UserApplicationRoles userWithAppRoles = convertToUserApplicationRoles(appId, user, app);
2185 if (userWithAppRoles.getRoles() != null && userWithAppRoles.getRoles().size() > 0)
2186 userApplicationRoles.add(userWithAppRoles);
2192 RemoteUserWithRoles[] remoteUsers = null;
2193 String remoteUsersString = applicationsRestClientService.getIncomingJsonString(appId, "/users");
2195 remoteUsers = doGetUsers(isAppUpgradeVersion(app), remoteUsersString);
2197 userApplicationRoles = new ArrayList<UserApplicationRoles>();
2198 for (RemoteUserWithRoles remoteUser : remoteUsers) {
2199 UserApplicationRoles userWithRemoteAppRoles = convertToUserApplicationRoles(appId, remoteUser);
2200 if (userWithRemoteAppRoles.getRoles() != null && userWithRemoteAppRoles.getRoles().size() > 0) {
2201 userApplicationRoles.add(userWithRemoteAppRoles);
2203 logger.debug(EELFLoggerDelegate.debugLogger,
2204 "User " + userWithRemoteAppRoles.getOrgUserId() + " doesn't have any roles assigned to any app.");
2209 return userApplicationRoles;
2216 * @param appgetUsersFromAppEndpoint
2219 private UserApplicationRoles convertToUserApplicationRoles(Long appId, EPUser user, EPApp app) {
2220 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
2221 userWithRemoteAppRoles.setAppId(appId);
2222 userWithRemoteAppRoles.setOrgUserId(user.getOrgUserId());
2223 userWithRemoteAppRoles.setFirstName(user.getFirstName());
2224 userWithRemoteAppRoles.setLastName(user.getLastName());
2225 userWithRemoteAppRoles.setRoles(convertToRemoteRoleList(user, app));
2226 return userWithRemoteAppRoles;
2235 @SuppressWarnings("unchecked")
2236 private List<RemoteRole> convertToRemoteRoleList(EPUser user, EPApp app) {
2237 List<RemoteRole> roleList = new ArrayList<RemoteRole>();
2238 SortedSet<EPRole> roleSet = user.getAppEPRoles(app);
2239 for (EPRole role : roleSet) {
2240 logger.debug(EELFLoggerDelegate.debugLogger, "In convertToRemoteRoleList() - for user {}, found Name {}", user.getOrgUserId(), role.getName());
2241 RemoteRole rRole = new RemoteRole();
2242 rRole.setId(role.getId());
2243 rRole.setName(role.getName());
2244 roleList.add(rRole);
2247 //Get the active roles of user for that application using query
2248 List<EPRole> userEpRoleList = new ArrayList<>();
2249 final Map<String, Long> params = new HashMap<>();
2250 params.put("appId", app.getId());
2251 params.put("userId", user.getId());
2252 userEpRoleList = dataAccessService.executeNamedQuery("getUserRoleOnUserIdAndAppId", params, null);
2254 for (EPRole remoteUserRoleList : userEpRoleList) {
2256 RemoteRole remoteRoleListId = roleList.stream().filter(x -> remoteUserRoleList.getId().equals(x.getId()))
2257 .findAny().orElse(null);
2258 if (remoteRoleListId == null) {
2259 logger.debug(EELFLoggerDelegate.debugLogger,
2260 "Adding the role to the rolelist () - for user {}, found Name {}", user.getOrgUserId(),
2262 remoteUserRoleList.getName());
2263 RemoteRole role = new RemoteRole();
2264 role.setId(remoteUserRoleList.getId());
2265 role.setName(remoteUserRoleList.getName());
2272 logger.debug(EELFLoggerDelegate.debugLogger, "rolelist size of the USER() - for user {}, found RoleListSize {}", user.getOrgUserId(), roleList.size());
2280 public RemoteUserWithRoles[] doGetUsers(boolean postOpenSource, String remoteUsersString) {
2282 ObjectMapper mapper = new ObjectMapper();
2284 return mapper.readValue(remoteUsersString, RemoteUserWithRoles[].class);
2285 } catch (IOException e) {
2286 logger.error(EELFLoggerDelegate.errorLogger,
2287 "doGetUsers : Failed : Unexpected property in incoming JSON",
2289 logger.error(EELFLoggerDelegate.errorLogger,
2290 "doGetUsers : Incoming JSON that caused it --> " + remoteUsersString);
2293 return new RemoteUserWithRoles[0];
2296 @SuppressWarnings("unchecked")
2297 public List<EPUserApp> getEPUserAppList(Long appId, Long userId, Long roleId) {
2298 List<EPUserApp> userRoleList = new ArrayList<EPUserApp>();
2299 final Map<String, Long> params = new HashMap<>();
2300 params.put("appId", appId);
2301 params.put("userId", userId);
2302 params.put("roleId", roleId);
2303 userRoleList = dataAccessService.executeNamedQuery("getUserRoleOnUserIdAndRoleIdAndAppId", params, null);
2304 return userRoleList;
2308 /*public static void main(String[] args) {
2309 List<EcompRole> str1 = new ArrayList<String>();
2315 List<String> str2 = new ArrayList<String>();
2319 List<EcompRole> userApplicationRolesList = setUserRoles;
2320 List<EcompRole> appRolesList = Arrays.asList(appRoles);