2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
8 * Unless otherwise specified, all software contained herein is licensed
9 * under the Apache License, Version 2.0 (the "License");
10 * you may not use this software except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * Unless otherwise specified, all documentation contained herein is licensed
22 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23 * you may not use this documentation except in compliance with the License.
24 * You may obtain a copy of the License at
26 * https://creativecommons.org/licenses/by/4.0/
28 * Unless required by applicable law or agreed to in writing, documentation
29 * distributed under the License is distributed on an "AS IS" BASIS,
30 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31 * See the License for the specific language governing permissions and
32 * limitations under the License.
34 * ============LICENSE_END============================================
39 package org.onap.portalapp.portal.service;
41 import java.io.IOException;
42 import java.util.ArrayList;
43 import java.util.Arrays;
44 import java.util.Collection;
45 import java.util.Date;
46 import java.util.HashMap;
47 import java.util.HashSet;
48 import java.util.LinkedHashSet;
49 import java.util.List;
52 import java.util.SortedSet;
53 import java.util.TreeSet;
54 import java.util.stream.Collectors;
56 import javax.servlet.http.HttpServletResponse;
58 import org.apache.commons.lang.StringUtils;
59 import org.apache.cxf.transport.http.HTTPException;
60 import org.hibernate.SQLQuery;
61 import org.hibernate.Session;
62 import org.hibernate.SessionFactory;
63 import org.hibernate.Transaction;
64 import org.json.JSONArray;
65 import org.json.JSONObject;
66 import org.onap.portalapp.externalsystemapproval.model.ExternalSystemRoleApproval;
67 import org.onap.portalapp.externalsystemapproval.model.ExternalSystemUser;
68 import org.onap.portalapp.portal.domain.CentralV2RoleFunction;
69 import org.onap.portalapp.portal.domain.EPApp;
70 import org.onap.portalapp.portal.domain.EPRole;
71 import org.onap.portalapp.portal.domain.EPUser;
72 import org.onap.portalapp.portal.domain.EPUserApp;
73 import org.onap.portalapp.portal.domain.EPUserAppCatalogRoles;
74 import org.onap.portalapp.portal.domain.EPUserAppRoles;
75 import org.onap.portalapp.portal.domain.EPUserAppRolesRequest;
76 import org.onap.portalapp.portal.domain.EPUserAppRolesRequestDetail;
77 import org.onap.portalapp.portal.domain.ExternalSystemAccess;
78 import org.onap.portalapp.portal.exceptions.SyncUserRolesException;
79 import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
80 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
81 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
82 import org.onap.portalapp.portal.transport.AppWithRolesForUser;
83 import org.onap.portalapp.portal.transport.CentralV2Role;
84 import org.onap.portalapp.portal.transport.EPUserAppCurrentRoles;
85 import org.onap.portalapp.portal.transport.EcompUserAppRoles;
86 import org.onap.portalapp.portal.transport.ExternalAccessUser;
87 import org.onap.portalapp.portal.transport.ExternalAccessUserRoleDetail;
88 import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator;
89 import org.onap.portalapp.portal.transport.ExternalRoleDescription;
90 import org.onap.portalapp.portal.transport.FieldsValidator;
91 import org.onap.portalapp.portal.transport.FunctionalMenuItem;
92 import org.onap.portalapp.portal.transport.FunctionalMenuRole;
93 import org.onap.portalapp.portal.transport.RemoteRole;
94 import org.onap.portalapp.portal.transport.RemoteRoleV1;
95 import org.onap.portalapp.portal.transport.RemoteUserWithRoles;
96 import org.onap.portalapp.portal.transport.RoleInAppForUser;
97 import org.onap.portalapp.portal.transport.RolesInAppForUser;
98 import org.onap.portalapp.portal.transport.UserApplicationRoles;
99 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
100 import org.onap.portalapp.portal.utils.EcompPortalUtils;
101 import org.onap.portalapp.portal.utils.PortalConstants;
102 import org.onap.portalapp.util.EPUserUtils;
103 import org.onap.portalapp.util.SystemType;
104 import org.onap.portalsdk.core.domain.Role;
105 import org.onap.portalsdk.core.domain.RoleFunction;
106 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
107 import org.onap.portalsdk.core.restful.domain.EcompRole;
108 import org.onap.portalsdk.core.service.DataAccessService;
109 import org.onap.portalsdk.core.service.RoleService;
110 import org.onap.portalsdk.core.util.SystemProperties;
111 import org.springframework.beans.factory.annotation.Autowired;
112 import org.springframework.http.HttpEntity;
113 import org.springframework.http.HttpHeaders;
114 import org.springframework.http.HttpMethod;
115 import org.springframework.http.HttpStatus;
116 import org.springframework.http.ResponseEntity;
117 import org.springframework.web.client.HttpClientErrorException;
118 import org.springframework.web.client.RestTemplate;
120 import com.fasterxml.jackson.core.JsonProcessingException;
121 import com.fasterxml.jackson.databind.DeserializationFeature;
122 import com.fasterxml.jackson.databind.ObjectMapper;
125 public class UserRolesCommonServiceImpl {
127 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesCommonServiceImpl.class);
129 private static final Object syncRests = new Object();
131 private static final String APP_ID = "appId";
134 private DataAccessService dataAccessService;
136 private SessionFactory sessionFactory;
138 private SearchService searchService;
140 private EPAppService appsService;
142 private ApplicationsRestClientService applicationsRestClientService;
144 private EPRoleService epRoleService;
146 private RoleService roleService;
148 private AdminRolesService adminRolesService;
150 private EPAppService appService;
152 private ExternalAccessRolesService externalAccessRolesService;
155 private AppsCacheService appsCacheService;
157 RestTemplate template = new RestTemplate();
162 * @return HashMap<Long, EcompRole>
164 private static HashMap<Long, EcompRole> hashMapFromEcompRoles(EcompRole[] ecompRoles) {
165 HashMap<Long, EcompRole> result = new HashMap<Long, EcompRole>();
166 if (ecompRoles != null) {
167 for (int i = 0; i < ecompRoles.length; i++) {
168 if (ecompRoles[i].getId() != null) {
169 result.put(ecompRoles[i].getId(), ecompRoles[i]);
180 protected void createLocalUserIfNecessary(String userId,boolean isSystemUser) {
181 if (StringUtils.isEmpty(userId)) {
182 logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty userId!");
185 Session localSession = null;
186 Transaction transaction = null;
188 localSession = sessionFactory.openSession();
189 transaction = localSession.beginTransaction();
190 @SuppressWarnings("unchecked")
191 List<EPUser> userList = localSession
192 .createQuery("from :name where orgUserId=:userId")
193 .setParameter("name",EPUser.class.getName())
194 .setParameter("userId",userId)
196 if (userList.size() == 0) {
197 EPUser client = null;
199 client = searchService.searchUserByUserId(userId);
201 client = new EPUser();
202 client.setOrgUserId(userId);
203 client.setSystemUser(true);
204 client.setFirstName(userId.substring(0,userId.indexOf("@")));
206 if (client == null) {
207 String msg = "createLocalUserIfNecessary: cannot create user " + userId
208 + ", because not found in phonebook";
209 logger.error(EELFLoggerDelegate.errorLogger, msg);
211 client.setLoginId(userId);
212 client.setActive(true);
213 localSession.save(client);
216 transaction.commit();
217 } catch (Exception e) {
218 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
219 EcompPortalUtils.rollbackTransaction(transaction, "searchOrCreateUser rollback, exception = " + e);
221 EcompPortalUtils.closeLocalSession(localSession, "searchOrCreateUser");
226 * This method return nothing and remove roles before adding any roles for an app
229 * @param localSession
230 * @param userAppRoles
231 * @param newUserAppRolesMap
233 private static void syncUserRolesExtension(EPUserApp userRole, Long appId, Session localSession, EcompRole[] userAppRoles, HashMap<Long, EcompRole> newUserAppRolesMap) {
235 Long userAppRoleId = 0L;
236 if (appId == PortalConstants.PORTAL_APP_ID) { // local app
237 userAppRoleId = userRole.getRoleId();
238 } else { // remote app
239 userAppRoleId = userRole.getAppRoleId();
242 if (!newUserAppRolesMap.containsKey(userAppRoleId)) {
243 localSession.delete(userRole);
245 newUserAppRolesMap.remove(userAppRoleId);
250 * Checks whether the role is inactive
254 * if role is inactive, throws exception
256 private void checkIfRoleInactive(EPRole epRole) throws Exception{
257 if(!epRole.getActive()){
258 throw new Exception(epRole.getName()+ " role is unavailable");
264 * @param sessionFactory
267 * @param userAppRoles
268 * @param extRequestValue
269 * set to false if request is from users page otherwise true
272 protected void syncUserRoles(SessionFactory sessionFactory, String userId, Long appId,
273 EcompRole[] userAppRoles, Boolean extRequestValue, String reqType) throws Exception {
274 Session localSession = null;
275 Transaction transaction = null;
276 String roleActive = null;
277 final Map<String, String> userAppParams = new HashMap<>();
278 final Map<String, String> appParams = new HashMap<>();
279 HashMap<Long, EcompRole> newUserAppRolesMap = hashMapFromEcompRoles(userAppRoles);
282 localSession = sessionFactory.openSession();
283 transaction = localSession.beginTransaction();
284 @SuppressWarnings("unchecked")
285 List<EPUser> userList = localSession
286 .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + userId + "'").list();
287 if (userList.size() > 0) {
288 EPUser client = userList.get(0);
289 roleActive = ("DELETE".equals(reqType)) ? "" : " and role.active = 'Y'";
290 @SuppressWarnings("unchecked")
291 List<EPUserApp> userRoles = localSession.createQuery("from " + EPUserApp.class.getName()
292 + " where app.id=" + appId + roleActive + " and userId=" + client.getId()).list();
294 if ("DELETE".equals(reqType)) {
295 for (EPUserApp userAppRoleList : userRoles) {
296 userAppParams.put("roleName", String.valueOf(userAppRoleList.getRole().getName()));
297 userAppParams.put("appId", String.valueOf(appId));
298 appParams.put("appRoleName", userAppRoleList.getRole().getName());
299 @SuppressWarnings("unchecked")
300 List<EPRole> rolesList = (!userAppRoleList.getRole().getName().equals(PortalConstants.ADMIN_ROLE)) ? (List<EPRole>) dataAccessService.executeNamedQuery("getAppRoles", userAppParams, null) : (List<EPRole>) dataAccessService.executeNamedQuery("getPortalAppRoles", appParams, null);
301 if(rolesList.size() > 0 || !rolesList.isEmpty()){
302 checkIfRoleInactive(rolesList.get(0));
307 for (EPUserApp userRole : userRoles) {
308 if (!userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && userRole.getRoleId() != PortalConstants.SYS_ADMIN_ROLE_ID && !extRequestValue){
309 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
311 else if (extRequestValue && ("PUT".equals(reqType) || "POST".equals(reqType) || "DELETE".equals(reqType))){
312 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
314 else if (extRequestValue && !userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)){
315 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
318 Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values();
319 if (newRolesToAdd.size() > 0) {
320 EPApp app = (EPApp) localSession.get(EPApp.class, appId);
322 HashMap<Long, EPRole> rolesMap = new HashMap<Long, EPRole>();
323 if (appId.equals(PortalConstants.PORTAL_APP_ID)) { // local app
324 String appIdValue = "";
325 if(!extRequestValue){
326 appIdValue = "and id != " + PortalConstants.SYS_ADMIN_ROLE_ID;
328 @SuppressWarnings("unchecked")
329 List<EPRole> roles = localSession
330 .createQuery("from " + EPRole.class.getName() + " where appId is null " + appIdValue).list();
331 for (EPRole role : roles) {
333 rolesMap.put(role.getId(), role);
335 } else { // remote app
336 @SuppressWarnings("unchecked")
337 List<EPRole> roles = localSession
338 .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list();
339 for (EPRole role : roles) {
340 if (!extRequestValue && app.getCentralAuth()) {
341 rolesMap.put(role.getId(), role);
343 rolesMap.put(role.getAppRoleId(), role);
349 for (EcompRole userRole : newRolesToAdd) {
350 EPUserApp userApp = new EPUserApp();
351 if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName().equals(PortalConstants.ADMIN_ROLE)) {
352 role = (EPRole) localSession.get(EPRole.class, new Long(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
353 userApp.setRole(role);
354 } else if ((userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) && !extRequestValue){
356 }else if((userRole.getId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)) && app.getId().equals(PortalConstants.PORTAL_APP_ID) && !extRequestValue){
360 userApp.setRole(rolesMap.get(userRole.getId()));
363 userApp.setUserId(client.getId());
365 localSession.save(userApp);
366 localSession.flush();
369 if (appId == PortalConstants.PORTAL_APP_ID) {
371 * for local app -- hack - always make sure fn_role
372 * table's app_id is null and not 1 for primary app in
373 * this case being onap portal app; reason: hibernate
374 * is rightly setting this to 1 while persisting to
375 * fn_role as per the mapping but SDK role management
376 * code expects the app_id to be null as there is no
377 * concept of App_id in SDK
379 localSession.flush();
380 SQLQuery sqlQuery = localSession
381 .createSQLQuery("update fn_role set app_id = null where app_id = 1 ");
382 sqlQuery.executeUpdate();
387 transaction.commit();
388 } catch (Exception e) {
389 logger.error(EELFLoggerDelegate.errorLogger, "syncUserRoles failed", e);
390 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
391 EcompPortalUtils.rollbackTransaction(transaction,
392 "Exception occurred in syncUserRoles, Details: " + e.toString());
393 if("DELETE".equals(reqType)){
394 throw new SyncUserRolesException(e.getMessage());
397 if(localSession != null)
398 localSession.close();
403 * Called when getting the list of roles for the user
406 * @param userAppRoles
407 * @return List<RoleInAppForUser>
409 protected List<RoleInAppForUser> constructRolesInAppForUserGet(EcompRole[] appRoles, EcompRole[] userAppRoles) {
410 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
412 Set<Long> userAppRolesMap = new HashSet<Long>();
413 if (userAppRoles != null) {
414 for (EcompRole ecompRole : userAppRoles) {
415 userAppRolesMap.add(ecompRole.getId());
418 logger.error(EELFLoggerDelegate.errorLogger,
419 "constructRolesInAppForUserGet has received userAppRoles list empty");
422 if (appRoles != null) {
423 for (EcompRole ecompRole : appRoles) {
424 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
425 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
426 rolesInAppForUser.add(roleForUser);
429 logger.error(EELFLoggerDelegate.errorLogger, "constructRolesInAppForUser has received appRoles list empty");
431 return rolesInAppForUser;
435 * Called when getting the list of roles for the user
438 * @param userAppRoles
439 * @param extRequestValue
440 * set to false if request is from users page otherwise true
441 * @return List<RoleInAppForUser>
443 protected List<RoleInAppForUser> constructRolesInAppForUserGet(List<Role> appRoles, EPRole[] userAppRoles, Boolean extRequestValue) {
444 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
446 Set<Long> userAppRolesMap = new HashSet<Long>();
447 if (userAppRoles != null) {
448 for (EPRole ecompRole : userAppRoles) {
449 userAppRolesMap.add(ecompRole.getId());
451 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - userAppRolesMap = {}", userAppRolesMap);
454 logger.error(EELFLoggerDelegate.errorLogger,
455 "constructRolesInAppForUserGet has received userAppRoles list empty.");
458 if (appRoles != null) {
460 for (Role ecompRole : appRoles) {
461 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - appRoles not null = {}", ecompRole);
463 if (ecompRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && !extRequestValue)
465 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
466 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
467 rolesInAppForUser.add(roleForUser);
468 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - rolesInAppForUser = {}", rolesInAppForUser);
472 logger.error(EELFLoggerDelegate.errorLogger,
473 "constructRolesInAppForUser has received appRoles list empty.");
475 return rolesInAppForUser;
480 * copies of methods in GetAppsWithUserRoleState
482 * @param sessionFactory
487 protected void syncAppRoles(SessionFactory sessionFactory, Long appId, EcompRole[] appRoles) throws Exception {
488 logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId);
489 HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles);
490 Session localSession = null;
491 Transaction transaction = null;
494 localSession = sessionFactory.openSession();
495 transaction = localSession.beginTransaction();
496 // Attention! All roles from remote application supposed to be
499 @SuppressWarnings("unchecked")
500 List<EPRole> currentAppRoles = localSession.createQuery("from :name where appId = :appId")
501 .setParameter("name",EPRole.class.getName())
502 .setParameter("appId",appId)
505 List<EPRole> obsoleteRoles = new ArrayList<EPRole>();
506 for (int i = 0; i < currentAppRoles.size(); i++) {
507 EPRole oldAppRole = currentAppRoles.get(i);
508 if (oldAppRole.getAppRoleId() != null) {
509 EcompRole role = null;
510 role = newRolesMap.get(oldAppRole.getAppRoleId());
512 if (!(role.getName() == null || oldAppRole.getName().equals(role.getName()))) {
513 oldAppRole.setName(role.getName());
514 localSession.update(oldAppRole);
516 oldAppRole.setActive(true);
517 newRolesMap.remove(oldAppRole.getAppRoleId());
519 obsoleteRoles.add(oldAppRole);
522 obsoleteRoles.add(oldAppRole);
525 Collection<EcompRole> newRolesToAdd = newRolesMap.values();
526 if (obsoleteRoles.size() > 0) {
527 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: we have obsolete roles to delete");
528 for (EPRole role : obsoleteRoles) {
529 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: obsolete role: " + role.toString());
530 Long roleId = role.getId();
531 // delete obsolete roles here
532 // Must delete all records with foreign key constraints on
534 // fn_user_role, fn_role_composite, fn_role_function,
535 // fn_user_pseudo_role, fn_menu_functional_roles.
536 // And for fn_menu_functional, if no other roles for that
537 // menu item, remove the url.
539 // Delete from fn_user_role
540 @SuppressWarnings("unchecked")
541 List<EPUserApp> userRoles = localSession.createQuery(
542 "from " + EPUserApp.class.getName() + " where app.id=" + appId + " and role_id=" + roleId)
545 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: number of userRoles to delete: " + userRoles.size());
546 for (EPUserApp userRole : userRoles) {
547 logger.debug(EELFLoggerDelegate.debugLogger,
548 "syncAppRoles: about to delete userRole: " + userRole.toString());
549 localSession.delete(userRole);
550 logger.debug(EELFLoggerDelegate.debugLogger,
551 "syncAppRoles: finished deleting userRole: " + userRole.toString());
554 // Delete from fn_menu_functional_roles
555 @SuppressWarnings("unchecked")
556 List<FunctionalMenuRole> funcMenuRoles = localSession
557 .createQuery("from " + FunctionalMenuRole.class.getName() + " where roleId=" + roleId)
559 int numMenuRoles = funcMenuRoles.size();
560 logger.debug(EELFLoggerDelegate.debugLogger,
561 "syncAppRoles: number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles);
562 for (FunctionalMenuRole funcMenuRole : funcMenuRoles) {
563 Long menuId = funcMenuRole.menuId;
564 // If this is the only role for this menu item, then the
565 // app and roles will be gone,
566 // so must null out the url too, to be consistent
567 @SuppressWarnings("unchecked")
568 List<FunctionalMenuRole> funcMenuRoles2 = localSession
569 .createQuery("from " + FunctionalMenuRole.class.getName() + " where menuId=" + menuId)
571 int numMenuRoles2 = funcMenuRoles2.size();
572 logger.debug(EELFLoggerDelegate.debugLogger,
573 "syncAppRoles: number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2);
574 localSession.delete(funcMenuRole);
575 if (numMenuRoles2 == 1) {
576 // If this is the only role for this menu item, then
577 // the app and roles will be gone,
578 // so must null out the url too, to be consistent
579 logger.debug(EELFLoggerDelegate.debugLogger,
580 "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url");
581 @SuppressWarnings("unchecked")
582 List<FunctionalMenuItem> funcMenuItems = localSession
584 "from " + FunctionalMenuItem.class.getName() + " where menuId=" + menuId)
586 if (funcMenuItems.size() > 0) {
587 logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item");
588 FunctionalMenuItem funcMenuItem = funcMenuItems.get(0);
589 funcMenuItem.url = "";
590 localSession.update(funcMenuItem);
594 boolean isPortalRequest = true;
595 externalAccessRolesService.deleteRoleDependencyRecords(localSession, roleId, appId, isPortalRequest);
596 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to delete the role: " + role.toString());
597 localSession.delete(role);
598 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: deleted the role");
601 for (EcompRole role : newRolesToAdd) {
602 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to add missing role: " + role.toString());
603 EPRole newRole = new EPRole();
604 // Attention! All roles from remote application supposed to be
606 newRole.setActive(true);
607 newRole.setName(role.getName());
608 newRole.setAppId(appId);
609 newRole.setAppRoleId(role.getId());
610 localSession.save(newRole);
612 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to commit the transaction");
613 transaction.commit();
614 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: committed the transaction");
615 } catch (Exception e) {
616 logger.error(EELFLoggerDelegate.errorLogger, "syncAppRoles failed", e);
617 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
618 EcompPortalUtils.rollbackTransaction(transaction,
619 "Exception occurred in syncAppRoles, Details: " + e.toString());
620 throw new Exception(e);
622 localSession.close();
631 * Called when updating the list of roles for the user
635 * @param userRolesInRemoteApp
636 * @return RolesInAppForUser
638 protected RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId,
639 Set<EcompRole> userRolesInRemoteApp) {
640 RolesInAppForUser result;
641 result = new RolesInAppForUser();
642 result.appId = appId;
643 result.orgUserId = userId;
645 for (EcompRole role : userRolesInRemoteApp) {
646 RoleInAppForUser roleInAppForUser = new RoleInAppForUser();
647 roleInAppForUser.roleId = role.getId();
648 roleInAppForUser.roleName = role.getName();
649 roleInAppForUser.isApplied = new Boolean(true);
650 result.roles.add(roleInAppForUser);
657 * @param roleInAppForUserList
660 protected boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) {
661 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
662 if (roleInAppForUser.isApplied.booleanValue()) {
670 * Builds JSON and posts it to a remote application to update user roles.
672 * @param roleInAppForUserList
674 * @param applicationsRestClientService
677 * @return Set of roles as sent; NOT the response from the app.
678 * @throws JsonProcessingException
679 * @throws HTTPException
681 protected Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
682 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId,boolean systemUser)
683 throws JsonProcessingException, HTTPException {
684 Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList);
685 Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList);
686 String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote);
687 EPApp externalApp = null;
688 SystemType type = SystemType.APPLICATION;
689 externalApp = appsCacheService.getApp(appId);
690 String appBaseUri = null;
691 Set<RemoteRoleV1> updatedUserRolesinRemoteV1 = new TreeSet<>();
692 if (externalApp != null) {
693 appBaseUri = (type == SystemType.APPLICATION) ? externalApp.getAppRestEndpoint() : "";
695 if(appBaseUri != null && appBaseUri.endsWith("/api")){
696 for(EcompRole eprole :updatedUserRolesinRemote)
698 RemoteRoleV1 role = new RemoteRoleV1();
699 role.setId(eprole.getId());
700 role.setName(eprole.getName());
701 updatedUserRolesinRemoteV1.add(role);
703 userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemoteV1);
705 applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString,
706 String.format("/user/%s/roles", userId));
707 // TODO: We should add code that verifies that the post operation did
708 // succeed. Because the SDK may still return 200 OK with an html page
709 // even when it fails!
710 return updateUserRolesInEcomp;
715 * @param roleInAppForUserList
716 * @return Set<EcompRole>
718 protected Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) {
719 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
720 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
721 if (roleInAppForUser.isApplied) {
722 EcompRole ecompRole = new EcompRole();
723 ecompRole.setId(roleInAppForUser.roleId);
724 ecompRole.setName(roleInAppForUser.roleName);
725 existingUserRoles.add(ecompRole);
728 return existingUserRoles;
732 * Constructs user app roles excluding Account Administrator role
734 * @param roleInAppForUserList
736 * List of roles with Role name, Role Id
738 protected Set<EcompRole> constructUsersRemoteAppRoles(List<RoleInAppForUser> roleInAppForUserList) {
739 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
740 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
741 if (roleInAppForUser.isApplied && !roleInAppForUser.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
742 EcompRole ecompRole = new EcompRole();
743 ecompRole.setId(roleInAppForUser.roleId);
744 ecompRole.setName(roleInAppForUser.roleName);
745 existingUserRoles.add(ecompRole);
748 return existingUserRoles;
752 * This is for a single app
754 * @param rolesInAppForUser
755 * @param externalSystemRequest
756 * set to false if requests from Users page otherwise true
757 * @return true on success, false otherwise
759 protected boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser, boolean externalSystemRequest, String reqType,boolean isSystemUser) throws Exception {
760 boolean result = false;
761 String userId = rolesInAppForUser.orgUserId;
762 Long appId = rolesInAppForUser.appId;
763 synchronized (syncRests) {
764 if (rolesInAppForUser != null) {
765 createLocalUserIfNecessary(userId, isSystemUser);
768 if (rolesInAppForUser != null) {
769 EcompRole[] userAppRoles = new EcompRole[rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size()];
770 for (int i = 0; i < rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size(); i++) {
771 RoleInAppForUser roleInAppForUser = rolesInAppForUser.roles.get(i);
772 EcompRole role = new EcompRole();
773 role.setId(roleInAppForUser.roleId);
774 role.setName(roleInAppForUser.roleName);
775 userAppRoles[i] = role;
778 syncUserRoles(sessionFactory, userId, appId, userAppRoles, externalSystemRequest, reqType);
780 } catch (Exception e) {
781 logger.error(EELFLoggerDelegate.errorLogger,
782 "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for orgUserId " + userId, e);
783 if("DELETE".equals(reqType)){
784 throw new Exception(e.getMessage());
796 * @return UserApplicationRoles
798 protected UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) {
799 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
800 userWithRemoteAppRoles.setAppId(appId);
801 userWithRemoteAppRoles.setOrgUserId(remoteUser.getOrgUserId());
802 userWithRemoteAppRoles.setFirstName(remoteUser.getFirstName());
803 userWithRemoteAppRoles.setLastName(remoteUser.getLastName());
804 userWithRemoteAppRoles.setRoles(remoteUser.getRoles());
805 return userWithRemoteAppRoles;
811 * @see org.onap.portalapp.portal.service.UserRolesService#
812 * importRolesFromRemoteApplication(java.lang.Long)
814 public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException {
815 EPRole[] appRolesFull = applicationsRestClientService.get(EPRole[].class, appId, "/rolesFull");
816 List<EPRole> rolesList = Arrays.asList(appRolesFull);
817 for (EPRole externalAppRole : rolesList) {
819 // Try to find an existing extern role for the app in the local
820 // onap DB. If so, then use its id to update the existing external
821 // application role record.
822 Long externAppId = externalAppRole.getId();
823 EPRole existingAppRole = epRoleService.getRole(appId, externAppId);
824 if (existingAppRole != null) {
825 logger.debug(EELFLoggerDelegate.debugLogger,
826 String.format("ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.",
827 appId, externAppId));
830 // persistExternalRoleInEcompDb(externalAppRole, appId,
838 * It adds new user for remote application
840 * @param roleInAppForUserList
841 * @param remoteAppUser
845 * @param searchService
846 * @param applicationsRestClientService
850 private EPUser addRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app,
851 ObjectMapper mapper, SearchService searchService,
852 ApplicationsRestClientService applicationsRestClientService) throws Exception {
853 EPUser addRemoteUser = null;
854 if (remoteUserShouldBeCreated(roleInAppForUserList)) {
855 createNewUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper,
856 isAppUpgradeVersion(app));
858 return addRemoteUser;
861 private EPUser pushRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app,
862 ObjectMapper mapper, SearchService searchService,
863 ApplicationsRestClientService applicationsRestClientService,boolean appRoleIdUsed) throws Exception {
864 EPUser addRemoteUser = null;
865 // if (remoteUserShouldBeCreated(roleInAppForUserList)) {
866 pushUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper,
867 isAppUpgradeVersion(app), roleInAppForUserList, appRoleIdUsed);
869 return addRemoteUser;
872 @SuppressWarnings("unchecked")
873 protected void pushUserOnRemoteApp(String userId, EPApp app,
874 ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
875 ObjectMapper mapper, boolean postOpenSource, List<RoleInAppForUser> roleInAppForUserList,boolean appRoleIdUsed) throws Exception {
877 EPUser client = null;
878 client = searchService.searchUserByUserId(userId);
880 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
881 if (client == null) {
882 String msg = "cannot create user " + userId + ", because he/she cannot be found in directory.";
883 logger.error(EELFLoggerDelegate.errorLogger, msg);
884 // throw new Exception(msg);
885 final Map<String, String> loginIdParams = new HashMap<>();
886 loginIdParams.put("orgUserIdValue", userId);
887 List<EPUser> userList = new ArrayList<>();
888 userList = dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null);
889 if (userList.size() > 0) {
890 logger.debug(EELFLoggerDelegate.debugLogger,
891 userList.get(0).getOrgUserId() + " User was found in Portal");
892 client = userList.get(0);
893 SortedSet<EPUserApp> userApps = new TreeSet<>();
894 client.setEPUserApps(userApps);
895 client.setSystemUser(false);
897 logger.error(EELFLoggerDelegate.errorLogger, "user cannot be found be in directory or in portal");
898 throw new Exception(msg);
903 client.setLoginId(userId);
904 client.setActive(true);
905 client.setOrgUserId(userId);
908 roleInAppForUserList.removeIf(role -> role.isApplied.equals(false));
909 SortedSet<Role> roles = new TreeSet<>();
911 List<EPRole> getAppRoles = externalAccessRolesService.getAppRoles(app.getId());
912 List<EPApp> appList = new ArrayList<>();
914 List<CentralV2Role> roleList = new ArrayList<>();
915 Map<String, Long> params = new HashMap<>();
917 List<EPRole> userRoles = new ArrayList<>();
919 for (RoleInAppForUser roleInappForUser : roleInAppForUserList) {
920 EPRole role = new EPRole();
921 role.setId(roleInappForUser.getRoleId());
922 role.setName(roleInappForUser.getRoleName());
927 List<EPRole> userAppRoles = new ArrayList<>();
928 for (EPRole role : userRoles) {
929 EPRole appRole = getAppRoles.stream()
930 .filter(applicationRole -> role.getId().equals(applicationRole.getAppRoleId())).findAny()
932 EPRole epRole = new EPRole();
933 if (appRole != null) {
934 epRole.setId(appRole.getId());
935 epRole.setName(appRole.getName());
937 userAppRoles.add(epRole);
939 userRoles = new ArrayList<>();
940 userRoles.addAll(userAppRoles);
942 roleList = externalAccessRolesService.createCentralRoleObject(appList, userRoles, roleList, params);
944 for (CentralV2Role epRole : roleList) {
945 Role role = new Role();
946 EPRole appRole = getAppRoles.stream()
947 .filter(applicationRole -> epRole.getId().equals(applicationRole.getId())).findAny().orElse(null);
948 if (appRole != null){
949 role.setId(appRole.getAppRoleId());
950 role.setName(epRole.getName());
951 role.setRoleFunctions(epRole.getRoleFunctions());
955 client.setRoles(roles);
956 String userInString = null;
957 userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
958 logger.debug(EELFLoggerDelegate.debugLogger,
959 "about to post a client to remote application, users json = " + userInString);
960 applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user/%s", userId));
964 * It checks whether the remote user exists or not
965 * if exits returns user object else null
969 * @param applicationsRestClientService
971 * @throws HTTPException
973 private EPUser checkIfRemoteUserExits(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService) throws HTTPException{
974 EPUser checkRemoteUser = null;
976 checkRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
977 } catch (HTTPException e) {
978 // Some apps are returning 400 if user is not found.
979 if (e.getResponseCode() == 400) {
980 logger.debug(EELFLoggerDelegate.debugLogger,
981 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing",
983 } else if(e.getResponseCode() == 404) {
984 logger.debug(EELFLoggerDelegate.debugLogger,
985 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 404; continuing",
988 // Other response code, let it come thru.
992 return checkRemoteUser;
999 * @see org.onap.portalapp.portal.service.UserRolesService#
1000 * setAppWithUserRoleStateForUser(org.onap.portalapp.portal.domain.
1001 * EPUser, org.onap.portalapp.portal.transport.AppWithRolesForUser)
1003 public ExternalRequestFieldsValidator setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser) {
1004 boolean result = false;
1005 boolean epRequestValue = false;
1007 String reqMessage = "";
1008 if (newAppRolesForUser != null && newAppRolesForUser.getOrgUserId() != null) {
1009 userId = newAppRolesForUser.getOrgUserId().trim();
1011 Long appId = newAppRolesForUser.getAppId();
1012 List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.getAppRoles();
1013 if (userId.length() > 0 ) {
1014 ObjectMapper mapper = new ObjectMapper();
1015 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1018 EPApp app = appsService.getApp(appId);
1019 applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
1021 boolean systemUser = newAppRolesForUser.isSystemUser();
1022 if ((app.getCentralAuth() || app.getId().equals(PortalConstants.PORTAL_APP_ID)) && systemUser) {
1024 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1025 applicationsRestClientService, appId, userId);
1026 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1027 userRolesInLocalApp);
1028 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1029 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1030 // Apply changes in external Access system
1031 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList,
1032 epRequestValue, systemUser);
1034 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal",
1037 }else if (!app.getCentralAuth() && systemUser)
1039 throw new Exception("For non-centralized application we cannot add systemUser");
1041 else{ // if centralized app
1042 if (app.getCentralAuth()) {
1043 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1044 pushRemoteUser(roleInAppForUserList, userId, app, mapper, searchService,
1045 applicationsRestClientService,false);
1048 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1049 applicationsRestClientService, appId, userId);
1050 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1051 userRolesInLocalApp);
1052 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1053 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1054 // Apply changes in external Access system
1055 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList,
1056 epRequestValue,false);
1058 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal", systemUser);
1060 // In case if portal is not centralized then follow existing approach
1061 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1062 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1063 applicationsRestClientService, appId, userId);
1064 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1065 userRolesInLocalApp);
1066 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal",false);
1067 } else{// remote app
1068 EPUser remoteAppUser = null;
1069 if(!app.getCentralAuth() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1071 remoteAppUser = checkIfRemoteUserExits(userId, app, applicationsRestClientService);
1073 if (remoteAppUser == null) {
1074 remoteAppUser = addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService, applicationsRestClientService);
1076 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
1077 applicationsRestClientService, appId, userId,systemUser);
1078 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1079 userRolesInRemoteApp);
1080 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null,false);
1082 // If no roles remain, request app to set user inactive.
1083 if (userRolesInRemoteApp.size() == 0) {
1084 logger.debug(EELFLoggerDelegate.debugLogger,
1085 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
1087 //remoteAppUser.setActive(false);
1088 postUserToRemoteApp(userId, user, app, applicationsRestClientService);
1093 } catch (Exception e) {
1094 /*String message = String.format(
1095 "Failed to create user or update user roles for User %s, AppId %s",
1096 userId, Long.toString(appId));
1097 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1100 String message = String.format(
1101 "Failed to create user or update user roles for User %s, AppId %s",
1102 userId, Long.toString(appId));
1103 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1105 reqMessage = e.getMessage();
1112 return new ExternalRequestFieldsValidator(result, reqMessage);
1116 * It adds user roles in External system and also make data consistent in both local and in External System
1118 * @param app details
1120 * @param roleInAppUser Contains list of active roles
1122 @SuppressWarnings("unchecked")
1123 private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser, boolean isPortalRequest,boolean isSystemUser) throws Exception
1126 // check if user exists
1127 final Map<String, String> userParams = new HashMap<>();
1128 userParams.put("orgUserIdValue", orgUserId);
1129 List<EPUser> userInfo = checkIfUserExists(userParams);
1130 if (userInfo.isEmpty()) {
1131 createLocalUserIfNecessary(orgUserId, isSystemUser);
1134 if (EPCommonSystemProperties
1135 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN) && !isSystemUser) {
1137 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
1141 ObjectMapper mapper = new ObjectMapper();
1142 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1143 HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
1144 ResponseEntity<String> getResponse = externalAccessRolesService.getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
1145 List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
1146 String res = getResponse.getBody();
1147 JSONObject jsonObj = null;
1148 JSONArray extRoles = null;
1149 if (!res.equals("{}")) {
1150 jsonObj = new JSONObject(res);
1151 extRoles = jsonObj.getJSONArray("role");
1153 ExternalAccessUserRoleDetail userRoleDetail = null;
1154 if (extRoles != null) {
1155 for (int i = 0; i < extRoles.length(); i++) {
1156 if (extRoles.getJSONObject(i).getString("name").startsWith(app.getNameSpace() + ".")
1157 && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".admin")
1158 && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".owner")) {
1159 if (extRoles.getJSONObject(i).has("description")) {
1160 ExternalRoleDescription desc = new ExternalRoleDescription(extRoles.getJSONObject(i).getString("description"));
1161 userRoleDetail = new ExternalAccessUserRoleDetail(
1162 extRoles.getJSONObject(i).getString("name"), desc);
1163 userRoleDetailList.add(userRoleDetail);
1165 userRoleDetail = new ExternalAccessUserRoleDetail(
1166 extRoles.getJSONObject(i).getString("name"), null);
1167 userRoleDetailList.add(userRoleDetail);
1174 List<ExternalAccessUserRoleDetail> userRoleListMatchingInExtAuthAndLocal = CheckIfRoleAreMatchingInUserRoleDetailList(userRoleDetailList,app);
1176 // If request coming from portal not from external role approval system then we have to check if user already
1177 // have account admin or system admin as GUI will not send these roles
1178 if (!isPortalRequest) {
1179 final Map<String, String> loginIdParams = new HashMap<>();
1180 loginIdParams.put("orgUserIdValue", orgUserId);
1181 EPUser user = (EPUser) dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null).get(0);
1182 final Map<String, Long> params = new HashMap<>();
1183 params.put("appId", app.getId());
1184 params.put("userId", user.getId());
1185 List<EcompUserAppRoles> userAppList = dataAccessService.executeNamedQuery("getUserAppExistingRoles",
1187 if (!roleInAppUser.isEmpty()) {
1188 for (EcompUserAppRoles userApp : userAppList) {
1189 if (userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)
1190 || userApp.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
1191 RoleInAppForUser addSpecialRole = new RoleInAppForUser();
1192 addSpecialRole.setIsApplied(true);
1193 addSpecialRole.setRoleId(userApp.getRoleId());
1194 addSpecialRole.setRoleName(userApp.getRoleName());
1195 roleInAppUser.add(addSpecialRole);
1200 List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct()
1201 .collect(Collectors.toList());
1202 final Map<String, RoleInAppForUser> currentUserRolesToUpdate = new HashMap<>();
1203 for (RoleInAppForUser roleInAppUserNew : roleInAppUserNonDupls) {
1204 currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), roleInAppUserNew);
1206 final Map<String, ExternalAccessUserRoleDetail> currentUserRolesInExternalSystem = new HashMap<>();
1207 for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleListMatchingInExtAuthAndLocal) {
1208 currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole);
1210 // Check if user roles does not exists in local but still there in External Central Auth System delete them all
1211 for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
1212 if (!(currentUserRolesToUpdate
1213 .containsKey(userRole.getName().substring(app.getNameSpace().length() + 1)))) {
1214 HttpEntity<String> entity = new HttpEntity<>(headers);
1215 logger.debug(EELFLoggerDelegate.debugLogger,
1216 "updateUserRolesInExternalSystem: Connecting to external system to DELETE user role {}",
1217 userRole.getName());
1218 ResponseEntity<String> deleteResponse = template.exchange(
1219 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1220 + "userRole/" + name + "/" + userRole.getName(),
1221 HttpMethod.DELETE, entity, String.class);
1222 logger.debug(EELFLoggerDelegate.debugLogger,
1223 "updateUserRolesInExternalSystem: Finished DELETE operation in external system for user role {} and the response is {}",
1224 userRole.getName(), deleteResponse.getBody());
1227 // Check if user roles does not exists in External Central Auth System add them all
1228 for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) {
1229 if (!(currentUserRolesInExternalSystem
1230 .containsKey(app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")))) {
1231 ExternalAccessUser extUser = new ExternalAccessUser(name,
1232 app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1233 String formattedUserRole = mapper.writeValueAsString(extUser);
1234 HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers);
1235 logger.debug(EELFLoggerDelegate.debugLogger, "updateUserRolesInExternalSystem: Connecting to external system for user {} and POST {}",
1236 name , addUserRole.getRoleName());
1237 ResponseEntity<String> addResponse = template
1238 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1239 + "userRole", HttpMethod.POST, entity, String.class);
1240 logger.debug(EELFLoggerDelegate.debugLogger,
1241 "updateUserRolesInExternalSystem: Finished adding user role in external system {} and added user role {}",
1242 addResponse.getBody(), addUserRole.getRoleName());
1243 if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 404) {
1244 logger.debug(EELFLoggerDelegate.debugLogger,
1245 "Finished POST operation in external system but unable to save user role", addResponse.getBody(),
1246 addUserRole.getRoleName());
1247 throw new Exception(addResponse.getBody());
1251 } catch (HttpClientErrorException e) {
1252 logger.error(EELFLoggerDelegate.errorLogger,
1253 "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}",
1255 if (e.getStatusCode() == HttpStatus.FORBIDDEN) {
1256 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid systemUser", orgUserId);
1257 throw new HttpClientErrorException(HttpStatus.FORBIDDEN, "Please enter the valid systemUser");
1259 if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
1260 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid role");
1261 throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "Please enter the valid role");
1263 EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
1267 catch (Exception e) {
1268 logger.error(EELFLoggerDelegate.errorLogger, "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}", app.getId(), e);
1269 EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
1275 private List<ExternalAccessUserRoleDetail> CheckIfRoleAreMatchingInUserRoleDetailList(
1276 List<ExternalAccessUserRoleDetail> userRoleDetailList, EPApp app) {
1277 Map<String, EPRole> epRoleList = externalAccessRolesService.getAppRoleNamesWithUnderscoreMap(app);
1278 //Add Account Admin role for partner app to prevent conflict
1279 if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1280 EPRole role = new EPRole();
1281 role.setName(PortalConstants.ADMIN_ROLE.replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1282 epRoleList.put(role.getName(), role);
1284 userRoleDetailList.removeIf(userRoleDetail -> !epRoleList.containsKey(userRoleDetail.getName().substring(app.getNameSpace().length()+1)));
1285 return userRoleDetailList;
1292 * @param applicationsRestClientService
1293 * @param searchService
1297 protected void createNewUserOnRemoteApp(String userId, EPApp app,
1298 ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
1299 ObjectMapper mapper, boolean postOpenSource) throws Exception {
1302 EPUser client = searchService.searchUserByUserId(userId);
1304 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1306 if (client == null) {
1307 String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook.";
1308 logger.error(EELFLoggerDelegate.errorLogger, msg);
1309 throw new Exception(msg);
1312 client.setLoginId(userId);
1313 client.setActive(true);
1315 String userInString = null;
1316 userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
1317 logger.debug(EELFLoggerDelegate.debugLogger,
1318 "about to post new client to remote application, users json = " + userInString);
1319 applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user", userId));
1323 @SuppressWarnings("unchecked")
1324 protected void applyChangesToAppRolesRequest(Long appId, Long userId, String updateStatus, EPUserAppRolesRequest epUserAppRolesRequest) {
1325 final Map<String, Long> epRequestParams = new HashMap<>();
1327 EPUserAppRolesRequest epAppRolesRequestData = epUserAppRolesRequest;
1328 epAppRolesRequestData.setUpdatedDate(new Date());
1329 epAppRolesRequestData.setRequestStatus(updateStatus);
1330 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1331 addiotonalUpdateParam.put("userId", userId);
1332 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1333 epRequestParams.put("reqId", epUserAppRolesRequest.getId());
1334 List<EPUserAppRolesRequestDetail> epUserAppRolessDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1335 epUserAppRolessDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1336 epRequestParams, null);
1337 if (epUserAppRolessDetailList.size() > 0) {
1338 for (EPUserAppRolesRequestDetail epRequestUpdateData : epUserAppRolessDetailList) {
1339 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateData;
1340 epAppRoleDetailData.setReqType(updateStatus);
1341 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1342 HashMap<String, Long> updateDetailsParam = new HashMap<String, Long>();
1343 addiotonalUpdateParam.put("reqId", epUserAppRolesRequest.getId());
1344 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParam);
1347 logger.debug(EELFLoggerDelegate.debugLogger, "The request is set to complete");
1349 } catch (Exception e) {
1350 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToAppRolesRequest failed", e);
1354 @SuppressWarnings("unchecked")
1355 public void applyChangesToUserAppRolesForMyLoginsRequest(EPUser user, Long appId) {
1356 final Map<String, Long> params = new HashMap<>();
1357 final Map<String, Long> epDetailParams = new HashMap<>();
1358 List<EPUserAppRolesRequest> epRequestIdVal = new ArrayList<EPUserAppRolesRequest>();
1359 params.put("appId", appId);
1360 params.put("userId", user.getId());
1362 epRequestIdVal = (List<EPUserAppRolesRequest>) dataAccessService
1363 .executeNamedQuery("userAppRolesRequestList", params, null);
1364 if (epRequestIdVal.size() > 0) {
1365 EPUserAppRolesRequest epAppRolesRequestData = epRequestIdVal.get(0);
1366 epAppRolesRequestData.setUpdatedDate(new Date());
1367 epAppRolesRequestData.setRequestStatus("O");
1368 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1369 addiotonalUpdateParam.put("userId", user.getId());
1370 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1371 epDetailParams.put("reqId", epAppRolesRequestData.getId());
1372 List<EPUserAppRolesRequestDetail> epUserAppRolesDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1373 epUserAppRolesDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1374 epDetailParams, null);
1375 if (epUserAppRolesDetailList.size() > 0) {
1376 for (EPUserAppRolesRequestDetail epRequestUpdateList : epUserAppRolesDetailList) {
1377 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateList;
1378 epAppRoleDetailData.setReqType("O");
1379 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1380 HashMap<String, Long> updateDetailsParams = new HashMap<String, Long>();
1381 addiotonalUpdateParam.put("reqId", epAppRolesRequestData.getId());
1382 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParams);
1384 logger.debug(EELFLoggerDelegate.debugLogger, "User App roles request from User Page is overridden");
1388 } catch (Exception e) {
1389 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e);
1394 * Pushes specified user details to the specified remote app.
1397 * OrgUserId identifying user at remote app in REST endpoint path
1399 * User details to be pushed
1402 * @param applicationsRestClientService
1403 * @throws HTTPException
1405 protected void postUserToRemoteApp(String userId, EPUser user, EPApp app,
1406 ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
1408 getUser(userId, app, applicationsRestClientService);
1413 * It returns user details for single org user id
1417 * if user exists it returns list of user details otherwise empty value
1419 @SuppressWarnings("unchecked")
1420 private List<EPUser> checkIfUserExists(Map<String, String> userParams){
1421 return (List<EPUser>)dataAccessService.executeNamedQuery("epUserAppId", userParams, null);
1425 * It checks whether the new user is valid or not otherwise throws exception
1430 * Checks if user is valid and returns message otherwise throws exception
1433 private String validateNewUser(String orgUserId, EPApp app) throws Exception {
1434 EPUser epUser = searchService.searchUserByUserId(orgUserId);
1435 if (epUser == null) {
1436 throw new Exception("User does not exist");
1437 } else if (!epUser.getOrgUserId().equals(orgUserId)) {
1438 throw new Exception("User does not exist");
1439 } else if (app == null) {
1440 throw new Exception("Application does not exist");
1442 return "Saved Successfully";
1446 * Checks if the fields exists or not
1449 * contains user information
1453 * throws exception if the field is not valid
1455 private void validateExternalRequestFields(List<EPUser> userList, EPApp app) throws Exception{
1456 if (userList.size() == 0 || userList.isEmpty() ) {
1457 throw new Exception("User does not exist");
1458 } else if(app == null) {
1459 throw new Exception("Application does not exist");
1460 } else if(!app.getEnabled() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1461 throw new Exception(app.getMlAppName()+" application is unavailable");
1465 @SuppressWarnings("unchecked")
1466 public ExternalRequestFieldsValidator setExternalRequestUserAppRole(ExternalSystemUser newAppRolesForUser, String reqType) {
1467 boolean result = false;
1468 boolean externalSystemRequest = true;
1469 final Map<String, Long> params = new HashMap<>();
1470 final Map<String, String> userParams = new HashMap<>();
1471 List<EPUser> userInfo = null;
1473 List<EPUserAppRolesRequest> epRequestId = null;
1474 String orgUserId = "";
1475 String updateStatus = "";
1476 String reqMessage = "";
1478 if (newAppRolesForUser != null && newAppRolesForUser.getLoginId() != null) {
1479 orgUserId = newAppRolesForUser.getLoginId().trim();
1481 String appName = newAppRolesForUser.getApplicationName();
1482 String logMessage = ("DELETE").equals(reqType) ? "Deleting": "Assigning/Updating" ;
1483 if (orgUserId.length() > 0) {
1484 ObjectMapper mapper = new ObjectMapper();
1485 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1486 int epRequestIdSize = 0;
1488 app = appsService.getAppDetail(appName);
1489 userParams.put("orgUserIdValue", orgUserId);
1490 userInfo = checkIfUserExists(userParams);
1491 reqMessage = "Updated Successfully";
1492 if (!reqType.equals("DELETE") && (userInfo.size() == 0 || userInfo.isEmpty())) {
1493 reqMessage = validateNewUser(orgUserId, app);
1495 if (userInfo.size() != 0 || !userInfo.isEmpty()) {
1496 validateExternalRequestFields(userInfo, app);
1497 user = userInfo.get(0);
1498 params.put("appId", app.getId());
1499 params.put("userId", user.getId());
1500 epRequestId = (List<EPUserAppRolesRequest>) dataAccessService
1501 .executeNamedQuery("userAppRolesRequestList", params, null);
1502 epRequestIdSize = epRequestId.size();
1505 //If Non-Centralized app make sure you sync app roles before assigning to user
1506 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !app.getCentralAuth()) {
1507 logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Starting GET roles for app {}",app.getId());
1508 EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, app.getId(), "/roles");
1509 logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Finshed GET roles for app {} and payload {}",app.getId(), appRoles);
1510 if (appRoles.length > 0) {
1511 syncAppRoles(sessionFactory, app.getId(), appRoles);
1514 List<RoleInAppForUser> roleInAppForUserList = roleInAppForUserList(newAppRolesForUser.getRoles(),
1515 app.getId(), app.getMlAppName());
1516 List<EcompUserAppRoles> userRoleList = null;
1517 if(!userInfo.isEmpty()){
1518 final Map<String, Long> appParams = new HashMap<>();
1519 appParams.put("userId", user.getId());
1520 appParams.put("appId", app.getId());
1521 userRoleList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", appParams, null);
1523 // Check if list contains just account admin role
1524 boolean checkIfAdminRoleExists = false;
1525 if (reqType.equals("DELETE") && userRoleList!=null) {
1526 checkIfAdminRoleExists = userRoleList.stream()
1527 .anyMatch(userRole -> userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1529 checkIfAdminRoleExists = roleInAppForUserList.stream()
1530 .anyMatch(roleList -> roleList.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1532 // if Centralized app
1533 if (app.getCentralAuth()) {
1534 // We should add If user does not exist in remote application
1536 // If adding just account admin role dont make remote application user call or
1537 // if request has only single non admin role then make remote call
1538 if (!(app.getId().equals(PortalConstants.PORTAL_APP_ID) && reqType.equals("DELETE"))
1539 && ((checkIfAdminRoleExists && roleInAppForUserList.size() > 1)
1540 || (!checkIfAdminRoleExists && roleInAppForUserList.size() >= 1))) {
1541 // check if admin role exist then delete
1542 List<RoleInAppForUser> remoteUserRoles = roleInAppForUserList.stream()
1543 .collect(Collectors.toList());
1544 remoteUserRoles.removeIf(role -> {
1545 return (role.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1547 String orgUserIdNewOrExist = (userInfo.size() != 0 || !userInfo.isEmpty()) ? user.getOrgUserId() : orgUserId;
1548 pushRemoteUser(remoteUserRoles, orgUserIdNewOrExist , app, mapper, searchService,
1549 applicationsRestClientService,true);
1551 } catch (Exception e) {
1552 reqMessage = e.getMessage();
1553 logger.error(EELFLoggerDelegate.errorLogger, "setExternalRequestUserAppRole: Failed to added remote user", e);
1554 throw new Exception(reqMessage);
1556 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1557 applicationsRestClientService, app.getId(), orgUserId);
1558 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1559 userRolesInLocalApp);
1560 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1561 if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1562 // Apply changes in external Access system
1563 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, externalSystemRequest,false);
1565 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
1566 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1567 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,false);
1569 // If local application is not centralized
1570 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1571 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1572 applicationsRestClientService, app.getId(), orgUserId);
1573 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1574 userRolesInLocalApp);
1575 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,false);
1576 } else {// remote app
1577 // If adding just account admin role don't do remote application user call
1578 if (!((roleInAppForUserList.size() == 1 || reqType.equals("DELETE")) && checkIfAdminRoleExists)) {
1579 EPUser remoteAppUser = null;
1580 remoteAppUser = checkIfRemoteUserExits(orgUserId, app, applicationsRestClientService);
1581 if (remoteAppUser == null) {
1582 addRemoteUser(roleInAppForUserList, orgUserId, app, mapper, searchService,
1583 applicationsRestClientService);
1584 reqMessage = "Saved Successfully";
1587 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
1588 applicationsRestClientService, app.getId(), orgUserId,false);
1590 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1591 userRolesInRemoteApp);
1592 logger.info(EELFLoggerDelegate.debugLogger,
1593 "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
1594 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1595 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1597 // If no roles remain, request app to set user inactive.
1599 * if (userRolesInRemoteApp.size() == 0) {
1600 * logger.debug(EELFLoggerDelegate.debugLogger,
1601 * "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive"
1602 * , app, orgUserId); //TODO Need to fix the logged in user is not set to
1603 * inactive remoteAppUser.setActive(false); postUserToRemoteApp(orgUserId, user,
1604 * app, applicationsRestClientService); }
1608 // Here we are adding only we have single account admin in roleInAppForUserList and this should not add in remote
1609 if(!(reqType.equals("DELETE")) && userInfo.isEmpty()){
1610 reqMessage = "Saved Successfully";
1612 Set<EcompRole> userRolesInRemoteApp = constructUsersEcompRoles(roleInAppForUserList);
1614 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1615 userRolesInRemoteApp);
1616 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}",
1617 logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1618 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1622 reqMessage = "Failed to save the user app role(s)";
1624 if (epRequestIdSize > 0 && !userInfo.isEmpty()) {
1626 applyChangesToAppRolesRequest(app.getId(), user.getId(), updateStatus, epRequestId.get(0));
1629 } catch (Exception e) {
1630 String message = String.format("setExternalRequestUserAppRole: Failed to create user or update user roles for User %s, AppId %s",
1631 orgUserId, appName);
1632 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1634 reqMessage = e.getMessage();
1635 if(epRequestIdSize > 0 && userInfo!=null && !userInfo.isEmpty()){
1637 applyChangesToAppRolesRequest(app.getId(), user.getId(),
1638 updateStatus, epRequestId.get(0));
1643 return new ExternalRequestFieldsValidator(result, reqMessage);
1648 * @param roleInAppForUserList
1650 * @param applicationsRestClientService
1653 * @return Set<EcompRole>
1654 * @throws JsonProcessingException
1655 * @throws HTTPException
1657 private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
1658 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
1659 throws JsonProcessingException, HTTPException {
1660 Set<EcompRole> updatedUserRoles = constructUsersEcompRoles(roleInAppForUserList);
1661 return updatedUserRoles;
1665 * It constructs and returns list of user app roles when the external API role approval system calls
1668 * @param roleInAppForUserList
1670 * @return list of user app roles
1672 * throws exceptions if role id does not exits
1674 private List<RoleInAppForUser> roleInAppForUserList(List<ExternalSystemRoleApproval> roleInAppForUserList,
1675 Long appId, String appName) throws Exception {
1676 List<RoleInAppForUser> existingUserRoles = new ArrayList<RoleInAppForUser>();
1677 EPRole existingAppRole = null;
1678 for (ExternalSystemRoleApproval roleInAppForUser : roleInAppForUserList) {
1679 RoleInAppForUser ecompRole = new RoleInAppForUser();
1680 existingAppRole = epRoleService.getAppRole(roleInAppForUser.getRoleName(), appId);
1681 if (existingAppRole == null) {
1682 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1683 roleInAppForUserList);
1684 throw new Exception("'" +roleInAppForUser.getRoleName() + "'" +" role does not exist for " + appName + " application");
1686 if (!existingAppRole.getActive()) {
1687 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1688 roleInAppForUserList);
1689 throw new Exception(roleInAppForUser.getRoleName() + " role is unavailable for "+ appName + " application");
1691 ecompRole.roleId = (appId == 1 || roleInAppForUser.getRoleName().equals(PortalConstants.ADMIN_ROLE)) ? existingAppRole.getId() : existingAppRole.getAppRoleId();
1692 ecompRole.roleName = roleInAppForUser.getRoleName();
1693 ecompRole.isApplied = true;
1694 existingUserRoles.add(ecompRole);
1697 return existingUserRoles;
1706 * @param applicationsRestClientService
1708 * @throws HTTPException
1710 protected EPUser getUserFromApp(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1711 throws HTTPException {
1713 if (app.getId() == PortalConstants.PORTAL_APP_ID) {
1714 // Map<String,String> params = new HashMap<String,String>();
1715 // params.put("sbcid",userId);
1716 @SuppressWarnings("unchecked")
1717 List<EPUser> userList = (List<EPUser>) dataAccessService
1718 .executeQuery("from EPUser where orgUserId='" + userId + "'", null);
1719 if (userList != null && !userList.isEmpty())
1720 return userList.get(0);
1726 return getUser(userId, app, applicationsRestClientService);
1729 protected EPUser getUser(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1730 throws HTTPException {
1731 return applicationsRestClientService.get(EPUser.class, app.getId(), String.format("/user/%s", userId), true);
1735 protected boolean isAppUpgradeVersion(EPApp app){
1740 public ExternalSystemAccess getExternalRequestAccess(){
1741 ExternalSystemAccess res = null;
1743 res = new ExternalSystemAccess(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE,
1744 Boolean.parseBoolean(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE)));
1745 } catch (Exception e) {
1746 logger.error(EELFLoggerDelegate.errorLogger, "getExternalRequestAccess failed" + e.getMessage());
1754 * @see org.onap.portalapp.portal.service.UserRolesService#
1755 * getAppRolesForUser(java.lang.Long, java.lang.String)
1757 @SuppressWarnings("unchecked")
1758 public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId, Boolean extRequestValue,EPUser user) {
1759 List<RoleInAppForUser> rolesInAppForUser = null;
1760 EPApp app = appsService.getApp(appId);
1761 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - app = {}", app);
1763 // for onap portal app, no need to make a remote call
1764 List<Role> roleList = new ArrayList<>();
1765 if (appId == PortalConstants.PORTAL_APP_ID) {
1766 if(app.getCentralAuth()){
1767 List<CentralV2Role> cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey());
1768 for(CentralV2Role cenRole : cenRoleList){
1769 Role role = new Role();
1770 role.setActive(cenRole.getActive());
1771 role.setId(cenRole.getId());
1772 role.setName(cenRole.getName());
1773 role.setPriority(cenRole.getPriority());
1777 roleList = roleService.getAvailableRoles(userId);
1779 List<Role> activeRoleList = new ArrayList<Role>();
1780 for(Role role: roleList) {
1781 if(role.getActive()) {
1782 if(role.getId() != 1){ // prevent portal admin from being added
1783 activeRoleList.add(role);
1784 } else if(extRequestValue){
1785 activeRoleList.add(role);
1790 EPUser localUser = getUserFromApp(userId, app, applicationsRestClientService);
1791 // If localUser does not exists return roles
1792 Set<EPRole> roleSet = null;
1793 EPRole[] roleSetList = null;
1794 if(localUser != null){
1795 roleSet = localUser.getAppEPRoles(app);
1796 roleSetList = roleSet.toArray(new EPRole[0]);
1798 rolesInAppForUser = constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue);
1799 return rolesInAppForUser;
1802 EcompRole[] appRoles = null;
1803 List<EcompRole> roles = new ArrayList<>();
1804 if (app.getCentralAuth()) {
1805 final Map<String, Long> appParams = new HashMap<>();
1806 appParams.put("appId", app.getId());
1807 List<EPRole> applicationRoles = dataAccessService.executeNamedQuery("getActiveRolesOfApplication",
1810 EPApp application = appService.getApp(appId);
1811 boolean checkIfUserisApplicationAccAdmin = adminRolesService.isAccountAdminOfApplication(user,
1814 List<EPRole> rolesetwithfunctioncds = new ArrayList<EPRole>();
1815 for (EPRole role : applicationRoles) {
1816 Map<String, Long> params = new HashMap<>();
1817 params.put("roleId", role.getId());
1818 params.put(APP_ID, app.getId());
1819 List<CentralV2RoleFunction> cenRoleFuncList = dataAccessService
1820 .executeNamedQuery("getAppRoleFunctionList", params, null);
1822 // SortedSet<CentralV2RoleFunction> roleFunctionSet =
1824 SortedSet<RoleFunction> roleFunctionSet = new TreeSet<>();
1825 for (CentralV2RoleFunction roleFunc : cenRoleFuncList) {
1827 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1828 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
1829 String type = externalAccessRolesService.getFunctionCodeType(roleFunc.getCode());
1830 String action = externalAccessRolesService.getFunctionCodeAction(roleFunc.getCode());
1831 String name = roleFunc.getName();
1833 RoleFunction function = new RoleFunction();
1834 function.setAction(action);
1835 function.setType(type);
1836 function.setCode(functionCode);
1837 function.setName(name);
1838 roleFunctionSet.add(function);
1839 role.setRoleFunctions(roleFunctionSet);
1842 rolesetwithfunctioncds.add(role);
1847 for (EPRole role1 : rolesetwithfunctioncds) {
1848 EcompRole ecompRole = new EcompRole();
1849 ecompRole.setId(role1.getId());
1850 ecompRole.setName(role1.getName());
1851 ecompRole.setRoleFunctions(role1.getRoleFunctions());
1852 roles.add(ecompRole);
1855 if (checkIfUserisApplicationAccAdmin) {
1856 appRoles = roles.toArray(new EcompRole[roles.size()]);
1857 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() If Logged in user checkIfUserisApplicationAccAdmin- appRoles = {}", appRoles);
1858 } else if (adminRolesService.isRoleAdmin(user) && !checkIfUserisApplicationAccAdmin) {
1859 List<EcompRole> roleAdminAppRoles = new ArrayList<>();
1860 List<String> roleAdminAppRolesNames = new ArrayList<>();
1861 final Map<String, Long> userParams = new HashMap<>();
1862 userParams.put("userId", user.getId());
1863 List<String> getUserApproverRoles = dataAccessService.executeNamedQuery("getUserApproverRoles", userParams, null);
1865 List<EcompRole> userapproverRolesList = new ArrayList<>();
1866 for (String str : getUserApproverRoles) {
1867 EcompRole epRole = roles.stream().filter(x -> str.equals(x.getName())).findAny().orElse(null);
1869 userapproverRolesList.add(epRole);
1871 // roles.removeAll(userapproverRolesList);
1872 for (EcompRole role : userapproverRolesList) {
1874 List<RoleFunction> roleFunList = new ArrayList<>();
1875 roleFunList.addAll(role.getRoleFunctions());
1876 boolean checkIfFunctionsExits = roleFunList.stream()
1877 .anyMatch(roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
1878 if (checkIfFunctionsExits) {
1879 roleAdminAppRoles.add(role);
1880 List<RoleFunction> filteredList = roleFunList.stream()
1881 .filter(x -> "Approver".equalsIgnoreCase(x.getType())).collect(Collectors.toList());
1882 roleAdminAppRolesNames.addAll(filteredList.stream().map(RoleFunction::getCode)
1883 .collect(Collectors.toList()));
1884 // roleAdminAppRolesNames = filteredList.stream().map(RoleFunction::getCode)
1885 // .collect(Collectors.toList());
1888 for (String name : roleAdminAppRolesNames) {
1889 EcompRole ecompRole = roles.stream().filter(x -> name.equals(x.getName())).findAny()
1891 if (ecompRole != null)
1892 roleAdminAppRoles.add(ecompRole);
1895 appRoles = roleAdminAppRoles.toArray(new EcompRole[roleAdminAppRoles.size()]);
1899 appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
1901 // Test this error case, for generating an internal ONAP Portal
1903 // EcompRole[] appRoles = null;
1904 // If there is an exception in the rest client api, then null will
1906 if (appRoles != null) {
1907 if(!app.getCentralAuth()) {
1908 syncAppRoles(sessionFactory, appId, appRoles);
1910 EcompRole[] userAppRoles = null;
1914 if(app.getCentralAuth()){
1915 final Map<String, String> params = new HashMap<>();
1916 final Map<String, Long> userParams = new HashMap<>();
1917 params.put("orgUserIdValue", userId);
1918 List<EPUser> actualUser = dataAccessService.executeNamedQuery("epUserAppId", params, null);
1919 userParams.put("appId", app.getId());
1920 userParams.put("userId", actualUser.get(0).getId());
1921 List<EPUserAppCurrentRoles> userAppsRolesList = dataAccessService.executeNamedQuery("getUserAppCurrentRoles", userParams, null);
1923 List<EcompRole> setUserRoles = new ArrayList<>();
1924 for(EPUserAppCurrentRoles role : userAppsRolesList){
1925 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - userAppsRolesList get userRolename = {}", role.getRoleName());
1926 EcompRole ecompRole = new EcompRole();
1927 ecompRole.setId(role.getRoleId());
1928 ecompRole.setName(role.getRoleName());
1929 setUserRoles.add(ecompRole);
1932 boolean checkIfUserisAccAdmin = setUserRoles.stream()
1933 .anyMatch(ecompRole -> ecompRole.getId() == 999L);
1935 if (!checkIfUserisAccAdmin) {
1936 List<EcompRole> userApplicationRolesList = setUserRoles;
1937 List<EcompRole> appRolesList = Arrays.asList(appRoles);
1938 Set<EcompRole> finalUserAppRolesList = new HashSet<>();
1940 List<String> roleNames = new ArrayList<>();
1941 for (EcompRole role : userApplicationRolesList) {
1942 EcompRole epRole = appRolesList.stream()
1943 .filter(x -> role.getName().equals(x.getName())).findAny().orElse(null);
1944 List<RoleFunction> roleFunList = new ArrayList<>();
1945 if(epRole.getRoleFunctions().size()>0)
1946 roleFunList.addAll(epRole.getRoleFunctions());
1947 boolean checkIfFunctionsExits = roleFunList.stream().anyMatch(
1948 roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
1949 if (checkIfFunctionsExits) {
1950 finalUserAppRolesList.add(role);
1951 List<RoleFunction> filteredList = roleFunList.stream()
1952 .filter(x -> "Approver".equalsIgnoreCase(x.getType()))
1953 .collect(Collectors.toList());
1954 roleNames = filteredList.stream().map(RoleFunction::getCode)
1955 .collect(Collectors.toList());
1958 for (String name : roleNames) {
1959 EcompRole ecompRole = appRolesList.stream()
1960 .filter(x -> name.equals(x.getName())).findAny().orElse(null);
1961 if (ecompRole != null)
1962 finalUserAppRolesList.add(ecompRole);
1967 for (String name : roleNames) {
1969 boolean checkIfFunctionsExits = userAppsRolesList.stream().anyMatch(
1970 role -> role.getRoleName().equalsIgnoreCase(name));
1971 if(checkIfFunctionsExits)
1973 EcompRole epRole = appRolesList.stream().filter(x -> name.equals(x.getName()))
1974 .findAny().orElse(null);
1976 setUserRoles.add(epRole);
1980 userAppRoles = setUserRoles.toArray(new EcompRole[setUserRoles.size()]);
1983 userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
1984 String.format("/user/%s/roles", userId));
1986 } catch (HTTPException e) {
1987 // Some apps are returning 400 if user is not found.
1988 if (e.getResponseCode() == 400) {
1989 logger.debug(EELFLoggerDelegate.debugLogger,
1990 "getAppRolesForUser caught exception with response code 400; continuing", e);
1992 // Other response code, let it come thru.
1996 if (userAppRoles == null) {
1997 if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
1998 EcompPortalUtils.setExternalAppResponseCode(200);
1999 String message = String.format(
2000 "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
2001 + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
2002 + "Overriding to 200 until framework SDK returns a useful response.",
2003 Long.toString(appId), userId);
2004 logger.warn(EELFLoggerDelegate.applicationLogger, message);
2008 HashMap<Long, EcompRole> appRolesActiveMap =hashMapFromEcompRoles(appRoles);
2009 ArrayList<EcompRole> activeRoles = new ArrayList<EcompRole>();
2010 if(userAppRoles != null){
2011 for (int i = 0; i < userAppRoles.length; i++) {
2012 if (appRolesActiveMap.containsKey(userAppRoles[i].getId())) {
2013 EcompRole role = new EcompRole();
2014 role.setId(userAppRoles[i].getId());
2015 role.setName(userAppRoles[i].getName());
2016 activeRoles.add(role);
2020 EcompRole[] userAppRolesActive = activeRoles.toArray(new EcompRole[activeRoles.size()]);
2022 // If the remote application isn't down we MUST sync user
2023 // roles here in case we have this user here!
2024 syncUserRoles(sessionFactory, userId, appId, userAppRolesActive, extRequestValue, null);
2025 } catch (Exception e) {
2026 // TODO: we may need to check if user exists, maybe remote
2028 String message = String.format(
2029 "getAppRolesForUser: user %s does not exist in remote application %s", userId,
2030 Long.toString(appId));
2031 logger.error(EELFLoggerDelegate.errorLogger, message, e);
2032 userAppRoles = new EcompRole[0];
2034 rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
2036 } catch (Exception e) {
2037 String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
2038 Long.toString(appId));
2039 logger.error(EELFLoggerDelegate.errorLogger, message, e);
2041 return rolesInAppForUser;
2044 private boolean postUserRolesToMylogins(AppWithRolesForUser userAppRolesData,
2045 ApplicationsRestClientService applicationsRestClientService, Long appId, Long userId)
2046 throws JsonProcessingException, HTTPException {
2047 boolean result = false;
2048 ObjectMapper mapper = new ObjectMapper();
2049 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
2050 String userRolesAsString = mapper.writeValueAsString(userAppRolesData);
2051 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, as the endpoint is not defined yet from the Mylogins");
2052 applicationsRestClientService.post(AppWithRolesForUser.class, appId, userRolesAsString, String.format("/user/%s/myLoginroles", userId));
2056 @SuppressWarnings("unchecked")
2057 public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser userAppRolesData, EPUser user) {
2058 FieldsValidator fieldsValidator = new FieldsValidator();
2059 final Map<String, Long> params = new HashMap<>();
2060 List<EPUserAppRoles> appRole= null;
2062 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, still the endpoint is yet to be defined");
2063 boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService,
2064 userAppRolesData.getAppId(), user.getId());
2065 logger.debug(EELFLoggerDelegate.debugLogger,"putUserAppRolesRequest: result {}", result);
2067 params.put("appId", userAppRolesData.getAppId());
2068 EPUserAppRolesRequest epAppRolesRequestData = new EPUserAppRolesRequest();
2069 epAppRolesRequestData.setCreatedDate(new Date());
2070 epAppRolesRequestData.setUpdatedDate(new Date());
2071 epAppRolesRequestData.setUserId(user.getId());
2072 epAppRolesRequestData.setAppId(userAppRolesData.getAppId());
2073 epAppRolesRequestData.setRequestStatus("P");
2074 List<RoleInAppForUser> appRoleIdList = userAppRolesData.getAppRoles();
2075 Set<EPUserAppRolesRequestDetail> appRoleDetails = new LinkedHashSet<EPUserAppRolesRequestDetail>();
2076 dataAccessService.saveDomainObject(epAppRolesRequestData, null);
2077 for (RoleInAppForUser userAppRoles : appRoleIdList) {
2078 Boolean isAppliedVal = userAppRoles.isApplied;
2079 params.put("appRoleId", userAppRoles.roleId);
2081 appRole = (List<EPUserAppRoles>) dataAccessService.executeNamedQuery("appRoles", params, null);
2082 if (!appRole.isEmpty()) {
2083 EPUserAppRolesRequestDetail epAppRoleDetail = new EPUserAppRolesRequestDetail();
2084 epAppRoleDetail.setReqRoleId(appRole.get(0).getRoleId());
2085 epAppRoleDetail.setReqType("P");
2086 epAppRoleDetail.setEpRequestIdData(epAppRolesRequestData);
2087 dataAccessService.saveDomainObject(epAppRoleDetail, null);
2091 epAppRolesRequestData.setEpRequestIdDetail(appRoleDetails);
2092 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
2094 } catch (Exception e) {
2095 logger.error(EELFLoggerDelegate.errorLogger, "putUserAppRolesRequest failed", e);
2096 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
2098 return fieldsValidator;
2101 public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(EPUser userid, String appName) {
2102 Map<String, String> params = new HashMap<>();
2103 params.put("userid", userid.getId().toString());
2104 //params.put("appid", appid);
2105 params.put("appName", appName);
2107 @SuppressWarnings("unchecked")
2108 List<EPUserAppCatalogRoles> userAppRoles = (List<EPUserAppCatalogRoles>) dataAccessService
2109 .executeNamedQuery("userAppCatalogRoles", params, null);
2110 return userAppRoles;
2113 public String updateRemoteUserProfile(String orgUserId, Long appId) {
2114 ObjectMapper mapper = new ObjectMapper();
2115 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
2116 EPUser client = searchService.searchUserByUserId(orgUserId);
2117 EPUser newUser = new EPUser();
2118 newUser.setActive(client.getActive());
2119 newUser.setFirstName(client.getFirstName());
2120 newUser.setLastName(client.getLastName());
2121 newUser.setLoginId(client.getLoginId());
2122 newUser.setLoginPwd(client.getLoginPwd());
2123 newUser.setMiddleInitial(client.getMiddleInitial());
2124 newUser.setEmail(client.getEmail());
2125 newUser.setOrgUserId(client.getLoginId());
2127 String userAsString = mapper.writeValueAsString(newUser);
2128 List<EPApp> appList = appsService.getUserRemoteApps(client.getId().toString());
2129 // applicationsRestClientService.post(EPUser.class, appId,
2130 // userAsString, String.format("/user", orgUserId));
2131 for (EPApp eachApp : appList) {
2133 applicationsRestClientService.post(EPUser.class, eachApp.getId(), userAsString,
2134 String.format("/user/%s", orgUserId));
2135 } catch (Exception e) {
2136 logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId()
2137 + " in remote app. appId = " + eachApp.getId());
2140 } catch (Exception e) {
2141 logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
2152 * @see org.onap.portalapp.portal.service.UserRolesService#
2153 * getCachedAppRolesForUser(java.lang.Long, java.lang.Long)
2155 @SuppressWarnings("deprecation")
2156 public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId) {
2157 // Find the records for this user-app combo, if any
2158 String filter = " where user_id = " + Long.toString(userId) + " and app_id = " + Long.toString(appId);
2159 @SuppressWarnings("unchecked")
2160 List<EPUserApp> roleList = dataAccessService.getList(EPUserApp.class, filter, null, null);
2161 logger.debug(EELFLoggerDelegate.debugLogger, "getCachedAppRolesForUser: list size is {}", roleList.size());
2166 * It retrieves and returns list of user app roles for local and remote applications based app id
2169 * @return list of user app roles
2170 * @throws HTTPException
2172 public List<UserApplicationRoles> getUsersFromAppEndpoint(Long appId) throws HTTPException {
2173 ArrayList<UserApplicationRoles> userApplicationRoles = new ArrayList<UserApplicationRoles>();
2175 EPApp app = appsService.getApp(appId);
2176 //If local or centralized application
2177 if (appId == PortalConstants.PORTAL_APP_ID || app.getCentralAuth()) {
2178 @SuppressWarnings("unchecked")
2179 List<EPUser> userList = (List<EPUser>) dataAccessService.executeNamedQuery("getActiveUsers", null, null);
2180 for (EPUser user : userList) {
2181 UserApplicationRoles userWithAppRoles = convertToUserApplicationRoles(appId, user, app);
2182 if (userWithAppRoles.getRoles() != null && userWithAppRoles.getRoles().size() > 0)
2183 userApplicationRoles.add(userWithAppRoles);
2189 RemoteUserWithRoles[] remoteUsers = null;
2190 String remoteUsersString = applicationsRestClientService.getIncomingJsonString(appId, "/users");
2192 remoteUsers = doGetUsers(isAppUpgradeVersion(app), remoteUsersString);
2194 userApplicationRoles = new ArrayList<UserApplicationRoles>();
2195 for (RemoteUserWithRoles remoteUser : remoteUsers) {
2196 UserApplicationRoles userWithRemoteAppRoles = convertToUserApplicationRoles(appId, remoteUser);
2197 if (userWithRemoteAppRoles.getRoles() != null && userWithRemoteAppRoles.getRoles().size() > 0) {
2198 userApplicationRoles.add(userWithRemoteAppRoles);
2200 logger.debug(EELFLoggerDelegate.debugLogger,
2201 "User " + userWithRemoteAppRoles.getOrgUserId() + " doesn't have any roles assigned to any app.");
2206 return userApplicationRoles;
2213 * @param appgetUsersFromAppEndpoint
2216 private UserApplicationRoles convertToUserApplicationRoles(Long appId, EPUser user, EPApp app) {
2217 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
2218 userWithRemoteAppRoles.setAppId(appId);
2219 userWithRemoteAppRoles.setOrgUserId(user.getOrgUserId());
2220 userWithRemoteAppRoles.setFirstName(user.getFirstName());
2221 userWithRemoteAppRoles.setLastName(user.getLastName());
2222 userWithRemoteAppRoles.setRoles(convertToRemoteRoleList(user, app));
2223 return userWithRemoteAppRoles;
2232 @SuppressWarnings("unchecked")
2233 private List<RemoteRole> convertToRemoteRoleList(EPUser user, EPApp app) {
2234 List<RemoteRole> roleList = new ArrayList<RemoteRole>();
2235 SortedSet<EPRole> roleSet = user.getAppEPRoles(app);
2236 for (EPRole role : roleSet) {
2237 logger.debug(EELFLoggerDelegate.debugLogger, "In convertToRemoteRoleList() - for user {}, found Name {}", user.getOrgUserId(), role.getName());
2238 RemoteRole rRole = new RemoteRole();
2239 rRole.setId(role.getId());
2240 rRole.setName(role.getName());
2241 roleList.add(rRole);
2244 //Get the active roles of user for that application using query
2245 List<EPRole> userEpRoleList = new ArrayList<>();
2246 final Map<String, Long> params = new HashMap<>();
2247 params.put("appId", app.getId());
2248 params.put("userId", user.getId());
2249 userEpRoleList = dataAccessService.executeNamedQuery("getUserRoleOnUserIdAndAppId", params, null);
2251 for (EPRole remoteUserRoleList : userEpRoleList) {
2253 RemoteRole remoteRoleListId = roleList.stream().filter(x -> remoteUserRoleList.getId().equals(x.getId()))
2254 .findAny().orElse(null);
2255 if (remoteRoleListId == null) {
2256 logger.debug(EELFLoggerDelegate.debugLogger,
2257 "Adding the role to the rolelist () - for user {}, found Name {}", user.getOrgUserId(),
2259 remoteUserRoleList.getName());
2260 RemoteRole role = new RemoteRole();
2261 role.setId(remoteUserRoleList.getId());
2262 role.setName(remoteUserRoleList.getName());
2269 logger.debug(EELFLoggerDelegate.debugLogger, "rolelist size of the USER() - for user {}, found RoleListSize {}", user.getOrgUserId(), roleList.size());
2277 public RemoteUserWithRoles[] doGetUsers(boolean postOpenSource, String remoteUsersString) {
2279 ObjectMapper mapper = new ObjectMapper();
2281 return mapper.readValue(remoteUsersString, RemoteUserWithRoles[].class);
2282 } catch (IOException e) {
2283 logger.error(EELFLoggerDelegate.errorLogger,
2284 "doGetUsers : Failed : Unexpected property in incoming JSON",
2286 logger.error(EELFLoggerDelegate.errorLogger,
2287 "doGetUsers : Incoming JSON that caused it --> " + remoteUsersString);
2290 return new RemoteUserWithRoles[0];
2293 @SuppressWarnings("unchecked")
2294 public List<EPUserApp> getEPUserAppList(Long appId, Long userId, Long roleId) {
2295 List<EPUserApp> userRoleList = new ArrayList<EPUserApp>();
2296 final Map<String, Long> params = new HashMap<>();
2297 params.put("appId", appId);
2298 params.put("userId", userId);
2299 params.put("roleId", roleId);
2300 userRoleList = dataAccessService.executeNamedQuery("getUserRoleOnUserIdAndRoleIdAndAppId", params, null);
2301 return userRoleList;
2305 /*public static void main(String[] args) {
2306 List<EcompRole> str1 = new ArrayList<String>();
2312 List<String> str2 = new ArrayList<String>();
2316 List<EcompRole> userApplicationRolesList = setUserRoles;
2317 List<EcompRole> appRolesList = Arrays.asList(appRoles);