2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2020 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 EPUser where orgUserId=:userId")
193 .setParameter("userId",userId)
195 if (userList.size() == 0) {
196 EPUser client = null;
198 client = searchService.searchUserByUserId(userId);
200 client = new EPUser();
201 client.setOrgUserId(userId);
202 client.setSystemUser(true);
203 client.setFirstName(userId.substring(0,userId.indexOf("@")));
205 if (client == null) {
206 String msg = "createLocalUserIfNecessary: cannot create user " + userId
207 + ", because not found in phonebook";
208 logger.error(EELFLoggerDelegate.errorLogger, msg);
210 client.setLoginId(userId);
211 client.setActive(true);
212 localSession.save(client);
215 transaction.commit();
216 } catch (Exception e) {
217 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
218 EcompPortalUtils.rollbackTransaction(transaction, "searchOrCreateUser rollback, exception = " + e);
220 EcompPortalUtils.closeLocalSession(localSession, "searchOrCreateUser");
225 * This method return nothing and remove roles before adding any roles for an app
228 * @param localSession
229 * @param userAppRoles
230 * @param newUserAppRolesMap
232 private static void syncUserRolesExtension(EPUserApp userRole, Long appId, Session localSession, EcompRole[] userAppRoles, HashMap<Long, EcompRole> newUserAppRolesMap) {
234 Long userAppRoleId = 0L;
235 if (appId == PortalConstants.PORTAL_APP_ID) { // local app
236 userAppRoleId = userRole.getRoleId();
237 } else { // remote app
238 userAppRoleId = userRole.getAppRoleId();
241 if (!newUserAppRolesMap.containsKey(userAppRoleId)) {
242 localSession.delete(userRole);
244 newUserAppRolesMap.remove(userAppRoleId);
249 * Checks whether the role is inactive
253 * if role is inactive, throws exception
255 private void checkIfRoleInactive(EPRole epRole) throws Exception{
256 if(!epRole.getActive()){
257 throw new Exception(epRole.getName()+ " role is unavailable");
263 * @param sessionFactory
266 * @param userAppRoles
267 * @param extRequestValue
268 * set to false if request is from users page otherwise true
271 @SuppressWarnings("unchecked")
272 protected void syncUserRoles(SessionFactory sessionFactory, String userId, Long appId,
273 EcompRole[] userAppRoles, Boolean extRequestValue, String reqType,boolean checkIfUserisRoleAdmin,EcompRole[] appRoles) 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);
280 List<EPRole> roleInfo = externalAccessRolesService.getPortalAppRoleInfo(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
282 EPRole adminRole = new EPRole();
283 if(roleInfo.size()>0)
285 adminRole = roleInfo.get(0);
286 logger.debug(EELFLoggerDelegate.debugLogger, "Admin RoleName form DB: " + adminRole.getName());
289 localSession = sessionFactory.openSession();
290 transaction = localSession.beginTransaction();
291 @SuppressWarnings("unchecked")
292 List<EPUser> userList = localSession
293 .createQuery("from EPUser where orgUserId=:userId")
294 .setParameter("userId",userId)
296 if (userList.size() > 0) {
297 EPUser client = userList.get(0);
298 roleActive = ("DELETE".equals(reqType)) ? "" : " and role.active = 'Y'";
299 @SuppressWarnings("unchecked")
300 List<EPUserApp> userRoles = localSession.createQuery("from EPUserApp where app.id=:appId and userId=:userId" + roleActive)
301 .setParameter("appId",appId)
302 .setParameter("userId",client.getId())
305 if ("DELETE".equals(reqType)) {
306 for (EPUserApp userAppRoleList : userRoles) {
307 userAppParams.put("roleName", String.valueOf(userAppRoleList.getRole().getName()));
308 userAppParams.put("appId", String.valueOf(appId));
309 appParams.put("appRoleName", userAppRoleList.getRole().getName());
310 @SuppressWarnings("unchecked")
311 List<EPRole> rolesList = (!userAppRoleList.getRole().getName().equals(adminRole.getName())) ? (List<EPRole>) dataAccessService.executeNamedQuery("getAppRoles", userAppParams, null) : (List<EPRole>) dataAccessService.executeNamedQuery("getPortalAppRoles", appParams, null);
312 if(rolesList.size() > 0 || !rolesList.isEmpty()){
313 checkIfRoleInactive(rolesList.get(0));
318 if (appRoles != null) {
319 List<EcompRole> appRolesList = Arrays.stream(appRoles).collect(Collectors.toList());
320 List<EPUserApp> finalUserRolesList = new ArrayList<>();
321 if (checkIfUserisRoleAdmin) {
322 for (EcompRole role : appRolesList) {
323 for (EPUserApp userAppRoleList : userRoles) {
324 if (userAppRoleList.getRole().getName().equals(role.getName()))
327 finalUserRolesList.add(userAppRoleList);
332 userRoles = new ArrayList<>();
333 userRoles.addAll(finalUserRolesList);
337 for (EPUserApp userRole : userRoles) {
338 if (!userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && userRole.getRoleId() != PortalConstants.SYS_ADMIN_ROLE_ID && !extRequestValue){
339 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
341 else if (extRequestValue && ("PUT".equals(reqType) || "POST".equals(reqType) || "DELETE".equals(reqType))){
342 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
344 else if (extRequestValue && !userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)){
345 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
350 Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values();
351 if (newRolesToAdd.size() > 0) {
352 EPApp app = (EPApp) localSession.get(EPApp.class, appId);
354 HashMap<Long, EPRole> rolesMap = new HashMap<Long, EPRole>();
355 if (appId.equals(PortalConstants.PORTAL_APP_ID)) { // local app
356 String appIdValue = "";
357 if(!extRequestValue){
358 appIdValue = "and id != " + PortalConstants.SYS_ADMIN_ROLE_ID;
360 @SuppressWarnings("unchecked")
361 List<EPRole> roles = localSession
362 .createQuery("from " + EPRole.class.getName() + " where appId is null " + appIdValue).list();
363 for (EPRole role : roles) {
365 rolesMap.put(role.getId(), role);
367 } else { // remote app
368 @SuppressWarnings("unchecked")
369 List<EPRole> roles = localSession
370 .createQuery("from EPRole where appId=:appId")
371 .setParameter("appId",appId)
373 for (EPRole role : roles) {
374 if (!extRequestValue && app.getCentralAuth()) {
375 rolesMap.put(role.getId(), role);
377 rolesMap.put(role.getAppRoleId(), role);
383 for (EcompRole userRole : newRolesToAdd) {
384 EPUserApp userApp = new EPUserApp();
385 if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName().equals(adminRole.getName())) {
386 role = (EPRole) localSession.get(EPRole.class, new Long(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
387 userApp.setRole(role);
388 } else if ((userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) && !extRequestValue){
390 }else if((userRole.getId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)) && app.getId().equals(PortalConstants.PORTAL_APP_ID) && !extRequestValue){
394 userApp.setRole(rolesMap.get(userRole.getId()));
397 userApp.setUserId(client.getId());
399 localSession.save(userApp);
400 localSession.flush();
403 if (appId == PortalConstants.PORTAL_APP_ID) {
405 * for local app -- hack - always make sure fn_role
406 * table's app_id is null and not 1 for primary app in
407 * this case being onap portal app; reason: hibernate
408 * is rightly setting this to 1 while persisting to
409 * fn_role as per the mapping but SDK role management
410 * code expects the app_id to be null as there is no
411 * concept of App_id in SDK
413 localSession.flush();
414 SQLQuery sqlQuery = localSession
415 .createSQLQuery("update fn_role set app_id = null where app_id = 1 ");
416 sqlQuery.executeUpdate();
421 transaction.commit();
422 } catch (Exception e) {
423 logger.error(EELFLoggerDelegate.errorLogger, "syncUserRoles failed", e);
424 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
425 EcompPortalUtils.rollbackTransaction(transaction,
426 "Exception occurred in syncUserRoles, Details: " + e.toString());
427 if("DELETE".equals(reqType)){
428 throw new SyncUserRolesException(e.getMessage());
431 if(localSession != null)
432 localSession.close();
437 * Called when getting the list of roles for the user
440 * @param userAppRoles
441 * @return List<RoleInAppForUser>
443 protected List<RoleInAppForUser> constructRolesInAppForUserGet(EcompRole[] appRoles, EcompRole[] userAppRoles) {
444 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
446 Set<Long> userAppRolesMap = new HashSet<Long>();
447 if (userAppRoles != null) {
448 for (EcompRole ecompRole : userAppRoles) {
449 userAppRolesMap.add(ecompRole.getId());
452 logger.error(EELFLoggerDelegate.errorLogger,
453 "constructRolesInAppForUserGet has received userAppRoles list empty");
456 if (appRoles != null) {
457 for (EcompRole ecompRole : appRoles) {
458 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
459 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
460 rolesInAppForUser.add(roleForUser);
463 logger.error(EELFLoggerDelegate.errorLogger, "constructRolesInAppForUser has received appRoles list empty");
465 return rolesInAppForUser;
469 * Called when getting the list of roles for the user
472 * @param userAppRoles
473 * @param extRequestValue
474 * set to false if request is from users page otherwise true
475 * @return List<RoleInAppForUser>
477 protected List<RoleInAppForUser> constructRolesInAppForUserGet(List<Role> appRoles, EPRole[] userAppRoles, Boolean extRequestValue) {
478 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
480 Set<Long> userAppRolesMap = new HashSet<Long>();
481 if (userAppRoles != null) {
482 for (EPRole ecompRole : userAppRoles) {
483 userAppRolesMap.add(ecompRole.getId());
485 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - userAppRolesMap = {}", userAppRolesMap);
488 logger.error(EELFLoggerDelegate.errorLogger,
489 "constructRolesInAppForUserGet has received userAppRoles list empty.");
492 if (appRoles != null) {
494 for (Role ecompRole : appRoles) {
495 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - appRoles not null = {}", ecompRole);
497 if (ecompRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && !extRequestValue)
499 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
500 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
501 rolesInAppForUser.add(roleForUser);
502 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - rolesInAppForUser = {}", rolesInAppForUser);
506 logger.error(EELFLoggerDelegate.errorLogger,
507 "constructRolesInAppForUser has received appRoles list empty.");
509 return rolesInAppForUser;
514 * copies of methods in GetAppsWithUserRoleState
516 * @param sessionFactory
521 protected void syncAppRoles(SessionFactory sessionFactory, Long appId, EcompRole[] appRoles) throws Exception {
522 logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId);
523 HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles);
524 Session localSession = null;
525 Transaction transaction = null;
528 localSession = sessionFactory.openSession();
529 transaction = localSession.beginTransaction();
530 // Attention! All roles from remote application supposed to be
533 @SuppressWarnings("unchecked")
534 List<EPRole> currentAppRoles = localSession.createQuery("from EPRole where appId = :appId")
535 .setParameter("appId",appId)
538 List<EPRole> obsoleteRoles = new ArrayList<EPRole>();
539 for (int i = 0; i < currentAppRoles.size(); i++) {
540 EPRole oldAppRole = currentAppRoles.get(i);
541 if (oldAppRole.getAppRoleId() != null) {
542 EcompRole role = null;
543 role = newRolesMap.get(oldAppRole.getAppRoleId());
545 if (!(role.getName() == null || oldAppRole.getName().equals(role.getName()))) {
546 oldAppRole.setName(role.getName());
547 localSession.update(oldAppRole);
549 oldAppRole.setActive(true);
550 newRolesMap.remove(oldAppRole.getAppRoleId());
552 obsoleteRoles.add(oldAppRole);
555 obsoleteRoles.add(oldAppRole);
558 Collection<EcompRole> newRolesToAdd = newRolesMap.values();
559 if (obsoleteRoles.size() > 0) {
560 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: we have obsolete roles to delete");
561 for (EPRole role : obsoleteRoles) {
562 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: obsolete role: " + role.toString());
563 Long roleId = role.getId();
564 // delete obsolete roles here
565 // Must delete all records with foreign key constraints on
567 // fn_user_role, fn_role_composite, fn_role_function,
568 // fn_user_pseudo_role, fn_menu_functional_roles.
569 // And for fn_menu_functional, if no other roles for that
570 // menu item, remove the url.
572 // Delete from fn_user_role
573 @SuppressWarnings("unchecked")
574 List<EPUserApp> userRoles = localSession.createQuery(
575 "from EPUserApp where app.id=:appId and role_id=:roleId")
576 .setParameter("appId",appId)
577 .setParameter("roleId",roleId)
580 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: number of userRoles to delete: " + userRoles.size());
581 for (EPUserApp userRole : userRoles) {
582 logger.debug(EELFLoggerDelegate.debugLogger,
583 "syncAppRoles: about to delete userRole: " + userRole.toString());
584 localSession.delete(userRole);
585 logger.debug(EELFLoggerDelegate.debugLogger,
586 "syncAppRoles: finished deleting userRole: " + userRole.toString());
589 // Delete from fn_menu_functional_roles
590 @SuppressWarnings("unchecked")
591 List<FunctionalMenuRole> funcMenuRoles = localSession
592 .createQuery("from FunctionalMenuRole where roleId=:roleId")
593 .setParameter("roleId",roleId)
595 int numMenuRoles = funcMenuRoles.size();
596 logger.debug(EELFLoggerDelegate.debugLogger,
597 "syncAppRoles: number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles);
598 for (FunctionalMenuRole funcMenuRole : funcMenuRoles) {
599 Long menuId = funcMenuRole.menuId;
600 // If this is the only role for this menu item, then the
601 // app and roles will be gone,
602 // so must null out the url too, to be consistent
603 @SuppressWarnings("unchecked")
604 List<FunctionalMenuRole> funcMenuRoles2 = localSession
605 .createQuery("from FunctionalMenuRole where menuId=:menuId")
606 .setParameter("menuId",menuId)
608 int numMenuRoles2 = funcMenuRoles2.size();
609 logger.debug(EELFLoggerDelegate.debugLogger,
610 "syncAppRoles: number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2);
611 localSession.delete(funcMenuRole);
612 if (numMenuRoles2 == 1) {
613 // If this is the only role for this menu item, then
614 // the app and roles will be gone,
615 // so must null out the url too, to be consistent
616 logger.debug(EELFLoggerDelegate.debugLogger,
617 "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url");
618 @SuppressWarnings("unchecked")
619 List<FunctionalMenuItem> funcMenuItems = localSession
620 .createQuery("from FunctionalMenuItem where menuId=:menuId")
621 .setParameter("menuId",menuId)
623 if (funcMenuItems.size() > 0) {
624 logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item");
625 FunctionalMenuItem funcMenuItem = funcMenuItems.get(0);
626 funcMenuItem.url = "";
627 localSession.update(funcMenuItem);
631 boolean isPortalRequest = true;
632 externalAccessRolesService.deleteRoleDependencyRecords(localSession, roleId, appId, isPortalRequest);
633 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to delete the role: " + role.toString());
634 localSession.delete(role);
635 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: deleted the role");
638 for (EcompRole role : newRolesToAdd) {
639 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to add missing role: " + role.toString());
640 EPRole newRole = new EPRole();
641 // Attention! All roles from remote application supposed to be
643 newRole.setActive(true);
644 newRole.setName(role.getName());
645 newRole.setAppId(appId);
646 newRole.setAppRoleId(role.getId());
647 localSession.save(newRole);
649 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to commit the transaction");
650 transaction.commit();
651 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: committed the transaction");
652 } catch (Exception e) {
653 logger.error(EELFLoggerDelegate.errorLogger, "syncAppRoles failed", e);
654 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
655 EcompPortalUtils.rollbackTransaction(transaction,
656 "Exception occurred in syncAppRoles, Details: " + e.toString());
657 throw new Exception(e);
659 localSession.close();
668 * Called when updating the list of roles for the user
672 * @param userRolesInRemoteApp
673 * @return RolesInAppForUser
675 protected RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId,
676 Set<EcompRole> userRolesInRemoteApp) {
677 RolesInAppForUser result;
678 result = new RolesInAppForUser();
679 result.appId = appId;
680 result.orgUserId = userId;
682 for (EcompRole role : userRolesInRemoteApp) {
683 RoleInAppForUser roleInAppForUser = new RoleInAppForUser();
684 roleInAppForUser.roleId = role.getId();
685 roleInAppForUser.roleName = role.getName();
686 roleInAppForUser.isApplied = new Boolean(true);
687 result.roles.add(roleInAppForUser);
694 * @param roleInAppForUserList
697 protected boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) {
698 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
699 if (roleInAppForUser.isApplied.booleanValue()) {
707 * Builds JSON and posts it to a remote application to update user roles.
709 * @param roleInAppForUserList
711 * @param applicationsRestClientService
714 * @return Set of roles as sent; NOT the response from the app.
715 * @throws JsonProcessingException
716 * @throws HTTPException
718 protected Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
719 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId,boolean systemUser)
720 throws JsonProcessingException, HTTPException {
721 Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList);
722 Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList);
723 String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote);
724 EPApp externalApp = null;
725 SystemType type = SystemType.APPLICATION;
726 externalApp = appsCacheService.getApp(appId);
727 String appBaseUri = null;
728 Set<RemoteRoleV1> updatedUserRolesinRemoteV1 = new TreeSet<>();
729 if (externalApp != null) {
730 appBaseUri = (type == SystemType.APPLICATION) ? externalApp.getAppRestEndpoint() : "";
732 if(appBaseUri != null && appBaseUri.endsWith("/api")){
733 for(EcompRole eprole :updatedUserRolesinRemote)
735 RemoteRoleV1 role = new RemoteRoleV1();
736 role.setId(eprole.getId());
737 role.setName(eprole.getName());
738 updatedUserRolesinRemoteV1.add(role);
740 userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemoteV1);
742 applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString,
743 String.format("/user/%s/roles", userId));
744 // TODO: We should add code that verifies that the post operation did
745 // succeed. Because the SDK may still return 200 OK with an html page
746 // even when it fails!
747 return updateUserRolesInEcomp;
752 * @param roleInAppForUserList
753 * @return Set<EcompRole>
755 protected Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) {
756 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
757 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
758 if (roleInAppForUser.isApplied) {
759 EcompRole ecompRole = new EcompRole();
760 ecompRole.setId(roleInAppForUser.roleId);
761 ecompRole.setName(roleInAppForUser.roleName);
762 existingUserRoles.add(ecompRole);
765 return existingUserRoles;
769 * Constructs user app roles excluding Account Administrator role
771 * @param roleInAppForUserList
773 * List of roles with Role name, Role Id
775 protected Set<EcompRole> constructUsersRemoteAppRoles(List<RoleInAppForUser> roleInAppForUserList) {
776 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
777 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
778 if (roleInAppForUser.isApplied && !roleInAppForUser.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
779 EcompRole ecompRole = new EcompRole();
780 ecompRole.setId(roleInAppForUser.roleId);
781 ecompRole.setName(roleInAppForUser.roleName);
782 existingUserRoles.add(ecompRole);
785 return existingUserRoles;
789 * This is for a single app
791 * @param rolesInAppForUser
792 * @param externalSystemRequest
793 * set to false if requests from Users page otherwise true
794 * @return true on success, false otherwise
796 protected boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser, boolean externalSystemRequest, String reqType,boolean isSystemUser,Set<EcompRole> rolesDeletedByApprover ,boolean isLoggedInUserRoleAdminOfApp ) throws Exception {
797 boolean result = false;
798 String userId = rolesInAppForUser.orgUserId;
799 Long appId = rolesInAppForUser.appId;
800 synchronized (syncRests) {
801 if (rolesInAppForUser != null) {
802 createLocalUserIfNecessary(userId, isSystemUser);
805 if (rolesInAppForUser != null) {
806 EcompRole[] userAppRoles = new EcompRole[rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size()];
807 for (int i = 0; i < rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size(); i++) {
808 RoleInAppForUser roleInAppForUser = rolesInAppForUser.roles.get(i);
809 EcompRole role = new EcompRole();
810 role.setId(roleInAppForUser.roleId);
811 role.setName(roleInAppForUser.roleName);
812 userAppRoles[i] = role;
815 EcompRole[] applicationRoles = null;
817 if(isLoggedInUserRoleAdminOfApp){
818 List<EcompRole> roles = Arrays.stream(userAppRoles).collect(Collectors.toList());
819 List<EcompRole> roles1 = rolesDeletedByApprover.stream().collect(Collectors.toList());
820 roles.addAll(roles1);
821 applicationRoles = roles.stream().toArray(n -> new EcompRole[n]);
824 syncUserRoles(sessionFactory, userId, appId, userAppRoles, externalSystemRequest, reqType,isLoggedInUserRoleAdminOfApp,applicationRoles);
826 } catch (Exception e) {
827 logger.error(EELFLoggerDelegate.errorLogger,
828 "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for orgUserId " + userId, e);
829 if("DELETE".equals(reqType)){
830 throw new Exception(e.getMessage());
842 * @return UserApplicationRoles
844 protected UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) {
845 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
846 userWithRemoteAppRoles.setAppId(appId);
847 userWithRemoteAppRoles.setOrgUserId(remoteUser.getOrgUserId());
848 userWithRemoteAppRoles.setFirstName(remoteUser.getFirstName());
849 userWithRemoteAppRoles.setLastName(remoteUser.getLastName());
850 userWithRemoteAppRoles.setRoles(remoteUser.getRoles());
851 return userWithRemoteAppRoles;
857 * @see org.onap.portalapp.portal.service.UserRolesService#
858 * importRolesFromRemoteApplication(java.lang.Long)
860 public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException {
861 EPRole[] appRolesFull = applicationsRestClientService.get(EPRole[].class, appId, "/rolesFull");
862 List<EPRole> rolesList = Arrays.asList(appRolesFull);
863 for (EPRole externalAppRole : rolesList) {
865 // Try to find an existing extern role for the app in the local
866 // onap DB. If so, then use its id to update the existing external
867 // application role record.
868 Long externAppId = externalAppRole.getId();
869 EPRole existingAppRole = epRoleService.getRole(appId, externAppId);
870 if (existingAppRole != null) {
871 logger.debug(EELFLoggerDelegate.debugLogger,
872 String.format("ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.",
873 appId, externAppId));
876 // persistExternalRoleInEcompDb(externalAppRole, appId,
884 * It adds new user for remote application
886 * @param roleInAppForUserList
887 * @param remoteAppUser
891 * @param searchService
892 * @param applicationsRestClientService
896 private EPUser addRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app,
897 ObjectMapper mapper, SearchService searchService,
898 ApplicationsRestClientService applicationsRestClientService) throws Exception {
899 EPUser addRemoteUser = null;
900 if (remoteUserShouldBeCreated(roleInAppForUserList)) {
901 createNewUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper,
902 isAppUpgradeVersion(app));
904 return addRemoteUser;
907 private EPUser pushRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app,
908 ObjectMapper mapper, SearchService searchService,
909 ApplicationsRestClientService applicationsRestClientService,boolean appRoleIdUsed) throws Exception {
910 EPUser addRemoteUser = null;
911 // if (remoteUserShouldBeCreated(roleInAppForUserList)) {
912 pushUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper,
913 isAppUpgradeVersion(app), roleInAppForUserList, appRoleIdUsed);
915 return addRemoteUser;
918 @SuppressWarnings("unchecked")
919 protected void pushUserOnRemoteApp(String userId, EPApp app,
920 ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
921 ObjectMapper mapper, boolean postOpenSource, List<RoleInAppForUser> roleInAppForUserList,boolean appRoleIdUsed) throws Exception {
923 EPUser client = null;
924 client = searchService.searchUserByUserId(userId);
926 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
927 if (client == null) {
928 String msg = "cannot create user " + userId + ", because he/she cannot be found in directory.";
929 logger.error(EELFLoggerDelegate.errorLogger, msg);
930 // throw new Exception(msg);
931 final Map<String, String> loginIdParams = new HashMap<>();
932 loginIdParams.put("orgUserIdValue", userId);
933 List<EPUser> userList = new ArrayList<>();
934 userList = dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null);
935 if (userList.size() > 0) {
936 logger.debug(EELFLoggerDelegate.debugLogger,
937 userList.get(0).getOrgUserId() + " User was found in Portal");
938 client = userList.get(0);
939 SortedSet<EPUserApp> userApps = new TreeSet<>();
940 client.setEPUserApps(userApps);
941 client.setSystemUser(false);
943 logger.error(EELFLoggerDelegate.errorLogger, "user cannot be found be in directory or in portal");
944 throw new Exception(msg);
949 client.setLoginId(userId);
950 client.setActive(true);
951 client.setOrgUserId(userId);
954 roleInAppForUserList.removeIf(role -> role.isApplied.equals(false));
955 SortedSet<Role> roles = new TreeSet<>();
957 List<EPRole> getAppRoles = externalAccessRolesService.getAppRoles(app.getId());
958 List<EPApp> appList = new ArrayList<>();
960 List<CentralV2Role> roleList = new ArrayList<>();
961 Map<String, Long> params = new HashMap<>();
963 List<EPRole> userRoles = new ArrayList<>();
965 for (RoleInAppForUser roleInappForUser : roleInAppForUserList) {
966 EPRole role = new EPRole();
967 role.setId(roleInappForUser.getRoleId());
968 role.setName(roleInappForUser.getRoleName());
973 List<EPRole> userAppRoles = new ArrayList<>();
974 for (EPRole role : userRoles) {
975 EPRole appRole = getAppRoles.stream()
976 .filter(applicationRole -> role.getId().equals(applicationRole.getAppRoleId())).findAny()
978 EPRole epRole = new EPRole();
979 if (appRole != null) {
980 epRole.setId(appRole.getId());
981 epRole.setName(appRole.getName());
983 userAppRoles.add(epRole);
985 userRoles = new ArrayList<>();
986 userRoles.addAll(userAppRoles);
988 roleList = externalAccessRolesService.createCentralRoleObject(appList, userRoles, roleList, params);
990 for (CentralV2Role epRole : roleList) {
991 Role role = new Role();
992 EPRole appRole = getAppRoles.stream()
993 .filter(applicationRole -> epRole.getId().equals(applicationRole.getId())).findAny().orElse(null);
994 if (appRole != null){
995 role.setId(appRole.getAppRoleId());
996 role.setName(epRole.getName());
997 role.setRoleFunctions(epRole.getRoleFunctions());
1001 client.setRoles(roles);
1002 String userInString = null;
1003 userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
1004 logger.debug(EELFLoggerDelegate.debugLogger,
1005 "about to post a client to remote application, users json = " + userInString);
1006 applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user/%s", userId));
1010 * It checks whether the remote user exists or not
1011 * if exits returns user object else null
1015 * @param applicationsRestClientService
1017 * @throws HTTPException
1019 private EPUser checkIfRemoteUserExits(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService) throws HTTPException{
1020 EPUser checkRemoteUser = null;
1022 checkRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
1023 } catch (HTTPException e) {
1024 // Some apps are returning 400 if user is not found.
1025 if (e.getResponseCode() == 400) {
1026 logger.debug(EELFLoggerDelegate.debugLogger,
1027 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing",
1029 } else if(e.getResponseCode() == 404) {
1030 logger.debug(EELFLoggerDelegate.debugLogger,
1031 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 404; continuing",
1034 // Other response code, let it come thru.
1038 return checkRemoteUser;
1045 * @see org.onap.portalapp.portal.service.UserRolesService#
1046 * setAppWithUserRoleStateForUser(org.onap.portalapp.portal.domain.
1047 * EPUser, org.onap.portalapp.portal.transport.AppWithRolesForUser)
1049 public ExternalRequestFieldsValidator setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser) {
1050 boolean result = false;
1051 boolean epRequestValue = false;
1053 String reqMessage = "";
1054 if (newAppRolesForUser != null && newAppRolesForUser.getOrgUserId() != null) {
1055 userId = newAppRolesForUser.getOrgUserId().trim();
1057 Long appId = newAppRolesForUser.getAppId();
1058 List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.getAppRoles();
1062 if (userId.length() > 0 ) {
1063 ObjectMapper mapper = new ObjectMapper();
1064 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1067 EPApp app = appsService.getApp(appId);
1069 boolean checkIfUserisApplicationAccAdmin = adminRolesService.isAccountAdminOfApplication(user,
1071 Set<EcompRole> rolesGotDeletedFromApprover = new TreeSet<EcompRole>();
1073 boolean checkIfUserisOnlyRoleAdmin = adminRolesService.isRoleAdmin(user) && !checkIfUserisApplicationAccAdmin;
1074 if (checkIfUserisOnlyRoleAdmin) {
1075 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
1076 if (!roleInAppForUser.isApplied) {
1077 EcompRole ecompRole = new EcompRole();
1078 ecompRole.setId(roleInAppForUser.roleId);
1079 ecompRole.setName(roleInAppForUser.roleName);
1080 rolesGotDeletedFromApprover.add(ecompRole);
1085 applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
1087 Boolean systemUser = (newAppRolesForUser.getIsSystemUser() != null ? newAppRolesForUser.getIsSystemUser() : false);
1089 if ((app.getCentralAuth() || app.getId().equals(PortalConstants.PORTAL_APP_ID)) && systemUser) {
1091 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1092 applicationsRestClientService, appId, userId);
1093 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1094 userRolesInLocalApp);
1095 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1096 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
1097 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1098 // Apply changes in external Access system
1100 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList,
1101 epRequestValue, systemUser,rolesGotDeletedByApprover,false);
1103 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal",
1104 systemUser,rolesGotDeletedByApprover,false);
1106 }else if (!app.getCentralAuth() && systemUser)
1108 throw new Exception("For non-centralized application we cannot add systemUser");
1110 else{ // if centralized app
1111 if (app.getCentralAuth()) {
1112 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1113 pushRemoteUser(roleInAppForUserList, userId, app, mapper, searchService,
1114 applicationsRestClientService,false);
1117 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1118 applicationsRestClientService, appId, userId);
1119 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1120 userRolesInLocalApp);
1121 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1122 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1124 // Apply changes in external Access system
1125 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList,
1126 epRequestValue,false,rolesGotDeletedFromApprover,checkIfUserisOnlyRoleAdmin);
1128 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal", systemUser,rolesGotDeletedFromApprover,checkIfUserisOnlyRoleAdmin);
1130 // In case if portal is not centralized then follow existing approach
1131 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1132 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1133 applicationsRestClientService, appId, userId);
1134 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1135 userRolesInLocalApp);
1136 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
1137 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal",false,rolesGotDeletedByApprover,false);
1138 } else{// remote app
1139 EPUser remoteAppUser = null;
1140 if(!app.getCentralAuth() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1142 remoteAppUser = checkIfRemoteUserExits(userId, app, applicationsRestClientService);
1144 if (remoteAppUser == null) {
1145 remoteAppUser = addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService, applicationsRestClientService);
1147 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
1148 applicationsRestClientService, appId, userId,systemUser);
1149 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1150 userRolesInRemoteApp);
1151 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
1152 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null,false,rolesGotDeletedByApprover,false);
1154 // If no roles remain, request app to set user inactive.
1155 if (userRolesInRemoteApp.size() == 0) {
1156 logger.debug(EELFLoggerDelegate.debugLogger,
1157 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
1159 //remoteAppUser.setActive(false);
1160 postUserToRemoteApp(userId, user, app, applicationsRestClientService);
1165 } catch (Exception e) {
1166 /*String message = String.format(
1167 "Failed to create user or update user roles for User %s, AppId %s",
1168 userId, Long.toString(appId));
1169 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1172 String message = String.format(
1173 "Failed to create user or update user roles for User %s, AppId %s",
1174 userId, Long.toString(appId));
1175 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1177 reqMessage = e.getMessage();
1184 return new ExternalRequestFieldsValidator(result, reqMessage);
1188 * It adds user roles in External system and also make data consistent in both local and in External System
1190 * @param app details
1192 * @param roleInAppUser Contains list of active roles
1194 @SuppressWarnings("unchecked")
1195 private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser, boolean isPortalRequest,boolean nonHumanUserId,Set<EcompRole> deletedRolesByApprover,boolean isLoggedInUserRoleAdminofApp) throws Exception
1198 // check if user exists
1199 final Map<String, String> userParams = new HashMap<>();
1200 userParams.put("orgUserIdValue", orgUserId);
1201 List<EPUser> userInfo = checkIfUserExists(userParams);
1202 if (userInfo.isEmpty()) {
1203 createLocalUserIfNecessary(orgUserId, nonHumanUserId);
1206 if (EPCommonSystemProperties
1207 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN) && !nonHumanUserId) {
1208 if(orgUserId.indexOf("@") ==-1) {
1209 name = orgUserId + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
1215 if(nonHumanUserId && orgUserId!=null) {
1216 if(orgUserId.indexOf("@") ==-1) {
1217 name = orgUserId + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
1221 ObjectMapper mapper = new ObjectMapper();
1222 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1223 HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
1224 ResponseEntity<String> getResponse = externalAccessRolesService.getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
1227 List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
1228 String res = getResponse.getBody();
1229 JSONObject jsonObj = null;
1230 JSONArray extRoles = null;
1231 if (!res.equals("{}")) {
1232 jsonObj = new JSONObject(res);
1233 extRoles = jsonObj.getJSONArray("role");
1235 ExternalAccessUserRoleDetail userRoleDetail = null;
1236 if (extRoles != null) {
1237 for (int i = 0; i < extRoles.length(); i++) {
1238 if (extRoles.getJSONObject(i).getString("name").startsWith(app.getNameSpace() + ".")
1239 && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".admin")
1240 && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".owner")) {
1241 if (extRoles.getJSONObject(i).has("description")) {
1242 ExternalRoleDescription desc = new ExternalRoleDescription(extRoles.getJSONObject(i).getString("description"));
1243 userRoleDetail = new ExternalAccessUserRoleDetail(
1244 extRoles.getJSONObject(i).getString("name"), desc);
1245 userRoleDetailList.add(userRoleDetail);
1247 userRoleDetail = new ExternalAccessUserRoleDetail(
1248 extRoles.getJSONObject(i).getString("name"), null);
1249 userRoleDetailList.add(userRoleDetail);
1256 List<ExternalAccessUserRoleDetail> userRoleListMatchingInExtAuthAndLocal = CheckIfRoleAreMatchingInUserRoleDetailList(userRoleDetailList,app);
1258 List<EcompUserAppRoles> userAppList = new ArrayList<>();
1259 // If request coming from portal not from external role approval system then we have to check if user already
1260 // have account admin or system admin as GUI will not send these roles
1261 if (!isPortalRequest) {
1262 final Map<String, String> loginIdParams = new HashMap<>();
1263 loginIdParams.put("orgUserIdValue", orgUserId);
1264 EPUser user = (EPUser) dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null).get(0);
1265 final Map<String, Long> params = new HashMap<>();
1266 params.put("appId", app.getId());
1267 params.put("userId", user.getId());
1268 userAppList = dataAccessService.executeNamedQuery("getUserAppExistingRoles",
1270 if (!roleInAppUser.isEmpty()) {
1271 for (EcompUserAppRoles userApp : userAppList) {
1272 if (userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)
1273 || userApp.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
1274 RoleInAppForUser addSpecialRole = new RoleInAppForUser();
1275 addSpecialRole.setIsApplied(true);
1276 addSpecialRole.setRoleId(userApp.getRoleId());
1277 addSpecialRole.setRoleName(userApp.getRoleName());
1278 roleInAppUser.add(addSpecialRole);
1283 List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct()
1284 .collect(Collectors.toList());
1285 Map<String, RoleInAppForUser> currentUserRolesToUpdate = new HashMap<>();
1286 for (RoleInAppForUser roleInAppUserNew : roleInAppUserNonDupls) {
1287 currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), roleInAppUserNew);
1289 final Map<String, ExternalAccessUserRoleDetail> currentUserRolesInExternalSystem = new HashMap<>();
1290 for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleListMatchingInExtAuthAndLocal) {
1291 currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole);
1294 if (isLoggedInUserRoleAdminofApp) {
1295 if (deletedRolesByApprover.size() > 0) {
1296 List<ExternalAccessUserRoleDetail> newUpdatedRoles = new ArrayList<>();
1297 Set<EcompRole> roles = new HashSet<>();
1298 for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
1299 for (EcompRole role : deletedRolesByApprover) {
1300 if ((userRole.getName().substring(app.getNameSpace().length() + 1)).equals(role.getName())) {
1302 newUpdatedRoles.add(userRole);
1306 if (newUpdatedRoles.size() > 0) {
1307 userRoleListMatchingInExtAuthAndLocal = new ArrayList<>();
1308 userRoleListMatchingInExtAuthAndLocal.addAll(newUpdatedRoles);
1310 userRoleListMatchingInExtAuthAndLocal = new ArrayList<>();
1311 currentUserRolesToUpdate = new HashMap<>();
1316 userRoleListMatchingInExtAuthAndLocal = new ArrayList<>();
1317 currentUserRolesToUpdate = new HashMap<>();
1322 // Check if user roles does not exists in local but still there in External Central Auth System delete them all
1323 for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
1324 if (!(currentUserRolesToUpdate
1325 .containsKey(userRole.getName().substring(app.getNameSpace().length() + 1)))) {
1326 HttpEntity<String> entity = new HttpEntity<>(headers);
1327 logger.debug(EELFLoggerDelegate.debugLogger,
1328 "updateUserRolesInExternalSystem: Connecting to external system to DELETE user role {}",
1329 userRole.getName());
1330 ResponseEntity<String> deleteResponse = template.exchange(
1331 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1332 + "userRole/" + name + "/" + userRole.getName(),
1333 HttpMethod.DELETE, entity, String.class);
1334 logger.debug(EELFLoggerDelegate.debugLogger,
1335 "updateUserRolesInExternalSystem: Finished DELETE operation in external system for user role {} and the response is {}",
1336 userRole.getName(), deleteResponse.getBody());
1339 // Check if user roles does not exists in External Central Auth System add them all
1340 for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) {
1341 if (!(currentUserRolesInExternalSystem
1342 .containsKey(app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")))) {
1343 ExternalAccessUser extUser = new ExternalAccessUser(name,
1344 app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1345 String formattedUserRole = mapper.writeValueAsString(extUser);
1346 HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers);
1347 logger.debug(EELFLoggerDelegate.debugLogger, "updateUserRolesInExternalSystem: Connecting to external system for user {} and POST {}",
1348 name , addUserRole.getRoleName());
1349 ResponseEntity<String> addResponse = template
1350 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1351 + "userRole", HttpMethod.POST, entity, String.class);
1352 logger.debug(EELFLoggerDelegate.debugLogger,
1353 "updateUserRolesInExternalSystem: Finished adding user role in external system {} and added user role {}",
1354 addResponse.getBody(), addUserRole.getRoleName());
1355 if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 404) {
1356 logger.debug(EELFLoggerDelegate.debugLogger,
1357 "Finished POST operation in external system but unable to save user role", addResponse.getBody(),
1358 addUserRole.getRoleName());
1359 throw new Exception(addResponse.getBody());
1363 } catch (HttpClientErrorException e) {
1364 logger.error(EELFLoggerDelegate.errorLogger,
1365 "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}",
1367 if (e.getStatusCode() == HttpStatus.FORBIDDEN) {
1368 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid systemUser", orgUserId);
1369 throw new HttpClientErrorException(HttpStatus.FORBIDDEN, "Please enter the valid systemUser");
1371 if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
1372 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid role");
1373 throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "Please enter the valid role");
1375 EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
1379 catch (Exception e) {
1380 logger.error(EELFLoggerDelegate.errorLogger, "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}", app.getId(), e);
1381 EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
1387 private List<ExternalAccessUserRoleDetail> CheckIfRoleAreMatchingInUserRoleDetailList(
1388 List<ExternalAccessUserRoleDetail> userRoleDetailList, EPApp app) {
1389 Map<String, EPRole> epRoleList = externalAccessRolesService.getAppRoleNamesWithUnderscoreMap(app);
1390 //Add Account Admin role for partner app to prevent conflict
1391 if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1392 EPRole role = new EPRole();
1393 role.setName(PortalConstants.ADMIN_ROLE.replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1394 epRoleList.put(role.getName(), role);
1396 userRoleDetailList.removeIf(userRoleDetail -> !epRoleList.containsKey(userRoleDetail.getName().substring(app.getNameSpace().length()+1)));
1397 return userRoleDetailList;
1404 * @param applicationsRestClientService
1405 * @param searchService
1409 protected void createNewUserOnRemoteApp(String userId, EPApp app,
1410 ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
1411 ObjectMapper mapper, boolean postOpenSource) throws Exception {
1414 EPUser client = searchService.searchUserByUserId(userId);
1416 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1418 if (client == null) {
1419 String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook.";
1420 logger.error(EELFLoggerDelegate.errorLogger, msg);
1421 throw new Exception(msg);
1424 client.setLoginId(userId);
1425 client.setActive(true);
1427 String userInString = null;
1428 userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
1429 logger.debug(EELFLoggerDelegate.debugLogger,
1430 "about to post new client to remote application, users json = " + userInString);
1431 applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user", userId));
1435 @SuppressWarnings("unchecked")
1436 protected void applyChangesToAppRolesRequest(Long appId, Long userId, String updateStatus, EPUserAppRolesRequest epUserAppRolesRequest) {
1437 final Map<String, Long> epRequestParams = new HashMap<>();
1439 EPUserAppRolesRequest epAppRolesRequestData = epUserAppRolesRequest;
1440 epAppRolesRequestData.setUpdatedDate(new Date());
1441 epAppRolesRequestData.setRequestStatus(updateStatus);
1442 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1443 addiotonalUpdateParam.put("userId", userId);
1444 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1445 epRequestParams.put("reqId", epUserAppRolesRequest.getId());
1446 List<EPUserAppRolesRequestDetail> epUserAppRolessDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1447 epUserAppRolessDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1448 epRequestParams, null);
1449 if (epUserAppRolessDetailList.size() > 0) {
1450 for (EPUserAppRolesRequestDetail epRequestUpdateData : epUserAppRolessDetailList) {
1451 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateData;
1452 epAppRoleDetailData.setReqType(updateStatus);
1453 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1454 HashMap<String, Long> updateDetailsParam = new HashMap<String, Long>();
1455 addiotonalUpdateParam.put("reqId", epUserAppRolesRequest.getId());
1456 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParam);
1459 logger.debug(EELFLoggerDelegate.debugLogger, "The request is set to complete");
1461 } catch (Exception e) {
1462 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToAppRolesRequest failed", e);
1466 @SuppressWarnings("unchecked")
1467 public void applyChangesToUserAppRolesForMyLoginsRequest(EPUser user, Long appId) {
1468 final Map<String, Long> params = new HashMap<>();
1469 final Map<String, Long> epDetailParams = new HashMap<>();
1470 List<EPUserAppRolesRequest> epRequestIdVal = new ArrayList<EPUserAppRolesRequest>();
1471 params.put("appId", appId);
1472 params.put("userId", user.getId());
1474 epRequestIdVal = (List<EPUserAppRolesRequest>) dataAccessService
1475 .executeNamedQuery("userAppRolesRequestList", params, null);
1476 if (epRequestIdVal.size() > 0) {
1477 EPUserAppRolesRequest epAppRolesRequestData = epRequestIdVal.get(0);
1478 epAppRolesRequestData.setUpdatedDate(new Date());
1479 epAppRolesRequestData.setRequestStatus("O");
1480 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1481 addiotonalUpdateParam.put("userId", user.getId());
1482 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1483 epDetailParams.put("reqId", epAppRolesRequestData.getId());
1484 List<EPUserAppRolesRequestDetail> epUserAppRolesDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1485 epUserAppRolesDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1486 epDetailParams, null);
1487 if (epUserAppRolesDetailList.size() > 0) {
1488 for (EPUserAppRolesRequestDetail epRequestUpdateList : epUserAppRolesDetailList) {
1489 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateList;
1490 epAppRoleDetailData.setReqType("O");
1491 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1492 HashMap<String, Long> updateDetailsParams = new HashMap<String, Long>();
1493 addiotonalUpdateParam.put("reqId", epAppRolesRequestData.getId());
1494 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParams);
1496 logger.debug(EELFLoggerDelegate.debugLogger, "User App roles request from User Page is overridden");
1500 } catch (Exception e) {
1501 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e);
1506 * Pushes specified user details to the specified remote app.
1509 * OrgUserId identifying user at remote app in REST endpoint path
1511 * User details to be pushed
1514 * @param applicationsRestClientService
1515 * @throws HTTPException
1517 protected void postUserToRemoteApp(String userId, EPUser user, EPApp app,
1518 ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
1520 getUser(userId, app, applicationsRestClientService);
1525 * It returns user details for single org user id
1529 * if user exists it returns list of user details otherwise empty value
1531 @SuppressWarnings("unchecked")
1532 private List<EPUser> checkIfUserExists(Map<String, String> userParams){
1533 return (List<EPUser>)dataAccessService.executeNamedQuery("epUserAppId", userParams, null);
1537 * It checks whether the new user is valid or not otherwise throws exception
1542 * Checks if user is valid and returns message otherwise throws exception
1545 private String validateNewUser(String orgUserId, EPApp app) throws Exception {
1546 EPUser epUser = searchService.searchUserByUserId(orgUserId);
1547 if (epUser == null) {
1548 throw new Exception("User does not exist");
1549 } else if (!epUser.getOrgUserId().equals(orgUserId)) {
1550 throw new Exception("User does not exist");
1551 } else if (app == null) {
1552 throw new Exception("Application does not exist");
1554 return "Saved Successfully";
1558 * Checks if the fields exists or not
1561 * contains user information
1565 * throws exception if the field is not valid
1567 private void validateExternalRequestFields(List<EPUser> userList, EPApp app) throws Exception{
1568 if (userList.size() == 0 || userList.isEmpty() ) {
1569 throw new Exception("User does not exist");
1570 } else if(app == null) {
1571 throw new Exception("Application does not exist");
1572 } else if(!app.getEnabled() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1573 throw new Exception(app.getMlAppName()+" application is unavailable");
1577 @SuppressWarnings("unchecked")
1578 public ExternalRequestFieldsValidator setExternalRequestUserAppRole(ExternalSystemUser newAppRolesForUser, String reqType) {
1579 boolean result = false;
1580 boolean externalSystemRequest = true;
1581 final Map<String, Long> params = new HashMap<>();
1582 final Map<String, String> userParams = new HashMap<>();
1583 List<EPUser> userInfo = null;
1585 List<EPUserAppRolesRequest> epRequestId = null;
1586 String orgUserId = "";
1587 String updateStatus = "";
1588 String reqMessage = "";
1590 if (newAppRolesForUser != null && newAppRolesForUser.getLoginId() != null) {
1591 orgUserId = newAppRolesForUser.getLoginId().trim();
1593 String appName = newAppRolesForUser.getApplicationName();
1594 String logMessage = ("DELETE").equals(reqType) ? "Deleting": "Assigning/Updating" ;
1595 if (orgUserId.length() > 0) {
1596 ObjectMapper mapper = new ObjectMapper();
1597 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1598 int epRequestIdSize = 0;
1600 app = appsService.getAppDetail(appName);
1601 userParams.put("orgUserIdValue", orgUserId);
1602 userInfo = checkIfUserExists(userParams);
1603 reqMessage = "Updated Successfully";
1604 if (!reqType.equals("DELETE") && (userInfo.size() == 0 || userInfo.isEmpty())) {
1605 reqMessage = validateNewUser(orgUserId, app);
1607 if (userInfo.size() != 0 || !userInfo.isEmpty()) {
1608 validateExternalRequestFields(userInfo, app);
1609 user = userInfo.get(0);
1610 params.put("appId", app.getId());
1611 params.put("userId", user.getId());
1612 epRequestId = (List<EPUserAppRolesRequest>) dataAccessService
1613 .executeNamedQuery("userAppRolesRequestList", params, null);
1614 epRequestIdSize = epRequestId.size();
1617 //If Non-Centralized app make sure you sync app roles before assigning to user
1618 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !app.getCentralAuth()) {
1619 logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Starting GET roles for app {}",app.getId());
1620 EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, app.getId(), "/roles");
1621 logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Finshed GET roles for app {} and payload {}",app.getId(), appRoles);
1622 if (appRoles.length > 0) {
1623 syncAppRoles(sessionFactory, app.getId(), appRoles);
1626 List<RoleInAppForUser> roleInAppForUserList = roleInAppForUserList(newAppRolesForUser.getRoles(),
1627 app.getId(), app.getMlAppName());
1628 List<EcompUserAppRoles> userRoleList = null;
1629 if(!userInfo.isEmpty()){
1630 final Map<String, Long> appParams = new HashMap<>();
1631 appParams.put("userId", user.getId());
1632 appParams.put("appId", app.getId());
1633 userRoleList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", appParams, null);
1635 // Check if list contains just account admin role
1636 boolean checkIfAdminRoleExists = false;
1637 if (reqType.equals("DELETE") && userRoleList!=null) {
1638 checkIfAdminRoleExists = userRoleList.stream()
1639 .anyMatch(userRole -> userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1641 checkIfAdminRoleExists = roleInAppForUserList.stream()
1642 .anyMatch(roleList -> roleList.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1644 // if Centralized app
1645 if (app.getCentralAuth()) {
1646 // We should add If user does not exist in remote application
1648 // If adding just account admin role dont make remote application user call or
1649 // if request has only single non admin role then make remote call
1650 if (!(app.getId().equals(PortalConstants.PORTAL_APP_ID) && reqType.equals("DELETE"))
1651 && ((checkIfAdminRoleExists && roleInAppForUserList.size() > 1)
1652 || (!checkIfAdminRoleExists && roleInAppForUserList.size() >= 1))) {
1653 // check if admin role exist then delete
1654 List<RoleInAppForUser> remoteUserRoles = roleInAppForUserList.stream()
1655 .collect(Collectors.toList());
1656 remoteUserRoles.removeIf(role -> {
1657 return (role.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1659 String orgUserIdNewOrExist = (userInfo.size() != 0 || !userInfo.isEmpty()) ? user.getOrgUserId() : orgUserId;
1660 pushRemoteUser(remoteUserRoles, orgUserIdNewOrExist , app, mapper, searchService,
1661 applicationsRestClientService,true);
1663 } catch (Exception e) {
1664 reqMessage = e.getMessage();
1665 logger.error(EELFLoggerDelegate.errorLogger, "setExternalRequestUserAppRole: Failed to added remote user", e);
1666 throw new Exception(reqMessage);
1668 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1669 applicationsRestClientService, app.getId(), orgUserId);
1670 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1671 userRolesInLocalApp);
1672 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1673 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
1675 if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1676 // Apply changes in external Access system
1677 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, externalSystemRequest,false,rolesGotDeletedByApprover,false);
1679 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
1680 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1681 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,false,rolesGotDeletedByApprover,false);
1683 // If local application is not centralized
1684 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1685 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1686 applicationsRestClientService, app.getId(), orgUserId);
1687 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1688 userRolesInLocalApp);
1689 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
1691 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,false,rolesGotDeletedByApprover,false);
1692 } else {// remote app
1693 // If adding just account admin role don't do remote application user call
1694 if (!((roleInAppForUserList.size() == 1 || reqType.equals("DELETE")) && checkIfAdminRoleExists)) {
1695 EPUser remoteAppUser = null;
1696 remoteAppUser = checkIfRemoteUserExits(orgUserId, app, applicationsRestClientService);
1697 if (remoteAppUser == null) {
1698 addRemoteUser(roleInAppForUserList, orgUserId, app, mapper, searchService,
1699 applicationsRestClientService);
1700 reqMessage = "Saved Successfully";
1703 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
1704 applicationsRestClientService, app.getId(), orgUserId,false);
1706 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1707 userRolesInRemoteApp);
1708 logger.info(EELFLoggerDelegate.debugLogger,
1709 "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
1710 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1711 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
1713 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1714 reqType,false,rolesGotDeletedByApprover,false);
1715 // If no roles remain, request app to set user inactive.
1717 * if (userRolesInRemoteApp.size() == 0) {
1718 * logger.debug(EELFLoggerDelegate.debugLogger,
1719 * "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive"
1720 * , app, orgUserId); //TODO Need to fix the logged in user is not set to
1721 * inactive remoteAppUser.setActive(false); postUserToRemoteApp(orgUserId, user,
1722 * app, applicationsRestClientService); }
1726 // Here we are adding only we have single account admin in roleInAppForUserList and this should not add in remote
1727 if(!(reqType.equals("DELETE")) && userInfo.isEmpty()){
1728 reqMessage = "Saved Successfully";
1730 Set<EcompRole> userRolesInRemoteApp = constructUsersEcompRoles(roleInAppForUserList);
1732 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1733 userRolesInRemoteApp);
1734 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}",
1735 logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1736 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
1738 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1739 reqType,false,rolesGotDeletedByApprover,false);
1742 reqMessage = "Failed to save the user app role(s)";
1744 if (epRequestIdSize > 0 && !userInfo.isEmpty()) {
1746 applyChangesToAppRolesRequest(app.getId(), user.getId(), updateStatus, epRequestId.get(0));
1749 } catch (Exception e) {
1750 String message = String.format("setExternalRequestUserAppRole: Failed to create user or update user roles for User %s, AppId %s",
1751 orgUserId, appName);
1752 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1754 reqMessage = e.getMessage();
1755 if(epRequestIdSize > 0 && userInfo!=null && !userInfo.isEmpty()){
1757 applyChangesToAppRolesRequest(app.getId(), user.getId(),
1758 updateStatus, epRequestId.get(0));
1763 return new ExternalRequestFieldsValidator(result, reqMessage);
1768 * @param roleInAppForUserList
1770 * @param applicationsRestClientService
1773 * @return Set<EcompRole>
1774 * @throws JsonProcessingException
1775 * @throws HTTPException
1777 private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
1778 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
1779 throws JsonProcessingException, HTTPException {
1780 Set<EcompRole> updatedUserRoles = constructUsersEcompRoles(roleInAppForUserList);
1781 return updatedUserRoles;
1785 * It constructs and returns list of user app roles when the external API role approval system calls
1788 * @param roleInAppForUserList
1790 * @return list of user app roles
1792 * throws exceptions if role id does not exits
1794 private List<RoleInAppForUser> roleInAppForUserList(List<ExternalSystemRoleApproval> roleInAppForUserList,
1795 Long appId, String appName) throws Exception {
1796 List<RoleInAppForUser> existingUserRoles = new ArrayList<RoleInAppForUser>();
1797 EPRole existingAppRole = null;
1798 for (ExternalSystemRoleApproval roleInAppForUser : roleInAppForUserList) {
1799 RoleInAppForUser ecompRole = new RoleInAppForUser();
1800 existingAppRole = epRoleService.getAppRole(roleInAppForUser.getRoleName(), appId);
1801 if (existingAppRole == null) {
1802 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1803 roleInAppForUserList);
1804 throw new Exception("'" +roleInAppForUser.getRoleName() + "'" +" role does not exist for " + appName + " application");
1806 if (!existingAppRole.getActive()) {
1807 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1808 roleInAppForUserList);
1809 throw new Exception(roleInAppForUser.getRoleName() + " role is unavailable for "+ appName + " application");
1812 List<EPRole> roleInfo = externalAccessRolesService.getPortalAppRoleInfo(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
1813 EPRole adminRole = new EPRole();
1814 if(roleInfo.size()>0)
1816 adminRole = roleInfo.get(0);
1817 logger.debug(EELFLoggerDelegate.debugLogger, "Admin RoleName form DB: " + adminRole.getName());
1819 ecompRole.roleId = (appId == 1 || roleInAppForUser.getRoleName().equals(adminRole.getName())) ? existingAppRole.getId() : existingAppRole.getAppRoleId();
1820 ecompRole.roleName = roleInAppForUser.getRoleName();
1821 ecompRole.isApplied = true;
1822 existingUserRoles.add(ecompRole);
1825 return existingUserRoles;
1834 * @param applicationsRestClientService
1836 * @throws HTTPException
1838 protected EPUser getUserFromApp(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1839 throws HTTPException {
1841 if (app.getId() == PortalConstants.PORTAL_APP_ID) {
1842 // Map<String,String> params = new HashMap<String,String>();
1843 // params.put("sbcid",userId);
1844 @SuppressWarnings("unchecked")
1845 List<EPUser> userList = (List<EPUser>) dataAccessService
1846 .executeQuery("from EPUser where orgUserId='" + userId + "'", null);
1847 if (userList != null && !userList.isEmpty())
1848 return userList.get(0);
1854 return getUser(userId, app, applicationsRestClientService);
1857 protected EPUser getUser(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1858 throws HTTPException {
1859 return applicationsRestClientService.get(EPUser.class, app.getId(), String.format("/user/%s", userId), true);
1863 protected boolean isAppUpgradeVersion(EPApp app){
1868 public ExternalSystemAccess getExternalRequestAccess(){
1869 ExternalSystemAccess res = null;
1871 res = new ExternalSystemAccess(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE,
1872 Boolean.parseBoolean(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE)));
1873 } catch (Exception e) {
1874 logger.error(EELFLoggerDelegate.errorLogger, "getExternalRequestAccess failed" + e.getMessage());
1882 * @see org.onap.portalapp.portal.service.UserRolesService#
1883 * getAppRolesForUser(java.lang.Long, java.lang.String)
1885 @SuppressWarnings("unchecked")
1886 public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId, Boolean extRequestValue,EPUser user) {
1887 List<RoleInAppForUser> rolesInAppForUser = null;
1888 EPApp app = appsService.getApp(appId);
1889 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - app = {}", app);
1891 // for onap portal app, no need to make a remote call
1892 List<Role> roleList = new ArrayList<>();
1893 if (appId == PortalConstants.PORTAL_APP_ID) {
1894 if(app.getCentralAuth()){
1895 List<CentralV2Role> cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey());
1896 for(CentralV2Role cenRole : cenRoleList){
1897 Role role = new Role();
1898 role.setActive(cenRole.getActive());
1899 role.setId(cenRole.getId());
1900 role.setName(cenRole.getName());
1901 role.setPriority(cenRole.getPriority());
1905 roleList = roleService.getAvailableRoles(userId);
1907 List<Role> activeRoleList = new ArrayList<Role>();
1908 for(Role role: roleList) {
1909 if(role.getActive()) {
1910 if(role.getId() != 1){ // prevent portal admin from being added
1911 activeRoleList.add(role);
1912 } else if(extRequestValue){
1913 activeRoleList.add(role);
1918 EPUser localUser = getUserFromApp(userId, app, applicationsRestClientService);
1919 // If localUser does not exists return roles
1920 Set<EPRole> roleSet = null;
1921 EPRole[] roleSetList = null;
1922 if(localUser != null){
1923 roleSet = localUser.getAppEPRoles(app);
1924 roleSetList = roleSet.toArray(new EPRole[0]);
1926 rolesInAppForUser = constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue);
1927 return rolesInAppForUser;
1930 EcompRole[] appRoles = null;
1931 boolean checkIfUserisApplicationAccAdmin = false;
1932 List<EcompRole> roles = new ArrayList<>();
1933 if (app.getCentralAuth()) {
1934 final Map<String, Long> appParams = new HashMap<>();
1935 appParams.put("appId", app.getId());
1936 List<EPRole> applicationRoles = dataAccessService.executeNamedQuery("getActiveRolesOfApplication",
1939 EPApp application = appService.getApp(appId);
1940 checkIfUserisApplicationAccAdmin = adminRolesService.isAccountAdminOfApplication(user,
1943 List<EPRole> rolesetwithfunctioncds = new ArrayList<EPRole>();
1944 for (EPRole role : applicationRoles) {
1945 Map<String, Long> params = new HashMap<>();
1946 params.put("roleId", role.getId());
1947 params.put(APP_ID, app.getId());
1948 List<CentralV2RoleFunction> cenRoleFuncList = dataAccessService
1949 .executeNamedQuery("getAppRoleFunctionList", params, null);
1951 // SortedSet<CentralV2RoleFunction> roleFunctionSet =
1953 SortedSet<RoleFunction> roleFunctionSet = new TreeSet<>();
1954 for (CentralV2RoleFunction roleFunc : cenRoleFuncList) {
1956 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1957 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
1958 String type = externalAccessRolesService.getFunctionCodeType(roleFunc.getCode());
1959 String action = externalAccessRolesService.getFunctionCodeAction(roleFunc.getCode());
1960 String name = roleFunc.getName();
1962 RoleFunction function = new RoleFunction();
1963 function.setAction(action);
1964 function.setType(type);
1965 function.setCode(functionCode);
1966 function.setName(name);
1967 roleFunctionSet.add(function);
1968 role.setRoleFunctions(roleFunctionSet);
1971 rolesetwithfunctioncds.add(role);
1976 for (EPRole role1 : rolesetwithfunctioncds) {
1977 EcompRole ecompRole = new EcompRole();
1978 ecompRole.setId(role1.getId());
1979 ecompRole.setName(role1.getName());
1980 ecompRole.setRoleFunctions(role1.getRoleFunctions());
1981 roles.add(ecompRole);
1984 if (checkIfUserisApplicationAccAdmin) {
1985 appRoles = roles.toArray(new EcompRole[roles.size()]);
1986 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() If Logged in user checkIfUserisApplicationAccAdmin- appRoles = {}", appRoles);
1987 } else if (adminRolesService.isRoleAdmin(user) && !checkIfUserisApplicationAccAdmin) {
1988 List<EcompRole> roleAdminAppRoles = new ArrayList<>();
1989 List<String> roleAdminAppRolesNames = new ArrayList<>();
1990 final Map<String, Long> userParams = new HashMap<>();
1991 userParams.put("userId", user.getId());
1992 List<String> getUserApproverRoles = dataAccessService.executeNamedQuery("getUserApproverRoles", userParams, null);
1994 List<EcompRole> userapproverRolesList = new ArrayList<>();
1995 for (String str : getUserApproverRoles) {
1996 EcompRole epRole = roles.stream().filter(x -> str.equals(x.getName())).findAny().orElse(null);
1998 userapproverRolesList.add(epRole);
2000 // roles.removeAll(userapproverRolesList);
2001 for (EcompRole role : userapproverRolesList) {
2003 List<RoleFunction> roleFunList = new ArrayList<>();
2004 roleFunList.addAll(role.getRoleFunctions());
2005 boolean checkIfFunctionsExits = roleFunList.stream()
2006 .anyMatch(roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
2007 if (checkIfFunctionsExits) {
2008 roleAdminAppRoles.add(role);
2009 List<RoleFunction> filteredList = roleFunList.stream()
2010 .filter(x -> "Approver".equalsIgnoreCase(x.getType())).collect(Collectors.toList());
2011 roleAdminAppRolesNames.addAll(filteredList.stream().map(RoleFunction::getCode)
2012 .collect(Collectors.toList()));
2013 // roleAdminAppRolesNames = filteredList.stream().map(RoleFunction::getCode)
2014 // .collect(Collectors.toList());
2017 for (String name : roleAdminAppRolesNames) {
2018 EcompRole ecompRole = roles.stream().filter(x -> name.equals(x.getName())).findAny()
2020 if (ecompRole != null)
2021 roleAdminAppRoles.add(ecompRole);
2024 appRoles = roleAdminAppRoles.toArray(new EcompRole[roleAdminAppRoles.size()]);
2028 appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
2030 // Test this error case, for generating an internal ONAP Portal
2032 // EcompRole[] appRoles = null;
2033 // If there is an exception in the rest client api, then null will
2035 if (appRoles != null) {
2036 if(!app.getCentralAuth()) {
2037 syncAppRoles(sessionFactory, appId, appRoles);
2039 EcompRole[] userAppRoles = null;
2043 if(app.getCentralAuth()){
2044 final Map<String, String> params = new HashMap<>();
2045 final Map<String, Long> userParams = new HashMap<>();
2046 params.put("orgUserIdValue", userId);
2047 List<EPUser> actualUser = dataAccessService.executeNamedQuery("epUserAppId", params, null);
2048 userParams.put("appId", app.getId());
2049 userParams.put("userId", actualUser.get(0).getId());
2050 List<EPUserAppCurrentRoles> userAppsRolesList = dataAccessService.executeNamedQuery("getUserAppCurrentRoles", userParams, null);
2052 List<EcompRole> setUserRoles = new ArrayList<>();
2053 for(EPUserAppCurrentRoles role : userAppsRolesList){
2054 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - userAppsRolesList get userRolename = {}", role.getRoleName());
2055 EcompRole ecompRole = new EcompRole();
2056 ecompRole.setId(role.getRoleId());
2057 ecompRole.setName(role.getRoleName());
2058 setUserRoles.add(ecompRole);
2061 boolean checkIfUserisAccAdmin = setUserRoles.stream()
2062 .anyMatch(ecompRole -> ecompRole.getId() == 999L);
2064 if (!checkIfUserisAccAdmin) {
2065 List<EcompRole> userApplicationRolesList = setUserRoles;
2066 List<EcompRole> appRolesList = Arrays.asList(appRoles);
2067 Set<EcompRole> finalUserAppRolesList = new HashSet<>();
2069 List<String> roleNames = new ArrayList<>();
2070 for (EcompRole role : userApplicationRolesList) {
2071 EcompRole epRole = appRolesList.stream()
2072 .filter(x -> role.getName().equals(x.getName())).findAny().orElse(null);
2073 List<RoleFunction> roleFunList = new ArrayList<>();
2075 if (epRole != null) {
2076 if (epRole.getRoleFunctions().size() > 0)
2077 roleFunList.addAll(epRole.getRoleFunctions());
2078 boolean checkIfFunctionsExits = roleFunList.stream().anyMatch(
2079 roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
2080 if (checkIfFunctionsExits) {
2081 finalUserAppRolesList.add(role);
2082 List<RoleFunction> filteredList = roleFunList.stream()
2083 .filter(x -> "Approver".equalsIgnoreCase(x.getType()))
2084 .collect(Collectors.toList());
2085 roleNames = filteredList.stream().map(RoleFunction::getCode)
2086 .collect(Collectors.toList());
2088 roleNames.add(epRole.getName());
2091 for (String name : roleNames) {
2092 EcompRole ecompRole = appRolesList.stream()
2093 .filter(x -> name.equals(x.getName())).findAny().orElse(null);
2094 if (ecompRole != null)
2095 finalUserAppRolesList.add(ecompRole);
2100 for (String name : roleNames) {
2102 boolean checkIfFunctionsExits = userAppsRolesList.stream().anyMatch(
2103 role -> role.getRoleName().equalsIgnoreCase(name));
2104 if(checkIfFunctionsExits)
2106 EcompRole epRole = appRolesList.stream().filter(x -> name.equals(x.getName()))
2107 .findAny().orElse(null);
2109 setUserRoles.add(epRole);
2113 userAppRoles = setUserRoles.toArray(new EcompRole[setUserRoles.size()]);
2116 userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
2117 String.format("/user/%s/roles", userId));
2119 } catch (HTTPException e) {
2120 // Some apps are returning 400 if user is not found.
2121 if (e.getResponseCode() == 400) {
2122 logger.debug(EELFLoggerDelegate.debugLogger,
2123 "getAppRolesForUser caught exception with response code 400; continuing", e);
2125 // Other response code, let it come thru.
2129 if (userAppRoles == null) {
2130 if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
2131 EcompPortalUtils.setExternalAppResponseCode(200);
2132 String message = String.format(
2133 "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
2134 + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
2135 + "Overriding to 200 until framework SDK returns a useful response.",
2136 Long.toString(appId), userId);
2137 logger.warn(EELFLoggerDelegate.applicationLogger, message);
2141 HashMap<Long, EcompRole> appRolesActiveMap =hashMapFromEcompRoles(appRoles);
2142 ArrayList<EcompRole> activeRoles = new ArrayList<EcompRole>();
2143 if(userAppRoles != null){
2144 for (int i = 0; i < userAppRoles.length; i++) {
2145 if (appRolesActiveMap.containsKey(userAppRoles[i].getId())) {
2146 EcompRole role = new EcompRole();
2147 role.setId(userAppRoles[i].getId());
2148 role.setName(userAppRoles[i].getName());
2149 activeRoles.add(role);
2153 EcompRole[] userAppRolesActive = activeRoles.toArray(new EcompRole[activeRoles.size()]);
2156 boolean checkIfUserisRoleAdmin = adminRolesService.isRoleAdmin(user) && !checkIfUserisApplicationAccAdmin;
2158 // If the remote application isn't down we MUST sync user
2159 // roles here in case we have this user here!
2160 syncUserRoles(sessionFactory, userId, appId, userAppRolesActive, extRequestValue, null,checkIfUserisRoleAdmin,appRoles);
2161 } catch (Exception e) {
2162 // TODO: we may need to check if user exists, maybe remote
2164 String message = String.format(
2165 "getAppRolesForUser: user %s does not exist in remote application %s", userId,
2166 Long.toString(appId));
2167 logger.error(EELFLoggerDelegate.errorLogger, message, e);
2168 userAppRoles = new EcompRole[0];
2170 rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
2172 } catch (Exception e) {
2173 String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
2174 Long.toString(appId));
2175 logger.error(EELFLoggerDelegate.errorLogger, message, e);
2177 return rolesInAppForUser;
2180 private boolean postUserRolesToMylogins(AppWithRolesForUser userAppRolesData,
2181 ApplicationsRestClientService applicationsRestClientService, Long appId, Long userId)
2182 throws JsonProcessingException, HTTPException {
2183 boolean result = false;
2184 ObjectMapper mapper = new ObjectMapper();
2185 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
2186 String userRolesAsString = mapper.writeValueAsString(userAppRolesData);
2187 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, as the endpoint is not defined yet from the Mylogins");
2188 applicationsRestClientService.post(AppWithRolesForUser.class, appId, userRolesAsString, String.format("/user/%s/myLoginroles", userId));
2192 @SuppressWarnings("unchecked")
2193 public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser userAppRolesData, EPUser user) {
2194 FieldsValidator fieldsValidator = new FieldsValidator();
2195 final Map<String, Long> params = new HashMap<>();
2196 List<EPUserAppRoles> appRole= null;
2198 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, still the endpoint is yet to be defined");
2199 boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService,
2200 userAppRolesData.getAppId(), user.getId());
2201 logger.debug(EELFLoggerDelegate.debugLogger,"putUserAppRolesRequest: result {}", result);
2203 params.put("appId", userAppRolesData.getAppId());
2204 EPUserAppRolesRequest epAppRolesRequestData = new EPUserAppRolesRequest();
2205 epAppRolesRequestData.setCreatedDate(new Date());
2206 epAppRolesRequestData.setUpdatedDate(new Date());
2207 epAppRolesRequestData.setUserId(user.getId());
2208 epAppRolesRequestData.setAppId(userAppRolesData.getAppId());
2209 epAppRolesRequestData.setRequestStatus("P");
2210 List<RoleInAppForUser> appRoleIdList = userAppRolesData.getAppRoles();
2211 Set<EPUserAppRolesRequestDetail> appRoleDetails = new LinkedHashSet<EPUserAppRolesRequestDetail>();
2212 dataAccessService.saveDomainObject(epAppRolesRequestData, null);
2213 for (RoleInAppForUser userAppRoles : appRoleIdList) {
2214 Boolean isAppliedVal = userAppRoles.isApplied;
2215 params.put("appRoleId", userAppRoles.roleId);
2217 appRole = (List<EPUserAppRoles>) dataAccessService.executeNamedQuery("appRoles", params, null);
2218 if (!appRole.isEmpty()) {
2219 EPUserAppRolesRequestDetail epAppRoleDetail = new EPUserAppRolesRequestDetail();
2220 epAppRoleDetail.setReqRoleId(appRole.get(0).getRoleId());
2221 epAppRoleDetail.setReqType("P");
2222 epAppRoleDetail.setEpRequestIdData(epAppRolesRequestData);
2223 dataAccessService.saveDomainObject(epAppRoleDetail, null);
2227 epAppRolesRequestData.setEpRequestIdDetail(appRoleDetails);
2228 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
2230 } catch (Exception e) {
2231 logger.error(EELFLoggerDelegate.errorLogger, "putUserAppRolesRequest failed", e);
2232 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
2234 return fieldsValidator;
2237 public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(EPUser userid, String appName) {
2238 Map<String, String> params = new HashMap<>();
2239 params.put("userid", userid.getId().toString());
2240 //params.put("appid", appid);
2241 params.put("appName", appName);
2243 @SuppressWarnings("unchecked")
2244 List<EPUserAppCatalogRoles> userAppRoles = (List<EPUserAppCatalogRoles>) dataAccessService
2245 .executeNamedQuery("userAppCatalogRoles", params, null);
2246 return userAppRoles;
2249 public String updateRemoteUserProfile(String orgUserId, Long appId) {
2250 ObjectMapper mapper = new ObjectMapper();
2251 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
2252 EPUser client = searchService.searchUserByUserId(orgUserId);
2253 EPUser newUser = new EPUser();
2254 newUser.setActive(client.getActive());
2255 newUser.setFirstName(client.getFirstName());
2256 newUser.setLastName(client.getLastName());
2257 newUser.setLoginId(client.getLoginId());
2258 newUser.setLoginPwd(client.getLoginPwd());
2259 newUser.setMiddleInitial(client.getMiddleInitial());
2260 newUser.setEmail(client.getEmail());
2261 newUser.setOrgUserId(client.getLoginId());
2263 String userAsString = mapper.writeValueAsString(newUser);
2264 List<EPApp> appList = appsService.getUserRemoteApps(client.getId().toString());
2265 // applicationsRestClientService.post(EPUser.class, appId,
2266 // userAsString, String.format("/user", orgUserId));
2267 for (EPApp eachApp : appList) {
2269 applicationsRestClientService.post(EPUser.class, eachApp.getId(), userAsString,
2270 String.format("/user/%s", orgUserId));
2271 } catch (Exception e) {
2272 logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId()
2273 + " in remote app. appId = " + eachApp.getId());
2276 } catch (Exception e) {
2277 logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
2288 * @see org.onap.portalapp.portal.service.UserRolesService#
2289 * getCachedAppRolesForUser(java.lang.Long, java.lang.Long)
2291 @SuppressWarnings("deprecation")
2292 public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId) {
2293 // Find the records for this user-app combo, if any
2294 String filter = " where user_id = " + Long.toString(userId) + " and app_id = " + Long.toString(appId);
2295 @SuppressWarnings("unchecked")
2296 List<EPUserApp> roleList = dataAccessService.getList(EPUserApp.class, filter, null, null);
2297 logger.debug(EELFLoggerDelegate.debugLogger, "getCachedAppRolesForUser: list size is {}", roleList.size());
2302 * It retrieves and returns list of user app roles for local and remote applications based app id
2305 * @return list of user app roles
2306 * @throws HTTPException
2308 public List<UserApplicationRoles> getUsersFromAppEndpoint(Long appId) throws HTTPException {
2309 ArrayList<UserApplicationRoles> userApplicationRoles = new ArrayList<UserApplicationRoles>();
2311 EPApp app = appsService.getApp(appId);
2312 //If local or centralized application
2313 if (appId == PortalConstants.PORTAL_APP_ID || app.getCentralAuth()) {
2314 Map<String, Object> params = new HashMap<>();
2315 params.put("id", app.getId());
2316 params.put("active", true);
2317 @SuppressWarnings("unchecked")
2318 //List<EPUser> userList = (List<EPUser>) dataAccessService.executeNamedQuery("getActiveUsers", null, null);
2319 //List<Object[]> userList = (List<Object[]>) dataAccessService.executeNamedQuery("getActiveUsersForApp", params, null);
2320 List<EPUser> userList = (List<EPUser>) dataAccessService.executeNamedQuery("getActiveUsersForApp", params, null);
2321 for (EPUser user : userList) {
2322 UserApplicationRoles userWithAppRoles = convertToUserApplicationRoles(user, app.getId());
2323 if (userWithAppRoles.getRoles() != null && userWithAppRoles.getRoles().size() > 0)
2324 userApplicationRoles.add(userWithAppRoles);
2330 RemoteUserWithRoles[] remoteUsers = null;
2331 String remoteUsersString = applicationsRestClientService.getIncomingJsonString(appId, "/users");
2333 remoteUsers = doGetUsers(isAppUpgradeVersion(app), remoteUsersString);
2335 userApplicationRoles = new ArrayList<UserApplicationRoles>();
2336 for (RemoteUserWithRoles remoteUser : remoteUsers) {
2337 UserApplicationRoles userWithRemoteAppRoles = convertToUserApplicationRoles(appId, remoteUser);
2338 if (userWithRemoteAppRoles.getRoles() != null && userWithRemoteAppRoles.getRoles().size() > 0) {
2339 userApplicationRoles.add(userWithRemoteAppRoles);
2341 logger.debug(EELFLoggerDelegate.debugLogger,
2342 "User " + userWithRemoteAppRoles.getOrgUserId() + " doesn't have any roles assigned to any app.");
2347 return userApplicationRoles;
2356 private UserApplicationRoles convertToUserApplicationRoles(EPUser user, Long appId) {
2357 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
2358 userWithRemoteAppRoles.setAppId(appId);
2359 userWithRemoteAppRoles.setOrgUserId(user.getOrgUserId());
2360 userWithRemoteAppRoles.setFirstName(user.getFirstName());
2361 userWithRemoteAppRoles.setLastName(user.getLastName());
2362 List<RemoteRole> roleList = new ArrayList<RemoteRole>();
2363 for(EPUserApp userApp :user.getEPUserApps()) {
2364 RemoteRole remoteRole = new RemoteRole();
2365 remoteRole.setName(userApp.getRole().getName());
2366 remoteRole.setId(userApp.getRole().getId());
2367 roleList.add(remoteRole);
2369 userWithRemoteAppRoles.setRoles(roleList);
2370 return userWithRemoteAppRoles;
2377 * @param appgetUsersFromAppEndpoint
2380 private UserApplicationRoles convertToUserApplicationRoles(Long appId, EPUser user, EPApp app) {
2381 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
2382 userWithRemoteAppRoles.setAppId(appId);
2383 userWithRemoteAppRoles.setOrgUserId(user.getOrgUserId());
2384 userWithRemoteAppRoles.setFirstName(user.getFirstName());
2385 userWithRemoteAppRoles.setLastName(user.getLastName());
2386 userWithRemoteAppRoles.setRoles(convertToRemoteRoleList(user, app));
2387 return userWithRemoteAppRoles;
2396 @SuppressWarnings("unchecked")
2397 private List<RemoteRole> convertToRemoteRoleList(EPUser user, EPApp app) {
2398 List<RemoteRole> roleList = new ArrayList<RemoteRole>();
2399 SortedSet<EPRole> roleSet = user.getAppEPRoles(app);
2400 for (EPRole role : roleSet) {
2401 logger.debug(EELFLoggerDelegate.debugLogger, "In convertToRemoteRoleList() - for user {}, found Name {}", user.getOrgUserId(), role.getName());
2402 RemoteRole rRole = new RemoteRole();
2403 rRole.setId(role.getId());
2404 rRole.setName(role.getName());
2405 roleList.add(rRole);
2408 //Get the active roles of user for that application using query
2409 List<EPRole> userEpRoleList = new ArrayList<>();
2410 final Map<String, Long> params = new HashMap<>();
2411 params.put("appId", app.getId());
2412 params.put("userId", user.getId());
2413 userEpRoleList = dataAccessService.executeNamedQuery("getUserRoleOnUserIdAndAppId", params, null);
2415 for (EPRole remoteUserRoleList : userEpRoleList) {
2417 RemoteRole remoteRoleListId = roleList.stream().filter(x -> remoteUserRoleList.getId().equals(x.getId()))
2418 .findAny().orElse(null);
2419 if (remoteRoleListId == null) {
2420 logger.debug(EELFLoggerDelegate.debugLogger,
2421 "Adding the role to the rolelist () - for user {}, found Name {}", user.getOrgUserId(),
2423 remoteUserRoleList.getName());
2424 RemoteRole role = new RemoteRole();
2425 role.setId(remoteUserRoleList.getId());
2426 role.setName(remoteUserRoleList.getName());
2433 logger.debug(EELFLoggerDelegate.debugLogger, "rolelist size of the USER() - for user {}, found RoleListSize {}", user.getOrgUserId(), roleList.size());
2441 public RemoteUserWithRoles[] doGetUsers(boolean postOpenSource, String remoteUsersString) {
2443 ObjectMapper mapper = new ObjectMapper();
2445 return mapper.readValue(remoteUsersString, RemoteUserWithRoles[].class);
2446 } catch (IOException e) {
2447 logger.error(EELFLoggerDelegate.errorLogger,
2448 "doGetUsers : Failed : Unexpected property in incoming JSON",
2450 logger.error(EELFLoggerDelegate.errorLogger,
2451 "doGetUsers : Incoming JSON that caused it --> " + remoteUsersString);
2454 return new RemoteUserWithRoles[0];
2457 @SuppressWarnings("unchecked")
2458 public List<EPUserApp> getEPUserAppList(Long appId, Long userId, Long roleId) {
2459 List<EPUserApp> userRoleList = new ArrayList<EPUserApp>();
2460 final Map<String, Long> params = new HashMap<>();
2461 params.put("appId", appId);
2462 params.put("userId", userId);
2463 params.put("roleId", roleId);
2464 userRoleList = dataAccessService.executeNamedQuery("getUserRoleOnUserIdAndRoleIdAndAppId", params, null);
2465 return userRoleList;
2469 /*public static void main(String[] args) {
2470 List<EcompRole> str1 = new ArrayList<String>();
2476 List<String> str2 = new ArrayList<String>();
2480 List<EcompRole> userApplicationRolesList = setUserRoles;
2481 List<EcompRole> appRolesList = Arrays.asList(appRoles);