2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
8 * Unless otherwise specified, all software contained herein is licensed
9 * under the Apache License, Version 2.0 (the "License");
10 * you may not use this software except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * Unless otherwise specified, all documentation contained herein is licensed
22 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23 * you may not use this documentation except in compliance with the License.
24 * You may obtain a copy of the License at
26 * https://creativecommons.org/licenses/by/4.0/
28 * Unless required by applicable law or agreed to in writing, documentation
29 * distributed under the License is distributed on an "AS IS" BASIS,
30 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31 * See the License for the specific language governing permissions and
32 * limitations under the License.
34 * ============LICENSE_END============================================
39 package org.onap.portalapp.portal.service;
41 import java.io.IOException;
42 import java.util.ArrayList;
43 import java.util.Arrays;
44 import java.util.Collection;
45 import java.util.Date;
46 import java.util.HashMap;
47 import java.util.HashSet;
48 import java.util.LinkedHashSet;
49 import java.util.List;
52 import java.util.SortedSet;
53 import java.util.TreeSet;
54 import java.util.stream.Collectors;
56 import javax.servlet.http.HttpServletResponse;
58 import org.apache.commons.lang.StringUtils;
59 import org.apache.cxf.transport.http.HTTPException;
60 import org.hibernate.SQLQuery;
61 import org.hibernate.Session;
62 import org.hibernate.SessionFactory;
63 import org.hibernate.Transaction;
64 import org.json.JSONArray;
65 import org.json.JSONObject;
66 import org.onap.portalapp.externalsystemapproval.model.ExternalSystemRoleApproval;
67 import org.onap.portalapp.externalsystemapproval.model.ExternalSystemUser;
68 import org.onap.portalapp.portal.domain.CentralV2RoleFunction;
69 import org.onap.portalapp.portal.domain.EPApp;
70 import org.onap.portalapp.portal.domain.EPRole;
71 import org.onap.portalapp.portal.domain.EPUser;
72 import org.onap.portalapp.portal.domain.EPUserApp;
73 import org.onap.portalapp.portal.domain.EPUserAppCatalogRoles;
74 import org.onap.portalapp.portal.domain.EPUserAppRoles;
75 import org.onap.portalapp.portal.domain.EPUserAppRolesRequest;
76 import org.onap.portalapp.portal.domain.EPUserAppRolesRequestDetail;
77 import org.onap.portalapp.portal.domain.ExternalSystemAccess;
78 import org.onap.portalapp.portal.exceptions.SyncUserRolesException;
79 import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
80 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
81 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
82 import org.onap.portalapp.portal.transport.AppWithRolesForUser;
83 import org.onap.portalapp.portal.transport.CentralV2Role;
84 import org.onap.portalapp.portal.transport.EPUserAppCurrentRoles;
85 import org.onap.portalapp.portal.transport.EcompUserAppRoles;
86 import org.onap.portalapp.portal.transport.ExternalAccessUser;
87 import org.onap.portalapp.portal.transport.ExternalAccessUserRoleDetail;
88 import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator;
89 import org.onap.portalapp.portal.transport.ExternalRoleDescription;
90 import org.onap.portalapp.portal.transport.FieldsValidator;
91 import org.onap.portalapp.portal.transport.FunctionalMenuItem;
92 import org.onap.portalapp.portal.transport.FunctionalMenuRole;
93 import org.onap.portalapp.portal.transport.RemoteRole;
94 import org.onap.portalapp.portal.transport.RemoteRoleV1;
95 import org.onap.portalapp.portal.transport.RemoteUserWithRoles;
96 import org.onap.portalapp.portal.transport.RoleInAppForUser;
97 import org.onap.portalapp.portal.transport.RolesInAppForUser;
98 import org.onap.portalapp.portal.transport.UserApplicationRoles;
99 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
100 import org.onap.portalapp.portal.utils.EcompPortalUtils;
101 import org.onap.portalapp.portal.utils.PortalConstants;
102 import org.onap.portalapp.util.EPUserUtils;
103 import org.onap.portalapp.util.SystemType;
104 import org.onap.portalsdk.core.domain.Role;
105 import org.onap.portalsdk.core.domain.RoleFunction;
106 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
107 import org.onap.portalsdk.core.restful.domain.EcompRole;
108 import org.onap.portalsdk.core.service.DataAccessService;
109 import org.onap.portalsdk.core.service.RoleService;
110 import org.onap.portalsdk.core.util.SystemProperties;
111 import org.springframework.beans.factory.annotation.Autowired;
112 import org.springframework.http.HttpEntity;
113 import org.springframework.http.HttpHeaders;
114 import org.springframework.http.HttpMethod;
115 import org.springframework.http.HttpStatus;
116 import org.springframework.http.ResponseEntity;
117 import org.springframework.web.client.HttpClientErrorException;
118 import org.springframework.web.client.RestTemplate;
120 import com.fasterxml.jackson.core.JsonProcessingException;
121 import com.fasterxml.jackson.databind.DeserializationFeature;
122 import com.fasterxml.jackson.databind.ObjectMapper;
125 public class UserRolesCommonServiceImpl {
127 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesCommonServiceImpl.class);
129 private static final Object syncRests = new Object();
131 private static final String APP_ID = "appId";
134 private DataAccessService dataAccessService;
136 private SessionFactory sessionFactory;
138 private SearchService searchService;
140 private EPAppService appsService;
142 private ApplicationsRestClientService applicationsRestClientService;
144 private EPRoleService epRoleService;
146 private RoleService roleService;
148 private AdminRolesService adminRolesService;
150 private EPAppService appService;
152 private ExternalAccessRolesService externalAccessRolesService;
155 private AppsCacheService appsCacheService;
157 RestTemplate template = new RestTemplate();
162 * @return HashMap<Long, EcompRole>
164 private static HashMap<Long, EcompRole> hashMapFromEcompRoles(EcompRole[] ecompRoles) {
165 HashMap<Long, EcompRole> result = new HashMap<Long, EcompRole>();
166 if (ecompRoles != null) {
167 for (int i = 0; i < ecompRoles.length; i++) {
168 if (ecompRoles[i].getId() != null) {
169 result.put(ecompRoles[i].getId(), ecompRoles[i]);
180 protected void createLocalUserIfNecessary(String userId,boolean isSystemUser) {
181 if (StringUtils.isEmpty(userId)) {
182 logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty userId!");
185 Session localSession = null;
186 Transaction transaction = null;
188 localSession = sessionFactory.openSession();
189 transaction = localSession.beginTransaction();
190 @SuppressWarnings("unchecked")
191 List<EPUser> userList = localSession
192 .createQuery("from EPUser where orgUserId=:userId")
193 .setParameter("userId",userId)
195 if (userList.size() == 0) {
196 EPUser client = null;
198 client = searchService.searchUserByUserId(userId);
200 client = new EPUser();
201 client.setOrgUserId(userId);
202 client.setSystemUser(true);
203 if (userId.indexOf("@") != -1) {
204 client.setFirstName(userId.substring(0,userId.indexOf("@")));
207 client.setFirstName(userId);
210 if (client == null) {
211 String msg = "createLocalUserIfNecessary: cannot create user " + userId
212 + ", because not found in phonebook";
213 logger.error(EELFLoggerDelegate.errorLogger, msg);
215 client.setLoginId(userId);
216 client.setActive(true);
217 localSession.save(client);
220 transaction.commit();
221 } catch (Exception e) {
222 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
223 EcompPortalUtils.rollbackTransaction(transaction, "searchOrCreateUser rollback, exception = " + e);
225 EcompPortalUtils.closeLocalSession(localSession, "searchOrCreateUser");
230 * This method return nothing and remove roles before adding any roles for an app
233 * @param localSession
234 * @param userAppRoles
235 * @param newUserAppRolesMap
237 private static void syncUserRolesExtension(EPUserApp userRole, Long appId, Session localSession, EcompRole[] userAppRoles, HashMap<Long, EcompRole> newUserAppRolesMap) {
239 Long userAppRoleId = 0L;
240 if (appId == PortalConstants.PORTAL_APP_ID) { // local app
241 userAppRoleId = userRole.getRoleId();
242 } else { // remote app
243 userAppRoleId = userRole.getAppRoleId();
246 if (!newUserAppRolesMap.containsKey(userAppRoleId)) {
247 localSession.delete(userRole);
249 newUserAppRolesMap.remove(userAppRoleId);
254 * Checks whether the role is inactive
258 * if role is inactive, throws exception
260 private void checkIfRoleInactive(EPRole epRole) throws Exception{
261 if(!epRole.getActive()){
262 throw new Exception(epRole.getName()+ " role is unavailable");
268 * @param sessionFactory
271 * @param userAppRoles
272 * @param extRequestValue
273 * set to false if request is from users page otherwise true
276 @SuppressWarnings("unchecked")
277 protected void syncUserRoles(SessionFactory sessionFactory, String userId, Long appId,
278 EcompRole[] userAppRoles, Boolean extRequestValue, String reqType,boolean checkIfUserisRoleAdmin,EcompRole[] appRoles) throws Exception {
279 Session localSession = null;
280 Transaction transaction = null;
281 String roleActive = null;
282 final Map<String, String> userAppParams = new HashMap<>();
283 final Map<String, String> appParams = new HashMap<>();
284 HashMap<Long, EcompRole> newUserAppRolesMap = hashMapFromEcompRoles(userAppRoles);
285 List<EPRole> roleInfo = externalAccessRolesService.getPortalAppRoleInfo(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
287 EPRole adminRole = new EPRole();
288 if(roleInfo.size()>0)
290 adminRole = roleInfo.get(0);
291 logger.debug(EELFLoggerDelegate.debugLogger, "Admin RoleName form DB: " + adminRole.getName());
294 localSession = sessionFactory.openSession();
295 transaction = localSession.beginTransaction();
296 @SuppressWarnings("unchecked")
297 List<EPUser> userList = localSession
298 .createQuery("from EPUser where orgUserId=:userId")
299 .setParameter("userId",userId)
301 if (userList.size() > 0) {
302 EPUser client = userList.get(0);
303 roleActive = ("DELETE".equals(reqType)) ? "" : " and role.active = 'Y'";
304 @SuppressWarnings("unchecked")
305 List<EPUserApp> userRoles = localSession.createQuery("from EPUserApp where app.id=:appId and userId=:userId" + roleActive)
306 .setParameter("appId",appId)
307 .setParameter("userId",client.getId())
310 if ("DELETE".equals(reqType)) {
311 for (EPUserApp userAppRoleList : userRoles) {
312 userAppParams.put("roleName", String.valueOf(userAppRoleList.getRole().getName()));
313 userAppParams.put("appId", String.valueOf(appId));
314 appParams.put("appRoleName", userAppRoleList.getRole().getName());
315 @SuppressWarnings("unchecked")
316 List<EPRole> rolesList = (!userAppRoleList.getRole().getName().equals(adminRole.getName())) ? (List<EPRole>) dataAccessService.executeNamedQuery("getAppRoles", userAppParams, null) : (List<EPRole>) dataAccessService.executeNamedQuery("getPortalAppRoles", appParams, null);
317 if(rolesList.size() > 0 || !rolesList.isEmpty()){
318 checkIfRoleInactive(rolesList.get(0));
323 if (appRoles != null) {
324 List<EcompRole> appRolesList = Arrays.stream(appRoles).collect(Collectors.toList());
325 List<EPUserApp> finalUserRolesList = new ArrayList<>();
326 if (checkIfUserisRoleAdmin) {
327 for (EcompRole role : appRolesList) {
328 for (EPUserApp userAppRoleList : userRoles) {
329 if (userAppRoleList.getRole().getName().equals(role.getName()))
332 finalUserRolesList.add(userAppRoleList);
337 userRoles = new ArrayList<>();
338 userRoles.addAll(finalUserRolesList);
342 for (EPUserApp userRole : userRoles) {
343 if (!userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && userRole.getRoleId() != PortalConstants.SYS_ADMIN_ROLE_ID && !extRequestValue){
344 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
346 else if (extRequestValue && ("PUT".equals(reqType) || "POST".equals(reqType) || "DELETE".equals(reqType))){
347 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
349 else if (extRequestValue && !userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)){
350 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
355 Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values();
356 if (newRolesToAdd.size() > 0) {
357 EPApp app = (EPApp) localSession.get(EPApp.class, appId);
359 HashMap<Long, EPRole> rolesMap = new HashMap<Long, EPRole>();
360 if (appId.equals(PortalConstants.PORTAL_APP_ID)) { // local app
361 String appIdValue = "";
362 if(!extRequestValue){
363 appIdValue = "and id != " + PortalConstants.SYS_ADMIN_ROLE_ID;
365 @SuppressWarnings("unchecked")
366 List<EPRole> roles = localSession
367 .createQuery("from " + EPRole.class.getName() + " where appId is null " + appIdValue).list();
368 for (EPRole role : roles) {
370 rolesMap.put(role.getId(), role);
372 } else { // remote app
373 @SuppressWarnings("unchecked")
374 List<EPRole> roles = localSession
375 .createQuery("from EPRole where appId=:appId")
376 .setParameter("appId",appId)
378 for (EPRole role : roles) {
379 if (!extRequestValue && app.getRolesInAAF()) {
380 rolesMap.put(role.getId(), role);
382 rolesMap.put(role.getAppRoleId(), role);
388 for (EcompRole userRole : newRolesToAdd) {
389 EPUserApp userApp = new EPUserApp();
390 if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName().equals(adminRole.getName())) {
391 role = (EPRole) localSession.get(EPRole.class, new Long(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
392 userApp.setRole(role);
393 } else if ((userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) && !extRequestValue){
395 }else if((userRole.getId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)) && app.getId().equals(PortalConstants.PORTAL_APP_ID) && !extRequestValue){
399 userApp.setRole(rolesMap.get(userRole.getId()));
402 userApp.setUserId(client.getId());
404 localSession.save(userApp);
405 localSession.flush();
408 if (appId == PortalConstants.PORTAL_APP_ID) {
410 * for local app -- hack - always make sure fn_role
411 * table's app_id is null and not 1 for primary app in
412 * this case being onap portal app; reason: hibernate
413 * is rightly setting this to 1 while persisting to
414 * fn_role as per the mapping but SDK role management
415 * code expects the app_id to be null as there is no
416 * concept of App_id in SDK
418 localSession.flush();
419 SQLQuery sqlQuery = localSession
420 .createSQLQuery("update fn_role set app_id = null where app_id = 1 ");
421 sqlQuery.executeUpdate();
426 transaction.commit();
427 } catch (Exception e) {
428 logger.error(EELFLoggerDelegate.errorLogger, "syncUserRoles failed", e);
429 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
430 EcompPortalUtils.rollbackTransaction(transaction,
431 "Exception occurred in syncUserRoles, Details: " + e.toString());
432 if("DELETE".equals(reqType)){
433 throw new SyncUserRolesException(e.getMessage());
436 if(localSession != null)
437 localSession.close();
442 * Called when getting the list of roles for the user
445 * @param userAppRoles
446 * @return List<RoleInAppForUser>
448 protected List<RoleInAppForUser> constructRolesInAppForUserGet(EcompRole[] appRoles, EcompRole[] userAppRoles) {
449 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
451 Set<Long> userAppRolesMap = new HashSet<Long>();
452 if (userAppRoles != null) {
453 for (EcompRole ecompRole : userAppRoles) {
454 userAppRolesMap.add(ecompRole.getId());
457 logger.error(EELFLoggerDelegate.errorLogger,
458 "constructRolesInAppForUserGet has received userAppRoles list empty");
461 if (appRoles != null) {
462 for (EcompRole ecompRole : appRoles) {
463 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
464 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
465 rolesInAppForUser.add(roleForUser);
468 logger.error(EELFLoggerDelegate.errorLogger, "constructRolesInAppForUser has received appRoles list empty");
470 return rolesInAppForUser;
474 * Called when getting the list of roles for the user
477 * @param userAppRoles
478 * @param extRequestValue
479 * set to false if request is from users page otherwise true
480 * @return List<RoleInAppForUser>
482 protected List<RoleInAppForUser> constructRolesInAppForUserGet(List<Role> appRoles, EPRole[] userAppRoles, Boolean extRequestValue) {
483 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
485 Set<Long> userAppRolesMap = new HashSet<Long>();
486 if (userAppRoles != null) {
487 for (EPRole ecompRole : userAppRoles) {
488 userAppRolesMap.add(ecompRole.getId());
490 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - userAppRolesMap = {}", userAppRolesMap);
493 logger.error(EELFLoggerDelegate.errorLogger,
494 "constructRolesInAppForUserGet has received userAppRoles list empty.");
497 if (appRoles != null) {
499 for (Role ecompRole : appRoles) {
500 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - appRoles not null = {}", ecompRole);
502 if (ecompRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && !extRequestValue)
504 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
505 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
506 rolesInAppForUser.add(roleForUser);
507 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - rolesInAppForUser = {}", rolesInAppForUser);
511 logger.error(EELFLoggerDelegate.errorLogger,
512 "constructRolesInAppForUser has received appRoles list empty.");
514 return rolesInAppForUser;
519 * copies of methods in GetAppsWithUserRoleState
521 * @param sessionFactory
526 protected void syncAppRoles(SessionFactory sessionFactory, Long appId, EcompRole[] appRoles) throws Exception {
527 logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId);
528 HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles);
529 Session localSession = null;
530 Transaction transaction = null;
533 localSession = sessionFactory.openSession();
534 transaction = localSession.beginTransaction();
535 // Attention! All roles from remote application supposed to be
538 @SuppressWarnings("unchecked")
539 List<EPRole> currentAppRoles = localSession.createQuery("from EPRole where appId = :appId")
540 .setParameter("appId",appId)
543 List<EPRole> obsoleteRoles = new ArrayList<EPRole>();
544 for (int i = 0; i < currentAppRoles.size(); i++) {
545 EPRole oldAppRole = currentAppRoles.get(i);
546 if (oldAppRole.getAppRoleId() != null) {
547 EcompRole role = null;
548 role = newRolesMap.get(oldAppRole.getAppRoleId());
550 if (!(role.getName() == null || oldAppRole.getName().equals(role.getName()))) {
551 oldAppRole.setName(role.getName());
552 localSession.update(oldAppRole);
554 oldAppRole.setActive(true);
555 newRolesMap.remove(oldAppRole.getAppRoleId());
557 obsoleteRoles.add(oldAppRole);
560 obsoleteRoles.add(oldAppRole);
563 Collection<EcompRole> newRolesToAdd = newRolesMap.values();
564 if (obsoleteRoles.size() > 0) {
565 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: we have obsolete roles to delete");
566 for (EPRole role : obsoleteRoles) {
567 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: obsolete role: " + role.toString());
568 Long roleId = role.getId();
569 // delete obsolete roles here
570 // Must delete all records with foreign key constraints on
572 // fn_user_role, fn_role_composite, fn_role_function,
573 // fn_user_pseudo_role, fn_menu_functional_roles.
574 // And for fn_menu_functional, if no other roles for that
575 // menu item, remove the url.
577 // Delete from fn_user_role
578 @SuppressWarnings("unchecked")
579 List<EPUserApp> userRoles = localSession.createQuery(
580 "from EPUserApp where app.id=:appId and role_id=:roleId")
581 .setParameter("appId",appId)
582 .setParameter("roleId",roleId)
585 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: number of userRoles to delete: " + userRoles.size());
586 for (EPUserApp userRole : userRoles) {
587 logger.debug(EELFLoggerDelegate.debugLogger,
588 "syncAppRoles: about to delete userRole: " + userRole.toString());
589 localSession.delete(userRole);
590 logger.debug(EELFLoggerDelegate.debugLogger,
591 "syncAppRoles: finished deleting userRole: " + userRole.toString());
594 // Delete from fn_menu_functional_roles
595 @SuppressWarnings("unchecked")
596 List<FunctionalMenuRole> funcMenuRoles = localSession
597 .createQuery("from FunctionalMenuRole where roleId=:roleId")
598 .setParameter("roleId",roleId)
600 int numMenuRoles = funcMenuRoles.size();
601 logger.debug(EELFLoggerDelegate.debugLogger,
602 "syncAppRoles: number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles);
603 for (FunctionalMenuRole funcMenuRole : funcMenuRoles) {
604 Long menuId = funcMenuRole.menuId;
605 // If this is the only role for this menu item, then the
606 // app and roles will be gone,
607 // so must null out the url too, to be consistent
608 @SuppressWarnings("unchecked")
609 List<FunctionalMenuRole> funcMenuRoles2 = localSession
610 .createQuery("from FunctionalMenuRole where menuId=:menuId")
611 .setParameter("menuId",menuId)
613 int numMenuRoles2 = funcMenuRoles2.size();
614 logger.debug(EELFLoggerDelegate.debugLogger,
615 "syncAppRoles: number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2);
616 localSession.delete(funcMenuRole);
617 if (numMenuRoles2 == 1) {
618 // If this is the only role for this menu item, then
619 // the app and roles will be gone,
620 // so must null out the url too, to be consistent
621 logger.debug(EELFLoggerDelegate.debugLogger,
622 "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url");
623 @SuppressWarnings("unchecked")
624 List<FunctionalMenuItem> funcMenuItems = localSession
625 .createQuery("from FunctionalMenuItem where menuId=:menuId")
626 .setParameter("menuId",menuId)
628 if (funcMenuItems.size() > 0) {
629 logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item");
630 FunctionalMenuItem funcMenuItem = funcMenuItems.get(0);
631 funcMenuItem.url = "";
632 localSession.update(funcMenuItem);
636 boolean isPortalRequest = true;
637 externalAccessRolesService.deleteRoleDependencyRecords(localSession, roleId, appId, isPortalRequest);
638 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to delete the role: " + role.toString());
639 localSession.delete(role);
640 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: deleted the role");
643 for (EcompRole role : newRolesToAdd) {
644 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to add missing role: " + role.toString());
645 EPRole newRole = new EPRole();
646 // Attention! All roles from remote application supposed to be
648 newRole.setActive(true);
649 newRole.setName(role.getName());
650 newRole.setAppId(appId);
651 newRole.setAppRoleId(role.getId());
652 localSession.save(newRole);
654 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to commit the transaction");
655 transaction.commit();
656 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: committed the transaction");
657 } catch (Exception e) {
658 logger.error(EELFLoggerDelegate.errorLogger, "syncAppRoles failed", e);
659 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
660 EcompPortalUtils.rollbackTransaction(transaction,
661 "Exception occurred in syncAppRoles, Details: " + e.toString());
662 throw new Exception(e);
664 localSession.close();
673 * Called when updating the list of roles for the user
677 * @param userRolesInRemoteApp
678 * @return RolesInAppForUser
680 protected RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId,
681 Set<EcompRole> userRolesInRemoteApp) {
682 RolesInAppForUser result;
683 result = new RolesInAppForUser();
684 result.appId = appId;
685 result.orgUserId = userId;
687 for (EcompRole role : userRolesInRemoteApp) {
688 RoleInAppForUser roleInAppForUser = new RoleInAppForUser();
689 roleInAppForUser.roleId = role.getId();
690 roleInAppForUser.roleName = role.getName();
691 roleInAppForUser.isApplied = new Boolean(true);
692 result.roles.add(roleInAppForUser);
699 * @param roleInAppForUserList
702 protected boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) {
703 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
704 if (roleInAppForUser.isApplied.booleanValue()) {
712 * Builds JSON and posts it to a remote application to update user roles.
714 * @param roleInAppForUserList
716 * @param applicationsRestClientService
719 * @return Set of roles as sent; NOT the response from the app.
720 * @throws JsonProcessingException
721 * @throws HTTPException
723 protected Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
724 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId,boolean systemUser)
725 throws JsonProcessingException, HTTPException {
726 Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList);
727 Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList);
728 String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote);
729 EPApp externalApp = null;
730 SystemType type = SystemType.APPLICATION;
731 externalApp = appsCacheService.getApp(appId);
732 String appBaseUri = null;
733 Set<RemoteRoleV1> updatedUserRolesinRemoteV1 = new TreeSet<>();
734 if (externalApp != null) {
735 appBaseUri = (type == SystemType.APPLICATION) ? externalApp.getAppRestEndpoint() : "";
737 if(appBaseUri != null && appBaseUri.endsWith("/api")){
738 for(EcompRole eprole :updatedUserRolesinRemote)
740 RemoteRoleV1 role = new RemoteRoleV1();
741 role.setId(eprole.getId());
742 role.setName(eprole.getName());
743 updatedUserRolesinRemoteV1.add(role);
745 userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemoteV1);
747 applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString,
748 String.format("/user/%s/roles", userId));
749 // TODO: We should add code that verifies that the post operation did
750 // succeed. Because the SDK may still return 200 OK with an html page
751 // even when it fails!
752 return updateUserRolesInEcomp;
757 * @param roleInAppForUserList
758 * @return Set<EcompRole>
760 protected Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) {
761 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
762 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
763 if (roleInAppForUser.isApplied) {
764 EcompRole ecompRole = new EcompRole();
765 ecompRole.setId(roleInAppForUser.roleId);
766 ecompRole.setName(roleInAppForUser.roleName);
767 existingUserRoles.add(ecompRole);
770 return existingUserRoles;
774 * Constructs user app roles excluding Account Administrator role
776 * @param roleInAppForUserList
778 * List of roles with Role name, Role Id
780 protected Set<EcompRole> constructUsersRemoteAppRoles(List<RoleInAppForUser> roleInAppForUserList) {
781 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
782 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
783 if (roleInAppForUser.isApplied && !roleInAppForUser.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
784 EcompRole ecompRole = new EcompRole();
785 ecompRole.setId(roleInAppForUser.roleId);
786 ecompRole.setName(roleInAppForUser.roleName);
787 existingUserRoles.add(ecompRole);
790 return existingUserRoles;
794 * This is for a single app
796 * @param rolesInAppForUser
797 * @param externalSystemRequest
798 * set to false if requests from Users page otherwise true
799 * @return true on success, false otherwise
801 protected boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser, boolean externalSystemRequest, String reqType,boolean isSystemUser,Set<EcompRole> rolesDeletedByApprover ,boolean isLoggedInUserRoleAdminOfApp ) throws Exception {
802 boolean result = false;
803 String userId = rolesInAppForUser.orgUserId;
804 Long appId = rolesInAppForUser.appId;
805 synchronized (syncRests) {
806 if (rolesInAppForUser != null) {
807 createLocalUserIfNecessary(userId, isSystemUser);
810 if (rolesInAppForUser != null) {
811 EcompRole[] userAppRoles = new EcompRole[rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size()];
812 for (int i = 0; i < rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size(); i++) {
813 RoleInAppForUser roleInAppForUser = rolesInAppForUser.roles.get(i);
814 EcompRole role = new EcompRole();
815 role.setId(roleInAppForUser.roleId);
816 role.setName(roleInAppForUser.roleName);
817 userAppRoles[i] = role;
820 EcompRole[] applicationRoles = null;
822 if(isLoggedInUserRoleAdminOfApp){
823 List<EcompRole> roles = Arrays.stream(userAppRoles).collect(Collectors.toList());
824 List<EcompRole> roles1 = rolesDeletedByApprover.stream().collect(Collectors.toList());
825 roles.addAll(roles1);
826 applicationRoles = roles.stream().toArray(n -> new EcompRole[n]);
829 syncUserRoles(sessionFactory, userId, appId, userAppRoles, externalSystemRequest, reqType,isLoggedInUserRoleAdminOfApp,applicationRoles);
831 } catch (Exception e) {
832 logger.error(EELFLoggerDelegate.errorLogger,
833 "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for orgUserId " + userId, e);
834 if("DELETE".equals(reqType)){
835 throw new Exception(e.getMessage());
847 * @return UserApplicationRoles
849 protected UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) {
850 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
851 userWithRemoteAppRoles.setAppId(appId);
852 userWithRemoteAppRoles.setOrgUserId(remoteUser.getOrgUserId());
853 userWithRemoteAppRoles.setFirstName(remoteUser.getFirstName());
854 userWithRemoteAppRoles.setLastName(remoteUser.getLastName());
855 userWithRemoteAppRoles.setRoles(remoteUser.getRoles());
856 return userWithRemoteAppRoles;
862 * @see org.onap.portalapp.portal.service.UserRolesService#
863 * importRolesFromRemoteApplication(java.lang.Long)
865 public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException {
866 EPRole[] appRolesFull = applicationsRestClientService.get(EPRole[].class, appId, "/rolesFull");
867 List<EPRole> rolesList = Arrays.asList(appRolesFull);
868 for (EPRole externalAppRole : rolesList) {
870 // Try to find an existing extern role for the app in the local
871 // onap DB. If so, then use its id to update the existing external
872 // application role record.
873 Long externAppId = externalAppRole.getId();
874 EPRole existingAppRole = epRoleService.getRole(appId, externAppId);
875 if (existingAppRole != null) {
876 logger.debug(EELFLoggerDelegate.debugLogger,
877 String.format("ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.",
878 appId, externAppId));
881 // persistExternalRoleInEcompDb(externalAppRole, appId,
889 * It adds new user for remote application
891 * @param roleInAppForUserList
892 * @param remoteAppUser
896 * @param searchService
897 * @param applicationsRestClientService
901 private EPUser addRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app,
902 ObjectMapper mapper, SearchService searchService,
903 ApplicationsRestClientService applicationsRestClientService) throws Exception {
904 EPUser addRemoteUser = null;
905 if (remoteUserShouldBeCreated(roleInAppForUserList)) {
906 createNewUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper,
907 isAppUpgradeVersion(app));
909 return addRemoteUser;
912 private EPUser pushRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app,
913 ObjectMapper mapper, SearchService searchService,
914 ApplicationsRestClientService applicationsRestClientService,boolean appRoleIdUsed) throws Exception {
915 EPUser addRemoteUser = null;
916 // if (remoteUserShouldBeCreated(roleInAppForUserList)) {
917 pushUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper,
918 isAppUpgradeVersion(app), roleInAppForUserList, appRoleIdUsed);
920 return addRemoteUser;
923 @SuppressWarnings("unchecked")
924 protected void pushUserOnRemoteApp(String userId, EPApp app,
925 ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
926 ObjectMapper mapper, boolean postOpenSource, List<RoleInAppForUser> roleInAppForUserList,boolean appRoleIdUsed) throws Exception {
928 EPUser client = null;
929 client = searchService.searchUserByUserId(userId);
931 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
932 if (client == null) {
933 String msg = "cannot create user " + userId + ", because he/she cannot be found in directory.";
934 logger.error(EELFLoggerDelegate.errorLogger, msg);
935 // throw new Exception(msg);
936 final Map<String, String> loginIdParams = new HashMap<>();
937 loginIdParams.put("orgUserIdValue", userId);
938 List<EPUser> userList = new ArrayList<>();
939 userList = dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null);
940 if (userList.size() > 0) {
941 logger.debug(EELFLoggerDelegate.debugLogger,
942 userList.get(0).getOrgUserId() + " User was found in Portal");
943 client = userList.get(0);
944 SortedSet<EPUserApp> userApps = new TreeSet<>();
945 client.setEPUserApps(userApps);
946 client.setSystemUser(false);
948 logger.error(EELFLoggerDelegate.errorLogger, "user cannot be found be in directory or in portal");
949 throw new Exception(msg);
954 client.setLoginId(userId);
955 client.setActive(true);
956 client.setOrgUserId(userId);
959 roleInAppForUserList.removeIf(role -> role.isApplied.equals(false));
960 SortedSet<Role> roles = new TreeSet<>();
962 List<EPRole> getAppRoles = externalAccessRolesService.getAppRoles(app.getId());
963 List<EPApp> appList = new ArrayList<>();
965 List<CentralV2Role> roleList = new ArrayList<>();
966 Map<String, Long> params = new HashMap<>();
968 List<EPRole> userRoles = new ArrayList<>();
970 for (RoleInAppForUser roleInappForUser : roleInAppForUserList) {
971 EPRole role = new EPRole();
972 role.setId(roleInappForUser.getRoleId());
973 role.setName(roleInappForUser.getRoleName());
978 List<EPRole> userAppRoles = new ArrayList<>();
979 for (EPRole role : userRoles) {
980 EPRole appRole = getAppRoles.stream()
981 .filter(applicationRole -> role.getId().equals(applicationRole.getAppRoleId())).findAny()
983 EPRole epRole = new EPRole();
984 if (appRole != null) {
985 epRole.setId(appRole.getId());
986 epRole.setName(appRole.getName());
988 userAppRoles.add(epRole);
990 userRoles = new ArrayList<>();
991 userRoles.addAll(userAppRoles);
993 roleList = externalAccessRolesService.createCentralRoleObject(appList, userRoles, roleList, params);
995 for (CentralV2Role epRole : roleList) {
996 Role role = new Role();
997 EPRole appRole = getAppRoles.stream()
998 .filter(applicationRole -> epRole.getId().equals(applicationRole.getId())).findAny().orElse(null);
999 if (appRole != null){
1000 role.setId(appRole.getAppRoleId());
1001 role.setName(epRole.getName());
1002 role.setRoleFunctions(epRole.getRoleFunctions());
1006 client.setRoles(roles);
1007 String userInString = null;
1008 userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
1009 logger.debug(EELFLoggerDelegate.debugLogger,
1010 "about to post a client to remote application, users json = " + userInString);
1011 applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user/%s", userId));
1015 * It checks whether the remote user exists or not
1016 * if exits returns user object else null
1020 * @param applicationsRestClientService
1022 * @throws HTTPException
1024 private EPUser checkIfRemoteUserExits(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService) throws HTTPException{
1025 EPUser checkRemoteUser = null;
1027 checkRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
1028 } catch (HTTPException e) {
1029 // Some apps are returning 400 if user is not found.
1030 if (e.getResponseCode() == 400) {
1031 logger.debug(EELFLoggerDelegate.debugLogger,
1032 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing",
1034 } else if(e.getResponseCode() == 404) {
1035 logger.debug(EELFLoggerDelegate.debugLogger,
1036 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 404; continuing",
1039 // Other response code, let it come thru.
1043 return checkRemoteUser;
1050 * @see org.onap.portalapp.portal.service.UserRolesService#
1051 * setAppWithUserRoleStateForUser(org.onap.portalapp.portal.domain.
1052 * EPUser, org.onap.portalapp.portal.transport.AppWithRolesForUser)
1054 public ExternalRequestFieldsValidator setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser) {
1055 boolean result = false;
1056 boolean epRequestValue = false;
1058 String reqMessage = "";
1059 if (newAppRolesForUser != null && newAppRolesForUser.getOrgUserId() != null) {
1060 userId = newAppRolesForUser.getOrgUserId().trim();
1062 Long appId = newAppRolesForUser.getAppId();
1063 List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.getAppRoles();
1067 if (userId.length() > 0 ) {
1068 ObjectMapper mapper = new ObjectMapper();
1069 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1072 EPApp app = appsService.getApp(appId);
1074 boolean checkIfUserisApplicationAccAdmin = adminRolesService.isAccountAdminOfApplication(user,
1076 Set<EcompRole> rolesGotDeletedFromApprover = new TreeSet<EcompRole>();
1078 boolean checkIfUserisOnlyRoleAdmin = adminRolesService.isRoleAdmin(user) && !checkIfUserisApplicationAccAdmin;
1079 if (checkIfUserisOnlyRoleAdmin) {
1080 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
1081 if (!roleInAppForUser.isApplied) {
1082 EcompRole ecompRole = new EcompRole();
1083 ecompRole.setId(roleInAppForUser.roleId);
1084 ecompRole.setName(roleInAppForUser.roleName);
1085 rolesGotDeletedFromApprover.add(ecompRole);
1089 applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
1091 Boolean systemUser = (newAppRolesForUser.getIsSystemUser() != null ? newAppRolesForUser.getIsSystemUser() : false);
1093 if ((app.getRolesInAAF() || app.getId().equals(PortalConstants.PORTAL_APP_ID)) && systemUser) {
1095 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1096 applicationsRestClientService, appId, userId);
1097 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1098 userRolesInLocalApp);
1099 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1100 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
1101 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1102 // Apply changes in external Access system
1104 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList,
1105 epRequestValue, systemUser,rolesGotDeletedByApprover,false);
1107 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal",
1108 systemUser,rolesGotDeletedByApprover,false);
1110 }else if (!app.getRolesInAAF() && systemUser)
1112 throw new Exception("For non-centralized application we cannot add systemUser");
1114 else{ // if centralized app
1115 if (app.getRolesInAAF()) {
1117 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && (app.getAppAck() != null && app.getAppAck())) {
1118 logger.debug(EELFLoggerDelegate.debugLogger,"setAppWithUserRoleStateForUser: calling pushRemoteUser method for Central application");
1119 logger.debug(EELFLoggerDelegate.debugLogger,"setAppWithUserRoleStateForUser:"+app.getAppAck());
1120 pushRemoteUser(roleInAppForUserList, userId, app, mapper, searchService,
1121 applicationsRestClientService,false);
1124 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1125 applicationsRestClientService, appId, userId);
1126 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1127 userRolesInLocalApp);
1128 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1129 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1131 // Apply changes in external Access system
1132 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList,
1133 epRequestValue,false,rolesGotDeletedFromApprover,checkIfUserisOnlyRoleAdmin);
1135 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal", systemUser,rolesGotDeletedFromApprover,checkIfUserisOnlyRoleAdmin);
1137 // In case if portal is not centralized then follow existing approach
1138 else if(!app.getRolesInAAF() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1139 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1140 applicationsRestClientService, appId, userId);
1141 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1142 userRolesInLocalApp);
1143 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
1144 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal",false,rolesGotDeletedByApprover,false);
1145 } else{// remote app
1146 EPUser remoteAppUser = null;
1147 if(!app.getRolesInAAF() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1149 remoteAppUser = checkIfRemoteUserExits(userId, app, applicationsRestClientService);
1151 if (remoteAppUser == null) {
1152 remoteAppUser = addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService, applicationsRestClientService);
1154 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
1155 applicationsRestClientService, appId, userId,systemUser);
1156 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1157 userRolesInRemoteApp);
1158 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
1159 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null,false,rolesGotDeletedByApprover,false);
1161 // If no roles remain, request app to set user inactive.
1162 if (userRolesInRemoteApp.size() == 0) {
1163 logger.debug(EELFLoggerDelegate.debugLogger,
1164 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
1166 //remoteAppUser.setActive(false);
1167 postUserToRemoteApp(userId, user, app, applicationsRestClientService);
1172 } catch (Exception e) {
1173 /*String message = String.format(
1174 "Failed to create user or update user roles for User %s, AppId %s",
1175 userId, Long.toString(appId));
1176 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1179 String message = String.format(
1180 "Failed to create user or update user roles for User %s, AppId %s",
1181 userId, Long.toString(appId));
1182 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1184 reqMessage = e.getMessage();
1191 return new ExternalRequestFieldsValidator(result, reqMessage);
1195 * It adds user roles in External system and also make data consistent in both local and in External System
1197 * @param app details
1199 * @param roleInAppUser Contains list of active roles
1201 @SuppressWarnings("unchecked")
1202 private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser, boolean isPortalRequest,boolean nonHumanUserId,Set<EcompRole> deletedRolesByApprover,boolean isLoggedInUserRoleAdminofApp) throws Exception
1205 // check if user exists
1206 final Map<String, String> userParams = new HashMap<>();
1207 userParams.put("orgUserIdValue", orgUserId);
1208 List<EPUser> userInfo = checkIfUserExists(userParams);
1209 if (userInfo.isEmpty()) {
1210 createLocalUserIfNecessary(orgUserId, nonHumanUserId);
1213 if (EPCommonSystemProperties
1214 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN) && !nonHumanUserId) {
1215 if(orgUserId.indexOf("@") ==-1) {
1216 name = orgUserId + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
1222 if(nonHumanUserId && orgUserId!=null) {
1223 if(orgUserId.indexOf("@") ==-1) {
1224 name = orgUserId + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
1228 ObjectMapper mapper = new ObjectMapper();
1229 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1230 HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
1231 ResponseEntity<String> getResponse = externalAccessRolesService.getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
1234 List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
1235 String res = getResponse.getBody();
1236 JSONObject jsonObj = null;
1237 JSONArray extRoles = null;
1238 if (!res.equals("{}")) {
1239 jsonObj = new JSONObject(res);
1240 extRoles = jsonObj.getJSONArray("role");
1242 ExternalAccessUserRoleDetail userRoleDetail = null;
1243 if (extRoles != null) {
1244 for (int i = 0; i < extRoles.length(); i++) {
1245 if (extRoles.getJSONObject(i).getString("name").startsWith(app.getNameSpace() + ".")
1246 && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".admin")
1247 && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".owner")) {
1248 if (extRoles.getJSONObject(i).has("description")) {
1249 ExternalRoleDescription desc = new ExternalRoleDescription(extRoles.getJSONObject(i).getString("description"));
1250 userRoleDetail = new ExternalAccessUserRoleDetail(
1251 extRoles.getJSONObject(i).getString("name"), desc);
1252 userRoleDetailList.add(userRoleDetail);
1254 userRoleDetail = new ExternalAccessUserRoleDetail(
1255 extRoles.getJSONObject(i).getString("name"), null);
1256 userRoleDetailList.add(userRoleDetail);
1263 List<ExternalAccessUserRoleDetail> userRoleListMatchingInExtAuthAndLocal = CheckIfRoleAreMatchingInUserRoleDetailList(userRoleDetailList,app);
1265 List<EcompUserAppRoles> userAppList = new ArrayList<>();
1266 // If request coming from portal not from external role approval system then we have to check if user already
1267 // have account admin or system admin as GUI will not send these roles
1268 if (!isPortalRequest) {
1269 final Map<String, String> loginIdParams = new HashMap<>();
1270 loginIdParams.put("orgUserIdValue", orgUserId);
1271 EPUser user = (EPUser) dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null).get(0);
1272 final Map<String, Long> params = new HashMap<>();
1273 params.put("appId", app.getId());
1274 params.put("userId", user.getId());
1275 userAppList = dataAccessService.executeNamedQuery("getUserAppExistingRoles",
1277 if (!roleInAppUser.isEmpty()) {
1278 for (EcompUserAppRoles userApp : userAppList) {
1279 if (userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)
1280 || userApp.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
1281 RoleInAppForUser addSpecialRole = new RoleInAppForUser();
1282 addSpecialRole.setIsApplied(true);
1283 addSpecialRole.setRoleId(userApp.getRoleId());
1284 addSpecialRole.setRoleName(userApp.getRoleName());
1285 roleInAppUser.add(addSpecialRole);
1290 List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct()
1291 .collect(Collectors.toList());
1292 Map<String, RoleInAppForUser> currentUserRolesToUpdate = new HashMap<>();
1293 for (RoleInAppForUser roleInAppUserNew : roleInAppUserNonDupls) {
1294 currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), roleInAppUserNew);
1296 final Map<String, ExternalAccessUserRoleDetail> currentUserRolesInExternalSystem = new HashMap<>();
1297 for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleListMatchingInExtAuthAndLocal) {
1298 currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole);
1301 if (isLoggedInUserRoleAdminofApp) {
1302 if (deletedRolesByApprover.size() > 0) {
1303 List<ExternalAccessUserRoleDetail> newUpdatedRoles = new ArrayList<>();
1304 Set<EcompRole> roles = new HashSet<>();
1305 for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
1306 for (EcompRole role : deletedRolesByApprover) {
1307 if ((userRole.getName().substring(app.getNameSpace().length() + 1)).equals(role.getName())) {
1309 newUpdatedRoles.add(userRole);
1313 if (newUpdatedRoles.size() > 0) {
1314 userRoleListMatchingInExtAuthAndLocal = new ArrayList<>();
1315 userRoleListMatchingInExtAuthAndLocal.addAll(newUpdatedRoles);
1317 userRoleListMatchingInExtAuthAndLocal = new ArrayList<>();
1318 currentUserRolesToUpdate = new HashMap<>();
1323 userRoleListMatchingInExtAuthAndLocal = new ArrayList<>();
1324 currentUserRolesToUpdate = new HashMap<>();
1329 // Check if user roles does not exists in local but still there in External Central Auth System delete them all
1330 for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
1331 if (!(currentUserRolesToUpdate
1332 .containsKey(userRole.getName().substring(app.getNameSpace().length() + 1)))) {
1333 HttpEntity<String> entity = new HttpEntity<>(headers);
1334 logger.debug(EELFLoggerDelegate.debugLogger,
1335 "updateUserRolesInExternalSystem: Connecting to external system to DELETE user role {}",
1336 userRole.getName());
1337 ResponseEntity<String> deleteResponse = template.exchange(
1338 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1339 + "userRole/" + name + "/" + userRole.getName(),
1340 HttpMethod.DELETE, entity, String.class);
1341 logger.debug(EELFLoggerDelegate.debugLogger,
1342 "updateUserRolesInExternalSystem: Finished DELETE operation in external system for user role {} and the response is {}",
1343 userRole.getName(), deleteResponse.getBody());
1346 // Check if user roles does not exists in External Central Auth System add them all
1347 for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) {
1348 if (!(currentUserRolesInExternalSystem
1349 .containsKey(app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")))) {
1350 ExternalAccessUser extUser = new ExternalAccessUser(name,
1351 app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1352 String formattedUserRole = mapper.writeValueAsString(extUser);
1353 HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers);
1354 logger.debug(EELFLoggerDelegate.debugLogger, "updateUserRolesInExternalSystem: Connecting to external system for user {} and POST {}",
1355 name , addUserRole.getRoleName());
1356 ResponseEntity<String> addResponse = template
1357 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1358 + "userRole", HttpMethod.POST, entity, String.class);
1359 logger.debug(EELFLoggerDelegate.debugLogger,
1360 "updateUserRolesInExternalSystem: Finished adding user role in external system {} and added user role {}",
1361 addResponse.getBody(), addUserRole.getRoleName());
1362 if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 404) {
1363 logger.debug(EELFLoggerDelegate.debugLogger,
1364 "Finished POST operation in external system but unable to save user role", addResponse.getBody(),
1365 addUserRole.getRoleName());
1366 throw new Exception(addResponse.getBody());
1370 } catch (HttpClientErrorException e) {
1371 logger.error(EELFLoggerDelegate.errorLogger,
1372 "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}",
1374 if (e.getStatusCode() == HttpStatus.FORBIDDEN) {
1375 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid systemUser", orgUserId);
1376 throw new HttpClientErrorException(HttpStatus.FORBIDDEN, "Please enter the valid systemUser");
1378 if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
1379 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid role");
1380 throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "Please enter the valid role");
1382 EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
1386 catch (Exception e) {
1387 logger.error(EELFLoggerDelegate.errorLogger, "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}", app.getId(), e);
1388 EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
1394 private List<ExternalAccessUserRoleDetail> CheckIfRoleAreMatchingInUserRoleDetailList(
1395 List<ExternalAccessUserRoleDetail> userRoleDetailList, EPApp app) {
1396 Map<String, EPRole> epRoleList = externalAccessRolesService.getAppRoleNamesWithUnderscoreMap(app);
1397 //Add Account Admin role for partner app to prevent conflict
1398 if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1399 EPRole role = new EPRole();
1400 role.setName(PortalConstants.ADMIN_ROLE.replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1401 epRoleList.put(role.getName(), role);
1403 userRoleDetailList.removeIf(userRoleDetail -> !epRoleList.containsKey(userRoleDetail.getName().substring(app.getNameSpace().length()+1)));
1404 return userRoleDetailList;
1411 * @param applicationsRestClientService
1412 * @param searchService
1416 protected void createNewUserOnRemoteApp(String userId, EPApp app,
1417 ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
1418 ObjectMapper mapper, boolean postOpenSource) throws Exception {
1421 EPUser client = searchService.searchUserByUserId(userId);
1423 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1425 if (client == null) {
1426 String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook.";
1427 logger.error(EELFLoggerDelegate.errorLogger, msg);
1428 throw new Exception(msg);
1431 client.setLoginId(userId);
1432 client.setActive(true);
1434 String userInString = null;
1435 userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
1436 logger.debug(EELFLoggerDelegate.debugLogger,
1437 "about to post new client to remote application, users json = " + userInString);
1438 applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user", userId));
1442 @SuppressWarnings("unchecked")
1443 protected void applyChangesToAppRolesRequest(Long appId, Long userId, String updateStatus, EPUserAppRolesRequest epUserAppRolesRequest) {
1444 final Map<String, Long> epRequestParams = new HashMap<>();
1446 EPUserAppRolesRequest epAppRolesRequestData = epUserAppRolesRequest;
1447 epAppRolesRequestData.setUpdatedDate(new Date());
1448 epAppRolesRequestData.setRequestStatus(updateStatus);
1449 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1450 addiotonalUpdateParam.put("userId", userId);
1451 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1452 epRequestParams.put("reqId", epUserAppRolesRequest.getId());
1453 List<EPUserAppRolesRequestDetail> epUserAppRolessDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1454 epUserAppRolessDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1455 epRequestParams, null);
1456 if (epUserAppRolessDetailList.size() > 0) {
1457 for (EPUserAppRolesRequestDetail epRequestUpdateData : epUserAppRolessDetailList) {
1458 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateData;
1459 epAppRoleDetailData.setReqType(updateStatus);
1460 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1461 HashMap<String, Long> updateDetailsParam = new HashMap<String, Long>();
1462 addiotonalUpdateParam.put("reqId", epUserAppRolesRequest.getId());
1463 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParam);
1466 logger.debug(EELFLoggerDelegate.debugLogger, "The request is set to complete");
1468 } catch (Exception e) {
1469 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToAppRolesRequest failed", e);
1473 @SuppressWarnings("unchecked")
1474 public void applyChangesToUserAppRolesForMyLoginsRequest(EPUser user, Long appId) {
1475 final Map<String, Long> params = new HashMap<>();
1476 final Map<String, Long> epDetailParams = new HashMap<>();
1477 List<EPUserAppRolesRequest> epRequestIdVal = new ArrayList<EPUserAppRolesRequest>();
1478 params.put("appId", appId);
1479 params.put("userId", user.getId());
1481 epRequestIdVal = (List<EPUserAppRolesRequest>) dataAccessService
1482 .executeNamedQuery("userAppRolesRequestList", params, null);
1483 if (epRequestIdVal.size() > 0) {
1484 EPUserAppRolesRequest epAppRolesRequestData = epRequestIdVal.get(0);
1485 epAppRolesRequestData.setUpdatedDate(new Date());
1486 epAppRolesRequestData.setRequestStatus("O");
1487 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1488 addiotonalUpdateParam.put("userId", user.getId());
1489 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1490 epDetailParams.put("reqId", epAppRolesRequestData.getId());
1491 List<EPUserAppRolesRequestDetail> epUserAppRolesDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1492 epUserAppRolesDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1493 epDetailParams, null);
1494 if (epUserAppRolesDetailList.size() > 0) {
1495 for (EPUserAppRolesRequestDetail epRequestUpdateList : epUserAppRolesDetailList) {
1496 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateList;
1497 epAppRoleDetailData.setReqType("O");
1498 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1499 HashMap<String, Long> updateDetailsParams = new HashMap<String, Long>();
1500 addiotonalUpdateParam.put("reqId", epAppRolesRequestData.getId());
1501 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParams);
1503 logger.debug(EELFLoggerDelegate.debugLogger, "User App roles request from User Page is overridden");
1507 } catch (Exception e) {
1508 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e);
1513 * Pushes specified user details to the specified remote app.
1516 * OrgUserId identifying user at remote app in REST endpoint path
1518 * User details to be pushed
1521 * @param applicationsRestClientService
1522 * @throws HTTPException
1524 protected void postUserToRemoteApp(String userId, EPUser user, EPApp app,
1525 ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
1527 getUser(userId, app, applicationsRestClientService);
1532 * It returns user details for single org user id
1536 * if user exists it returns list of user details otherwise empty value
1538 @SuppressWarnings("unchecked")
1539 private List<EPUser> checkIfUserExists(Map<String, String> userParams){
1540 return (List<EPUser>)dataAccessService.executeNamedQuery("epUserAppId", userParams, null);
1544 * It checks whether the new user is valid or not otherwise throws exception
1549 * Checks if user is valid and returns message otherwise throws exception
1552 private String validateNewUser(String orgUserId, EPApp app) throws Exception {
1553 EPUser epUser = searchService.searchUserByUserId(orgUserId);
1554 if (epUser == null) {
1555 throw new Exception("User does not exist");
1556 } else if (!epUser.getOrgUserId().equals(orgUserId)) {
1557 throw new Exception("User does not exist");
1558 } else if (app == null) {
1559 throw new Exception("Application does not exist");
1561 return "Saved Successfully";
1565 * Checks if the fields exists or not
1568 * contains user information
1572 * throws exception if the field is not valid
1574 private void validateExternalRequestFields(List<EPUser> userList, EPApp app) throws Exception{
1575 if (userList.size() == 0 || userList.isEmpty() ) {
1576 throw new Exception("User does not exist");
1577 } else if(app == null) {
1578 throw new Exception("Application does not exist");
1579 } else if(!app.getEnabled() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1580 throw new Exception(app.getMlAppName()+" application is unavailable");
1584 @SuppressWarnings("unchecked")
1585 public ExternalRequestFieldsValidator setExternalRequestUserAppRole(ExternalSystemUser newAppRolesForUser, String reqType) {
1586 boolean result = false;
1587 boolean externalSystemRequest = true;
1588 final Map<String, Long> params = new HashMap<>();
1589 final Map<String, String> userParams = new HashMap<>();
1590 List<EPUser> userInfo = null;
1592 List<EPUserAppRolesRequest> epRequestId = null;
1593 String orgUserId = "";
1594 String updateStatus = "";
1595 String reqMessage = "";
1597 if (newAppRolesForUser != null && newAppRolesForUser.getLoginId() != null) {
1598 orgUserId = newAppRolesForUser.getLoginId().trim();
1600 String appName = newAppRolesForUser.getApplicationName();
1601 String logMessage = ("DELETE").equals(reqType) ? "Deleting": "Assigning/Updating" ;
1602 if (orgUserId.length() > 0) {
1603 ObjectMapper mapper = new ObjectMapper();
1604 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1605 int epRequestIdSize = 0;
1607 app = appsService.getAppDetail(appName);
1608 userParams.put("orgUserIdValue", orgUserId);
1609 userInfo = checkIfUserExists(userParams);
1610 reqMessage = "Updated Successfully";
1611 if (!reqType.equals("DELETE") && (userInfo.size() == 0 || userInfo.isEmpty())) {
1612 reqMessage = validateNewUser(orgUserId, app);
1614 if (userInfo.size() != 0 || !userInfo.isEmpty()) {
1615 validateExternalRequestFields(userInfo, app);
1616 user = userInfo.get(0);
1617 params.put("appId", app.getId());
1618 params.put("userId", user.getId());
1619 epRequestId = (List<EPUserAppRolesRequest>) dataAccessService
1620 .executeNamedQuery("userAppRolesRequestList", params, null);
1621 epRequestIdSize = epRequestId.size();
1624 //If Non-Centralized app make sure you sync app roles before assigning to user
1625 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !app.getRolesInAAF()) {
1626 logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Starting GET roles for app {}",app.getId());
1627 EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, app.getId(), "/roles");
1628 logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Finshed GET roles for app {} and payload {}",app.getId(), appRoles);
1629 if (appRoles.length > 0) {
1630 syncAppRoles(sessionFactory, app.getId(), appRoles);
1633 List<RoleInAppForUser> roleInAppForUserList = roleInAppForUserList(newAppRolesForUser.getRoles(),
1634 app.getId(), app.getMlAppName());
1635 List<EcompUserAppRoles> userRoleList = null;
1636 if(!userInfo.isEmpty()){
1637 final Map<String, Long> appParams = new HashMap<>();
1638 appParams.put("userId", user.getId());
1639 appParams.put("appId", app.getId());
1640 userRoleList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", appParams, null);
1642 // Check if list contains just account admin role
1643 boolean checkIfAdminRoleExists = false;
1644 if (reqType.equals("DELETE") && userRoleList!=null) {
1645 checkIfAdminRoleExists = userRoleList.stream()
1646 .anyMatch(userRole -> userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1648 checkIfAdminRoleExists = roleInAppForUserList.stream()
1649 .anyMatch(roleList -> roleList.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1651 // if Centralized app
1652 if (app.getRolesInAAF()) {
1653 // We should add If user does not exist in remote application
1655 // If adding just account admin role dont make remote application user call or
1656 // if request has only single non admin role then make remote call
1657 if (!(app.getId().equals(PortalConstants.PORTAL_APP_ID) && reqType.equals("DELETE"))
1658 && ((checkIfAdminRoleExists && roleInAppForUserList.size() > 1)
1659 || (!checkIfAdminRoleExists && roleInAppForUserList.size() >= 1))) {
1660 // check if admin role exist then delete
1661 List<RoleInAppForUser> remoteUserRoles = roleInAppForUserList.stream()
1662 .collect(Collectors.toList());
1663 remoteUserRoles.removeIf(role -> {
1664 return (role.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1666 String orgUserIdNewOrExist = (userInfo.size() != 0 || !userInfo.isEmpty()) ? user.getOrgUserId() : orgUserId;
1667 pushRemoteUser(remoteUserRoles, orgUserIdNewOrExist , app, mapper, searchService,
1668 applicationsRestClientService,true);
1670 } catch (Exception e) {
1671 reqMessage = e.getMessage();
1672 logger.error(EELFLoggerDelegate.errorLogger, "setExternalRequestUserAppRole: Failed to added remote user", e);
1673 throw new Exception(reqMessage);
1675 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1676 applicationsRestClientService, app.getId(), orgUserId);
1677 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1678 userRolesInLocalApp);
1679 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1680 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
1682 if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1683 // Apply changes in external Access system
1684 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, externalSystemRequest,false,rolesGotDeletedByApprover,false);
1686 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
1687 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1688 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,false,rolesGotDeletedByApprover,false);
1690 // If local application is not centralized
1691 else if(!app.getRolesInAAF() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1692 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1693 applicationsRestClientService, app.getId(), orgUserId);
1694 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1695 userRolesInLocalApp);
1696 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
1698 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,false,rolesGotDeletedByApprover,false);
1699 } else {// remote app
1700 // If adding just account admin role don't do remote application user call
1701 if (!((roleInAppForUserList.size() == 1 || reqType.equals("DELETE")) && checkIfAdminRoleExists)) {
1702 EPUser remoteAppUser = null;
1703 remoteAppUser = checkIfRemoteUserExits(orgUserId, app, applicationsRestClientService);
1704 if (remoteAppUser == null) {
1705 addRemoteUser(roleInAppForUserList, orgUserId, app, mapper, searchService,
1706 applicationsRestClientService);
1707 reqMessage = "Saved Successfully";
1710 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
1711 applicationsRestClientService, app.getId(), orgUserId,false);
1713 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1714 userRolesInRemoteApp);
1715 logger.info(EELFLoggerDelegate.debugLogger,
1716 "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
1717 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1718 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
1720 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1721 reqType,false,rolesGotDeletedByApprover,false);
1722 // If no roles remain, request app to set user inactive.
1724 * if (userRolesInRemoteApp.size() == 0) {
1725 * logger.debug(EELFLoggerDelegate.debugLogger,
1726 * "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive"
1727 * , app, orgUserId); //TODO Need to fix the logged in user is not set to
1728 * inactive remoteAppUser.setActive(false); postUserToRemoteApp(orgUserId, user,
1729 * app, applicationsRestClientService); }
1733 // Here we are adding only we have single account admin in roleInAppForUserList and this should not add in remote
1734 if(!(reqType.equals("DELETE")) && userInfo.isEmpty()){
1735 reqMessage = "Saved Successfully";
1737 Set<EcompRole> userRolesInRemoteApp = constructUsersEcompRoles(roleInAppForUserList);
1739 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1740 userRolesInRemoteApp);
1741 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}",
1742 logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1743 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
1745 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1746 reqType,false,rolesGotDeletedByApprover,false);
1749 reqMessage = "Failed to save the user app role(s)";
1751 if (epRequestIdSize > 0 && !userInfo.isEmpty()) {
1753 applyChangesToAppRolesRequest(app.getId(), user.getId(), updateStatus, epRequestId.get(0));
1756 } catch (Exception e) {
1757 String message = String.format("setExternalRequestUserAppRole: Failed to create user or update user roles for User %s, AppId %s",
1758 orgUserId, appName);
1759 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1761 reqMessage = e.getMessage();
1762 if(epRequestIdSize > 0 && userInfo!=null && !userInfo.isEmpty()){
1764 applyChangesToAppRolesRequest(app.getId(), user.getId(),
1765 updateStatus, epRequestId.get(0));
1770 return new ExternalRequestFieldsValidator(result, reqMessage);
1775 * @param roleInAppForUserList
1777 * @param applicationsRestClientService
1780 * @return Set<EcompRole>
1781 * @throws JsonProcessingException
1782 * @throws HTTPException
1784 private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
1785 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
1786 throws JsonProcessingException, HTTPException {
1787 Set<EcompRole> updatedUserRoles = constructUsersEcompRoles(roleInAppForUserList);
1788 return updatedUserRoles;
1792 * It constructs and returns list of user app roles when the external API role approval system calls
1795 * @param roleInAppForUserList
1797 * @return list of user app roles
1799 * throws exceptions if role id does not exits
1801 private List<RoleInAppForUser> roleInAppForUserList(List<ExternalSystemRoleApproval> roleInAppForUserList,
1802 Long appId, String appName) throws Exception {
1803 List<RoleInAppForUser> existingUserRoles = new ArrayList<RoleInAppForUser>();
1804 EPRole existingAppRole = null;
1805 for (ExternalSystemRoleApproval roleInAppForUser : roleInAppForUserList) {
1806 RoleInAppForUser ecompRole = new RoleInAppForUser();
1807 existingAppRole = epRoleService.getAppRole(roleInAppForUser.getRoleName(), appId);
1808 if (existingAppRole == null) {
1809 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1810 roleInAppForUserList);
1811 throw new Exception("'" +roleInAppForUser.getRoleName() + "'" +" role does not exist for " + appName + " application");
1813 if (!existingAppRole.getActive()) {
1814 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1815 roleInAppForUserList);
1816 throw new Exception(roleInAppForUser.getRoleName() + " role is unavailable for "+ appName + " application");
1819 List<EPRole> roleInfo = externalAccessRolesService.getPortalAppRoleInfo(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
1820 EPRole adminRole = new EPRole();
1821 if(roleInfo.size()>0)
1823 adminRole = roleInfo.get(0);
1824 logger.debug(EELFLoggerDelegate.debugLogger, "Admin RoleName form DB: " + adminRole.getName());
1826 ecompRole.roleId = (appId == 1 || roleInAppForUser.getRoleName().equals(adminRole.getName())) ? existingAppRole.getId() : existingAppRole.getAppRoleId();
1827 ecompRole.roleName = roleInAppForUser.getRoleName();
1828 ecompRole.isApplied = true;
1829 existingUserRoles.add(ecompRole);
1832 return existingUserRoles;
1841 * @param applicationsRestClientService
1843 * @throws HTTPException
1845 protected EPUser getUserFromApp(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1846 throws HTTPException {
1848 if (app.getId() == PortalConstants.PORTAL_APP_ID) {
1849 // Map<String,String> params = new HashMap<String,String>();
1850 // params.put("sbcid",userId);
1851 @SuppressWarnings("unchecked")
1852 List<EPUser> userList = (List<EPUser>) dataAccessService
1853 .executeQuery("from EPUser where orgUserId='" + userId + "'", null);
1854 if (userList != null && !userList.isEmpty())
1855 return userList.get(0);
1861 return getUser(userId, app, applicationsRestClientService);
1864 protected EPUser getUser(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1865 throws HTTPException {
1866 return applicationsRestClientService.get(EPUser.class, app.getId(), String.format("/user/%s", userId), true);
1870 protected boolean isAppUpgradeVersion(EPApp app){
1875 public ExternalSystemAccess getExternalRequestAccess(){
1876 ExternalSystemAccess res = null;
1878 res = new ExternalSystemAccess(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE,
1879 Boolean.parseBoolean(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE)));
1880 } catch (Exception e) {
1881 logger.error(EELFLoggerDelegate.errorLogger, "getExternalRequestAccess failed" + e.getMessage());
1889 * @see org.onap.portalapp.portal.service.UserRolesService#
1890 * getAppRolesForUser(java.lang.Long, java.lang.String)
1892 @SuppressWarnings("unchecked")
1893 public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId, Boolean extRequestValue,EPUser user) {
1894 List<RoleInAppForUser> rolesInAppForUser = null;
1895 EPApp app = appsService.getApp(appId);
1896 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - app = {}", app);
1898 // for onap portal app, no need to make a remote call
1899 List<Role> roleList = new ArrayList<>();
1900 if (appId == PortalConstants.PORTAL_APP_ID) {
1901 if(app.getRolesInAAF()){
1902 List<CentralV2Role> cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey());
1903 for(CentralV2Role cenRole : cenRoleList){
1904 Role role = new Role();
1905 role.setActive(cenRole.getActive());
1906 role.setId(cenRole.getId());
1907 role.setName(cenRole.getName());
1908 role.setPriority(cenRole.getPriority());
1912 roleList = roleService.getAvailableRoles(userId);
1914 List<Role> activeRoleList = new ArrayList<Role>();
1915 for(Role role: roleList) {
1916 if(role.getActive()) {
1917 if(role.getId() != 1){ // prevent portal admin from being added
1918 activeRoleList.add(role);
1919 } else if(extRequestValue){
1920 activeRoleList.add(role);
1925 EPUser localUser = getUserFromApp(userId, app, applicationsRestClientService);
1926 // If localUser does not exists return roles
1927 Set<EPRole> roleSet = null;
1928 EPRole[] roleSetList = null;
1929 if(localUser != null){
1930 roleSet = localUser.getAppEPRoles(app);
1931 roleSetList = roleSet.toArray(new EPRole[0]);
1933 rolesInAppForUser = constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue);
1934 return rolesInAppForUser;
1937 EcompRole[] appRoles = null;
1938 boolean checkIfUserisApplicationAccAdmin = false;
1939 List<EcompRole> roles = new ArrayList<>();
1940 if (app.getRolesInAAF()) {
1941 final Map<String, Long> appParams = new HashMap<>();
1942 appParams.put("appId", app.getId());
1943 List<EPRole> applicationRoles = dataAccessService.executeNamedQuery("getActiveRolesOfApplication",
1946 EPApp application = appService.getApp(appId);
1947 checkIfUserisApplicationAccAdmin = adminRolesService.isAccountAdminOfApplication(user,
1950 List<EPRole> rolesetwithfunctioncds = new ArrayList<EPRole>();
1951 for (EPRole role : applicationRoles) {
1952 Map<String, Long> params = new HashMap<>();
1953 params.put("roleId", role.getId());
1954 params.put(APP_ID, app.getId());
1955 List<CentralV2RoleFunction> cenRoleFuncList = dataAccessService
1956 .executeNamedQuery("getAppRoleFunctionList", params, null);
1958 // SortedSet<CentralV2RoleFunction> roleFunctionSet =
1960 SortedSet<RoleFunction> roleFunctionSet = new TreeSet<>();
1961 for (CentralV2RoleFunction roleFunc : cenRoleFuncList) {
1963 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1964 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
1965 String type = externalAccessRolesService.getFunctionCodeType(roleFunc.getCode());
1966 String action = externalAccessRolesService.getFunctionCodeAction(roleFunc.getCode());
1967 String name = roleFunc.getName();
1969 RoleFunction function = new RoleFunction();
1970 function.setAction(action);
1971 function.setType(type);
1972 function.setCode(functionCode);
1973 function.setName(name);
1974 roleFunctionSet.add(function);
1975 role.setRoleFunctions(roleFunctionSet);
1978 rolesetwithfunctioncds.add(role);
1983 for (EPRole role1 : rolesetwithfunctioncds) {
1984 EcompRole ecompRole = new EcompRole();
1985 ecompRole.setId(role1.getId());
1986 ecompRole.setName(role1.getName());
1987 ecompRole.setRoleFunctions(role1.getRoleFunctions());
1988 roles.add(ecompRole);
1991 if (checkIfUserisApplicationAccAdmin) {
1992 appRoles = roles.toArray(new EcompRole[roles.size()]);
1993 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() If Logged in user checkIfUserisApplicationAccAdmin- appRoles = {}", appRoles);
1994 } else if (adminRolesService.isRoleAdmin(user) && !checkIfUserisApplicationAccAdmin) {
1995 List<EcompRole> roleAdminAppRoles = new ArrayList<>();
1996 List<String> roleAdminAppRolesNames = new ArrayList<>();
1997 final Map<String, Long> userParams = new HashMap<>();
1998 userParams.put("userId", user.getId());
1999 List<String> getUserApproverRoles = dataAccessService.executeNamedQuery("getUserApproverRoles", userParams, null);
2001 List<EcompRole> userapproverRolesList = new ArrayList<>();
2002 for (String str : getUserApproverRoles) {
2003 EcompRole epRole = roles.stream().filter(x -> str.equals(x.getName())).findAny().orElse(null);
2005 userapproverRolesList.add(epRole);
2007 // roles.removeAll(userapproverRolesList);
2008 for (EcompRole role : userapproverRolesList) {
2010 List<RoleFunction> roleFunList = new ArrayList<>();
2011 roleFunList.addAll(role.getRoleFunctions());
2012 boolean checkIfFunctionsExits = roleFunList.stream()
2013 .anyMatch(roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
2014 if (checkIfFunctionsExits) {
2015 roleAdminAppRoles.add(role);
2016 List<RoleFunction> filteredList = roleFunList.stream()
2017 .filter(x -> "Approver".equalsIgnoreCase(x.getType())).collect(Collectors.toList());
2018 roleAdminAppRolesNames.addAll(filteredList.stream().map(RoleFunction::getCode)
2019 .collect(Collectors.toList()));
2020 // roleAdminAppRolesNames = filteredList.stream().map(RoleFunction::getCode)
2021 // .collect(Collectors.toList());
2024 for (String name : roleAdminAppRolesNames) {
2025 EcompRole ecompRole = roles.stream().filter(x -> name.equals(x.getName())).findAny()
2027 if (ecompRole != null)
2028 roleAdminAppRoles.add(ecompRole);
2031 appRoles = roleAdminAppRoles.toArray(new EcompRole[roleAdminAppRoles.size()]);
2035 appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
2037 // Test this error case, for generating an internal ONAP Portal
2039 // EcompRole[] appRoles = null;
2040 // If there is an exception in the rest client api, then null will
2042 if (appRoles != null) {
2043 if(!app.getRolesInAAF()) {
2044 syncAppRoles(sessionFactory, appId, appRoles);
2046 EcompRole[] userAppRoles = null;
2050 if(app.getRolesInAAF()){
2051 final Map<String, String> params = new HashMap<>();
2052 final Map<String, Long> userParams = new HashMap<>();
2053 params.put("orgUserIdValue", userId);
2054 List<EPUser> actualUser = dataAccessService.executeNamedQuery("epUserAppId", params, null);
2055 userParams.put("appId", app.getId());
2056 userParams.put("userId", actualUser.get(0).getId());
2057 List<EPUserAppCurrentRoles> userAppsRolesList = dataAccessService.executeNamedQuery("getUserAppCurrentRoles", userParams, null);
2059 List<EcompRole> setUserRoles = new ArrayList<>();
2060 for(EPUserAppCurrentRoles role : userAppsRolesList){
2061 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - userAppsRolesList get userRolename = {}", role.getRoleName());
2062 EcompRole ecompRole = new EcompRole();
2063 ecompRole.setId(role.getRoleId());
2064 ecompRole.setName(role.getRoleName());
2065 setUserRoles.add(ecompRole);
2068 boolean checkIfUserisAccAdmin = setUserRoles.stream()
2069 .anyMatch(ecompRole -> ecompRole.getId() == 999L);
2071 if (!checkIfUserisAccAdmin) {
2072 List<EcompRole> userApplicationRolesList = setUserRoles;
2073 List<EcompRole> appRolesList = Arrays.asList(appRoles);
2074 Set<EcompRole> finalUserAppRolesList = new HashSet<>();
2076 List<String> roleNames = new ArrayList<>();
2077 for (EcompRole role : userApplicationRolesList) {
2078 EcompRole epRole = appRolesList.stream()
2079 .filter(x -> role.getName().equals(x.getName())).findAny().orElse(null);
2080 List<RoleFunction> roleFunList = new ArrayList<>();
2082 if (epRole != null) {
2083 if (epRole.getRoleFunctions().size() > 0)
2084 roleFunList.addAll(epRole.getRoleFunctions());
2085 boolean checkIfFunctionsExits = roleFunList.stream().anyMatch(
2086 roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
2087 if (checkIfFunctionsExits) {
2088 finalUserAppRolesList.add(role);
2089 List<RoleFunction> filteredList = roleFunList.stream()
2090 .filter(x -> "Approver".equalsIgnoreCase(x.getType()))
2091 .collect(Collectors.toList());
2092 roleNames = filteredList.stream().map(RoleFunction::getCode)
2093 .collect(Collectors.toList());
2095 roleNames.add(epRole.getName());
2098 for (String name : roleNames) {
2099 EcompRole ecompRole = appRolesList.stream()
2100 .filter(x -> name.equals(x.getName())).findAny().orElse(null);
2101 if (ecompRole != null)
2102 finalUserAppRolesList.add(ecompRole);
2107 for (String name : roleNames) {
2109 boolean checkIfFunctionsExits = userAppsRolesList.stream().anyMatch(
2110 role -> role.getRoleName().equalsIgnoreCase(name));
2111 if(checkIfFunctionsExits)
2113 EcompRole epRole = appRolesList.stream().filter(x -> name.equals(x.getName()))
2114 .findAny().orElse(null);
2116 setUserRoles.add(epRole);
2120 userAppRoles = setUserRoles.toArray(new EcompRole[setUserRoles.size()]);
2123 userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
2124 String.format("/user/%s/roles", userId));
2126 } catch (HTTPException e) {
2127 // Some apps are returning 400 if user is not found.
2128 if (e.getResponseCode() == 400) {
2129 logger.debug(EELFLoggerDelegate.debugLogger,
2130 "getAppRolesForUser caught exception with response code 400; continuing", e);
2132 // Other response code, let it come thru.
2136 if (userAppRoles == null) {
2137 if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
2138 EcompPortalUtils.setExternalAppResponseCode(200);
2139 String message = String.format(
2140 "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
2141 + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
2142 + "Overriding to 200 until framework SDK returns a useful response.",
2143 Long.toString(appId), userId);
2144 logger.warn(EELFLoggerDelegate.applicationLogger, message);
2148 HashMap<Long, EcompRole> appRolesActiveMap =hashMapFromEcompRoles(appRoles);
2149 ArrayList<EcompRole> activeRoles = new ArrayList<EcompRole>();
2150 if(userAppRoles != null){
2151 for (int i = 0; i < userAppRoles.length; i++) {
2152 if (appRolesActiveMap.containsKey(userAppRoles[i].getId())) {
2153 EcompRole role = new EcompRole();
2154 role.setId(userAppRoles[i].getId());
2155 role.setName(userAppRoles[i].getName());
2156 activeRoles.add(role);
2160 EcompRole[] userAppRolesActive = activeRoles.toArray(new EcompRole[activeRoles.size()]);
2163 boolean checkIfUserisRoleAdmin = adminRolesService.isRoleAdmin(user) && !checkIfUserisApplicationAccAdmin;
2165 // If the remote application isn't down we MUST sync user
2166 // roles here in case we have this user here!
2167 syncUserRoles(sessionFactory, userId, appId, userAppRolesActive, extRequestValue, null,checkIfUserisRoleAdmin,appRoles);
2168 } catch (Exception e) {
2169 // TODO: we may need to check if user exists, maybe remote
2171 String message = String.format(
2172 "getAppRolesForUser: user %s does not exist in remote application %s", userId,
2173 Long.toString(appId));
2174 logger.error(EELFLoggerDelegate.errorLogger, message, e);
2175 userAppRoles = new EcompRole[0];
2177 rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
2179 } catch (Exception e) {
2180 String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
2181 Long.toString(appId));
2182 logger.error(EELFLoggerDelegate.errorLogger, message, e);
2184 return rolesInAppForUser;
2187 private boolean postUserRolesToMylogins(AppWithRolesForUser userAppRolesData,
2188 ApplicationsRestClientService applicationsRestClientService, Long appId, Long userId)
2189 throws JsonProcessingException, HTTPException {
2190 boolean result = false;
2191 ObjectMapper mapper = new ObjectMapper();
2192 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
2193 String userRolesAsString = mapper.writeValueAsString(userAppRolesData);
2194 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, as the endpoint is not defined yet from the Mylogins");
2195 applicationsRestClientService.post(AppWithRolesForUser.class, appId, userRolesAsString, String.format("/user/%s/myLoginroles", userId));
2199 @SuppressWarnings("unchecked")
2200 public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser userAppRolesData, EPUser user) {
2201 FieldsValidator fieldsValidator = new FieldsValidator();
2202 final Map<String, Long> params = new HashMap<>();
2203 List<EPUserAppRoles> appRole= null;
2205 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, still the endpoint is yet to be defined");
2206 boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService,
2207 userAppRolesData.getAppId(), user.getId());
2208 logger.debug(EELFLoggerDelegate.debugLogger,"putUserAppRolesRequest: result {}", result);
2210 params.put("appId", userAppRolesData.getAppId());
2211 EPUserAppRolesRequest epAppRolesRequestData = new EPUserAppRolesRequest();
2212 epAppRolesRequestData.setCreatedDate(new Date());
2213 epAppRolesRequestData.setUpdatedDate(new Date());
2214 epAppRolesRequestData.setUserId(user.getId());
2215 epAppRolesRequestData.setAppId(userAppRolesData.getAppId());
2216 epAppRolesRequestData.setRequestStatus("P");
2217 List<RoleInAppForUser> appRoleIdList = userAppRolesData.getAppRoles();
2218 Set<EPUserAppRolesRequestDetail> appRoleDetails = new LinkedHashSet<EPUserAppRolesRequestDetail>();
2219 dataAccessService.saveDomainObject(epAppRolesRequestData, null);
2220 for (RoleInAppForUser userAppRoles : appRoleIdList) {
2221 Boolean isAppliedVal = userAppRoles.isApplied;
2222 params.put("appRoleId", userAppRoles.roleId);
2224 appRole = (List<EPUserAppRoles>) dataAccessService.executeNamedQuery("appRoles", params, null);
2225 if (!appRole.isEmpty()) {
2226 EPUserAppRolesRequestDetail epAppRoleDetail = new EPUserAppRolesRequestDetail();
2227 epAppRoleDetail.setReqRoleId(appRole.get(0).getRoleId());
2228 epAppRoleDetail.setReqType("P");
2229 epAppRoleDetail.setEpRequestIdData(epAppRolesRequestData);
2230 dataAccessService.saveDomainObject(epAppRoleDetail, null);
2234 epAppRolesRequestData.setEpRequestIdDetail(appRoleDetails);
2235 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
2237 } catch (Exception e) {
2238 logger.error(EELFLoggerDelegate.errorLogger, "putUserAppRolesRequest failed", e);
2239 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
2241 return fieldsValidator;
2244 public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(EPUser userid, String appName) {
2245 Map<String, String> params = new HashMap<>();
2246 params.put("userid", userid.getId().toString());
2247 //params.put("appid", appid);
2248 params.put("appName", appName);
2250 @SuppressWarnings("unchecked")
2251 List<EPUserAppCatalogRoles> userAppRoles = (List<EPUserAppCatalogRoles>) dataAccessService
2252 .executeNamedQuery("userAppCatalogRoles", params, null);
2253 return userAppRoles;
2256 public String updateRemoteUserProfile(String orgUserId, Long appId) {
2257 ObjectMapper mapper = new ObjectMapper();
2258 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
2259 EPUser client = searchService.searchUserByUserId(orgUserId);
2260 EPUser newUser = new EPUser();
2261 newUser.setActive(client.getActive());
2262 newUser.setFirstName(client.getFirstName());
2263 newUser.setLastName(client.getLastName());
2264 newUser.setLoginId(client.getLoginId());
2265 newUser.setLoginPwd(client.getLoginPwd());
2266 newUser.setMiddleInitial(client.getMiddleInitial());
2267 newUser.setEmail(client.getEmail());
2268 newUser.setOrgUserId(client.getLoginId());
2270 String userAsString = mapper.writeValueAsString(newUser);
2271 List<EPApp> appList = appsService.getUserRemoteApps(client.getId().toString());
2272 // applicationsRestClientService.post(EPUser.class, appId,
2273 // userAsString, String.format("/user", orgUserId));
2274 for (EPApp eachApp : appList) {
2276 applicationsRestClientService.post(EPUser.class, eachApp.getId(), userAsString,
2277 String.format("/user/%s", orgUserId));
2278 } catch (Exception e) {
2279 logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId()
2280 + " in remote app. appId = " + eachApp.getId());
2283 } catch (Exception e) {
2284 logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
2295 * @see org.onap.portalapp.portal.service.UserRolesService#
2296 * getCachedAppRolesForUser(java.lang.Long, java.lang.Long)
2298 @SuppressWarnings("deprecation")
2299 public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId) {
2300 // Find the records for this user-app combo, if any
2301 String filter = " where user_id = " + Long.toString(userId) + " and app_id = " + Long.toString(appId);
2302 @SuppressWarnings("unchecked")
2303 List<EPUserApp> roleList = dataAccessService.getList(EPUserApp.class, filter, null, null);
2304 logger.debug(EELFLoggerDelegate.debugLogger, "getCachedAppRolesForUser: list size is {}", roleList.size());
2309 * It retrieves and returns list of user app roles for local and remote applications based app id
2312 * @return list of user app roles
2313 * @throws HTTPException
2315 public List<UserApplicationRoles> getUsersFromAppEndpoint(Long appId) throws HTTPException {
2316 ArrayList<UserApplicationRoles> userApplicationRoles = new ArrayList<UserApplicationRoles>();
2318 EPApp app = appsService.getApp(appId);
2319 //If local or centralized application
2320 if (appId == PortalConstants.PORTAL_APP_ID || app.getRolesInAAF()) {
2321 Map<String, Object> params = new HashMap<>();
2322 params.put("id", app.getId());
2323 params.put("active", true);
2324 @SuppressWarnings("unchecked")
2325 //List<EPUser> userList = (List<EPUser>) dataAccessService.executeNamedQuery("getActiveUsers", null, null);
2326 //List<Object[]> userList = (List<Object[]>) dataAccessService.executeNamedQuery("getActiveUsersForApp", params, null);
2327 List<EPUser> userList = (List<EPUser>) dataAccessService.executeNamedQuery("getActiveUsersForApp", params, null);
2328 for (EPUser user : userList) {
2329 UserApplicationRoles userWithAppRoles = convertToUserApplicationRoles(user, app.getId());
2330 if (userWithAppRoles.getRoles() != null && userWithAppRoles.getRoles().size() > 0)
2331 userApplicationRoles.add(userWithAppRoles);
2337 RemoteUserWithRoles[] remoteUsers = null;
2338 String remoteUsersString = applicationsRestClientService.getIncomingJsonString(appId, "/users");
2340 remoteUsers = doGetUsers(isAppUpgradeVersion(app), remoteUsersString);
2342 userApplicationRoles = new ArrayList<UserApplicationRoles>();
2343 for (RemoteUserWithRoles remoteUser : remoteUsers) {
2344 UserApplicationRoles userWithRemoteAppRoles = convertToUserApplicationRoles(appId, remoteUser);
2345 if (userWithRemoteAppRoles.getRoles() != null && userWithRemoteAppRoles.getRoles().size() > 0) {
2346 userApplicationRoles.add(userWithRemoteAppRoles);
2348 logger.debug(EELFLoggerDelegate.debugLogger,
2349 "User " + userWithRemoteAppRoles.getOrgUserId() + " doesn't have any roles assigned to any app.");
2354 return userApplicationRoles;
2363 private UserApplicationRoles convertToUserApplicationRoles(EPUser user, Long appId) {
2364 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
2365 userWithRemoteAppRoles.setAppId(appId);
2366 userWithRemoteAppRoles.setOrgUserId(user.getOrgUserId());
2367 userWithRemoteAppRoles.setFirstName(user.getFirstName());
2368 userWithRemoteAppRoles.setLastName(user.getLastName());
2369 List<RemoteRole> roleList = new ArrayList<RemoteRole>();
2370 for(EPUserApp userApp :user.getEPUserApps()) {
2371 RemoteRole remoteRole = new RemoteRole();
2372 remoteRole.setName(userApp.getRole().getName());
2373 remoteRole.setId(userApp.getRole().getId());
2374 roleList.add(remoteRole);
2376 userWithRemoteAppRoles.setRoles(roleList);
2377 return userWithRemoteAppRoles;
2384 * @param appgetUsersFromAppEndpoint
2387 private UserApplicationRoles convertToUserApplicationRoles(Long appId, EPUser user, EPApp app) {
2388 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
2389 userWithRemoteAppRoles.setAppId(appId);
2390 userWithRemoteAppRoles.setOrgUserId(user.getOrgUserId());
2391 userWithRemoteAppRoles.setFirstName(user.getFirstName());
2392 userWithRemoteAppRoles.setLastName(user.getLastName());
2393 userWithRemoteAppRoles.setRoles(convertToRemoteRoleList(user, app));
2394 return userWithRemoteAppRoles;
2403 @SuppressWarnings("unchecked")
2404 private List<RemoteRole> convertToRemoteRoleList(EPUser user, EPApp app) {
2405 List<RemoteRole> roleList = new ArrayList<RemoteRole>();
2406 SortedSet<EPRole> roleSet = user.getAppEPRoles(app);
2407 for (EPRole role : roleSet) {
2408 logger.debug(EELFLoggerDelegate.debugLogger, "In convertToRemoteRoleList() - for user {}, found Name {}", user.getOrgUserId(), role.getName());
2409 RemoteRole rRole = new RemoteRole();
2410 rRole.setId(role.getId());
2411 rRole.setName(role.getName());
2412 roleList.add(rRole);
2415 //Get the active roles of user for that application using query
2416 List<EPRole> userEpRoleList = new ArrayList<>();
2417 final Map<String, Long> params = new HashMap<>();
2418 params.put("appId", app.getId());
2419 params.put("userId", user.getId());
2420 userEpRoleList = dataAccessService.executeNamedQuery("getUserRoleOnUserIdAndAppId", params, null);
2422 for (EPRole remoteUserRoleList : userEpRoleList) {
2424 RemoteRole remoteRoleListId = roleList.stream().filter(x -> remoteUserRoleList.getId().equals(x.getId()))
2425 .findAny().orElse(null);
2426 if (remoteRoleListId == null) {
2427 logger.debug(EELFLoggerDelegate.debugLogger,
2428 "Adding the role to the rolelist () - for user {}, found Name {}", user.getOrgUserId(),
2430 remoteUserRoleList.getName());
2431 RemoteRole role = new RemoteRole();
2432 role.setId(remoteUserRoleList.getId());
2433 role.setName(remoteUserRoleList.getName());
2440 logger.debug(EELFLoggerDelegate.debugLogger, "rolelist size of the USER() - for user {}, found RoleListSize {}", user.getOrgUserId(), roleList.size());
2448 public RemoteUserWithRoles[] doGetUsers(boolean postOpenSource, String remoteUsersString) {
2450 ObjectMapper mapper = new ObjectMapper();
2452 return mapper.readValue(remoteUsersString, RemoteUserWithRoles[].class);
2453 } catch (IOException e) {
2454 logger.error(EELFLoggerDelegate.errorLogger,
2455 "doGetUsers : Failed : Unexpected property in incoming JSON",
2457 logger.error(EELFLoggerDelegate.errorLogger,
2458 "doGetUsers : Incoming JSON that caused it --> " + remoteUsersString);
2461 return new RemoteUserWithRoles[0];
2464 @SuppressWarnings("unchecked")
2465 public List<EPUserApp> getEPUserAppList(Long appId, Long userId, Long roleId) {
2466 List<EPUserApp> userRoleList = new ArrayList<EPUserApp>();
2467 final Map<String, Long> params = new HashMap<>();
2468 params.put("appId", appId);
2469 params.put("userId", userId);
2470 params.put("roleId", roleId);
2471 userRoleList = dataAccessService.executeNamedQuery("getUserRoleOnUserIdAndRoleIdAndAppId", params, null);
2472 return userRoleList;
2476 /*public static void main(String[] args) {
2477 List<EcompRole> str1 = new ArrayList<String>();
2483 List<String> str2 = new ArrayList<String>();
2487 List<EcompRole> userApplicationRolesList = setUserRoles;
2488 List<EcompRole> appRolesList = Arrays.asList(appRoles);