2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
8 * Unless otherwise specified, all software contained herein is licensed
9 * under the Apache License, Version 2.0 (the "License");
10 * you may not use this software except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * Unless otherwise specified, all documentation contained herein is licensed
22 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23 * you may not use this documentation except in compliance with the License.
24 * You may obtain a copy of the License at
26 * https://creativecommons.org/licenses/by/4.0/
28 * Unless required by applicable law or agreed to in writing, documentation
29 * distributed under the License is distributed on an "AS IS" BASIS,
30 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31 * See the License for the specific language governing permissions and
32 * limitations under the License.
34 * ============LICENSE_END============================================
39 package org.onap.portalapp.portal.service;
41 import java.io.IOException;
42 import java.util.ArrayList;
43 import java.util.Arrays;
44 import java.util.Collection;
45 import java.util.Date;
46 import java.util.HashMap;
47 import java.util.HashSet;
48 import java.util.LinkedHashSet;
49 import java.util.List;
52 import java.util.SortedSet;
53 import java.util.TreeSet;
54 import java.util.stream.Collectors;
56 import javax.servlet.http.HttpServletResponse;
58 import org.apache.commons.lang.StringUtils;
59 import org.apache.cxf.transport.http.HTTPException;
60 import org.hibernate.SQLQuery;
61 import org.hibernate.Session;
62 import org.hibernate.SessionFactory;
63 import org.hibernate.Transaction;
64 import org.json.JSONArray;
65 import org.json.JSONObject;
66 import org.onap.portalapp.externalsystemapproval.model.ExternalSystemRoleApproval;
67 import org.onap.portalapp.externalsystemapproval.model.ExternalSystemUser;
68 import org.onap.portalapp.portal.domain.CentralV2RoleFunction;
69 import org.onap.portalapp.portal.domain.EPApp;
70 import org.onap.portalapp.portal.domain.EPRole;
71 import org.onap.portalapp.portal.domain.EPUser;
72 import org.onap.portalapp.portal.domain.EPUserApp;
73 import org.onap.portalapp.portal.domain.EPUserAppCatalogRoles;
74 import org.onap.portalapp.portal.domain.EPUserAppRoles;
75 import org.onap.portalapp.portal.domain.EPUserAppRolesRequest;
76 import org.onap.portalapp.portal.domain.EPUserAppRolesRequestDetail;
77 import org.onap.portalapp.portal.domain.ExternalSystemAccess;
78 import org.onap.portalapp.portal.exceptions.SyncUserRolesException;
79 import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
80 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
81 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
82 import org.onap.portalapp.portal.transport.AppWithRolesForUser;
83 import org.onap.portalapp.portal.transport.CentralV2Role;
84 import org.onap.portalapp.portal.transport.EPUserAppCurrentRoles;
85 import org.onap.portalapp.portal.transport.EcompUserAppRoles;
86 import org.onap.portalapp.portal.transport.ExternalAccessUser;
87 import org.onap.portalapp.portal.transport.ExternalAccessUserRoleDetail;
88 import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator;
89 import org.onap.portalapp.portal.transport.ExternalRoleDescription;
90 import org.onap.portalapp.portal.transport.FieldsValidator;
91 import org.onap.portalapp.portal.transport.FunctionalMenuItem;
92 import org.onap.portalapp.portal.transport.FunctionalMenuRole;
93 import org.onap.portalapp.portal.transport.RemoteRole;
94 import org.onap.portalapp.portal.transport.RemoteRoleV1;
95 import org.onap.portalapp.portal.transport.RemoteUserWithRoles;
96 import org.onap.portalapp.portal.transport.RoleInAppForUser;
97 import org.onap.portalapp.portal.transport.RolesInAppForUser;
98 import org.onap.portalapp.portal.transport.UserApplicationRoles;
99 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
100 import org.onap.portalapp.portal.utils.EcompPortalUtils;
101 import org.onap.portalapp.portal.utils.PortalConstants;
102 import org.onap.portalapp.util.EPUserUtils;
103 import org.onap.portalapp.util.SystemType;
104 import org.onap.portalsdk.core.domain.Role;
105 import org.onap.portalsdk.core.domain.RoleFunction;
106 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
107 import org.onap.portalsdk.core.restful.domain.EcompRole;
108 import org.onap.portalsdk.core.service.DataAccessService;
109 import org.onap.portalsdk.core.service.RoleService;
110 import org.onap.portalsdk.core.util.SystemProperties;
111 import org.springframework.beans.factory.annotation.Autowired;
112 import org.springframework.http.HttpEntity;
113 import org.springframework.http.HttpHeaders;
114 import org.springframework.http.HttpMethod;
115 import org.springframework.http.HttpStatus;
116 import org.springframework.http.ResponseEntity;
117 import org.springframework.web.client.HttpClientErrorException;
118 import org.springframework.web.client.RestTemplate;
120 import com.fasterxml.jackson.core.JsonProcessingException;
121 import com.fasterxml.jackson.databind.DeserializationFeature;
122 import com.fasterxml.jackson.databind.ObjectMapper;
125 public class UserRolesCommonServiceImpl {
127 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesCommonServiceImpl.class);
129 private static final Object syncRests = new Object();
131 private static final String APP_ID = "appId";
134 private DataAccessService dataAccessService;
136 private SessionFactory sessionFactory;
138 private SearchService searchService;
140 private EPAppService appsService;
142 private ApplicationsRestClientService applicationsRestClientService;
144 private EPRoleService epRoleService;
146 private RoleService roleService;
148 private AdminRolesService adminRolesService;
150 private EPAppService appService;
152 private ExternalAccessRolesService externalAccessRolesService;
155 private AppsCacheService appsCacheService;
157 RestTemplate template = new RestTemplate();
162 * @return HashMap<Long, EcompRole>
164 private static HashMap<Long, EcompRole> hashMapFromEcompRoles(EcompRole[] ecompRoles) {
165 HashMap<Long, EcompRole> result = new HashMap<Long, EcompRole>();
166 if (ecompRoles != null) {
167 for (int i = 0; i < ecompRoles.length; i++) {
168 if (ecompRoles[i].getId() != null) {
169 result.put(ecompRoles[i].getId(), ecompRoles[i]);
180 protected void createLocalUserIfNecessary(String userId,boolean isSystemUser) {
181 if (StringUtils.isEmpty(userId)) {
182 logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty userId!");
185 Session localSession = null;
186 Transaction transaction = null;
188 localSession = sessionFactory.openSession();
189 transaction = localSession.beginTransaction();
190 @SuppressWarnings("unchecked")
191 List<EPUser> userList = localSession
192 .createQuery("from :name where orgUserId=:userId")
193 .setParameter("name",EPUser.class.getName())
194 .setParameter("userId",userId)
196 if (userList.size() == 0) {
197 EPUser client = null;
199 client = searchService.searchUserByUserId(userId);
201 client = new EPUser();
202 client.setOrgUserId(userId);
203 client.setSystemUser(true);
204 client.setFirstName(userId.substring(0,userId.indexOf("@")));
206 if (client == null) {
207 String msg = "createLocalUserIfNecessary: cannot create user " + userId
208 + ", because not found in phonebook";
209 logger.error(EELFLoggerDelegate.errorLogger, msg);
211 client.setLoginId(userId);
212 client.setActive(true);
213 localSession.save(client);
216 transaction.commit();
217 } catch (Exception e) {
218 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
219 EcompPortalUtils.rollbackTransaction(transaction, "searchOrCreateUser rollback, exception = " + e);
221 EcompPortalUtils.closeLocalSession(localSession, "searchOrCreateUser");
226 * This method return nothing and remove roles before adding any roles for an app
229 * @param localSession
230 * @param userAppRoles
231 * @param newUserAppRolesMap
233 private static void syncUserRolesExtension(EPUserApp userRole, Long appId, Session localSession, EcompRole[] userAppRoles, HashMap<Long, EcompRole> newUserAppRolesMap) {
235 Long userAppRoleId = 0L;
236 if (appId == PortalConstants.PORTAL_APP_ID) { // local app
237 userAppRoleId = userRole.getRoleId();
238 } else { // remote app
239 userAppRoleId = userRole.getAppRoleId();
242 if (!newUserAppRolesMap.containsKey(userAppRoleId)) {
243 localSession.delete(userRole);
245 newUserAppRolesMap.remove(userAppRoleId);
250 * Checks whether the role is inactive
254 * if role is inactive, throws exception
256 private void checkIfRoleInactive(EPRole epRole) throws Exception{
257 if(!epRole.getActive()){
258 throw new Exception(epRole.getName()+ " role is unavailable");
264 * @param sessionFactory
267 * @param userAppRoles
268 * @param extRequestValue
269 * set to false if request is from users page otherwise true
272 protected void syncUserRoles(SessionFactory sessionFactory, String userId, Long appId,
273 EcompRole[] userAppRoles, Boolean extRequestValue, String reqType) throws Exception {
274 Session localSession = null;
275 Transaction transaction = null;
276 String roleActive = null;
277 final Map<String, String> userAppParams = new HashMap<>();
278 final Map<String, String> appParams = new HashMap<>();
279 HashMap<Long, EcompRole> newUserAppRolesMap = hashMapFromEcompRoles(userAppRoles);
282 localSession = sessionFactory.openSession();
283 transaction = localSession.beginTransaction();
284 @SuppressWarnings("unchecked")
285 List<EPUser> userList = localSession
286 .createQuery("from :name where orgUserId=:userId")
287 .setParameter("name",EPUser.class.getName())
288 .setParameter("userId",userId)
290 if (userList.size() > 0) {
291 EPUser client = userList.get(0);
292 roleActive = ("DELETE".equals(reqType)) ? "" : " and role.active = 'Y'";
293 @SuppressWarnings("unchecked")
294 List<EPUserApp> userRoles = localSession.createQuery("from " + EPUserApp.class.getName()
295 + " where app.id=" + appId + roleActive + " and userId=" + client.getId()).list();
297 if ("DELETE".equals(reqType)) {
298 for (EPUserApp userAppRoleList : userRoles) {
299 userAppParams.put("roleName", String.valueOf(userAppRoleList.getRole().getName()));
300 userAppParams.put("appId", String.valueOf(appId));
301 appParams.put("appRoleName", userAppRoleList.getRole().getName());
302 @SuppressWarnings("unchecked")
303 List<EPRole> rolesList = (!userAppRoleList.getRole().getName().equals(PortalConstants.ADMIN_ROLE)) ? (List<EPRole>) dataAccessService.executeNamedQuery("getAppRoles", userAppParams, null) : (List<EPRole>) dataAccessService.executeNamedQuery("getPortalAppRoles", appParams, null);
304 if(rolesList.size() > 0 || !rolesList.isEmpty()){
305 checkIfRoleInactive(rolesList.get(0));
310 for (EPUserApp userRole : userRoles) {
311 if (!userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && userRole.getRoleId() != PortalConstants.SYS_ADMIN_ROLE_ID && !extRequestValue){
312 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
314 else if (extRequestValue && ("PUT".equals(reqType) || "POST".equals(reqType) || "DELETE".equals(reqType))){
315 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
317 else if (extRequestValue && !userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)){
318 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
321 Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values();
322 if (newRolesToAdd.size() > 0) {
323 EPApp app = (EPApp) localSession.get(EPApp.class, appId);
325 HashMap<Long, EPRole> rolesMap = new HashMap<Long, EPRole>();
326 if (appId.equals(PortalConstants.PORTAL_APP_ID)) { // local app
327 String appIdValue = "";
328 if(!extRequestValue){
329 appIdValue = "and id != " + PortalConstants.SYS_ADMIN_ROLE_ID;
331 @SuppressWarnings("unchecked")
332 List<EPRole> roles = localSession
333 .createQuery("from " + EPRole.class.getName() + " where appId is null " + appIdValue).list();
334 for (EPRole role : roles) {
336 rolesMap.put(role.getId(), role);
338 } else { // remote app
339 @SuppressWarnings("unchecked")
340 List<EPRole> roles = localSession
341 .createQuery("from :name where appId=:appId")
342 .setParameter("name",EPRole.class.getName())
343 .setParameter("appId",appId)
345 for (EPRole role : roles) {
346 if (!extRequestValue && app.getCentralAuth()) {
347 rolesMap.put(role.getId(), role);
349 rolesMap.put(role.getAppRoleId(), role);
355 for (EcompRole userRole : newRolesToAdd) {
356 EPUserApp userApp = new EPUserApp();
357 if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName().equals(PortalConstants.ADMIN_ROLE)) {
358 role = (EPRole) localSession.get(EPRole.class, new Long(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
359 userApp.setRole(role);
360 } else if ((userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) && !extRequestValue){
362 }else if((userRole.getId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)) && app.getId().equals(PortalConstants.PORTAL_APP_ID) && !extRequestValue){
366 userApp.setRole(rolesMap.get(userRole.getId()));
369 userApp.setUserId(client.getId());
371 localSession.save(userApp);
372 localSession.flush();
375 if (appId == PortalConstants.PORTAL_APP_ID) {
377 * for local app -- hack - always make sure fn_role
378 * table's app_id is null and not 1 for primary app in
379 * this case being onap portal app; reason: hibernate
380 * is rightly setting this to 1 while persisting to
381 * fn_role as per the mapping but SDK role management
382 * code expects the app_id to be null as there is no
383 * concept of App_id in SDK
385 localSession.flush();
386 SQLQuery sqlQuery = localSession
387 .createSQLQuery("update fn_role set app_id = null where app_id = 1 ");
388 sqlQuery.executeUpdate();
393 transaction.commit();
394 } catch (Exception e) {
395 logger.error(EELFLoggerDelegate.errorLogger, "syncUserRoles failed", e);
396 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
397 EcompPortalUtils.rollbackTransaction(transaction,
398 "Exception occurred in syncUserRoles, Details: " + e.toString());
399 if("DELETE".equals(reqType)){
400 throw new SyncUserRolesException(e.getMessage());
403 if(localSession != null)
404 localSession.close();
409 * Called when getting the list of roles for the user
412 * @param userAppRoles
413 * @return List<RoleInAppForUser>
415 protected List<RoleInAppForUser> constructRolesInAppForUserGet(EcompRole[] appRoles, EcompRole[] userAppRoles) {
416 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
418 Set<Long> userAppRolesMap = new HashSet<Long>();
419 if (userAppRoles != null) {
420 for (EcompRole ecompRole : userAppRoles) {
421 userAppRolesMap.add(ecompRole.getId());
424 logger.error(EELFLoggerDelegate.errorLogger,
425 "constructRolesInAppForUserGet has received userAppRoles list empty");
428 if (appRoles != null) {
429 for (EcompRole ecompRole : appRoles) {
430 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
431 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
432 rolesInAppForUser.add(roleForUser);
435 logger.error(EELFLoggerDelegate.errorLogger, "constructRolesInAppForUser has received appRoles list empty");
437 return rolesInAppForUser;
441 * Called when getting the list of roles for the user
444 * @param userAppRoles
445 * @param extRequestValue
446 * set to false if request is from users page otherwise true
447 * @return List<RoleInAppForUser>
449 protected List<RoleInAppForUser> constructRolesInAppForUserGet(List<Role> appRoles, EPRole[] userAppRoles, Boolean extRequestValue) {
450 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
452 Set<Long> userAppRolesMap = new HashSet<Long>();
453 if (userAppRoles != null) {
454 for (EPRole ecompRole : userAppRoles) {
455 userAppRolesMap.add(ecompRole.getId());
457 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - userAppRolesMap = {}", userAppRolesMap);
460 logger.error(EELFLoggerDelegate.errorLogger,
461 "constructRolesInAppForUserGet has received userAppRoles list empty.");
464 if (appRoles != null) {
466 for (Role ecompRole : appRoles) {
467 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - appRoles not null = {}", ecompRole);
469 if (ecompRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && !extRequestValue)
471 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
472 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
473 rolesInAppForUser.add(roleForUser);
474 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - rolesInAppForUser = {}", rolesInAppForUser);
478 logger.error(EELFLoggerDelegate.errorLogger,
479 "constructRolesInAppForUser has received appRoles list empty.");
481 return rolesInAppForUser;
486 * copies of methods in GetAppsWithUserRoleState
488 * @param sessionFactory
493 protected void syncAppRoles(SessionFactory sessionFactory, Long appId, EcompRole[] appRoles) throws Exception {
494 logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId);
495 HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles);
496 Session localSession = null;
497 Transaction transaction = null;
500 localSession = sessionFactory.openSession();
501 transaction = localSession.beginTransaction();
502 // Attention! All roles from remote application supposed to be
505 @SuppressWarnings("unchecked")
506 List<EPRole> currentAppRoles = localSession.createQuery("from :name where appId = :appId")
507 .setParameter("name",EPRole.class.getName())
508 .setParameter("appId",appId)
511 List<EPRole> obsoleteRoles = new ArrayList<EPRole>();
512 for (int i = 0; i < currentAppRoles.size(); i++) {
513 EPRole oldAppRole = currentAppRoles.get(i);
514 if (oldAppRole.getAppRoleId() != null) {
515 EcompRole role = null;
516 role = newRolesMap.get(oldAppRole.getAppRoleId());
518 if (!(role.getName() == null || oldAppRole.getName().equals(role.getName()))) {
519 oldAppRole.setName(role.getName());
520 localSession.update(oldAppRole);
522 oldAppRole.setActive(true);
523 newRolesMap.remove(oldAppRole.getAppRoleId());
525 obsoleteRoles.add(oldAppRole);
528 obsoleteRoles.add(oldAppRole);
531 Collection<EcompRole> newRolesToAdd = newRolesMap.values();
532 if (obsoleteRoles.size() > 0) {
533 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: we have obsolete roles to delete");
534 for (EPRole role : obsoleteRoles) {
535 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: obsolete role: " + role.toString());
536 Long roleId = role.getId();
537 // delete obsolete roles here
538 // Must delete all records with foreign key constraints on
540 // fn_user_role, fn_role_composite, fn_role_function,
541 // fn_user_pseudo_role, fn_menu_functional_roles.
542 // And for fn_menu_functional, if no other roles for that
543 // menu item, remove the url.
545 // Delete from fn_user_role
546 @SuppressWarnings("unchecked")
547 List<EPUserApp> userRoles = localSession.createQuery(
548 "from :name where app.id=:appId and role_id=:roleId")
549 .setParameter("name",EPUserApp.class.getName())
550 .setParameter("appId",appId)
551 .setParameter("roleId",roleId)
554 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: number of userRoles to delete: " + userRoles.size());
555 for (EPUserApp userRole : userRoles) {
556 logger.debug(EELFLoggerDelegate.debugLogger,
557 "syncAppRoles: about to delete userRole: " + userRole.toString());
558 localSession.delete(userRole);
559 logger.debug(EELFLoggerDelegate.debugLogger,
560 "syncAppRoles: finished deleting userRole: " + userRole.toString());
563 // Delete from fn_menu_functional_roles
564 @SuppressWarnings("unchecked")
565 List<FunctionalMenuRole> funcMenuRoles = localSession
566 .createQuery("from :name where roleId=:roleId")
567 .setParameter("name",FunctionalMenuRole.class.getName())
568 .setParameter("roleId",roleId)
570 int numMenuRoles = funcMenuRoles.size();
571 logger.debug(EELFLoggerDelegate.debugLogger,
572 "syncAppRoles: number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles);
573 for (FunctionalMenuRole funcMenuRole : funcMenuRoles) {
574 Long menuId = funcMenuRole.menuId;
575 // If this is the only role for this menu item, then the
576 // app and roles will be gone,
577 // so must null out the url too, to be consistent
578 @SuppressWarnings("unchecked")
579 List<FunctionalMenuRole> funcMenuRoles2 = localSession
580 .createQuery("from :name where menuId=:menuId")
581 .setParameter("name",FunctionalMenuRole.class.getName())
582 .setParameter("menuId",menuId)
584 int numMenuRoles2 = funcMenuRoles2.size();
585 logger.debug(EELFLoggerDelegate.debugLogger,
586 "syncAppRoles: number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2);
587 localSession.delete(funcMenuRole);
588 if (numMenuRoles2 == 1) {
589 // If this is the only role for this menu item, then
590 // the app and roles will be gone,
591 // so must null out the url too, to be consistent
592 logger.debug(EELFLoggerDelegate.debugLogger,
593 "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url");
594 @SuppressWarnings("unchecked")
595 List<FunctionalMenuItem> funcMenuItems = localSession
596 .createQuery("from :name where menuId=:menuId")
597 .setParameter("name",FunctionalMenuItem.class.getName())
598 .setParameter("menuId",menuId)
600 if (funcMenuItems.size() > 0) {
601 logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item");
602 FunctionalMenuItem funcMenuItem = funcMenuItems.get(0);
603 funcMenuItem.url = "";
604 localSession.update(funcMenuItem);
608 boolean isPortalRequest = true;
609 externalAccessRolesService.deleteRoleDependencyRecords(localSession, roleId, appId, isPortalRequest);
610 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to delete the role: " + role.toString());
611 localSession.delete(role);
612 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: deleted the role");
615 for (EcompRole role : newRolesToAdd) {
616 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to add missing role: " + role.toString());
617 EPRole newRole = new EPRole();
618 // Attention! All roles from remote application supposed to be
620 newRole.setActive(true);
621 newRole.setName(role.getName());
622 newRole.setAppId(appId);
623 newRole.setAppRoleId(role.getId());
624 localSession.save(newRole);
626 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to commit the transaction");
627 transaction.commit();
628 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: committed the transaction");
629 } catch (Exception e) {
630 logger.error(EELFLoggerDelegate.errorLogger, "syncAppRoles failed", e);
631 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
632 EcompPortalUtils.rollbackTransaction(transaction,
633 "Exception occurred in syncAppRoles, Details: " + e.toString());
634 throw new Exception(e);
636 localSession.close();
645 * Called when updating the list of roles for the user
649 * @param userRolesInRemoteApp
650 * @return RolesInAppForUser
652 protected RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId,
653 Set<EcompRole> userRolesInRemoteApp) {
654 RolesInAppForUser result;
655 result = new RolesInAppForUser();
656 result.appId = appId;
657 result.orgUserId = userId;
659 for (EcompRole role : userRolesInRemoteApp) {
660 RoleInAppForUser roleInAppForUser = new RoleInAppForUser();
661 roleInAppForUser.roleId = role.getId();
662 roleInAppForUser.roleName = role.getName();
663 roleInAppForUser.isApplied = new Boolean(true);
664 result.roles.add(roleInAppForUser);
671 * @param roleInAppForUserList
674 protected boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) {
675 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
676 if (roleInAppForUser.isApplied.booleanValue()) {
684 * Builds JSON and posts it to a remote application to update user roles.
686 * @param roleInAppForUserList
688 * @param applicationsRestClientService
691 * @return Set of roles as sent; NOT the response from the app.
692 * @throws JsonProcessingException
693 * @throws HTTPException
695 protected Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
696 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId,boolean systemUser)
697 throws JsonProcessingException, HTTPException {
698 Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList);
699 Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList);
700 String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote);
701 EPApp externalApp = null;
702 SystemType type = SystemType.APPLICATION;
703 externalApp = appsCacheService.getApp(appId);
704 String appBaseUri = null;
705 Set<RemoteRoleV1> updatedUserRolesinRemoteV1 = new TreeSet<>();
706 if (externalApp != null) {
707 appBaseUri = (type == SystemType.APPLICATION) ? externalApp.getAppRestEndpoint() : "";
709 if(appBaseUri != null && appBaseUri.endsWith("/api")){
710 for(EcompRole eprole :updatedUserRolesinRemote)
712 RemoteRoleV1 role = new RemoteRoleV1();
713 role.setId(eprole.getId());
714 role.setName(eprole.getName());
715 updatedUserRolesinRemoteV1.add(role);
717 userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemoteV1);
719 applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString,
720 String.format("/user/%s/roles", userId));
721 // TODO: We should add code that verifies that the post operation did
722 // succeed. Because the SDK may still return 200 OK with an html page
723 // even when it fails!
724 return updateUserRolesInEcomp;
729 * @param roleInAppForUserList
730 * @return Set<EcompRole>
732 protected Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) {
733 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
734 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
735 if (roleInAppForUser.isApplied) {
736 EcompRole ecompRole = new EcompRole();
737 ecompRole.setId(roleInAppForUser.roleId);
738 ecompRole.setName(roleInAppForUser.roleName);
739 existingUserRoles.add(ecompRole);
742 return existingUserRoles;
746 * Constructs user app roles excluding Account Administrator role
748 * @param roleInAppForUserList
750 * List of roles with Role name, Role Id
752 protected Set<EcompRole> constructUsersRemoteAppRoles(List<RoleInAppForUser> roleInAppForUserList) {
753 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
754 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
755 if (roleInAppForUser.isApplied && !roleInAppForUser.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
756 EcompRole ecompRole = new EcompRole();
757 ecompRole.setId(roleInAppForUser.roleId);
758 ecompRole.setName(roleInAppForUser.roleName);
759 existingUserRoles.add(ecompRole);
762 return existingUserRoles;
766 * This is for a single app
768 * @param rolesInAppForUser
769 * @param externalSystemRequest
770 * set to false if requests from Users page otherwise true
771 * @return true on success, false otherwise
773 protected boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser, boolean externalSystemRequest, String reqType,boolean isSystemUser) throws Exception {
774 boolean result = false;
775 String userId = rolesInAppForUser.orgUserId;
776 Long appId = rolesInAppForUser.appId;
777 synchronized (syncRests) {
778 if (rolesInAppForUser != null) {
779 createLocalUserIfNecessary(userId, isSystemUser);
782 if (rolesInAppForUser != null) {
783 EcompRole[] userAppRoles = new EcompRole[rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size()];
784 for (int i = 0; i < rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size(); i++) {
785 RoleInAppForUser roleInAppForUser = rolesInAppForUser.roles.get(i);
786 EcompRole role = new EcompRole();
787 role.setId(roleInAppForUser.roleId);
788 role.setName(roleInAppForUser.roleName);
789 userAppRoles[i] = role;
792 syncUserRoles(sessionFactory, userId, appId, userAppRoles, externalSystemRequest, reqType);
794 } catch (Exception e) {
795 logger.error(EELFLoggerDelegate.errorLogger,
796 "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for orgUserId " + userId, e);
797 if("DELETE".equals(reqType)){
798 throw new Exception(e.getMessage());
810 * @return UserApplicationRoles
812 protected UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) {
813 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
814 userWithRemoteAppRoles.setAppId(appId);
815 userWithRemoteAppRoles.setOrgUserId(remoteUser.getOrgUserId());
816 userWithRemoteAppRoles.setFirstName(remoteUser.getFirstName());
817 userWithRemoteAppRoles.setLastName(remoteUser.getLastName());
818 userWithRemoteAppRoles.setRoles(remoteUser.getRoles());
819 return userWithRemoteAppRoles;
825 * @see org.onap.portalapp.portal.service.UserRolesService#
826 * importRolesFromRemoteApplication(java.lang.Long)
828 public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException {
829 EPRole[] appRolesFull = applicationsRestClientService.get(EPRole[].class, appId, "/rolesFull");
830 List<EPRole> rolesList = Arrays.asList(appRolesFull);
831 for (EPRole externalAppRole : rolesList) {
833 // Try to find an existing extern role for the app in the local
834 // onap DB. If so, then use its id to update the existing external
835 // application role record.
836 Long externAppId = externalAppRole.getId();
837 EPRole existingAppRole = epRoleService.getRole(appId, externAppId);
838 if (existingAppRole != null) {
839 logger.debug(EELFLoggerDelegate.debugLogger,
840 String.format("ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.",
841 appId, externAppId));
844 // persistExternalRoleInEcompDb(externalAppRole, appId,
852 * It adds new user for remote application
854 * @param roleInAppForUserList
855 * @param remoteAppUser
859 * @param searchService
860 * @param applicationsRestClientService
864 private EPUser addRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app,
865 ObjectMapper mapper, SearchService searchService,
866 ApplicationsRestClientService applicationsRestClientService) throws Exception {
867 EPUser addRemoteUser = null;
868 if (remoteUserShouldBeCreated(roleInAppForUserList)) {
869 createNewUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper,
870 isAppUpgradeVersion(app));
872 return addRemoteUser;
875 private EPUser pushRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app,
876 ObjectMapper mapper, SearchService searchService,
877 ApplicationsRestClientService applicationsRestClientService,boolean appRoleIdUsed) throws Exception {
878 EPUser addRemoteUser = null;
879 // if (remoteUserShouldBeCreated(roleInAppForUserList)) {
880 pushUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper,
881 isAppUpgradeVersion(app), roleInAppForUserList, appRoleIdUsed);
883 return addRemoteUser;
886 @SuppressWarnings("unchecked")
887 protected void pushUserOnRemoteApp(String userId, EPApp app,
888 ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
889 ObjectMapper mapper, boolean postOpenSource, List<RoleInAppForUser> roleInAppForUserList,boolean appRoleIdUsed) throws Exception {
891 EPUser client = null;
892 client = searchService.searchUserByUserId(userId);
894 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
895 if (client == null) {
896 String msg = "cannot create user " + userId + ", because he/she cannot be found in directory.";
897 logger.error(EELFLoggerDelegate.errorLogger, msg);
898 // throw new Exception(msg);
899 final Map<String, String> loginIdParams = new HashMap<>();
900 loginIdParams.put("orgUserIdValue", userId);
901 List<EPUser> userList = new ArrayList<>();
902 userList = dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null);
903 if (userList.size() > 0) {
904 logger.debug(EELFLoggerDelegate.debugLogger,
905 userList.get(0).getOrgUserId() + " User was found in Portal");
906 client = userList.get(0);
907 SortedSet<EPUserApp> userApps = new TreeSet<>();
908 client.setEPUserApps(userApps);
909 client.setSystemUser(false);
911 logger.error(EELFLoggerDelegate.errorLogger, "user cannot be found be in directory or in portal");
912 throw new Exception(msg);
917 client.setLoginId(userId);
918 client.setActive(true);
919 client.setOrgUserId(userId);
922 roleInAppForUserList.removeIf(role -> role.isApplied.equals(false));
923 SortedSet<Role> roles = new TreeSet<>();
925 List<EPRole> getAppRoles = externalAccessRolesService.getAppRoles(app.getId());
926 List<EPApp> appList = new ArrayList<>();
928 List<CentralV2Role> roleList = new ArrayList<>();
929 Map<String, Long> params = new HashMap<>();
931 List<EPRole> userRoles = new ArrayList<>();
933 for (RoleInAppForUser roleInappForUser : roleInAppForUserList) {
934 EPRole role = new EPRole();
935 role.setId(roleInappForUser.getRoleId());
936 role.setName(roleInappForUser.getRoleName());
941 List<EPRole> userAppRoles = new ArrayList<>();
942 for (EPRole role : userRoles) {
943 EPRole appRole = getAppRoles.stream()
944 .filter(applicationRole -> role.getId().equals(applicationRole.getAppRoleId())).findAny()
946 EPRole epRole = new EPRole();
947 if (appRole != null) {
948 epRole.setId(appRole.getId());
949 epRole.setName(appRole.getName());
951 userAppRoles.add(epRole);
953 userRoles = new ArrayList<>();
954 userRoles.addAll(userAppRoles);
956 roleList = externalAccessRolesService.createCentralRoleObject(appList, userRoles, roleList, params);
958 for (CentralV2Role epRole : roleList) {
959 Role role = new Role();
960 EPRole appRole = getAppRoles.stream()
961 .filter(applicationRole -> epRole.getId().equals(applicationRole.getId())).findAny().orElse(null);
962 if (appRole != null){
963 role.setId(appRole.getAppRoleId());
964 role.setName(epRole.getName());
965 role.setRoleFunctions(epRole.getRoleFunctions());
969 client.setRoles(roles);
970 String userInString = null;
971 userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
972 logger.debug(EELFLoggerDelegate.debugLogger,
973 "about to post a client to remote application, users json = " + userInString);
974 applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user/%s", userId));
978 * It checks whether the remote user exists or not
979 * if exits returns user object else null
983 * @param applicationsRestClientService
985 * @throws HTTPException
987 private EPUser checkIfRemoteUserExits(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService) throws HTTPException{
988 EPUser checkRemoteUser = null;
990 checkRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
991 } catch (HTTPException e) {
992 // Some apps are returning 400 if user is not found.
993 if (e.getResponseCode() == 400) {
994 logger.debug(EELFLoggerDelegate.debugLogger,
995 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing",
997 } else if(e.getResponseCode() == 404) {
998 logger.debug(EELFLoggerDelegate.debugLogger,
999 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 404; continuing",
1002 // Other response code, let it come thru.
1006 return checkRemoteUser;
1013 * @see org.onap.portalapp.portal.service.UserRolesService#
1014 * setAppWithUserRoleStateForUser(org.onap.portalapp.portal.domain.
1015 * EPUser, org.onap.portalapp.portal.transport.AppWithRolesForUser)
1017 public ExternalRequestFieldsValidator setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser) {
1018 boolean result = false;
1019 boolean epRequestValue = false;
1021 String reqMessage = "";
1022 if (newAppRolesForUser != null && newAppRolesForUser.getOrgUserId() != null) {
1023 userId = newAppRolesForUser.getOrgUserId().trim();
1025 Long appId = newAppRolesForUser.getAppId();
1026 List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.getAppRoles();
1027 if (userId.length() > 0 ) {
1028 ObjectMapper mapper = new ObjectMapper();
1029 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1032 EPApp app = appsService.getApp(appId);
1033 applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
1035 boolean systemUser = newAppRolesForUser.isSystemUser();
1036 if ((app.getCentralAuth() || app.getId().equals(PortalConstants.PORTAL_APP_ID)) && systemUser) {
1038 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1039 applicationsRestClientService, appId, userId);
1040 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1041 userRolesInLocalApp);
1042 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1043 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1044 // Apply changes in external Access system
1045 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList,
1046 epRequestValue, systemUser);
1048 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal",
1051 }else if (!app.getCentralAuth() && systemUser)
1053 throw new Exception("For non-centralized application we cannot add systemUser");
1055 else{ // if centralized app
1056 if (app.getCentralAuth()) {
1057 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1058 pushRemoteUser(roleInAppForUserList, userId, app, mapper, searchService,
1059 applicationsRestClientService,false);
1062 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1063 applicationsRestClientService, appId, userId);
1064 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1065 userRolesInLocalApp);
1066 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1067 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1068 // Apply changes in external Access system
1069 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList,
1070 epRequestValue,false);
1072 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal", systemUser);
1074 // In case if portal is not centralized then follow existing approach
1075 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1076 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1077 applicationsRestClientService, appId, userId);
1078 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1079 userRolesInLocalApp);
1080 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal",false);
1081 } else{// remote app
1082 EPUser remoteAppUser = null;
1083 if(!app.getCentralAuth() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1085 remoteAppUser = checkIfRemoteUserExits(userId, app, applicationsRestClientService);
1087 if (remoteAppUser == null) {
1088 remoteAppUser = addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService, applicationsRestClientService);
1090 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
1091 applicationsRestClientService, appId, userId,systemUser);
1092 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1093 userRolesInRemoteApp);
1094 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null,false);
1096 // If no roles remain, request app to set user inactive.
1097 if (userRolesInRemoteApp.size() == 0) {
1098 logger.debug(EELFLoggerDelegate.debugLogger,
1099 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
1101 //remoteAppUser.setActive(false);
1102 postUserToRemoteApp(userId, user, app, applicationsRestClientService);
1107 } catch (Exception e) {
1108 /*String message = String.format(
1109 "Failed to create user or update user roles for User %s, AppId %s",
1110 userId, Long.toString(appId));
1111 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1114 String message = String.format(
1115 "Failed to create user or update user roles for User %s, AppId %s",
1116 userId, Long.toString(appId));
1117 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1119 reqMessage = e.getMessage();
1126 return new ExternalRequestFieldsValidator(result, reqMessage);
1130 * It adds user roles in External system and also make data consistent in both local and in External System
1132 * @param app details
1134 * @param roleInAppUser Contains list of active roles
1136 @SuppressWarnings("unchecked")
1137 private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser, boolean isPortalRequest,boolean isSystemUser) throws Exception
1140 // check if user exists
1141 final Map<String, String> userParams = new HashMap<>();
1142 userParams.put("orgUserIdValue", orgUserId);
1143 List<EPUser> userInfo = checkIfUserExists(userParams);
1144 if (userInfo.isEmpty()) {
1145 createLocalUserIfNecessary(orgUserId, isSystemUser);
1148 if (EPCommonSystemProperties
1149 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN) && !isSystemUser) {
1151 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
1155 ObjectMapper mapper = new ObjectMapper();
1156 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1157 HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
1158 ResponseEntity<String> getResponse = externalAccessRolesService.getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
1159 List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
1160 String res = getResponse.getBody();
1161 JSONObject jsonObj = null;
1162 JSONArray extRoles = null;
1163 if (!res.equals("{}")) {
1164 jsonObj = new JSONObject(res);
1165 extRoles = jsonObj.getJSONArray("role");
1167 ExternalAccessUserRoleDetail userRoleDetail = null;
1168 if (extRoles != null) {
1169 for (int i = 0; i < extRoles.length(); i++) {
1170 if (extRoles.getJSONObject(i).getString("name").startsWith(app.getNameSpace() + ".")
1171 && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".admin")
1172 && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".owner")) {
1173 if (extRoles.getJSONObject(i).has("description")) {
1174 ExternalRoleDescription desc = new ExternalRoleDescription(extRoles.getJSONObject(i).getString("description"));
1175 userRoleDetail = new ExternalAccessUserRoleDetail(
1176 extRoles.getJSONObject(i).getString("name"), desc);
1177 userRoleDetailList.add(userRoleDetail);
1179 userRoleDetail = new ExternalAccessUserRoleDetail(
1180 extRoles.getJSONObject(i).getString("name"), null);
1181 userRoleDetailList.add(userRoleDetail);
1188 List<ExternalAccessUserRoleDetail> userRoleListMatchingInExtAuthAndLocal = CheckIfRoleAreMatchingInUserRoleDetailList(userRoleDetailList,app);
1190 // If request coming from portal not from external role approval system then we have to check if user already
1191 // have account admin or system admin as GUI will not send these roles
1192 if (!isPortalRequest) {
1193 final Map<String, String> loginIdParams = new HashMap<>();
1194 loginIdParams.put("orgUserIdValue", orgUserId);
1195 EPUser user = (EPUser) dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null).get(0);
1196 final Map<String, Long> params = new HashMap<>();
1197 params.put("appId", app.getId());
1198 params.put("userId", user.getId());
1199 List<EcompUserAppRoles> userAppList = dataAccessService.executeNamedQuery("getUserAppExistingRoles",
1201 if (!roleInAppUser.isEmpty()) {
1202 for (EcompUserAppRoles userApp : userAppList) {
1203 if (userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)
1204 || userApp.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
1205 RoleInAppForUser addSpecialRole = new RoleInAppForUser();
1206 addSpecialRole.setIsApplied(true);
1207 addSpecialRole.setRoleId(userApp.getRoleId());
1208 addSpecialRole.setRoleName(userApp.getRoleName());
1209 roleInAppUser.add(addSpecialRole);
1214 List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct()
1215 .collect(Collectors.toList());
1216 final Map<String, RoleInAppForUser> currentUserRolesToUpdate = new HashMap<>();
1217 for (RoleInAppForUser roleInAppUserNew : roleInAppUserNonDupls) {
1218 currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), roleInAppUserNew);
1220 final Map<String, ExternalAccessUserRoleDetail> currentUserRolesInExternalSystem = new HashMap<>();
1221 for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleListMatchingInExtAuthAndLocal) {
1222 currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole);
1224 // Check if user roles does not exists in local but still there in External Central Auth System delete them all
1225 for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
1226 if (!(currentUserRolesToUpdate
1227 .containsKey(userRole.getName().substring(app.getNameSpace().length() + 1)))) {
1228 HttpEntity<String> entity = new HttpEntity<>(headers);
1229 logger.debug(EELFLoggerDelegate.debugLogger,
1230 "updateUserRolesInExternalSystem: Connecting to external system to DELETE user role {}",
1231 userRole.getName());
1232 ResponseEntity<String> deleteResponse = template.exchange(
1233 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1234 + "userRole/" + name + "/" + userRole.getName(),
1235 HttpMethod.DELETE, entity, String.class);
1236 logger.debug(EELFLoggerDelegate.debugLogger,
1237 "updateUserRolesInExternalSystem: Finished DELETE operation in external system for user role {} and the response is {}",
1238 userRole.getName(), deleteResponse.getBody());
1241 // Check if user roles does not exists in External Central Auth System add them all
1242 for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) {
1243 if (!(currentUserRolesInExternalSystem
1244 .containsKey(app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")))) {
1245 ExternalAccessUser extUser = new ExternalAccessUser(name,
1246 app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1247 String formattedUserRole = mapper.writeValueAsString(extUser);
1248 HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers);
1249 logger.debug(EELFLoggerDelegate.debugLogger, "updateUserRolesInExternalSystem: Connecting to external system for user {} and POST {}",
1250 name , addUserRole.getRoleName());
1251 ResponseEntity<String> addResponse = template
1252 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1253 + "userRole", HttpMethod.POST, entity, String.class);
1254 logger.debug(EELFLoggerDelegate.debugLogger,
1255 "updateUserRolesInExternalSystem: Finished adding user role in external system {} and added user role {}",
1256 addResponse.getBody(), addUserRole.getRoleName());
1257 if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 404) {
1258 logger.debug(EELFLoggerDelegate.debugLogger,
1259 "Finished POST operation in external system but unable to save user role", addResponse.getBody(),
1260 addUserRole.getRoleName());
1261 throw new Exception(addResponse.getBody());
1265 } catch (HttpClientErrorException e) {
1266 logger.error(EELFLoggerDelegate.errorLogger,
1267 "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}",
1269 if (e.getStatusCode() == HttpStatus.FORBIDDEN) {
1270 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid systemUser", orgUserId);
1271 throw new HttpClientErrorException(HttpStatus.FORBIDDEN, "Please enter the valid systemUser");
1273 if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
1274 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid role");
1275 throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "Please enter the valid role");
1277 EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
1281 catch (Exception e) {
1282 logger.error(EELFLoggerDelegate.errorLogger, "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}", app.getId(), e);
1283 EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
1289 private List<ExternalAccessUserRoleDetail> CheckIfRoleAreMatchingInUserRoleDetailList(
1290 List<ExternalAccessUserRoleDetail> userRoleDetailList, EPApp app) {
1291 Map<String, EPRole> epRoleList = externalAccessRolesService.getAppRoleNamesWithUnderscoreMap(app);
1292 //Add Account Admin role for partner app to prevent conflict
1293 if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1294 EPRole role = new EPRole();
1295 role.setName(PortalConstants.ADMIN_ROLE.replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1296 epRoleList.put(role.getName(), role);
1298 userRoleDetailList.removeIf(userRoleDetail -> !epRoleList.containsKey(userRoleDetail.getName().substring(app.getNameSpace().length()+1)));
1299 return userRoleDetailList;
1306 * @param applicationsRestClientService
1307 * @param searchService
1311 protected void createNewUserOnRemoteApp(String userId, EPApp app,
1312 ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
1313 ObjectMapper mapper, boolean postOpenSource) throws Exception {
1316 EPUser client = searchService.searchUserByUserId(userId);
1318 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1320 if (client == null) {
1321 String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook.";
1322 logger.error(EELFLoggerDelegate.errorLogger, msg);
1323 throw new Exception(msg);
1326 client.setLoginId(userId);
1327 client.setActive(true);
1329 String userInString = null;
1330 userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
1331 logger.debug(EELFLoggerDelegate.debugLogger,
1332 "about to post new client to remote application, users json = " + userInString);
1333 applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user", userId));
1337 @SuppressWarnings("unchecked")
1338 protected void applyChangesToAppRolesRequest(Long appId, Long userId, String updateStatus, EPUserAppRolesRequest epUserAppRolesRequest) {
1339 final Map<String, Long> epRequestParams = new HashMap<>();
1341 EPUserAppRolesRequest epAppRolesRequestData = epUserAppRolesRequest;
1342 epAppRolesRequestData.setUpdatedDate(new Date());
1343 epAppRolesRequestData.setRequestStatus(updateStatus);
1344 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1345 addiotonalUpdateParam.put("userId", userId);
1346 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1347 epRequestParams.put("reqId", epUserAppRolesRequest.getId());
1348 List<EPUserAppRolesRequestDetail> epUserAppRolessDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1349 epUserAppRolessDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1350 epRequestParams, null);
1351 if (epUserAppRolessDetailList.size() > 0) {
1352 for (EPUserAppRolesRequestDetail epRequestUpdateData : epUserAppRolessDetailList) {
1353 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateData;
1354 epAppRoleDetailData.setReqType(updateStatus);
1355 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1356 HashMap<String, Long> updateDetailsParam = new HashMap<String, Long>();
1357 addiotonalUpdateParam.put("reqId", epUserAppRolesRequest.getId());
1358 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParam);
1361 logger.debug(EELFLoggerDelegate.debugLogger, "The request is set to complete");
1363 } catch (Exception e) {
1364 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToAppRolesRequest failed", e);
1368 @SuppressWarnings("unchecked")
1369 public void applyChangesToUserAppRolesForMyLoginsRequest(EPUser user, Long appId) {
1370 final Map<String, Long> params = new HashMap<>();
1371 final Map<String, Long> epDetailParams = new HashMap<>();
1372 List<EPUserAppRolesRequest> epRequestIdVal = new ArrayList<EPUserAppRolesRequest>();
1373 params.put("appId", appId);
1374 params.put("userId", user.getId());
1376 epRequestIdVal = (List<EPUserAppRolesRequest>) dataAccessService
1377 .executeNamedQuery("userAppRolesRequestList", params, null);
1378 if (epRequestIdVal.size() > 0) {
1379 EPUserAppRolesRequest epAppRolesRequestData = epRequestIdVal.get(0);
1380 epAppRolesRequestData.setUpdatedDate(new Date());
1381 epAppRolesRequestData.setRequestStatus("O");
1382 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1383 addiotonalUpdateParam.put("userId", user.getId());
1384 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1385 epDetailParams.put("reqId", epAppRolesRequestData.getId());
1386 List<EPUserAppRolesRequestDetail> epUserAppRolesDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1387 epUserAppRolesDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1388 epDetailParams, null);
1389 if (epUserAppRolesDetailList.size() > 0) {
1390 for (EPUserAppRolesRequestDetail epRequestUpdateList : epUserAppRolesDetailList) {
1391 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateList;
1392 epAppRoleDetailData.setReqType("O");
1393 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1394 HashMap<String, Long> updateDetailsParams = new HashMap<String, Long>();
1395 addiotonalUpdateParam.put("reqId", epAppRolesRequestData.getId());
1396 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParams);
1398 logger.debug(EELFLoggerDelegate.debugLogger, "User App roles request from User Page is overridden");
1402 } catch (Exception e) {
1403 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e);
1408 * Pushes specified user details to the specified remote app.
1411 * OrgUserId identifying user at remote app in REST endpoint path
1413 * User details to be pushed
1416 * @param applicationsRestClientService
1417 * @throws HTTPException
1419 protected void postUserToRemoteApp(String userId, EPUser user, EPApp app,
1420 ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
1422 getUser(userId, app, applicationsRestClientService);
1427 * It returns user details for single org user id
1431 * if user exists it returns list of user details otherwise empty value
1433 @SuppressWarnings("unchecked")
1434 private List<EPUser> checkIfUserExists(Map<String, String> userParams){
1435 return (List<EPUser>)dataAccessService.executeNamedQuery("epUserAppId", userParams, null);
1439 * It checks whether the new user is valid or not otherwise throws exception
1444 * Checks if user is valid and returns message otherwise throws exception
1447 private String validateNewUser(String orgUserId, EPApp app) throws Exception {
1448 EPUser epUser = searchService.searchUserByUserId(orgUserId);
1449 if (epUser == null) {
1450 throw new Exception("User does not exist");
1451 } else if (!epUser.getOrgUserId().equals(orgUserId)) {
1452 throw new Exception("User does not exist");
1453 } else if (app == null) {
1454 throw new Exception("Application does not exist");
1456 return "Saved Successfully";
1460 * Checks if the fields exists or not
1463 * contains user information
1467 * throws exception if the field is not valid
1469 private void validateExternalRequestFields(List<EPUser> userList, EPApp app) throws Exception{
1470 if (userList.size() == 0 || userList.isEmpty() ) {
1471 throw new Exception("User does not exist");
1472 } else if(app == null) {
1473 throw new Exception("Application does not exist");
1474 } else if(!app.getEnabled() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1475 throw new Exception(app.getMlAppName()+" application is unavailable");
1479 @SuppressWarnings("unchecked")
1480 public ExternalRequestFieldsValidator setExternalRequestUserAppRole(ExternalSystemUser newAppRolesForUser, String reqType) {
1481 boolean result = false;
1482 boolean externalSystemRequest = true;
1483 final Map<String, Long> params = new HashMap<>();
1484 final Map<String, String> userParams = new HashMap<>();
1485 List<EPUser> userInfo = null;
1487 List<EPUserAppRolesRequest> epRequestId = null;
1488 String orgUserId = "";
1489 String updateStatus = "";
1490 String reqMessage = "";
1492 if (newAppRolesForUser != null && newAppRolesForUser.getLoginId() != null) {
1493 orgUserId = newAppRolesForUser.getLoginId().trim();
1495 String appName = newAppRolesForUser.getApplicationName();
1496 String logMessage = ("DELETE").equals(reqType) ? "Deleting": "Assigning/Updating" ;
1497 if (orgUserId.length() > 0) {
1498 ObjectMapper mapper = new ObjectMapper();
1499 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1500 int epRequestIdSize = 0;
1502 app = appsService.getAppDetail(appName);
1503 userParams.put("orgUserIdValue", orgUserId);
1504 userInfo = checkIfUserExists(userParams);
1505 reqMessage = "Updated Successfully";
1506 if (!reqType.equals("DELETE") && (userInfo.size() == 0 || userInfo.isEmpty())) {
1507 reqMessage = validateNewUser(orgUserId, app);
1509 if (userInfo.size() != 0 || !userInfo.isEmpty()) {
1510 validateExternalRequestFields(userInfo, app);
1511 user = userInfo.get(0);
1512 params.put("appId", app.getId());
1513 params.put("userId", user.getId());
1514 epRequestId = (List<EPUserAppRolesRequest>) dataAccessService
1515 .executeNamedQuery("userAppRolesRequestList", params, null);
1516 epRequestIdSize = epRequestId.size();
1519 //If Non-Centralized app make sure you sync app roles before assigning to user
1520 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !app.getCentralAuth()) {
1521 logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Starting GET roles for app {}",app.getId());
1522 EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, app.getId(), "/roles");
1523 logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Finshed GET roles for app {} and payload {}",app.getId(), appRoles);
1524 if (appRoles.length > 0) {
1525 syncAppRoles(sessionFactory, app.getId(), appRoles);
1528 List<RoleInAppForUser> roleInAppForUserList = roleInAppForUserList(newAppRolesForUser.getRoles(),
1529 app.getId(), app.getMlAppName());
1530 List<EcompUserAppRoles> userRoleList = null;
1531 if(!userInfo.isEmpty()){
1532 final Map<String, Long> appParams = new HashMap<>();
1533 appParams.put("userId", user.getId());
1534 appParams.put("appId", app.getId());
1535 userRoleList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", appParams, null);
1537 // Check if list contains just account admin role
1538 boolean checkIfAdminRoleExists = false;
1539 if (reqType.equals("DELETE") && userRoleList!=null) {
1540 checkIfAdminRoleExists = userRoleList.stream()
1541 .anyMatch(userRole -> userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1543 checkIfAdminRoleExists = roleInAppForUserList.stream()
1544 .anyMatch(roleList -> roleList.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1546 // if Centralized app
1547 if (app.getCentralAuth()) {
1548 // We should add If user does not exist in remote application
1550 // If adding just account admin role dont make remote application user call or
1551 // if request has only single non admin role then make remote call
1552 if (!(app.getId().equals(PortalConstants.PORTAL_APP_ID) && reqType.equals("DELETE"))
1553 && ((checkIfAdminRoleExists && roleInAppForUserList.size() > 1)
1554 || (!checkIfAdminRoleExists && roleInAppForUserList.size() >= 1))) {
1555 // check if admin role exist then delete
1556 List<RoleInAppForUser> remoteUserRoles = roleInAppForUserList.stream()
1557 .collect(Collectors.toList());
1558 remoteUserRoles.removeIf(role -> {
1559 return (role.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1561 String orgUserIdNewOrExist = (userInfo.size() != 0 || !userInfo.isEmpty()) ? user.getOrgUserId() : orgUserId;
1562 pushRemoteUser(remoteUserRoles, orgUserIdNewOrExist , app, mapper, searchService,
1563 applicationsRestClientService,true);
1565 } catch (Exception e) {
1566 reqMessage = e.getMessage();
1567 logger.error(EELFLoggerDelegate.errorLogger, "setExternalRequestUserAppRole: Failed to added remote user", e);
1568 throw new Exception(reqMessage);
1570 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1571 applicationsRestClientService, app.getId(), orgUserId);
1572 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1573 userRolesInLocalApp);
1574 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1575 if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1576 // Apply changes in external Access system
1577 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, externalSystemRequest,false);
1579 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
1580 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1581 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,false);
1583 // If local application is not centralized
1584 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1585 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1586 applicationsRestClientService, app.getId(), orgUserId);
1587 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1588 userRolesInLocalApp);
1589 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,false);
1590 } else {// remote app
1591 // If adding just account admin role don't do remote application user call
1592 if (!((roleInAppForUserList.size() == 1 || reqType.equals("DELETE")) && checkIfAdminRoleExists)) {
1593 EPUser remoteAppUser = null;
1594 remoteAppUser = checkIfRemoteUserExits(orgUserId, app, applicationsRestClientService);
1595 if (remoteAppUser == null) {
1596 addRemoteUser(roleInAppForUserList, orgUserId, app, mapper, searchService,
1597 applicationsRestClientService);
1598 reqMessage = "Saved Successfully";
1601 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
1602 applicationsRestClientService, app.getId(), orgUserId,false);
1604 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1605 userRolesInRemoteApp);
1606 logger.info(EELFLoggerDelegate.debugLogger,
1607 "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
1608 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1609 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1611 // If no roles remain, request app to set user inactive.
1613 * if (userRolesInRemoteApp.size() == 0) {
1614 * logger.debug(EELFLoggerDelegate.debugLogger,
1615 * "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive"
1616 * , app, orgUserId); //TODO Need to fix the logged in user is not set to
1617 * inactive remoteAppUser.setActive(false); postUserToRemoteApp(orgUserId, user,
1618 * app, applicationsRestClientService); }
1622 // Here we are adding only we have single account admin in roleInAppForUserList and this should not add in remote
1623 if(!(reqType.equals("DELETE")) && userInfo.isEmpty()){
1624 reqMessage = "Saved Successfully";
1626 Set<EcompRole> userRolesInRemoteApp = constructUsersEcompRoles(roleInAppForUserList);
1628 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1629 userRolesInRemoteApp);
1630 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}",
1631 logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1632 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1636 reqMessage = "Failed to save the user app role(s)";
1638 if (epRequestIdSize > 0 && !userInfo.isEmpty()) {
1640 applyChangesToAppRolesRequest(app.getId(), user.getId(), updateStatus, epRequestId.get(0));
1643 } catch (Exception e) {
1644 String message = String.format("setExternalRequestUserAppRole: Failed to create user or update user roles for User %s, AppId %s",
1645 orgUserId, appName);
1646 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1648 reqMessage = e.getMessage();
1649 if(epRequestIdSize > 0 && userInfo!=null && !userInfo.isEmpty()){
1651 applyChangesToAppRolesRequest(app.getId(), user.getId(),
1652 updateStatus, epRequestId.get(0));
1657 return new ExternalRequestFieldsValidator(result, reqMessage);
1662 * @param roleInAppForUserList
1664 * @param applicationsRestClientService
1667 * @return Set<EcompRole>
1668 * @throws JsonProcessingException
1669 * @throws HTTPException
1671 private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
1672 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
1673 throws JsonProcessingException, HTTPException {
1674 Set<EcompRole> updatedUserRoles = constructUsersEcompRoles(roleInAppForUserList);
1675 return updatedUserRoles;
1679 * It constructs and returns list of user app roles when the external API role approval system calls
1682 * @param roleInAppForUserList
1684 * @return list of user app roles
1686 * throws exceptions if role id does not exits
1688 private List<RoleInAppForUser> roleInAppForUserList(List<ExternalSystemRoleApproval> roleInAppForUserList,
1689 Long appId, String appName) throws Exception {
1690 List<RoleInAppForUser> existingUserRoles = new ArrayList<RoleInAppForUser>();
1691 EPRole existingAppRole = null;
1692 for (ExternalSystemRoleApproval roleInAppForUser : roleInAppForUserList) {
1693 RoleInAppForUser ecompRole = new RoleInAppForUser();
1694 existingAppRole = epRoleService.getAppRole(roleInAppForUser.getRoleName(), appId);
1695 if (existingAppRole == null) {
1696 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1697 roleInAppForUserList);
1698 throw new Exception("'" +roleInAppForUser.getRoleName() + "'" +" role does not exist for " + appName + " application");
1700 if (!existingAppRole.getActive()) {
1701 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1702 roleInAppForUserList);
1703 throw new Exception(roleInAppForUser.getRoleName() + " role is unavailable for "+ appName + " application");
1705 ecompRole.roleId = (appId == 1 || roleInAppForUser.getRoleName().equals(PortalConstants.ADMIN_ROLE)) ? existingAppRole.getId() : existingAppRole.getAppRoleId();
1706 ecompRole.roleName = roleInAppForUser.getRoleName();
1707 ecompRole.isApplied = true;
1708 existingUserRoles.add(ecompRole);
1711 return existingUserRoles;
1720 * @param applicationsRestClientService
1722 * @throws HTTPException
1724 protected EPUser getUserFromApp(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1725 throws HTTPException {
1727 if (app.getId() == PortalConstants.PORTAL_APP_ID) {
1728 // Map<String,String> params = new HashMap<String,String>();
1729 // params.put("sbcid",userId);
1730 @SuppressWarnings("unchecked")
1731 List<EPUser> userList = (List<EPUser>) dataAccessService
1732 .executeQuery("from EPUser where orgUserId='" + userId + "'", null);
1733 if (userList != null && !userList.isEmpty())
1734 return userList.get(0);
1740 return getUser(userId, app, applicationsRestClientService);
1743 protected EPUser getUser(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1744 throws HTTPException {
1745 return applicationsRestClientService.get(EPUser.class, app.getId(), String.format("/user/%s", userId), true);
1749 protected boolean isAppUpgradeVersion(EPApp app){
1754 public ExternalSystemAccess getExternalRequestAccess(){
1755 ExternalSystemAccess res = null;
1757 res = new ExternalSystemAccess(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE,
1758 Boolean.parseBoolean(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE)));
1759 } catch (Exception e) {
1760 logger.error(EELFLoggerDelegate.errorLogger, "getExternalRequestAccess failed" + e.getMessage());
1768 * @see org.onap.portalapp.portal.service.UserRolesService#
1769 * getAppRolesForUser(java.lang.Long, java.lang.String)
1771 @SuppressWarnings("unchecked")
1772 public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId, Boolean extRequestValue,EPUser user) {
1773 List<RoleInAppForUser> rolesInAppForUser = null;
1774 EPApp app = appsService.getApp(appId);
1775 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - app = {}", app);
1777 // for onap portal app, no need to make a remote call
1778 List<Role> roleList = new ArrayList<>();
1779 if (appId == PortalConstants.PORTAL_APP_ID) {
1780 if(app.getCentralAuth()){
1781 List<CentralV2Role> cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey());
1782 for(CentralV2Role cenRole : cenRoleList){
1783 Role role = new Role();
1784 role.setActive(cenRole.getActive());
1785 role.setId(cenRole.getId());
1786 role.setName(cenRole.getName());
1787 role.setPriority(cenRole.getPriority());
1791 roleList = roleService.getAvailableRoles(userId);
1793 List<Role> activeRoleList = new ArrayList<Role>();
1794 for(Role role: roleList) {
1795 if(role.getActive()) {
1796 if(role.getId() != 1){ // prevent portal admin from being added
1797 activeRoleList.add(role);
1798 } else if(extRequestValue){
1799 activeRoleList.add(role);
1804 EPUser localUser = getUserFromApp(userId, app, applicationsRestClientService);
1805 // If localUser does not exists return roles
1806 Set<EPRole> roleSet = null;
1807 EPRole[] roleSetList = null;
1808 if(localUser != null){
1809 roleSet = localUser.getAppEPRoles(app);
1810 roleSetList = roleSet.toArray(new EPRole[0]);
1812 rolesInAppForUser = constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue);
1813 return rolesInAppForUser;
1816 EcompRole[] appRoles = null;
1817 List<EcompRole> roles = new ArrayList<>();
1818 if (app.getCentralAuth()) {
1819 final Map<String, Long> appParams = new HashMap<>();
1820 appParams.put("appId", app.getId());
1821 List<EPRole> applicationRoles = dataAccessService.executeNamedQuery("getActiveRolesOfApplication",
1824 EPApp application = appService.getApp(appId);
1825 boolean checkIfUserisApplicationAccAdmin = adminRolesService.isAccountAdminOfApplication(user,
1828 List<EPRole> rolesetwithfunctioncds = new ArrayList<EPRole>();
1829 for (EPRole role : applicationRoles) {
1830 Map<String, Long> params = new HashMap<>();
1831 params.put("roleId", role.getId());
1832 params.put(APP_ID, app.getId());
1833 List<CentralV2RoleFunction> cenRoleFuncList = dataAccessService
1834 .executeNamedQuery("getAppRoleFunctionList", params, null);
1836 // SortedSet<CentralV2RoleFunction> roleFunctionSet =
1838 SortedSet<RoleFunction> roleFunctionSet = new TreeSet<>();
1839 for (CentralV2RoleFunction roleFunc : cenRoleFuncList) {
1841 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1842 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
1843 String type = externalAccessRolesService.getFunctionCodeType(roleFunc.getCode());
1844 String action = externalAccessRolesService.getFunctionCodeAction(roleFunc.getCode());
1845 String name = roleFunc.getName();
1847 RoleFunction function = new RoleFunction();
1848 function.setAction(action);
1849 function.setType(type);
1850 function.setCode(functionCode);
1851 function.setName(name);
1852 roleFunctionSet.add(function);
1853 role.setRoleFunctions(roleFunctionSet);
1856 rolesetwithfunctioncds.add(role);
1861 for (EPRole role1 : rolesetwithfunctioncds) {
1862 EcompRole ecompRole = new EcompRole();
1863 ecompRole.setId(role1.getId());
1864 ecompRole.setName(role1.getName());
1865 ecompRole.setRoleFunctions(role1.getRoleFunctions());
1866 roles.add(ecompRole);
1869 if (checkIfUserisApplicationAccAdmin) {
1870 appRoles = roles.toArray(new EcompRole[roles.size()]);
1871 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() If Logged in user checkIfUserisApplicationAccAdmin- appRoles = {}", appRoles);
1872 } else if (adminRolesService.isRoleAdmin(user) && !checkIfUserisApplicationAccAdmin) {
1873 List<EcompRole> roleAdminAppRoles = new ArrayList<>();
1874 List<String> roleAdminAppRolesNames = new ArrayList<>();
1875 final Map<String, Long> userParams = new HashMap<>();
1876 userParams.put("userId", user.getId());
1877 List<String> getUserApproverRoles = dataAccessService.executeNamedQuery("getUserApproverRoles", userParams, null);
1879 List<EcompRole> userapproverRolesList = new ArrayList<>();
1880 for (String str : getUserApproverRoles) {
1881 EcompRole epRole = roles.stream().filter(x -> str.equals(x.getName())).findAny().orElse(null);
1883 userapproverRolesList.add(epRole);
1885 // roles.removeAll(userapproverRolesList);
1886 for (EcompRole role : userapproverRolesList) {
1888 List<RoleFunction> roleFunList = new ArrayList<>();
1889 roleFunList.addAll(role.getRoleFunctions());
1890 boolean checkIfFunctionsExits = roleFunList.stream()
1891 .anyMatch(roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
1892 if (checkIfFunctionsExits) {
1893 roleAdminAppRoles.add(role);
1894 List<RoleFunction> filteredList = roleFunList.stream()
1895 .filter(x -> "Approver".equalsIgnoreCase(x.getType())).collect(Collectors.toList());
1896 roleAdminAppRolesNames.addAll(filteredList.stream().map(RoleFunction::getCode)
1897 .collect(Collectors.toList()));
1898 // roleAdminAppRolesNames = filteredList.stream().map(RoleFunction::getCode)
1899 // .collect(Collectors.toList());
1902 for (String name : roleAdminAppRolesNames) {
1903 EcompRole ecompRole = roles.stream().filter(x -> name.equals(x.getName())).findAny()
1905 if (ecompRole != null)
1906 roleAdminAppRoles.add(ecompRole);
1909 appRoles = roleAdminAppRoles.toArray(new EcompRole[roleAdminAppRoles.size()]);
1913 appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
1915 // Test this error case, for generating an internal ONAP Portal
1917 // EcompRole[] appRoles = null;
1918 // If there is an exception in the rest client api, then null will
1920 if (appRoles != null) {
1921 if(!app.getCentralAuth()) {
1922 syncAppRoles(sessionFactory, appId, appRoles);
1924 EcompRole[] userAppRoles = null;
1928 if(app.getCentralAuth()){
1929 final Map<String, String> params = new HashMap<>();
1930 final Map<String, Long> userParams = new HashMap<>();
1931 params.put("orgUserIdValue", userId);
1932 List<EPUser> actualUser = dataAccessService.executeNamedQuery("epUserAppId", params, null);
1933 userParams.put("appId", app.getId());
1934 userParams.put("userId", actualUser.get(0).getId());
1935 List<EPUserAppCurrentRoles> userAppsRolesList = dataAccessService.executeNamedQuery("getUserAppCurrentRoles", userParams, null);
1937 List<EcompRole> setUserRoles = new ArrayList<>();
1938 for(EPUserAppCurrentRoles role : userAppsRolesList){
1939 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - userAppsRolesList get userRolename = {}", role.getRoleName());
1940 EcompRole ecompRole = new EcompRole();
1941 ecompRole.setId(role.getRoleId());
1942 ecompRole.setName(role.getRoleName());
1943 setUserRoles.add(ecompRole);
1946 boolean checkIfUserisAccAdmin = setUserRoles.stream()
1947 .anyMatch(ecompRole -> ecompRole.getId() == 999L);
1949 if (!checkIfUserisAccAdmin) {
1950 List<EcompRole> userApplicationRolesList = setUserRoles;
1951 List<EcompRole> appRolesList = Arrays.asList(appRoles);
1952 Set<EcompRole> finalUserAppRolesList = new HashSet<>();
1954 List<String> roleNames = new ArrayList<>();
1955 for (EcompRole role : userApplicationRolesList) {
1956 EcompRole epRole = appRolesList.stream()
1957 .filter(x -> role.getName().equals(x.getName())).findAny().orElse(null);
1958 List<RoleFunction> roleFunList = new ArrayList<>();
1959 if(epRole.getRoleFunctions().size()>0)
1960 roleFunList.addAll(epRole.getRoleFunctions());
1961 boolean checkIfFunctionsExits = roleFunList.stream().anyMatch(
1962 roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
1963 if (checkIfFunctionsExits) {
1964 finalUserAppRolesList.add(role);
1965 List<RoleFunction> filteredList = roleFunList.stream()
1966 .filter(x -> "Approver".equalsIgnoreCase(x.getType()))
1967 .collect(Collectors.toList());
1968 roleNames = filteredList.stream().map(RoleFunction::getCode)
1969 .collect(Collectors.toList());
1972 for (String name : roleNames) {
1973 EcompRole ecompRole = appRolesList.stream()
1974 .filter(x -> name.equals(x.getName())).findAny().orElse(null);
1975 if (ecompRole != null)
1976 finalUserAppRolesList.add(ecompRole);
1981 for (String name : roleNames) {
1983 boolean checkIfFunctionsExits = userAppsRolesList.stream().anyMatch(
1984 role -> role.getRoleName().equalsIgnoreCase(name));
1985 if(checkIfFunctionsExits)
1987 EcompRole epRole = appRolesList.stream().filter(x -> name.equals(x.getName()))
1988 .findAny().orElse(null);
1990 setUserRoles.add(epRole);
1994 userAppRoles = setUserRoles.toArray(new EcompRole[setUserRoles.size()]);
1997 userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
1998 String.format("/user/%s/roles", userId));
2000 } catch (HTTPException e) {
2001 // Some apps are returning 400 if user is not found.
2002 if (e.getResponseCode() == 400) {
2003 logger.debug(EELFLoggerDelegate.debugLogger,
2004 "getAppRolesForUser caught exception with response code 400; continuing", e);
2006 // Other response code, let it come thru.
2010 if (userAppRoles == null) {
2011 if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
2012 EcompPortalUtils.setExternalAppResponseCode(200);
2013 String message = String.format(
2014 "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
2015 + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
2016 + "Overriding to 200 until framework SDK returns a useful response.",
2017 Long.toString(appId), userId);
2018 logger.warn(EELFLoggerDelegate.applicationLogger, message);
2022 HashMap<Long, EcompRole> appRolesActiveMap =hashMapFromEcompRoles(appRoles);
2023 ArrayList<EcompRole> activeRoles = new ArrayList<EcompRole>();
2024 if(userAppRoles != null){
2025 for (int i = 0; i < userAppRoles.length; i++) {
2026 if (appRolesActiveMap.containsKey(userAppRoles[i].getId())) {
2027 EcompRole role = new EcompRole();
2028 role.setId(userAppRoles[i].getId());
2029 role.setName(userAppRoles[i].getName());
2030 activeRoles.add(role);
2034 EcompRole[] userAppRolesActive = activeRoles.toArray(new EcompRole[activeRoles.size()]);
2036 // If the remote application isn't down we MUST sync user
2037 // roles here in case we have this user here!
2038 syncUserRoles(sessionFactory, userId, appId, userAppRolesActive, extRequestValue, null);
2039 } catch (Exception e) {
2040 // TODO: we may need to check if user exists, maybe remote
2042 String message = String.format(
2043 "getAppRolesForUser: user %s does not exist in remote application %s", userId,
2044 Long.toString(appId));
2045 logger.error(EELFLoggerDelegate.errorLogger, message, e);
2046 userAppRoles = new EcompRole[0];
2048 rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
2050 } catch (Exception e) {
2051 String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
2052 Long.toString(appId));
2053 logger.error(EELFLoggerDelegate.errorLogger, message, e);
2055 return rolesInAppForUser;
2058 private boolean postUserRolesToMylogins(AppWithRolesForUser userAppRolesData,
2059 ApplicationsRestClientService applicationsRestClientService, Long appId, Long userId)
2060 throws JsonProcessingException, HTTPException {
2061 boolean result = false;
2062 ObjectMapper mapper = new ObjectMapper();
2063 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
2064 String userRolesAsString = mapper.writeValueAsString(userAppRolesData);
2065 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, as the endpoint is not defined yet from the Mylogins");
2066 applicationsRestClientService.post(AppWithRolesForUser.class, appId, userRolesAsString, String.format("/user/%s/myLoginroles", userId));
2070 @SuppressWarnings("unchecked")
2071 public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser userAppRolesData, EPUser user) {
2072 FieldsValidator fieldsValidator = new FieldsValidator();
2073 final Map<String, Long> params = new HashMap<>();
2074 List<EPUserAppRoles> appRole= null;
2076 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, still the endpoint is yet to be defined");
2077 boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService,
2078 userAppRolesData.getAppId(), user.getId());
2079 logger.debug(EELFLoggerDelegate.debugLogger,"putUserAppRolesRequest: result {}", result);
2081 params.put("appId", userAppRolesData.getAppId());
2082 EPUserAppRolesRequest epAppRolesRequestData = new EPUserAppRolesRequest();
2083 epAppRolesRequestData.setCreatedDate(new Date());
2084 epAppRolesRequestData.setUpdatedDate(new Date());
2085 epAppRolesRequestData.setUserId(user.getId());
2086 epAppRolesRequestData.setAppId(userAppRolesData.getAppId());
2087 epAppRolesRequestData.setRequestStatus("P");
2088 List<RoleInAppForUser> appRoleIdList = userAppRolesData.getAppRoles();
2089 Set<EPUserAppRolesRequestDetail> appRoleDetails = new LinkedHashSet<EPUserAppRolesRequestDetail>();
2090 dataAccessService.saveDomainObject(epAppRolesRequestData, null);
2091 for (RoleInAppForUser userAppRoles : appRoleIdList) {
2092 Boolean isAppliedVal = userAppRoles.isApplied;
2093 params.put("appRoleId", userAppRoles.roleId);
2095 appRole = (List<EPUserAppRoles>) dataAccessService.executeNamedQuery("appRoles", params, null);
2096 if (!appRole.isEmpty()) {
2097 EPUserAppRolesRequestDetail epAppRoleDetail = new EPUserAppRolesRequestDetail();
2098 epAppRoleDetail.setReqRoleId(appRole.get(0).getRoleId());
2099 epAppRoleDetail.setReqType("P");
2100 epAppRoleDetail.setEpRequestIdData(epAppRolesRequestData);
2101 dataAccessService.saveDomainObject(epAppRoleDetail, null);
2105 epAppRolesRequestData.setEpRequestIdDetail(appRoleDetails);
2106 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
2108 } catch (Exception e) {
2109 logger.error(EELFLoggerDelegate.errorLogger, "putUserAppRolesRequest failed", e);
2110 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
2112 return fieldsValidator;
2115 public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(EPUser userid, String appName) {
2116 Map<String, String> params = new HashMap<>();
2117 params.put("userid", userid.getId().toString());
2118 //params.put("appid", appid);
2119 params.put("appName", appName);
2121 @SuppressWarnings("unchecked")
2122 List<EPUserAppCatalogRoles> userAppRoles = (List<EPUserAppCatalogRoles>) dataAccessService
2123 .executeNamedQuery("userAppCatalogRoles", params, null);
2124 return userAppRoles;
2127 public String updateRemoteUserProfile(String orgUserId, Long appId) {
2128 ObjectMapper mapper = new ObjectMapper();
2129 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
2130 EPUser client = searchService.searchUserByUserId(orgUserId);
2131 EPUser newUser = new EPUser();
2132 newUser.setActive(client.getActive());
2133 newUser.setFirstName(client.getFirstName());
2134 newUser.setLastName(client.getLastName());
2135 newUser.setLoginId(client.getLoginId());
2136 newUser.setLoginPwd(client.getLoginPwd());
2137 newUser.setMiddleInitial(client.getMiddleInitial());
2138 newUser.setEmail(client.getEmail());
2139 newUser.setOrgUserId(client.getLoginId());
2141 String userAsString = mapper.writeValueAsString(newUser);
2142 List<EPApp> appList = appsService.getUserRemoteApps(client.getId().toString());
2143 // applicationsRestClientService.post(EPUser.class, appId,
2144 // userAsString, String.format("/user", orgUserId));
2145 for (EPApp eachApp : appList) {
2147 applicationsRestClientService.post(EPUser.class, eachApp.getId(), userAsString,
2148 String.format("/user/%s", orgUserId));
2149 } catch (Exception e) {
2150 logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId()
2151 + " in remote app. appId = " + eachApp.getId());
2154 } catch (Exception e) {
2155 logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
2166 * @see org.onap.portalapp.portal.service.UserRolesService#
2167 * getCachedAppRolesForUser(java.lang.Long, java.lang.Long)
2169 @SuppressWarnings("deprecation")
2170 public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId) {
2171 // Find the records for this user-app combo, if any
2172 String filter = " where user_id = " + Long.toString(userId) + " and app_id = " + Long.toString(appId);
2173 @SuppressWarnings("unchecked")
2174 List<EPUserApp> roleList = dataAccessService.getList(EPUserApp.class, filter, null, null);
2175 logger.debug(EELFLoggerDelegate.debugLogger, "getCachedAppRolesForUser: list size is {}", roleList.size());
2180 * It retrieves and returns list of user app roles for local and remote applications based app id
2183 * @return list of user app roles
2184 * @throws HTTPException
2186 public List<UserApplicationRoles> getUsersFromAppEndpoint(Long appId) throws HTTPException {
2187 ArrayList<UserApplicationRoles> userApplicationRoles = new ArrayList<UserApplicationRoles>();
2189 EPApp app = appsService.getApp(appId);
2190 //If local or centralized application
2191 if (appId == PortalConstants.PORTAL_APP_ID || app.getCentralAuth()) {
2192 @SuppressWarnings("unchecked")
2193 List<EPUser> userList = (List<EPUser>) dataAccessService.executeNamedQuery("getActiveUsers", null, null);
2194 for (EPUser user : userList) {
2195 UserApplicationRoles userWithAppRoles = convertToUserApplicationRoles(appId, user, app);
2196 if (userWithAppRoles.getRoles() != null && userWithAppRoles.getRoles().size() > 0)
2197 userApplicationRoles.add(userWithAppRoles);
2203 RemoteUserWithRoles[] remoteUsers = null;
2204 String remoteUsersString = applicationsRestClientService.getIncomingJsonString(appId, "/users");
2206 remoteUsers = doGetUsers(isAppUpgradeVersion(app), remoteUsersString);
2208 userApplicationRoles = new ArrayList<UserApplicationRoles>();
2209 for (RemoteUserWithRoles remoteUser : remoteUsers) {
2210 UserApplicationRoles userWithRemoteAppRoles = convertToUserApplicationRoles(appId, remoteUser);
2211 if (userWithRemoteAppRoles.getRoles() != null && userWithRemoteAppRoles.getRoles().size() > 0) {
2212 userApplicationRoles.add(userWithRemoteAppRoles);
2214 logger.debug(EELFLoggerDelegate.debugLogger,
2215 "User " + userWithRemoteAppRoles.getOrgUserId() + " doesn't have any roles assigned to any app.");
2220 return userApplicationRoles;
2227 * @param appgetUsersFromAppEndpoint
2230 private UserApplicationRoles convertToUserApplicationRoles(Long appId, EPUser user, EPApp app) {
2231 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
2232 userWithRemoteAppRoles.setAppId(appId);
2233 userWithRemoteAppRoles.setOrgUserId(user.getOrgUserId());
2234 userWithRemoteAppRoles.setFirstName(user.getFirstName());
2235 userWithRemoteAppRoles.setLastName(user.getLastName());
2236 userWithRemoteAppRoles.setRoles(convertToRemoteRoleList(user, app));
2237 return userWithRemoteAppRoles;
2246 @SuppressWarnings("unchecked")
2247 private List<RemoteRole> convertToRemoteRoleList(EPUser user, EPApp app) {
2248 List<RemoteRole> roleList = new ArrayList<RemoteRole>();
2249 SortedSet<EPRole> roleSet = user.getAppEPRoles(app);
2250 for (EPRole role : roleSet) {
2251 logger.debug(EELFLoggerDelegate.debugLogger, "In convertToRemoteRoleList() - for user {}, found Name {}", user.getOrgUserId(), role.getName());
2252 RemoteRole rRole = new RemoteRole();
2253 rRole.setId(role.getId());
2254 rRole.setName(role.getName());
2255 roleList.add(rRole);
2258 //Get the active roles of user for that application using query
2259 List<EPRole> userEpRoleList = new ArrayList<>();
2260 final Map<String, Long> params = new HashMap<>();
2261 params.put("appId", app.getId());
2262 params.put("userId", user.getId());
2263 userEpRoleList = dataAccessService.executeNamedQuery("getUserRoleOnUserIdAndAppId", params, null);
2265 for (EPRole remoteUserRoleList : userEpRoleList) {
2267 RemoteRole remoteRoleListId = roleList.stream().filter(x -> remoteUserRoleList.getId().equals(x.getId()))
2268 .findAny().orElse(null);
2269 if (remoteRoleListId == null) {
2270 logger.debug(EELFLoggerDelegate.debugLogger,
2271 "Adding the role to the rolelist () - for user {}, found Name {}", user.getOrgUserId(),
2273 remoteUserRoleList.getName());
2274 RemoteRole role = new RemoteRole();
2275 role.setId(remoteUserRoleList.getId());
2276 role.setName(remoteUserRoleList.getName());
2283 logger.debug(EELFLoggerDelegate.debugLogger, "rolelist size of the USER() - for user {}, found RoleListSize {}", user.getOrgUserId(), roleList.size());
2291 public RemoteUserWithRoles[] doGetUsers(boolean postOpenSource, String remoteUsersString) {
2293 ObjectMapper mapper = new ObjectMapper();
2295 return mapper.readValue(remoteUsersString, RemoteUserWithRoles[].class);
2296 } catch (IOException e) {
2297 logger.error(EELFLoggerDelegate.errorLogger,
2298 "doGetUsers : Failed : Unexpected property in incoming JSON",
2300 logger.error(EELFLoggerDelegate.errorLogger,
2301 "doGetUsers : Incoming JSON that caused it --> " + remoteUsersString);
2304 return new RemoteUserWithRoles[0];
2307 @SuppressWarnings("unchecked")
2308 public List<EPUserApp> getEPUserAppList(Long appId, Long userId, Long roleId) {
2309 List<EPUserApp> userRoleList = new ArrayList<EPUserApp>();
2310 final Map<String, Long> params = new HashMap<>();
2311 params.put("appId", appId);
2312 params.put("userId", userId);
2313 params.put("roleId", roleId);
2314 userRoleList = dataAccessService.executeNamedQuery("getUserRoleOnUserIdAndRoleIdAndAppId", params, null);
2315 return userRoleList;
2319 /*public static void main(String[] args) {
2320 List<EcompRole> str1 = new ArrayList<String>();
2326 List<String> str2 = new ArrayList<String>();
2330 List<EcompRole> userApplicationRolesList = setUserRoles;
2331 List<EcompRole> appRolesList = Arrays.asList(appRoles);