2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
8 * Unless otherwise specified, all software contained herein is licensed
9 * under the Apache License, Version 2.0 (the "License");
10 * you may not use this software except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * Unless otherwise specified, all documentation contained herein is licensed
22 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23 * you may not use this documentation except in compliance with the License.
24 * You may obtain a copy of the License at
26 * https://creativecommons.org/licenses/by/4.0/
28 * Unless required by applicable law or agreed to in writing, documentation
29 * distributed under the License is distributed on an "AS IS" BASIS,
30 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31 * See the License for the specific language governing permissions and
32 * limitations under the License.
34 * ============LICENSE_END============================================
39 package org.onap.portalapp.portal.service;
41 import java.io.IOException;
42 import java.util.ArrayList;
43 import java.util.Arrays;
44 import java.util.Collection;
45 import java.util.Date;
46 import java.util.HashMap;
47 import java.util.HashSet;
48 import java.util.LinkedHashSet;
49 import java.util.List;
52 import java.util.SortedSet;
53 import java.util.TreeSet;
54 import java.util.stream.Collectors;
56 import javax.servlet.http.HttpServletResponse;
58 import org.apache.commons.lang.StringUtils;
59 import org.apache.cxf.transport.http.HTTPException;
60 import org.hibernate.SQLQuery;
61 import org.hibernate.Session;
62 import org.hibernate.SessionFactory;
63 import org.hibernate.Transaction;
64 import org.json.JSONArray;
65 import org.json.JSONObject;
66 import org.onap.portalapp.externalsystemapproval.model.ExternalSystemRoleApproval;
67 import org.onap.portalapp.externalsystemapproval.model.ExternalSystemUser;
68 import org.onap.portalapp.portal.domain.CentralV2RoleFunction;
69 import org.onap.portalapp.portal.domain.EPApp;
70 import org.onap.portalapp.portal.domain.EPRole;
71 import org.onap.portalapp.portal.domain.EPUser;
72 import org.onap.portalapp.portal.domain.EPUserApp;
73 import org.onap.portalapp.portal.domain.EPUserAppCatalogRoles;
74 import org.onap.portalapp.portal.domain.EPUserAppRoles;
75 import org.onap.portalapp.portal.domain.EPUserAppRolesRequest;
76 import org.onap.portalapp.portal.domain.EPUserAppRolesRequestDetail;
77 import org.onap.portalapp.portal.domain.ExternalSystemAccess;
78 import org.onap.portalapp.portal.exceptions.SyncUserRolesException;
79 import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
80 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
81 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
82 import org.onap.portalapp.portal.transport.AppWithRolesForUser;
83 import org.onap.portalapp.portal.transport.CentralV2Role;
84 import org.onap.portalapp.portal.transport.EPUserAppCurrentRoles;
85 import org.onap.portalapp.portal.transport.EcompUserAppRoles;
86 import org.onap.portalapp.portal.transport.ExternalAccessUser;
87 import org.onap.portalapp.portal.transport.ExternalAccessUserRoleDetail;
88 import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator;
89 import org.onap.portalapp.portal.transport.ExternalRoleDescription;
90 import org.onap.portalapp.portal.transport.FieldsValidator;
91 import org.onap.portalapp.portal.transport.FunctionalMenuItem;
92 import org.onap.portalapp.portal.transport.FunctionalMenuRole;
93 import org.onap.portalapp.portal.transport.RemoteRole;
94 import org.onap.portalapp.portal.transport.RemoteRoleV1;
95 import org.onap.portalapp.portal.transport.RemoteUserWithRoles;
96 import org.onap.portalapp.portal.transport.RoleInAppForUser;
97 import org.onap.portalapp.portal.transport.RolesInAppForUser;
98 import org.onap.portalapp.portal.transport.UserApplicationRoles;
99 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
100 import org.onap.portalapp.portal.utils.EcompPortalUtils;
101 import org.onap.portalapp.portal.utils.PortalConstants;
102 import org.onap.portalapp.util.EPUserUtils;
103 import org.onap.portalapp.util.SystemType;
104 import org.onap.portalsdk.core.domain.Role;
105 import org.onap.portalsdk.core.domain.RoleFunction;
106 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
107 import org.onap.portalsdk.core.restful.domain.EcompRole;
108 import org.onap.portalsdk.core.service.DataAccessService;
109 import org.onap.portalsdk.core.service.RoleService;
110 import org.onap.portalsdk.core.util.SystemProperties;
111 import org.springframework.beans.factory.annotation.Autowired;
112 import org.springframework.http.HttpEntity;
113 import org.springframework.http.HttpHeaders;
114 import org.springframework.http.HttpMethod;
115 import org.springframework.http.HttpStatus;
116 import org.springframework.http.ResponseEntity;
117 import org.springframework.web.client.HttpClientErrorException;
118 import org.springframework.web.client.RestTemplate;
120 import com.fasterxml.jackson.core.JsonProcessingException;
121 import com.fasterxml.jackson.databind.DeserializationFeature;
122 import com.fasterxml.jackson.databind.ObjectMapper;
125 public class UserRolesCommonServiceImpl {
127 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesCommonServiceImpl.class);
129 private static final Object syncRests = new Object();
131 private static final String APP_ID = "appId";
134 private DataAccessService dataAccessService;
136 private SessionFactory sessionFactory;
138 private SearchService searchService;
140 private EPAppService appsService;
142 private ApplicationsRestClientService applicationsRestClientService;
144 private EPRoleService epRoleService;
146 private RoleService roleService;
148 private AdminRolesService adminRolesService;
150 private EPAppService appService;
152 private ExternalAccessRolesService externalAccessRolesService;
155 private AppsCacheService appsCacheService;
157 RestTemplate template = new RestTemplate();
162 * @return HashMap<Long, EcompRole>
164 private static HashMap<Long, EcompRole> hashMapFromEcompRoles(EcompRole[] ecompRoles) {
165 HashMap<Long, EcompRole> result = new HashMap<Long, EcompRole>();
166 if (ecompRoles != null) {
167 for (int i = 0; i < ecompRoles.length; i++) {
168 if (ecompRoles[i].getId() != null) {
169 result.put(ecompRoles[i].getId(), ecompRoles[i]);
180 protected void createLocalUserIfNecessary(String userId,boolean isSystemUser) {
181 if (StringUtils.isEmpty(userId)) {
182 logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty userId!");
185 Session localSession = null;
186 Transaction transaction = null;
188 localSession = sessionFactory.openSession();
189 transaction = localSession.beginTransaction();
190 @SuppressWarnings("unchecked")
191 List<EPUser> userList = localSession
192 .createQuery("from :name where orgUserId=:userId")
193 .setParameter("name",EPUser.class.getName())
194 .setParameter("userId",userId)
196 if (userList.size() == 0) {
197 EPUser client = null;
199 client = searchService.searchUserByUserId(userId);
201 client = new EPUser();
202 client.setOrgUserId(userId);
203 client.setSystemUser(true);
204 client.setFirstName(userId.substring(0,userId.indexOf("@")));
206 if (client == null) {
207 String msg = "createLocalUserIfNecessary: cannot create user " + userId
208 + ", because not found in phonebook";
209 logger.error(EELFLoggerDelegate.errorLogger, msg);
211 client.setLoginId(userId);
212 client.setActive(true);
213 localSession.save(client);
216 transaction.commit();
217 } catch (Exception e) {
218 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
219 EcompPortalUtils.rollbackTransaction(transaction, "searchOrCreateUser rollback, exception = " + e);
221 EcompPortalUtils.closeLocalSession(localSession, "searchOrCreateUser");
226 * This method return nothing and remove roles before adding any roles for an app
229 * @param localSession
230 * @param userAppRoles
231 * @param newUserAppRolesMap
233 private static void syncUserRolesExtension(EPUserApp userRole, Long appId, Session localSession, EcompRole[] userAppRoles, HashMap<Long, EcompRole> newUserAppRolesMap) {
235 Long userAppRoleId = 0L;
236 if (appId == PortalConstants.PORTAL_APP_ID) { // local app
237 userAppRoleId = userRole.getRoleId();
238 } else { // remote app
239 userAppRoleId = userRole.getAppRoleId();
242 if (!newUserAppRolesMap.containsKey(userAppRoleId)) {
243 localSession.delete(userRole);
245 newUserAppRolesMap.remove(userAppRoleId);
250 * Checks whether the role is inactive
254 * if role is inactive, throws exception
256 private void checkIfRoleInactive(EPRole epRole) throws Exception{
257 if(!epRole.getActive()){
258 throw new Exception(epRole.getName()+ " role is unavailable");
264 * @param sessionFactory
267 * @param userAppRoles
268 * @param extRequestValue
269 * set to false if request is from users page otherwise true
272 protected void syncUserRoles(SessionFactory sessionFactory, String userId, Long appId,
273 EcompRole[] userAppRoles, Boolean extRequestValue, String reqType) throws Exception {
274 Session localSession = null;
275 Transaction transaction = null;
276 String roleActive = null;
277 final Map<String, String> userAppParams = new HashMap<>();
278 final Map<String, String> appParams = new HashMap<>();
279 HashMap<Long, EcompRole> newUserAppRolesMap = hashMapFromEcompRoles(userAppRoles);
282 localSession = sessionFactory.openSession();
283 transaction = localSession.beginTransaction();
284 @SuppressWarnings("unchecked")
285 List<EPUser> userList = localSession
286 .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + userId + "'").list();
287 if (userList.size() > 0) {
288 EPUser client = userList.get(0);
289 roleActive = ("DELETE".equals(reqType)) ? "" : " and role.active = 'Y'";
290 @SuppressWarnings("unchecked")
291 List<EPUserApp> userRoles = localSession.createQuery("from " + EPUserApp.class.getName()
292 + " where app.id=" + appId + roleActive + " and userId=" + client.getId()).list();
294 if ("DELETE".equals(reqType)) {
295 for (EPUserApp userAppRoleList : userRoles) {
296 userAppParams.put("roleName", String.valueOf(userAppRoleList.getRole().getName()));
297 userAppParams.put("appId", String.valueOf(appId));
298 appParams.put("appRoleName", userAppRoleList.getRole().getName());
299 @SuppressWarnings("unchecked")
300 List<EPRole> rolesList = (!userAppRoleList.getRole().getName().equals(PortalConstants.ADMIN_ROLE)) ? (List<EPRole>) dataAccessService.executeNamedQuery("getAppRoles", userAppParams, null) : (List<EPRole>) dataAccessService.executeNamedQuery("getPortalAppRoles", appParams, null);
301 if(rolesList.size() > 0 || !rolesList.isEmpty()){
302 checkIfRoleInactive(rolesList.get(0));
307 for (EPUserApp userRole : userRoles) {
308 if (!userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && userRole.getRoleId() != PortalConstants.SYS_ADMIN_ROLE_ID && !extRequestValue){
309 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
311 else if (extRequestValue && ("PUT".equals(reqType) || "POST".equals(reqType) || "DELETE".equals(reqType))){
312 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
314 else if (extRequestValue && !userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)){
315 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
318 Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values();
319 if (newRolesToAdd.size() > 0) {
320 EPApp app = (EPApp) localSession.get(EPApp.class, appId);
322 HashMap<Long, EPRole> rolesMap = new HashMap<Long, EPRole>();
323 if (appId.equals(PortalConstants.PORTAL_APP_ID)) { // local app
324 String appIdValue = "";
325 if(!extRequestValue){
326 appIdValue = "and id != " + PortalConstants.SYS_ADMIN_ROLE_ID;
328 @SuppressWarnings("unchecked")
329 List<EPRole> roles = localSession
330 .createQuery("from " + EPRole.class.getName() + " where appId is null " + appIdValue).list();
331 for (EPRole role : roles) {
333 rolesMap.put(role.getId(), role);
335 } else { // remote app
336 @SuppressWarnings("unchecked")
337 List<EPRole> roles = localSession
338 .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list();
339 for (EPRole role : roles) {
340 if (!extRequestValue && app.getCentralAuth()) {
341 rolesMap.put(role.getId(), role);
343 rolesMap.put(role.getAppRoleId(), role);
349 for (EcompRole userRole : newRolesToAdd) {
350 EPUserApp userApp = new EPUserApp();
351 if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName().equals(PortalConstants.ADMIN_ROLE)) {
352 role = (EPRole) localSession.get(EPRole.class, new Long(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
353 userApp.setRole(role);
354 } else if ((userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) && !extRequestValue){
356 }else if((userRole.getId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)) && app.getId().equals(PortalConstants.PORTAL_APP_ID) && !extRequestValue){
360 userApp.setRole(rolesMap.get(userRole.getId()));
363 userApp.setUserId(client.getId());
365 localSession.save(userApp);
366 localSession.flush();
369 if (appId == PortalConstants.PORTAL_APP_ID) {
371 * for local app -- hack - always make sure fn_role
372 * table's app_id is null and not 1 for primary app in
373 * this case being onap portal app; reason: hibernate
374 * is rightly setting this to 1 while persisting to
375 * fn_role as per the mapping but SDK role management
376 * code expects the app_id to be null as there is no
377 * concept of App_id in SDK
379 localSession.flush();
380 SQLQuery sqlQuery = localSession
381 .createSQLQuery("update fn_role set app_id = null where app_id = 1 ");
382 sqlQuery.executeUpdate();
387 transaction.commit();
388 } catch (Exception e) {
389 logger.error(EELFLoggerDelegate.errorLogger, "syncUserRoles failed", e);
390 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
391 EcompPortalUtils.rollbackTransaction(transaction,
392 "Exception occurred in syncUserRoles, Details: " + e.toString());
393 if("DELETE".equals(reqType)){
394 throw new SyncUserRolesException(e.getMessage());
397 if(localSession != null)
398 localSession.close();
403 * Called when getting the list of roles for the user
406 * @param userAppRoles
407 * @return List<RoleInAppForUser>
409 protected List<RoleInAppForUser> constructRolesInAppForUserGet(EcompRole[] appRoles, EcompRole[] userAppRoles) {
410 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
412 Set<Long> userAppRolesMap = new HashSet<Long>();
413 if (userAppRoles != null) {
414 for (EcompRole ecompRole : userAppRoles) {
415 userAppRolesMap.add(ecompRole.getId());
418 logger.error(EELFLoggerDelegate.errorLogger,
419 "constructRolesInAppForUserGet has received userAppRoles list empty");
422 if (appRoles != null) {
423 for (EcompRole ecompRole : appRoles) {
424 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
425 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
426 rolesInAppForUser.add(roleForUser);
429 logger.error(EELFLoggerDelegate.errorLogger, "constructRolesInAppForUser has received appRoles list empty");
431 return rolesInAppForUser;
435 * Called when getting the list of roles for the user
438 * @param userAppRoles
439 * @param extRequestValue
440 * set to false if request is from users page otherwise true
441 * @return List<RoleInAppForUser>
443 protected List<RoleInAppForUser> constructRolesInAppForUserGet(List<Role> appRoles, EPRole[] userAppRoles, Boolean extRequestValue) {
444 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
446 Set<Long> userAppRolesMap = new HashSet<Long>();
447 if (userAppRoles != null) {
448 for (EPRole ecompRole : userAppRoles) {
449 userAppRolesMap.add(ecompRole.getId());
451 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - userAppRolesMap = {}", userAppRolesMap);
454 logger.error(EELFLoggerDelegate.errorLogger,
455 "constructRolesInAppForUserGet has received userAppRoles list empty.");
458 if (appRoles != null) {
460 for (Role ecompRole : appRoles) {
461 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - appRoles not null = {}", ecompRole);
463 if (ecompRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && !extRequestValue)
465 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
466 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
467 rolesInAppForUser.add(roleForUser);
468 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - rolesInAppForUser = {}", rolesInAppForUser);
472 logger.error(EELFLoggerDelegate.errorLogger,
473 "constructRolesInAppForUser has received appRoles list empty.");
475 return rolesInAppForUser;
480 * copies of methods in GetAppsWithUserRoleState
482 * @param sessionFactory
487 protected void syncAppRoles(SessionFactory sessionFactory, Long appId, EcompRole[] appRoles) throws Exception {
488 logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId);
489 HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles);
490 Session localSession = null;
491 Transaction transaction = null;
494 localSession = sessionFactory.openSession();
495 transaction = localSession.beginTransaction();
496 // Attention! All roles from remote application supposed to be
498 @SuppressWarnings("unchecked")
499 List<EPRole> currentAppRoles = localSession
500 .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list();
501 List<EPRole> obsoleteRoles = new ArrayList<EPRole>();
502 for (int i = 0; i < currentAppRoles.size(); i++) {
503 EPRole oldAppRole = currentAppRoles.get(i);
504 if (oldAppRole.getAppRoleId() != null) {
505 EcompRole role = null;
506 role = newRolesMap.get(oldAppRole.getAppRoleId());
508 if (!(role.getName() == null || oldAppRole.getName().equals(role.getName()))) {
509 oldAppRole.setName(role.getName());
510 localSession.update(oldAppRole);
512 oldAppRole.setActive(true);
513 newRolesMap.remove(oldAppRole.getAppRoleId());
515 obsoleteRoles.add(oldAppRole);
518 obsoleteRoles.add(oldAppRole);
521 Collection<EcompRole> newRolesToAdd = newRolesMap.values();
522 if (obsoleteRoles.size() > 0) {
523 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: we have obsolete roles to delete");
524 for (EPRole role : obsoleteRoles) {
525 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: obsolete role: " + role.toString());
526 Long roleId = role.getId();
527 // delete obsolete roles here
528 // Must delete all records with foreign key constraints on
530 // fn_user_role, fn_role_composite, fn_role_function,
531 // fn_user_pseudo_role, fn_menu_functional_roles.
532 // And for fn_menu_functional, if no other roles for that
533 // menu item, remove the url.
535 // Delete from fn_user_role
536 @SuppressWarnings("unchecked")
537 List<EPUserApp> userRoles = localSession.createQuery(
538 "from " + EPUserApp.class.getName() + " where app.id=" + appId + " and role_id=" + roleId)
541 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: number of userRoles to delete: " + userRoles.size());
542 for (EPUserApp userRole : userRoles) {
543 logger.debug(EELFLoggerDelegate.debugLogger,
544 "syncAppRoles: about to delete userRole: " + userRole.toString());
545 localSession.delete(userRole);
546 logger.debug(EELFLoggerDelegate.debugLogger,
547 "syncAppRoles: finished deleting userRole: " + userRole.toString());
550 // Delete from fn_menu_functional_roles
551 @SuppressWarnings("unchecked")
552 List<FunctionalMenuRole> funcMenuRoles = localSession
553 .createQuery("from " + FunctionalMenuRole.class.getName() + " where roleId=" + roleId)
555 int numMenuRoles = funcMenuRoles.size();
556 logger.debug(EELFLoggerDelegate.debugLogger,
557 "syncAppRoles: number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles);
558 for (FunctionalMenuRole funcMenuRole : funcMenuRoles) {
559 Long menuId = funcMenuRole.menuId;
560 // If this is the only role for this menu item, then the
561 // app and roles will be gone,
562 // so must null out the url too, to be consistent
563 @SuppressWarnings("unchecked")
564 List<FunctionalMenuRole> funcMenuRoles2 = localSession
565 .createQuery("from " + FunctionalMenuRole.class.getName() + " where menuId=" + menuId)
567 int numMenuRoles2 = funcMenuRoles2.size();
568 logger.debug(EELFLoggerDelegate.debugLogger,
569 "syncAppRoles: number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2);
570 localSession.delete(funcMenuRole);
571 if (numMenuRoles2 == 1) {
572 // If this is the only role for this menu item, then
573 // the app and roles will be gone,
574 // so must null out the url too, to be consistent
575 logger.debug(EELFLoggerDelegate.debugLogger,
576 "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url");
577 @SuppressWarnings("unchecked")
578 List<FunctionalMenuItem> funcMenuItems = localSession
580 "from " + FunctionalMenuItem.class.getName() + " where menuId=" + menuId)
582 if (funcMenuItems.size() > 0) {
583 logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item");
584 FunctionalMenuItem funcMenuItem = funcMenuItems.get(0);
585 funcMenuItem.url = "";
586 localSession.update(funcMenuItem);
590 boolean isPortalRequest = true;
591 externalAccessRolesService.deleteRoleDependencyRecords(localSession, roleId, appId, isPortalRequest);
592 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to delete the role: " + role.toString());
593 localSession.delete(role);
594 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: deleted the role");
597 for (EcompRole role : newRolesToAdd) {
598 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to add missing role: " + role.toString());
599 EPRole newRole = new EPRole();
600 // Attention! All roles from remote application supposed to be
602 newRole.setActive(true);
603 newRole.setName(role.getName());
604 newRole.setAppId(appId);
605 newRole.setAppRoleId(role.getId());
606 localSession.save(newRole);
608 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to commit the transaction");
609 transaction.commit();
610 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: committed the transaction");
611 } catch (Exception e) {
612 logger.error(EELFLoggerDelegate.errorLogger, "syncAppRoles failed", e);
613 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
614 EcompPortalUtils.rollbackTransaction(transaction,
615 "Exception occurred in syncAppRoles, Details: " + e.toString());
616 throw new Exception(e);
618 localSession.close();
627 * Called when updating the list of roles for the user
631 * @param userRolesInRemoteApp
632 * @return RolesInAppForUser
634 protected RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId,
635 Set<EcompRole> userRolesInRemoteApp) {
636 RolesInAppForUser result;
637 result = new RolesInAppForUser();
638 result.appId = appId;
639 result.orgUserId = userId;
641 for (EcompRole role : userRolesInRemoteApp) {
642 RoleInAppForUser roleInAppForUser = new RoleInAppForUser();
643 roleInAppForUser.roleId = role.getId();
644 roleInAppForUser.roleName = role.getName();
645 roleInAppForUser.isApplied = new Boolean(true);
646 result.roles.add(roleInAppForUser);
653 * @param roleInAppForUserList
656 protected boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) {
657 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
658 if (roleInAppForUser.isApplied.booleanValue()) {
666 * Builds JSON and posts it to a remote application to update user roles.
668 * @param roleInAppForUserList
670 * @param applicationsRestClientService
673 * @return Set of roles as sent; NOT the response from the app.
674 * @throws JsonProcessingException
675 * @throws HTTPException
677 protected Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
678 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId,boolean systemUser)
679 throws JsonProcessingException, HTTPException {
680 Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList);
681 Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList);
682 String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote);
683 EPApp externalApp = null;
684 SystemType type = SystemType.APPLICATION;
685 externalApp = appsCacheService.getApp(appId);
686 String appBaseUri = null;
687 Set<RemoteRoleV1> updatedUserRolesinRemoteV1 = new TreeSet<>();
688 if (externalApp != null) {
689 appBaseUri = (type == SystemType.APPLICATION) ? externalApp.getAppRestEndpoint() : "";
691 if(appBaseUri != null && appBaseUri.endsWith("/api")){
692 for(EcompRole eprole :updatedUserRolesinRemote)
694 RemoteRoleV1 role = new RemoteRoleV1();
695 role.setId(eprole.getId());
696 role.setName(eprole.getName());
697 updatedUserRolesinRemoteV1.add(role);
699 userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemoteV1);
701 applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString,
702 String.format("/user/%s/roles", userId));
703 // TODO: We should add code that verifies that the post operation did
704 // succeed. Because the SDK may still return 200 OK with an html page
705 // even when it fails!
706 return updateUserRolesInEcomp;
711 * @param roleInAppForUserList
712 * @return Set<EcompRole>
714 protected Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) {
715 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
716 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
717 if (roleInAppForUser.isApplied) {
718 EcompRole ecompRole = new EcompRole();
719 ecompRole.setId(roleInAppForUser.roleId);
720 ecompRole.setName(roleInAppForUser.roleName);
721 existingUserRoles.add(ecompRole);
724 return existingUserRoles;
728 * Constructs user app roles excluding Account Administrator role
730 * @param roleInAppForUserList
732 * List of roles with Role name, Role Id
734 protected Set<EcompRole> constructUsersRemoteAppRoles(List<RoleInAppForUser> roleInAppForUserList) {
735 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
736 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
737 if (roleInAppForUser.isApplied && !roleInAppForUser.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
738 EcompRole ecompRole = new EcompRole();
739 ecompRole.setId(roleInAppForUser.roleId);
740 ecompRole.setName(roleInAppForUser.roleName);
741 existingUserRoles.add(ecompRole);
744 return existingUserRoles;
748 * This is for a single app
750 * @param rolesInAppForUser
751 * @param externalSystemRequest
752 * set to false if requests from Users page otherwise true
753 * @return true on success, false otherwise
755 protected boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser, boolean externalSystemRequest, String reqType,boolean isSystemUser) throws Exception {
756 boolean result = false;
757 String userId = rolesInAppForUser.orgUserId;
758 Long appId = rolesInAppForUser.appId;
759 synchronized (syncRests) {
760 if (rolesInAppForUser != null) {
761 createLocalUserIfNecessary(userId, isSystemUser);
764 if (rolesInAppForUser != null) {
765 EcompRole[] userAppRoles = new EcompRole[rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size()];
766 for (int i = 0; i < rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size(); i++) {
767 RoleInAppForUser roleInAppForUser = rolesInAppForUser.roles.get(i);
768 EcompRole role = new EcompRole();
769 role.setId(roleInAppForUser.roleId);
770 role.setName(roleInAppForUser.roleName);
771 userAppRoles[i] = role;
774 syncUserRoles(sessionFactory, userId, appId, userAppRoles, externalSystemRequest, reqType);
776 } catch (Exception e) {
777 logger.error(EELFLoggerDelegate.errorLogger,
778 "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for orgUserId " + userId, e);
779 if("DELETE".equals(reqType)){
780 throw new Exception(e.getMessage());
792 * @return UserApplicationRoles
794 protected UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) {
795 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
796 userWithRemoteAppRoles.setAppId(appId);
797 userWithRemoteAppRoles.setOrgUserId(remoteUser.getOrgUserId());
798 userWithRemoteAppRoles.setFirstName(remoteUser.getFirstName());
799 userWithRemoteAppRoles.setLastName(remoteUser.getLastName());
800 userWithRemoteAppRoles.setRoles(remoteUser.getRoles());
801 return userWithRemoteAppRoles;
807 * @see org.onap.portalapp.portal.service.UserRolesService#
808 * importRolesFromRemoteApplication(java.lang.Long)
810 public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException {
811 EPRole[] appRolesFull = applicationsRestClientService.get(EPRole[].class, appId, "/rolesFull");
812 List<EPRole> rolesList = Arrays.asList(appRolesFull);
813 for (EPRole externalAppRole : rolesList) {
815 // Try to find an existing extern role for the app in the local
816 // onap DB. If so, then use its id to update the existing external
817 // application role record.
818 Long externAppId = externalAppRole.getId();
819 EPRole existingAppRole = epRoleService.getRole(appId, externAppId);
820 if (existingAppRole != null) {
821 logger.debug(EELFLoggerDelegate.debugLogger,
822 String.format("ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.",
823 appId, externAppId));
826 // persistExternalRoleInEcompDb(externalAppRole, appId,
834 * It adds new user for remote application
836 * @param roleInAppForUserList
837 * @param remoteAppUser
841 * @param searchService
842 * @param applicationsRestClientService
846 private EPUser addRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app,
847 ObjectMapper mapper, SearchService searchService,
848 ApplicationsRestClientService applicationsRestClientService) throws Exception {
849 EPUser addRemoteUser = null;
850 if (remoteUserShouldBeCreated(roleInAppForUserList)) {
851 createNewUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper,
852 isAppUpgradeVersion(app));
854 return addRemoteUser;
857 private EPUser pushRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app,
858 ObjectMapper mapper, SearchService searchService,
859 ApplicationsRestClientService applicationsRestClientService,boolean appRoleIdUsed) throws Exception {
860 EPUser addRemoteUser = null;
861 // if (remoteUserShouldBeCreated(roleInAppForUserList)) {
862 pushUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper,
863 isAppUpgradeVersion(app), roleInAppForUserList, appRoleIdUsed);
865 return addRemoteUser;
868 @SuppressWarnings("unchecked")
869 protected void pushUserOnRemoteApp(String userId, EPApp app,
870 ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
871 ObjectMapper mapper, boolean postOpenSource, List<RoleInAppForUser> roleInAppForUserList,boolean appRoleIdUsed) throws Exception {
873 EPUser client = null;
874 client = searchService.searchUserByUserId(userId);
876 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
877 if (client == null) {
878 String msg = "cannot create user " + userId + ", because he/she cannot be found in directory.";
879 logger.error(EELFLoggerDelegate.errorLogger, msg);
880 // throw new Exception(msg);
881 final Map<String, String> loginIdParams = new HashMap<>();
882 loginIdParams.put("orgUserIdValue", userId);
883 List<EPUser> userList = new ArrayList<>();
884 userList = dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null);
885 if (userList.size() > 0) {
886 logger.debug(EELFLoggerDelegate.debugLogger,
887 userList.get(0).getOrgUserId() + " User was found in Portal");
888 client = userList.get(0);
889 SortedSet<EPUserApp> userApps = new TreeSet<>();
890 client.setEPUserApps(userApps);
891 client.setSystemUser(false);
893 logger.error(EELFLoggerDelegate.errorLogger, "user cannot be found be in directory or in portal");
894 throw new Exception(msg);
899 client.setLoginId(userId);
900 client.setActive(true);
901 client.setOrgUserId(userId);
904 roleInAppForUserList.removeIf(role -> role.isApplied.equals(false));
905 SortedSet<Role> roles = new TreeSet<>();
907 List<EPRole> getAppRoles = externalAccessRolesService.getAppRoles(app.getId());
908 List<EPApp> appList = new ArrayList<>();
910 List<CentralV2Role> roleList = new ArrayList<>();
911 Map<String, Long> params = new HashMap<>();
913 List<EPRole> userRoles = new ArrayList<>();
915 for (RoleInAppForUser roleInappForUser : roleInAppForUserList) {
916 EPRole role = new EPRole();
917 role.setId(roleInappForUser.getRoleId());
918 role.setName(roleInappForUser.getRoleName());
923 List<EPRole> userAppRoles = new ArrayList<>();
924 for (EPRole role : userRoles) {
925 EPRole appRole = getAppRoles.stream()
926 .filter(applicationRole -> role.getId().equals(applicationRole.getAppRoleId())).findAny()
928 EPRole epRole = new EPRole();
929 if (appRole != null) {
930 epRole.setId(appRole.getId());
931 epRole.setName(appRole.getName());
933 userAppRoles.add(epRole);
935 userRoles = new ArrayList<>();
936 userRoles.addAll(userAppRoles);
938 roleList = externalAccessRolesService.createCentralRoleObject(appList, userRoles, roleList, params);
940 for (CentralV2Role epRole : roleList) {
941 Role role = new Role();
942 EPRole appRole = getAppRoles.stream()
943 .filter(applicationRole -> epRole.getId().equals(applicationRole.getId())).findAny().orElse(null);
944 if (appRole != null){
945 role.setId(appRole.getAppRoleId());
946 role.setName(epRole.getName());
947 role.setRoleFunctions(epRole.getRoleFunctions());
951 client.setRoles(roles);
952 String userInString = null;
953 userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
954 logger.debug(EELFLoggerDelegate.debugLogger,
955 "about to post a client to remote application, users json = " + userInString);
956 applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user/%s", userId));
960 * It checks whether the remote user exists or not
961 * if exits returns user object else null
965 * @param applicationsRestClientService
967 * @throws HTTPException
969 private EPUser checkIfRemoteUserExits(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService) throws HTTPException{
970 EPUser checkRemoteUser = null;
972 checkRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
973 } catch (HTTPException e) {
974 // Some apps are returning 400 if user is not found.
975 if (e.getResponseCode() == 400) {
976 logger.debug(EELFLoggerDelegate.debugLogger,
977 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing",
979 } else if(e.getResponseCode() == 404) {
980 logger.debug(EELFLoggerDelegate.debugLogger,
981 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 404; continuing",
984 // Other response code, let it come thru.
988 return checkRemoteUser;
995 * @see org.onap.portalapp.portal.service.UserRolesService#
996 * setAppWithUserRoleStateForUser(org.onap.portalapp.portal.domain.
997 * EPUser, org.onap.portalapp.portal.transport.AppWithRolesForUser)
999 public ExternalRequestFieldsValidator setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser) {
1000 boolean result = false;
1001 boolean epRequestValue = false;
1003 String reqMessage = "";
1004 if (newAppRolesForUser != null && newAppRolesForUser.getOrgUserId() != null) {
1005 userId = newAppRolesForUser.getOrgUserId().trim();
1007 Long appId = newAppRolesForUser.getAppId();
1008 List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.getAppRoles();
1009 if (userId.length() > 0 ) {
1010 ObjectMapper mapper = new ObjectMapper();
1011 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1014 EPApp app = appsService.getApp(appId);
1015 applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
1017 boolean systemUser = newAppRolesForUser.isSystemUser();
1018 if ((app.getCentralAuth() || app.getId().equals(PortalConstants.PORTAL_APP_ID)) && systemUser) {
1020 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1021 applicationsRestClientService, appId, userId);
1022 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1023 userRolesInLocalApp);
1024 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1025 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1026 // Apply changes in external Access system
1027 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList,
1028 epRequestValue, systemUser);
1030 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal",
1033 }else if (!app.getCentralAuth() && systemUser)
1035 throw new Exception("For non-centralized application we cannot add systemUser");
1037 else{ // if centralized app
1038 if (app.getCentralAuth()) {
1039 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1040 pushRemoteUser(roleInAppForUserList, userId, app, mapper, searchService,
1041 applicationsRestClientService,false);
1044 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1045 applicationsRestClientService, appId, userId);
1046 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1047 userRolesInLocalApp);
1048 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1049 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1050 // Apply changes in external Access system
1051 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList,
1052 epRequestValue,false);
1054 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal", systemUser);
1056 // In case if portal is not centralized then follow existing approach
1057 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1058 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1059 applicationsRestClientService, appId, userId);
1060 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1061 userRolesInLocalApp);
1062 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal",false);
1063 } else{// remote app
1064 EPUser remoteAppUser = null;
1065 if(!app.getCentralAuth() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1067 remoteAppUser = checkIfRemoteUserExits(userId, app, applicationsRestClientService);
1069 if (remoteAppUser == null) {
1070 remoteAppUser = addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService, applicationsRestClientService);
1072 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
1073 applicationsRestClientService, appId, userId,systemUser);
1074 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1075 userRolesInRemoteApp);
1076 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null,false);
1078 // If no roles remain, request app to set user inactive.
1079 if (userRolesInRemoteApp.size() == 0) {
1080 logger.debug(EELFLoggerDelegate.debugLogger,
1081 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
1083 //remoteAppUser.setActive(false);
1084 postUserToRemoteApp(userId, user, app, applicationsRestClientService);
1089 } catch (Exception e) {
1090 /*String message = String.format(
1091 "Failed to create user or update user roles for User %s, AppId %s",
1092 userId, Long.toString(appId));
1093 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1096 String message = String.format(
1097 "Failed to create user or update user roles for User %s, AppId %s",
1098 userId, Long.toString(appId));
1099 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1101 reqMessage = e.getMessage();
1108 return new ExternalRequestFieldsValidator(result, reqMessage);
1112 * It adds user roles in External system and also make data consistent in both local and in External System
1114 * @param app details
1116 * @param roleInAppUser Contains list of active roles
1118 @SuppressWarnings("unchecked")
1119 private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser, boolean isPortalRequest,boolean isSystemUser) throws Exception
1122 // check if user exists
1123 final Map<String, String> userParams = new HashMap<>();
1124 userParams.put("orgUserIdValue", orgUserId);
1125 List<EPUser> userInfo = checkIfUserExists(userParams);
1126 if (userInfo.isEmpty()) {
1127 createLocalUserIfNecessary(orgUserId, isSystemUser);
1130 if (EPCommonSystemProperties
1131 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN) && !isSystemUser) {
1133 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
1137 ObjectMapper mapper = new ObjectMapper();
1138 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1139 HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
1140 ResponseEntity<String> getResponse = externalAccessRolesService.getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
1141 List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
1142 String res = getResponse.getBody();
1143 JSONObject jsonObj = null;
1144 JSONArray extRoles = null;
1145 if (!res.equals("{}")) {
1146 jsonObj = new JSONObject(res);
1147 extRoles = jsonObj.getJSONArray("role");
1149 ExternalAccessUserRoleDetail userRoleDetail = null;
1150 if (extRoles != null) {
1151 for (int i = 0; i < extRoles.length(); i++) {
1152 if (extRoles.getJSONObject(i).getString("name").startsWith(app.getNameSpace() + ".")
1153 && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".admin")
1154 && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".owner")) {
1155 if (extRoles.getJSONObject(i).has("description")) {
1156 ExternalRoleDescription desc = new ExternalRoleDescription(extRoles.getJSONObject(i).getString("description"));
1157 userRoleDetail = new ExternalAccessUserRoleDetail(
1158 extRoles.getJSONObject(i).getString("name"), desc);
1159 userRoleDetailList.add(userRoleDetail);
1161 userRoleDetail = new ExternalAccessUserRoleDetail(
1162 extRoles.getJSONObject(i).getString("name"), null);
1163 userRoleDetailList.add(userRoleDetail);
1170 List<ExternalAccessUserRoleDetail> userRoleListMatchingInExtAuthAndLocal = CheckIfRoleAreMatchingInUserRoleDetailList(userRoleDetailList,app);
1172 // If request coming from portal not from external role approval system then we have to check if user already
1173 // have account admin or system admin as GUI will not send these roles
1174 if (!isPortalRequest) {
1175 final Map<String, String> loginIdParams = new HashMap<>();
1176 loginIdParams.put("orgUserIdValue", orgUserId);
1177 EPUser user = (EPUser) dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null).get(0);
1178 final Map<String, Long> params = new HashMap<>();
1179 params.put("appId", app.getId());
1180 params.put("userId", user.getId());
1181 List<EcompUserAppRoles> userAppList = dataAccessService.executeNamedQuery("getUserAppExistingRoles",
1183 if (!roleInAppUser.isEmpty()) {
1184 for (EcompUserAppRoles userApp : userAppList) {
1185 if (userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)
1186 || userApp.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
1187 RoleInAppForUser addSpecialRole = new RoleInAppForUser();
1188 addSpecialRole.setIsApplied(true);
1189 addSpecialRole.setRoleId(userApp.getRoleId());
1190 addSpecialRole.setRoleName(userApp.getRoleName());
1191 roleInAppUser.add(addSpecialRole);
1196 List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct()
1197 .collect(Collectors.toList());
1198 final Map<String, RoleInAppForUser> currentUserRolesToUpdate = new HashMap<>();
1199 for (RoleInAppForUser roleInAppUserNew : roleInAppUserNonDupls) {
1200 currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), roleInAppUserNew);
1202 final Map<String, ExternalAccessUserRoleDetail> currentUserRolesInExternalSystem = new HashMap<>();
1203 for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleListMatchingInExtAuthAndLocal) {
1204 currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole);
1206 // Check if user roles does not exists in local but still there in External Central Auth System delete them all
1207 for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
1208 if (!(currentUserRolesToUpdate
1209 .containsKey(userRole.getName().substring(app.getNameSpace().length() + 1)))) {
1210 HttpEntity<String> entity = new HttpEntity<>(headers);
1211 logger.debug(EELFLoggerDelegate.debugLogger,
1212 "updateUserRolesInExternalSystem: Connecting to external system to DELETE user role {}",
1213 userRole.getName());
1214 ResponseEntity<String> deleteResponse = template.exchange(
1215 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1216 + "userRole/" + name + "/" + userRole.getName(),
1217 HttpMethod.DELETE, entity, String.class);
1218 logger.debug(EELFLoggerDelegate.debugLogger,
1219 "updateUserRolesInExternalSystem: Finished DELETE operation in external system for user role {} and the response is {}",
1220 userRole.getName(), deleteResponse.getBody());
1223 // Check if user roles does not exists in External Central Auth System add them all
1224 for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) {
1225 if (!(currentUserRolesInExternalSystem
1226 .containsKey(app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")))) {
1227 ExternalAccessUser extUser = new ExternalAccessUser(name,
1228 app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1229 String formattedUserRole = mapper.writeValueAsString(extUser);
1230 HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers);
1231 logger.debug(EELFLoggerDelegate.debugLogger, "updateUserRolesInExternalSystem: Connecting to external system for user {} and POST {}",
1232 name , addUserRole.getRoleName());
1233 ResponseEntity<String> addResponse = template
1234 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1235 + "userRole", HttpMethod.POST, entity, String.class);
1236 logger.debug(EELFLoggerDelegate.debugLogger,
1237 "updateUserRolesInExternalSystem: Finished adding user role in external system {} and added user role {}",
1238 addResponse.getBody(), addUserRole.getRoleName());
1239 if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 404) {
1240 logger.debug(EELFLoggerDelegate.debugLogger,
1241 "Finished POST operation in external system but unable to save user role", addResponse.getBody(),
1242 addUserRole.getRoleName());
1243 throw new Exception(addResponse.getBody());
1247 } catch (HttpClientErrorException e) {
1248 logger.error(EELFLoggerDelegate.errorLogger,
1249 "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}",
1251 if (e.getStatusCode() == HttpStatus.FORBIDDEN) {
1252 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid systemUser", orgUserId);
1253 throw new HttpClientErrorException(HttpStatus.FORBIDDEN, "Please enter the valid systemUser");
1255 if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
1256 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid role");
1257 throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "Please enter the valid role");
1259 EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
1263 catch (Exception e) {
1264 logger.error(EELFLoggerDelegate.errorLogger, "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}", app.getId(), e);
1265 EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
1271 private List<ExternalAccessUserRoleDetail> CheckIfRoleAreMatchingInUserRoleDetailList(
1272 List<ExternalAccessUserRoleDetail> userRoleDetailList, EPApp app) {
1273 Map<String, EPRole> epRoleList = externalAccessRolesService.getAppRoleNamesWithUnderscoreMap(app);
1274 //Add Account Admin role for partner app to prevent conflict
1275 if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1276 EPRole role = new EPRole();
1277 role.setName(PortalConstants.ADMIN_ROLE.replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1278 epRoleList.put(role.getName(), role);
1280 userRoleDetailList.removeIf(userRoleDetail -> !epRoleList.containsKey(userRoleDetail.getName().substring(app.getNameSpace().length()+1)));
1281 return userRoleDetailList;
1288 * @param applicationsRestClientService
1289 * @param searchService
1293 protected void createNewUserOnRemoteApp(String userId, EPApp app,
1294 ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
1295 ObjectMapper mapper, boolean postOpenSource) throws Exception {
1298 EPUser client = searchService.searchUserByUserId(userId);
1300 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1302 if (client == null) {
1303 String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook.";
1304 logger.error(EELFLoggerDelegate.errorLogger, msg);
1305 throw new Exception(msg);
1308 client.setLoginId(userId);
1309 client.setActive(true);
1311 String userInString = null;
1312 userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
1313 logger.debug(EELFLoggerDelegate.debugLogger,
1314 "about to post new client to remote application, users json = " + userInString);
1315 applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user", userId));
1319 @SuppressWarnings("unchecked")
1320 protected void applyChangesToAppRolesRequest(Long appId, Long userId, String updateStatus, EPUserAppRolesRequest epUserAppRolesRequest) {
1321 final Map<String, Long> epRequestParams = new HashMap<>();
1323 EPUserAppRolesRequest epAppRolesRequestData = epUserAppRolesRequest;
1324 epAppRolesRequestData.setUpdatedDate(new Date());
1325 epAppRolesRequestData.setRequestStatus(updateStatus);
1326 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1327 addiotonalUpdateParam.put("userId", userId);
1328 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1329 epRequestParams.put("reqId", epUserAppRolesRequest.getId());
1330 List<EPUserAppRolesRequestDetail> epUserAppRolessDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1331 epUserAppRolessDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1332 epRequestParams, null);
1333 if (epUserAppRolessDetailList.size() > 0) {
1334 for (EPUserAppRolesRequestDetail epRequestUpdateData : epUserAppRolessDetailList) {
1335 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateData;
1336 epAppRoleDetailData.setReqType(updateStatus);
1337 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1338 HashMap<String, Long> updateDetailsParam = new HashMap<String, Long>();
1339 addiotonalUpdateParam.put("reqId", epUserAppRolesRequest.getId());
1340 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParam);
1343 logger.debug(EELFLoggerDelegate.debugLogger, "The request is set to complete");
1345 } catch (Exception e) {
1346 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToAppRolesRequest failed", e);
1350 @SuppressWarnings("unchecked")
1351 public void applyChangesToUserAppRolesForMyLoginsRequest(EPUser user, Long appId) {
1352 final Map<String, Long> params = new HashMap<>();
1353 final Map<String, Long> epDetailParams = new HashMap<>();
1354 List<EPUserAppRolesRequest> epRequestIdVal = new ArrayList<EPUserAppRolesRequest>();
1355 params.put("appId", appId);
1356 params.put("userId", user.getId());
1358 epRequestIdVal = (List<EPUserAppRolesRequest>) dataAccessService
1359 .executeNamedQuery("userAppRolesRequestList", params, null);
1360 if (epRequestIdVal.size() > 0) {
1361 EPUserAppRolesRequest epAppRolesRequestData = epRequestIdVal.get(0);
1362 epAppRolesRequestData.setUpdatedDate(new Date());
1363 epAppRolesRequestData.setRequestStatus("O");
1364 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1365 addiotonalUpdateParam.put("userId", user.getId());
1366 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1367 epDetailParams.put("reqId", epAppRolesRequestData.getId());
1368 List<EPUserAppRolesRequestDetail> epUserAppRolesDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1369 epUserAppRolesDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1370 epDetailParams, null);
1371 if (epUserAppRolesDetailList.size() > 0) {
1372 for (EPUserAppRolesRequestDetail epRequestUpdateList : epUserAppRolesDetailList) {
1373 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateList;
1374 epAppRoleDetailData.setReqType("O");
1375 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1376 HashMap<String, Long> updateDetailsParams = new HashMap<String, Long>();
1377 addiotonalUpdateParam.put("reqId", epAppRolesRequestData.getId());
1378 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParams);
1380 logger.debug(EELFLoggerDelegate.debugLogger, "User App roles request from User Page is overridden");
1384 } catch (Exception e) {
1385 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e);
1390 * Pushes specified user details to the specified remote app.
1393 * OrgUserId identifying user at remote app in REST endpoint path
1395 * User details to be pushed
1398 * @param applicationsRestClientService
1399 * @throws HTTPException
1401 protected void postUserToRemoteApp(String userId, EPUser user, EPApp app,
1402 ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
1404 getUser(userId, app, applicationsRestClientService);
1409 * It returns user details for single org user id
1413 * if user exists it returns list of user details otherwise empty value
1415 @SuppressWarnings("unchecked")
1416 private List<EPUser> checkIfUserExists(Map<String, String> userParams){
1417 return (List<EPUser>)dataAccessService.executeNamedQuery("epUserAppId", userParams, null);
1421 * It checks whether the new user is valid or not otherwise throws exception
1426 * Checks if user is valid and returns message otherwise throws exception
1429 private String validateNewUser(String orgUserId, EPApp app) throws Exception {
1430 EPUser epUser = searchService.searchUserByUserId(orgUserId);
1431 if (epUser == null) {
1432 throw new Exception("User does not exist");
1433 } else if (!epUser.getOrgUserId().equals(orgUserId)) {
1434 throw new Exception("User does not exist");
1435 } else if (app == null) {
1436 throw new Exception("Application does not exist");
1438 return "Saved Successfully";
1442 * Checks if the fields exists or not
1445 * contains user information
1449 * throws exception if the field is not valid
1451 private void validateExternalRequestFields(List<EPUser> userList, EPApp app) throws Exception{
1452 if (userList.size() == 0 || userList.isEmpty() ) {
1453 throw new Exception("User does not exist");
1454 } else if(app == null) {
1455 throw new Exception("Application does not exist");
1456 } else if(!app.getEnabled() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1457 throw new Exception(app.getMlAppName()+" application is unavailable");
1461 @SuppressWarnings("unchecked")
1462 public ExternalRequestFieldsValidator setExternalRequestUserAppRole(ExternalSystemUser newAppRolesForUser, String reqType) {
1463 boolean result = false;
1464 boolean externalSystemRequest = true;
1465 final Map<String, Long> params = new HashMap<>();
1466 final Map<String, String> userParams = new HashMap<>();
1467 List<EPUser> userInfo = null;
1469 List<EPUserAppRolesRequest> epRequestId = null;
1470 String orgUserId = "";
1471 String updateStatus = "";
1472 String reqMessage = "";
1474 if (newAppRolesForUser != null && newAppRolesForUser.getLoginId() != null) {
1475 orgUserId = newAppRolesForUser.getLoginId().trim();
1477 String appName = newAppRolesForUser.getApplicationName();
1478 String logMessage = ("DELETE").equals(reqType) ? "Deleting": "Assigning/Updating" ;
1479 if (orgUserId.length() > 0) {
1480 ObjectMapper mapper = new ObjectMapper();
1481 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1482 int epRequestIdSize = 0;
1484 app = appsService.getAppDetail(appName);
1485 userParams.put("orgUserIdValue", orgUserId);
1486 userInfo = checkIfUserExists(userParams);
1487 reqMessage = "Updated Successfully";
1488 if (!reqType.equals("DELETE") && (userInfo.size() == 0 || userInfo.isEmpty())) {
1489 reqMessage = validateNewUser(orgUserId, app);
1491 if (userInfo.size() != 0 || !userInfo.isEmpty()) {
1492 validateExternalRequestFields(userInfo, app);
1493 user = userInfo.get(0);
1494 params.put("appId", app.getId());
1495 params.put("userId", user.getId());
1496 epRequestId = (List<EPUserAppRolesRequest>) dataAccessService
1497 .executeNamedQuery("userAppRolesRequestList", params, null);
1498 epRequestIdSize = epRequestId.size();
1501 //If Non-Centralized app make sure you sync app roles before assigning to user
1502 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !app.getCentralAuth()) {
1503 logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Starting GET roles for app {}",app.getId());
1504 EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, app.getId(), "/roles");
1505 logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Finshed GET roles for app {} and payload {}",app.getId(), appRoles);
1506 if (appRoles.length > 0) {
1507 syncAppRoles(sessionFactory, app.getId(), appRoles);
1510 List<RoleInAppForUser> roleInAppForUserList = roleInAppForUserList(newAppRolesForUser.getRoles(),
1511 app.getId(), app.getMlAppName());
1512 List<EcompUserAppRoles> userRoleList = null;
1513 if(!userInfo.isEmpty()){
1514 final Map<String, Long> appParams = new HashMap<>();
1515 appParams.put("userId", user.getId());
1516 appParams.put("appId", app.getId());
1517 userRoleList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", appParams, null);
1519 // Check if list contains just account admin role
1520 boolean checkIfAdminRoleExists = false;
1521 if (reqType.equals("DELETE") && userRoleList!=null) {
1522 checkIfAdminRoleExists = userRoleList.stream()
1523 .anyMatch(userRole -> userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1525 checkIfAdminRoleExists = roleInAppForUserList.stream()
1526 .anyMatch(roleList -> roleList.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1528 // if Centralized app
1529 if (app.getCentralAuth()) {
1530 // We should add If user does not exist in remote application
1532 // If adding just account admin role dont make remote application user call or
1533 // if request has only single non admin role then make remote call
1534 if (!(app.getId().equals(PortalConstants.PORTAL_APP_ID) && reqType.equals("DELETE"))
1535 && ((checkIfAdminRoleExists && roleInAppForUserList.size() > 1)
1536 || (!checkIfAdminRoleExists && roleInAppForUserList.size() >= 1))) {
1537 // check if admin role exist then delete
1538 List<RoleInAppForUser> remoteUserRoles = roleInAppForUserList.stream()
1539 .collect(Collectors.toList());
1540 remoteUserRoles.removeIf(role -> {
1541 return (role.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1543 String orgUserIdNewOrExist = (userInfo.size() != 0 || !userInfo.isEmpty()) ? user.getOrgUserId() : orgUserId;
1544 pushRemoteUser(remoteUserRoles, orgUserIdNewOrExist , app, mapper, searchService,
1545 applicationsRestClientService,true);
1547 } catch (Exception e) {
1548 reqMessage = e.getMessage();
1549 logger.error(EELFLoggerDelegate.errorLogger, "setExternalRequestUserAppRole: Failed to added remote user", e);
1550 throw new Exception(reqMessage);
1552 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1553 applicationsRestClientService, app.getId(), orgUserId);
1554 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1555 userRolesInLocalApp);
1556 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1557 if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1558 // Apply changes in external Access system
1559 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, externalSystemRequest,false);
1561 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
1562 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1563 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,false);
1565 // If local application is not centralized
1566 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1567 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1568 applicationsRestClientService, app.getId(), orgUserId);
1569 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1570 userRolesInLocalApp);
1571 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,false);
1572 } else {// remote app
1573 // If adding just account admin role don't do remote application user call
1574 if (!((roleInAppForUserList.size() == 1 || reqType.equals("DELETE")) && checkIfAdminRoleExists)) {
1575 EPUser remoteAppUser = null;
1576 remoteAppUser = checkIfRemoteUserExits(orgUserId, app, applicationsRestClientService);
1577 if (remoteAppUser == null) {
1578 addRemoteUser(roleInAppForUserList, orgUserId, app, mapper, searchService,
1579 applicationsRestClientService);
1580 reqMessage = "Saved Successfully";
1583 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
1584 applicationsRestClientService, app.getId(), orgUserId,false);
1586 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1587 userRolesInRemoteApp);
1588 logger.info(EELFLoggerDelegate.debugLogger,
1589 "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
1590 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1591 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1593 // If no roles remain, request app to set user inactive.
1595 * if (userRolesInRemoteApp.size() == 0) {
1596 * logger.debug(EELFLoggerDelegate.debugLogger,
1597 * "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive"
1598 * , app, orgUserId); //TODO Need to fix the logged in user is not set to
1599 * inactive remoteAppUser.setActive(false); postUserToRemoteApp(orgUserId, user,
1600 * app, applicationsRestClientService); }
1604 // Here we are adding only we have single account admin in roleInAppForUserList and this should not add in remote
1605 if(!(reqType.equals("DELETE")) && userInfo.isEmpty()){
1606 reqMessage = "Saved Successfully";
1608 Set<EcompRole> userRolesInRemoteApp = constructUsersEcompRoles(roleInAppForUserList);
1610 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1611 userRolesInRemoteApp);
1612 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}",
1613 logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1614 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1618 reqMessage = "Failed to save the user app role(s)";
1620 if (epRequestIdSize > 0 && !userInfo.isEmpty()) {
1622 applyChangesToAppRolesRequest(app.getId(), user.getId(), updateStatus, epRequestId.get(0));
1625 } catch (Exception e) {
1626 String message = String.format("setExternalRequestUserAppRole: Failed to create user or update user roles for User %s, AppId %s",
1627 orgUserId, appName);
1628 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1630 reqMessage = e.getMessage();
1631 if(epRequestIdSize > 0 && userInfo!=null && !userInfo.isEmpty()){
1633 applyChangesToAppRolesRequest(app.getId(), user.getId(),
1634 updateStatus, epRequestId.get(0));
1639 return new ExternalRequestFieldsValidator(result, reqMessage);
1644 * @param roleInAppForUserList
1646 * @param applicationsRestClientService
1649 * @return Set<EcompRole>
1650 * @throws JsonProcessingException
1651 * @throws HTTPException
1653 private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
1654 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
1655 throws JsonProcessingException, HTTPException {
1656 Set<EcompRole> updatedUserRoles = constructUsersEcompRoles(roleInAppForUserList);
1657 return updatedUserRoles;
1661 * It constructs and returns list of user app roles when the external API role approval system calls
1664 * @param roleInAppForUserList
1666 * @return list of user app roles
1668 * throws exceptions if role id does not exits
1670 private List<RoleInAppForUser> roleInAppForUserList(List<ExternalSystemRoleApproval> roleInAppForUserList,
1671 Long appId, String appName) throws Exception {
1672 List<RoleInAppForUser> existingUserRoles = new ArrayList<RoleInAppForUser>();
1673 EPRole existingAppRole = null;
1674 for (ExternalSystemRoleApproval roleInAppForUser : roleInAppForUserList) {
1675 RoleInAppForUser ecompRole = new RoleInAppForUser();
1676 existingAppRole = epRoleService.getAppRole(roleInAppForUser.getRoleName(), appId);
1677 if (existingAppRole == null) {
1678 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1679 roleInAppForUserList);
1680 throw new Exception("'" +roleInAppForUser.getRoleName() + "'" +" role does not exist for " + appName + " application");
1682 if (!existingAppRole.getActive()) {
1683 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1684 roleInAppForUserList);
1685 throw new Exception(roleInAppForUser.getRoleName() + " role is unavailable for "+ appName + " application");
1687 ecompRole.roleId = (appId == 1 || roleInAppForUser.getRoleName().equals(PortalConstants.ADMIN_ROLE)) ? existingAppRole.getId() : existingAppRole.getAppRoleId();
1688 ecompRole.roleName = roleInAppForUser.getRoleName();
1689 ecompRole.isApplied = true;
1690 existingUserRoles.add(ecompRole);
1693 return existingUserRoles;
1702 * @param applicationsRestClientService
1704 * @throws HTTPException
1706 protected EPUser getUserFromApp(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1707 throws HTTPException {
1709 if (app.getId() == PortalConstants.PORTAL_APP_ID) {
1710 // Map<String,String> params = new HashMap<String,String>();
1711 // params.put("sbcid",userId);
1712 @SuppressWarnings("unchecked")
1713 List<EPUser> userList = (List<EPUser>) dataAccessService
1714 .executeQuery("from EPUser where orgUserId='" + userId + "'", null);
1715 if (userList != null && !userList.isEmpty())
1716 return userList.get(0);
1722 return getUser(userId, app, applicationsRestClientService);
1725 protected EPUser getUser(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1726 throws HTTPException {
1727 return applicationsRestClientService.get(EPUser.class, app.getId(), String.format("/user/%s", userId), true);
1731 protected boolean isAppUpgradeVersion(EPApp app){
1736 public ExternalSystemAccess getExternalRequestAccess(){
1737 ExternalSystemAccess res = null;
1739 res = new ExternalSystemAccess(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE,
1740 Boolean.parseBoolean(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE)));
1741 } catch (Exception e) {
1742 logger.error(EELFLoggerDelegate.errorLogger, "getExternalRequestAccess failed" + e.getMessage());
1750 * @see org.onap.portalapp.portal.service.UserRolesService#
1751 * getAppRolesForUser(java.lang.Long, java.lang.String)
1753 @SuppressWarnings("unchecked")
1754 public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId, Boolean extRequestValue,EPUser user) {
1755 List<RoleInAppForUser> rolesInAppForUser = null;
1756 EPApp app = appsService.getApp(appId);
1757 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - app = {}", app);
1759 // for onap portal app, no need to make a remote call
1760 List<Role> roleList = new ArrayList<>();
1761 if (appId == PortalConstants.PORTAL_APP_ID) {
1762 if(app.getCentralAuth()){
1763 List<CentralV2Role> cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey());
1764 for(CentralV2Role cenRole : cenRoleList){
1765 Role role = new Role();
1766 role.setActive(cenRole.getActive());
1767 role.setId(cenRole.getId());
1768 role.setName(cenRole.getName());
1769 role.setPriority(cenRole.getPriority());
1773 roleList = roleService.getAvailableRoles(userId);
1775 List<Role> activeRoleList = new ArrayList<Role>();
1776 for(Role role: roleList) {
1777 if(role.getActive()) {
1778 if(role.getId() != 1){ // prevent portal admin from being added
1779 activeRoleList.add(role);
1780 } else if(extRequestValue){
1781 activeRoleList.add(role);
1786 EPUser localUser = getUserFromApp(userId, app, applicationsRestClientService);
1787 // If localUser does not exists return roles
1788 Set<EPRole> roleSet = null;
1789 EPRole[] roleSetList = null;
1790 if(localUser != null){
1791 roleSet = localUser.getAppEPRoles(app);
1792 roleSetList = roleSet.toArray(new EPRole[0]);
1794 rolesInAppForUser = constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue);
1795 return rolesInAppForUser;
1798 EcompRole[] appRoles = null;
1799 List<EcompRole> roles = new ArrayList<>();
1800 if (app.getCentralAuth()) {
1801 final Map<String, Long> appParams = new HashMap<>();
1802 appParams.put("appId", app.getId());
1803 List<EPRole> applicationRoles = dataAccessService.executeNamedQuery("getActiveRolesOfApplication",
1806 EPApp application = appService.getApp(appId);
1807 boolean checkIfUserisApplicationAccAdmin = adminRolesService.isAccountAdminOfApplication(user,
1810 List<EPRole> rolesetwithfunctioncds = new ArrayList<EPRole>();
1811 for (EPRole role : applicationRoles) {
1812 Map<String, Long> params = new HashMap<>();
1813 params.put("roleId", role.getId());
1814 params.put(APP_ID, app.getId());
1815 List<CentralV2RoleFunction> cenRoleFuncList = dataAccessService
1816 .executeNamedQuery("getAppRoleFunctionList", params, null);
1818 // SortedSet<CentralV2RoleFunction> roleFunctionSet =
1820 SortedSet<RoleFunction> roleFunctionSet = new TreeSet<>();
1821 for (CentralV2RoleFunction roleFunc : cenRoleFuncList) {
1823 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1824 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
1825 String type = externalAccessRolesService.getFunctionCodeType(roleFunc.getCode());
1826 String action = externalAccessRolesService.getFunctionCodeAction(roleFunc.getCode());
1827 String name = roleFunc.getName();
1829 RoleFunction function = new RoleFunction();
1830 function.setAction(action);
1831 function.setType(type);
1832 function.setCode(functionCode);
1833 function.setName(name);
1834 roleFunctionSet.add(function);
1835 role.setRoleFunctions(roleFunctionSet);
1838 rolesetwithfunctioncds.add(role);
1843 for (EPRole role1 : rolesetwithfunctioncds) {
1844 EcompRole ecompRole = new EcompRole();
1845 ecompRole.setId(role1.getId());
1846 ecompRole.setName(role1.getName());
1847 ecompRole.setRoleFunctions(role1.getRoleFunctions());
1848 roles.add(ecompRole);
1851 if (checkIfUserisApplicationAccAdmin) {
1852 appRoles = roles.toArray(new EcompRole[roles.size()]);
1853 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() If Logged in user checkIfUserisApplicationAccAdmin- appRoles = {}", appRoles);
1854 } else if (adminRolesService.isRoleAdmin(user) && !checkIfUserisApplicationAccAdmin) {
1855 List<EcompRole> roleAdminAppRoles = new ArrayList<>();
1856 List<String> roleAdminAppRolesNames = new ArrayList<>();
1857 final Map<String, Long> userParams = new HashMap<>();
1858 userParams.put("userId", user.getId());
1859 List<String> getUserApproverRoles = dataAccessService.executeNamedQuery("getUserApproverRoles", userParams, null);
1861 List<EcompRole> userapproverRolesList = new ArrayList<>();
1862 for (String str : getUserApproverRoles) {
1863 EcompRole epRole = roles.stream().filter(x -> str.equals(x.getName())).findAny().orElse(null);
1865 userapproverRolesList.add(epRole);
1867 // roles.removeAll(userapproverRolesList);
1868 for (EcompRole role : userapproverRolesList) {
1870 List<RoleFunction> roleFunList = new ArrayList<>();
1871 roleFunList.addAll(role.getRoleFunctions());
1872 boolean checkIfFunctionsExits = roleFunList.stream()
1873 .anyMatch(roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
1874 if (checkIfFunctionsExits) {
1875 roleAdminAppRoles.add(role);
1876 List<RoleFunction> filteredList = roleFunList.stream()
1877 .filter(x -> "Approver".equalsIgnoreCase(x.getType())).collect(Collectors.toList());
1878 roleAdminAppRolesNames.addAll(filteredList.stream().map(RoleFunction::getCode)
1879 .collect(Collectors.toList()));
1880 // roleAdminAppRolesNames = filteredList.stream().map(RoleFunction::getCode)
1881 // .collect(Collectors.toList());
1884 for (String name : roleAdminAppRolesNames) {
1885 EcompRole ecompRole = roles.stream().filter(x -> name.equals(x.getName())).findAny()
1887 if (ecompRole != null)
1888 roleAdminAppRoles.add(ecompRole);
1891 appRoles = roleAdminAppRoles.toArray(new EcompRole[roleAdminAppRoles.size()]);
1895 appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
1897 // Test this error case, for generating an internal ONAP Portal
1899 // EcompRole[] appRoles = null;
1900 // If there is an exception in the rest client api, then null will
1902 if (appRoles != null) {
1903 if(!app.getCentralAuth()) {
1904 syncAppRoles(sessionFactory, appId, appRoles);
1906 EcompRole[] userAppRoles = null;
1910 if(app.getCentralAuth()){
1911 final Map<String, String> params = new HashMap<>();
1912 final Map<String, Long> userParams = new HashMap<>();
1913 params.put("orgUserIdValue", userId);
1914 List<EPUser> actualUser = dataAccessService.executeNamedQuery("epUserAppId", params, null);
1915 userParams.put("appId", app.getId());
1916 userParams.put("userId", actualUser.get(0).getId());
1917 List<EPUserAppCurrentRoles> userAppsRolesList = dataAccessService.executeNamedQuery("getUserAppCurrentRoles", userParams, null);
1919 List<EcompRole> setUserRoles = new ArrayList<>();
1920 for(EPUserAppCurrentRoles role : userAppsRolesList){
1921 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - userAppsRolesList get userRolename = {}", role.getRoleName());
1922 EcompRole ecompRole = new EcompRole();
1923 ecompRole.setId(role.getRoleId());
1924 ecompRole.setName(role.getRoleName());
1925 setUserRoles.add(ecompRole);
1928 boolean checkIfUserisAccAdmin = setUserRoles.stream()
1929 .anyMatch(ecompRole -> ecompRole.getId() == 999L);
1931 if (!checkIfUserisAccAdmin) {
1932 List<EcompRole> userApplicationRolesList = setUserRoles;
1933 List<EcompRole> appRolesList = Arrays.asList(appRoles);
1934 Set<EcompRole> finalUserAppRolesList = new HashSet<>();
1936 List<String> roleNames = new ArrayList<>();
1937 for (EcompRole role : userApplicationRolesList) {
1938 EcompRole epRole = appRolesList.stream()
1939 .filter(x -> role.getName().equals(x.getName())).findAny().orElse(null);
1940 List<RoleFunction> roleFunList = new ArrayList<>();
1941 if(epRole.getRoleFunctions().size()>0)
1942 roleFunList.addAll(epRole.getRoleFunctions());
1943 boolean checkIfFunctionsExits = roleFunList.stream().anyMatch(
1944 roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
1945 if (checkIfFunctionsExits) {
1946 finalUserAppRolesList.add(role);
1947 List<RoleFunction> filteredList = roleFunList.stream()
1948 .filter(x -> "Approver".equalsIgnoreCase(x.getType()))
1949 .collect(Collectors.toList());
1950 roleNames = filteredList.stream().map(RoleFunction::getCode)
1951 .collect(Collectors.toList());
1954 for (String name : roleNames) {
1955 EcompRole ecompRole = appRolesList.stream()
1956 .filter(x -> name.equals(x.getName())).findAny().orElse(null);
1957 if (ecompRole != null)
1958 finalUserAppRolesList.add(ecompRole);
1963 for (String name : roleNames) {
1965 boolean checkIfFunctionsExits = userAppsRolesList.stream().anyMatch(
1966 role -> role.getRoleName().equalsIgnoreCase(name));
1967 if(checkIfFunctionsExits)
1969 EcompRole epRole = appRolesList.stream().filter(x -> name.equals(x.getName()))
1970 .findAny().orElse(null);
1972 setUserRoles.add(epRole);
1976 userAppRoles = setUserRoles.toArray(new EcompRole[setUserRoles.size()]);
1979 userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
1980 String.format("/user/%s/roles", userId));
1982 } catch (HTTPException e) {
1983 // Some apps are returning 400 if user is not found.
1984 if (e.getResponseCode() == 400) {
1985 logger.debug(EELFLoggerDelegate.debugLogger,
1986 "getAppRolesForUser caught exception with response code 400; continuing", e);
1988 // Other response code, let it come thru.
1992 if (userAppRoles == null) {
1993 if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
1994 EcompPortalUtils.setExternalAppResponseCode(200);
1995 String message = String.format(
1996 "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
1997 + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
1998 + "Overriding to 200 until framework SDK returns a useful response.",
1999 Long.toString(appId), userId);
2000 logger.warn(EELFLoggerDelegate.applicationLogger, message);
2004 HashMap<Long, EcompRole> appRolesActiveMap =hashMapFromEcompRoles(appRoles);
2005 ArrayList<EcompRole> activeRoles = new ArrayList<EcompRole>();
2006 if(userAppRoles != null){
2007 for (int i = 0; i < userAppRoles.length; i++) {
2008 if (appRolesActiveMap.containsKey(userAppRoles[i].getId())) {
2009 EcompRole role = new EcompRole();
2010 role.setId(userAppRoles[i].getId());
2011 role.setName(userAppRoles[i].getName());
2012 activeRoles.add(role);
2016 EcompRole[] userAppRolesActive = activeRoles.toArray(new EcompRole[activeRoles.size()]);
2018 // If the remote application isn't down we MUST sync user
2019 // roles here in case we have this user here!
2020 syncUserRoles(sessionFactory, userId, appId, userAppRolesActive, extRequestValue, null);
2021 } catch (Exception e) {
2022 // TODO: we may need to check if user exists, maybe remote
2024 String message = String.format(
2025 "getAppRolesForUser: user %s does not exist in remote application %s", userId,
2026 Long.toString(appId));
2027 logger.error(EELFLoggerDelegate.errorLogger, message, e);
2028 userAppRoles = new EcompRole[0];
2030 rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
2032 } catch (Exception e) {
2033 String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
2034 Long.toString(appId));
2035 logger.error(EELFLoggerDelegate.errorLogger, message, e);
2037 return rolesInAppForUser;
2040 private boolean postUserRolesToMylogins(AppWithRolesForUser userAppRolesData,
2041 ApplicationsRestClientService applicationsRestClientService, Long appId, Long userId)
2042 throws JsonProcessingException, HTTPException {
2043 boolean result = false;
2044 ObjectMapper mapper = new ObjectMapper();
2045 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
2046 String userRolesAsString = mapper.writeValueAsString(userAppRolesData);
2047 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, as the endpoint is not defined yet from the Mylogins");
2048 applicationsRestClientService.post(AppWithRolesForUser.class, appId, userRolesAsString, String.format("/user/%s/myLoginroles", userId));
2052 @SuppressWarnings("unchecked")
2053 public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser userAppRolesData, EPUser user) {
2054 FieldsValidator fieldsValidator = new FieldsValidator();
2055 final Map<String, Long> params = new HashMap<>();
2056 List<EPUserAppRoles> appRole= null;
2058 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, still the endpoint is yet to be defined");
2059 boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService,
2060 userAppRolesData.getAppId(), user.getId());
2061 logger.debug(EELFLoggerDelegate.debugLogger,"putUserAppRolesRequest: result {}", result);
2063 params.put("appId", userAppRolesData.getAppId());
2064 EPUserAppRolesRequest epAppRolesRequestData = new EPUserAppRolesRequest();
2065 epAppRolesRequestData.setCreatedDate(new Date());
2066 epAppRolesRequestData.setUpdatedDate(new Date());
2067 epAppRolesRequestData.setUserId(user.getId());
2068 epAppRolesRequestData.setAppId(userAppRolesData.getAppId());
2069 epAppRolesRequestData.setRequestStatus("P");
2070 List<RoleInAppForUser> appRoleIdList = userAppRolesData.getAppRoles();
2071 Set<EPUserAppRolesRequestDetail> appRoleDetails = new LinkedHashSet<EPUserAppRolesRequestDetail>();
2072 dataAccessService.saveDomainObject(epAppRolesRequestData, null);
2073 for (RoleInAppForUser userAppRoles : appRoleIdList) {
2074 Boolean isAppliedVal = userAppRoles.isApplied;
2075 params.put("appRoleId", userAppRoles.roleId);
2077 appRole = (List<EPUserAppRoles>) dataAccessService.executeNamedQuery("appRoles", params, null);
2078 if (!appRole.isEmpty()) {
2079 EPUserAppRolesRequestDetail epAppRoleDetail = new EPUserAppRolesRequestDetail();
2080 epAppRoleDetail.setReqRoleId(appRole.get(0).getRoleId());
2081 epAppRoleDetail.setReqType("P");
2082 epAppRoleDetail.setEpRequestIdData(epAppRolesRequestData);
2083 dataAccessService.saveDomainObject(epAppRoleDetail, null);
2087 epAppRolesRequestData.setEpRequestIdDetail(appRoleDetails);
2088 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
2090 } catch (Exception e) {
2091 logger.error(EELFLoggerDelegate.errorLogger, "putUserAppRolesRequest failed", e);
2092 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
2094 return fieldsValidator;
2097 public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(EPUser userid, String appName) {
2098 Map<String, String> params = new HashMap<>();
2099 params.put("userid", userid.getId().toString());
2100 //params.put("appid", appid);
2101 params.put("appName", appName);
2103 @SuppressWarnings("unchecked")
2104 List<EPUserAppCatalogRoles> userAppRoles = (List<EPUserAppCatalogRoles>) dataAccessService
2105 .executeNamedQuery("userAppCatalogRoles", params, null);
2106 return userAppRoles;
2109 public String updateRemoteUserProfile(String orgUserId, Long appId) {
2110 ObjectMapper mapper = new ObjectMapper();
2111 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
2112 EPUser client = searchService.searchUserByUserId(orgUserId);
2113 EPUser newUser = new EPUser();
2114 newUser.setActive(client.getActive());
2115 newUser.setFirstName(client.getFirstName());
2116 newUser.setLastName(client.getLastName());
2117 newUser.setLoginId(client.getLoginId());
2118 newUser.setLoginPwd(client.getLoginPwd());
2119 newUser.setMiddleInitial(client.getMiddleInitial());
2120 newUser.setEmail(client.getEmail());
2121 newUser.setOrgUserId(client.getLoginId());
2123 String userAsString = mapper.writeValueAsString(newUser);
2124 List<EPApp> appList = appsService.getUserRemoteApps(client.getId().toString());
2125 // applicationsRestClientService.post(EPUser.class, appId,
2126 // userAsString, String.format("/user", orgUserId));
2127 for (EPApp eachApp : appList) {
2129 applicationsRestClientService.post(EPUser.class, eachApp.getId(), userAsString,
2130 String.format("/user/%s", orgUserId));
2131 } catch (Exception e) {
2132 logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId()
2133 + " in remote app. appId = " + eachApp.getId());
2136 } catch (Exception e) {
2137 logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
2148 * @see org.onap.portalapp.portal.service.UserRolesService#
2149 * getCachedAppRolesForUser(java.lang.Long, java.lang.Long)
2151 @SuppressWarnings("deprecation")
2152 public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId) {
2153 // Find the records for this user-app combo, if any
2154 String filter = " where user_id = " + Long.toString(userId) + " and app_id = " + Long.toString(appId);
2155 @SuppressWarnings("unchecked")
2156 List<EPUserApp> roleList = dataAccessService.getList(EPUserApp.class, filter, null, null);
2157 logger.debug(EELFLoggerDelegate.debugLogger, "getCachedAppRolesForUser: list size is {}", roleList.size());
2162 * It retrieves and returns list of user app roles for local and remote applications based app id
2165 * @return list of user app roles
2166 * @throws HTTPException
2168 public List<UserApplicationRoles> getUsersFromAppEndpoint(Long appId) throws HTTPException {
2169 ArrayList<UserApplicationRoles> userApplicationRoles = new ArrayList<UserApplicationRoles>();
2171 EPApp app = appsService.getApp(appId);
2172 //If local or centralized application
2173 if (appId == PortalConstants.PORTAL_APP_ID || app.getCentralAuth()) {
2174 @SuppressWarnings("unchecked")
2175 List<EPUser> userList = (List<EPUser>) dataAccessService.executeNamedQuery("getActiveUsers", null, null);
2176 for (EPUser user : userList) {
2177 UserApplicationRoles userWithAppRoles = convertToUserApplicationRoles(appId, user, app);
2178 if (userWithAppRoles.getRoles() != null && userWithAppRoles.getRoles().size() > 0)
2179 userApplicationRoles.add(userWithAppRoles);
2185 RemoteUserWithRoles[] remoteUsers = null;
2186 String remoteUsersString = applicationsRestClientService.getIncomingJsonString(appId, "/users");
2188 remoteUsers = doGetUsers(isAppUpgradeVersion(app), remoteUsersString);
2190 userApplicationRoles = new ArrayList<UserApplicationRoles>();
2191 for (RemoteUserWithRoles remoteUser : remoteUsers) {
2192 UserApplicationRoles userWithRemoteAppRoles = convertToUserApplicationRoles(appId, remoteUser);
2193 if (userWithRemoteAppRoles.getRoles() != null && userWithRemoteAppRoles.getRoles().size() > 0) {
2194 userApplicationRoles.add(userWithRemoteAppRoles);
2196 logger.debug(EELFLoggerDelegate.debugLogger,
2197 "User " + userWithRemoteAppRoles.getOrgUserId() + " doesn't have any roles assigned to any app.");
2202 return userApplicationRoles;
2209 * @param appgetUsersFromAppEndpoint
2212 private UserApplicationRoles convertToUserApplicationRoles(Long appId, EPUser user, EPApp app) {
2213 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
2214 userWithRemoteAppRoles.setAppId(appId);
2215 userWithRemoteAppRoles.setOrgUserId(user.getOrgUserId());
2216 userWithRemoteAppRoles.setFirstName(user.getFirstName());
2217 userWithRemoteAppRoles.setLastName(user.getLastName());
2218 userWithRemoteAppRoles.setRoles(convertToRemoteRoleList(user, app));
2219 return userWithRemoteAppRoles;
2228 @SuppressWarnings("unchecked")
2229 private List<RemoteRole> convertToRemoteRoleList(EPUser user, EPApp app) {
2230 List<RemoteRole> roleList = new ArrayList<RemoteRole>();
2231 SortedSet<EPRole> roleSet = user.getAppEPRoles(app);
2232 for (EPRole role : roleSet) {
2233 logger.debug(EELFLoggerDelegate.debugLogger, "In convertToRemoteRoleList() - for user {}, found Name {}", user.getOrgUserId(), role.getName());
2234 RemoteRole rRole = new RemoteRole();
2235 rRole.setId(role.getId());
2236 rRole.setName(role.getName());
2237 roleList.add(rRole);
2240 //Get the active roles of user for that application using query
2241 List<EPRole> userEpRoleList = new ArrayList<>();
2242 final Map<String, Long> params = new HashMap<>();
2243 params.put("appId", app.getId());
2244 params.put("userId", user.getId());
2245 userEpRoleList = dataAccessService.executeNamedQuery("getUserRoleOnUserIdAndAppId", params, null);
2247 for (EPRole remoteUserRoleList : userEpRoleList) {
2249 RemoteRole remoteRoleListId = roleList.stream().filter(x -> remoteUserRoleList.getId().equals(x.getId()))
2250 .findAny().orElse(null);
2251 if (remoteRoleListId == null) {
2252 logger.debug(EELFLoggerDelegate.debugLogger,
2253 "Adding the role to the rolelist () - for user {}, found Name {}", user.getOrgUserId(),
2255 remoteUserRoleList.getName());
2256 RemoteRole role = new RemoteRole();
2257 role.setId(remoteUserRoleList.getId());
2258 role.setName(remoteUserRoleList.getName());
2265 logger.debug(EELFLoggerDelegate.debugLogger, "rolelist size of the USER() - for user {}, found RoleListSize {}", user.getOrgUserId(), roleList.size());
2273 public RemoteUserWithRoles[] doGetUsers(boolean postOpenSource, String remoteUsersString) {
2275 ObjectMapper mapper = new ObjectMapper();
2277 return mapper.readValue(remoteUsersString, RemoteUserWithRoles[].class);
2278 } catch (IOException e) {
2279 logger.error(EELFLoggerDelegate.errorLogger,
2280 "doGetUsers : Failed : Unexpected property in incoming JSON",
2282 logger.error(EELFLoggerDelegate.errorLogger,
2283 "doGetUsers : Incoming JSON that caused it --> " + remoteUsersString);
2286 return new RemoteUserWithRoles[0];
2289 @SuppressWarnings("unchecked")
2290 public List<EPUserApp> getEPUserAppList(Long appId, Long userId, Long roleId) {
2291 List<EPUserApp> userRoleList = new ArrayList<EPUserApp>();
2292 final Map<String, Long> params = new HashMap<>();
2293 params.put("appId", appId);
2294 params.put("userId", userId);
2295 params.put("roleId", roleId);
2296 userRoleList = dataAccessService.executeNamedQuery("getUserRoleOnUserIdAndRoleIdAndAppId", params, null);
2297 return userRoleList;
2301 /*public static void main(String[] args) {
2302 List<EcompRole> str1 = new ArrayList<String>();
2308 List<String> str2 = new ArrayList<String>();
2312 List<EcompRole> userApplicationRolesList = setUserRoles;
2313 List<EcompRole> appRolesList = Arrays.asList(appRoles);