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()) {
1130 // Apply changes in external Access system
1131 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList,
1132 epRequestValue,false,rolesGotDeletedFromApprover,checkIfUserisOnlyRoleAdmin);
1134 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal", systemUser,rolesGotDeletedFromApprover,checkIfUserisOnlyRoleAdmin);
1136 // In case if portal is not centralized then follow existing approach
1137 else if(!app.getRolesInAAF() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1138 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1139 applicationsRestClientService, appId, userId);
1140 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1141 userRolesInLocalApp);
1142 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
1143 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal",false,rolesGotDeletedByApprover,false);
1144 } else{// remote app
1145 EPUser remoteAppUser = null;
1146 if(!app.getRolesInAAF() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1148 remoteAppUser = checkIfRemoteUserExits(userId, app, applicationsRestClientService);
1150 if (remoteAppUser == null) {
1151 remoteAppUser = addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService, applicationsRestClientService);
1153 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
1154 applicationsRestClientService, appId, userId,systemUser);
1155 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1156 userRolesInRemoteApp);
1157 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
1158 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null,false,rolesGotDeletedByApprover,false);
1160 // If no roles remain, request app to set user inactive.
1161 if (userRolesInRemoteApp.size() == 0) {
1162 logger.debug(EELFLoggerDelegate.debugLogger,
1163 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
1165 //remoteAppUser.setActive(false);
1166 postUserToRemoteApp(userId, user, app, applicationsRestClientService);
1171 } catch (Exception e) {
1172 /*String message = String.format(
1173 "Failed to create user or update user roles for User %s, AppId %s",
1174 userId, Long.toString(appId));
1175 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1178 String message = String.format(
1179 "Failed to create user or update user roles for User %s, AppId %s",
1180 userId, Long.toString(appId));
1181 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1183 reqMessage = e.getMessage();
1190 return new ExternalRequestFieldsValidator(result, reqMessage);
1194 * It adds user roles in External system and also make data consistent in both local and in External System
1196 * @param app details
1198 * @param roleInAppUser Contains list of active roles
1200 @SuppressWarnings("unchecked")
1201 private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser, boolean isPortalRequest,boolean nonHumanUserId,Set<EcompRole> deletedRolesByApprover,boolean isLoggedInUserRoleAdminofApp) throws Exception
1204 // check if user exists
1205 final Map<String, String> userParams = new HashMap<>();
1206 userParams.put("orgUserIdValue", orgUserId);
1207 List<EPUser> userInfo = checkIfUserExists(userParams);
1208 if (userInfo.isEmpty()) {
1209 createLocalUserIfNecessary(orgUserId, nonHumanUserId);
1212 if (EPCommonSystemProperties
1213 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN) && !nonHumanUserId) {
1214 if(orgUserId.indexOf("@") ==-1) {
1215 name = orgUserId + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
1221 if(nonHumanUserId && orgUserId!=null) {
1222 if(orgUserId.indexOf("@") ==-1) {
1223 name = orgUserId + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
1227 ObjectMapper mapper = new ObjectMapper();
1228 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1229 HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
1230 ResponseEntity<String> getResponse = externalAccessRolesService.getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
1233 List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
1234 String res = getResponse.getBody();
1235 JSONObject jsonObj = null;
1236 JSONArray extRoles = null;
1237 if (!res.equals("{}")) {
1238 jsonObj = new JSONObject(res);
1239 extRoles = jsonObj.getJSONArray("role");
1241 ExternalAccessUserRoleDetail userRoleDetail = null;
1242 if (extRoles != null) {
1243 for (int i = 0; i < extRoles.length(); i++) {
1244 if (extRoles.getJSONObject(i).getString("name").startsWith(app.getNameSpace() + ".")
1245 && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".admin")
1246 && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".owner")) {
1247 if (extRoles.getJSONObject(i).has("description")) {
1248 ExternalRoleDescription desc = new ExternalRoleDescription(extRoles.getJSONObject(i).getString("description"));
1249 userRoleDetail = new ExternalAccessUserRoleDetail(
1250 extRoles.getJSONObject(i).getString("name"), desc);
1251 userRoleDetailList.add(userRoleDetail);
1253 userRoleDetail = new ExternalAccessUserRoleDetail(
1254 extRoles.getJSONObject(i).getString("name"), null);
1255 userRoleDetailList.add(userRoleDetail);
1262 List<ExternalAccessUserRoleDetail> userRoleListMatchingInExtAuthAndLocal = CheckIfRoleAreMatchingInUserRoleDetailList(userRoleDetailList,app);
1264 List<EcompUserAppRoles> userAppList = new ArrayList<>();
1265 // If request coming from portal not from external role approval system then we have to check if user already
1266 // have account admin or system admin as GUI will not send these roles
1267 if (!isPortalRequest) {
1268 final Map<String, String> loginIdParams = new HashMap<>();
1269 loginIdParams.put("orgUserIdValue", orgUserId);
1270 EPUser user = (EPUser) dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null).get(0);
1271 final Map<String, Long> params = new HashMap<>();
1272 params.put("appId", app.getId());
1273 params.put("userId", user.getId());
1274 userAppList = dataAccessService.executeNamedQuery("getUserAppExistingRoles",
1276 if (!roleInAppUser.isEmpty()) {
1277 for (EcompUserAppRoles userApp : userAppList) {
1278 if (userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)
1279 || userApp.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
1280 RoleInAppForUser addSpecialRole = new RoleInAppForUser();
1281 addSpecialRole.setIsApplied(true);
1282 addSpecialRole.setRoleId(userApp.getRoleId());
1283 addSpecialRole.setRoleName(userApp.getRoleName());
1284 roleInAppUser.add(addSpecialRole);
1289 List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct()
1290 .collect(Collectors.toList());
1291 Map<String, RoleInAppForUser> currentUserRolesToUpdate = new HashMap<>();
1292 for (RoleInAppForUser roleInAppUserNew : roleInAppUserNonDupls) {
1293 currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), roleInAppUserNew);
1295 final Map<String, ExternalAccessUserRoleDetail> currentUserRolesInExternalSystem = new HashMap<>();
1296 for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleListMatchingInExtAuthAndLocal) {
1297 currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole);
1300 if (isLoggedInUserRoleAdminofApp) {
1301 if (deletedRolesByApprover.size() > 0) {
1302 List<ExternalAccessUserRoleDetail> newUpdatedRoles = new ArrayList<>();
1303 Set<EcompRole> roles = new HashSet<>();
1304 for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
1305 for (EcompRole role : deletedRolesByApprover) {
1306 if ((userRole.getName().substring(app.getNameSpace().length() + 1)).equals(role.getName())) {
1308 newUpdatedRoles.add(userRole);
1312 if (newUpdatedRoles.size() > 0) {
1313 userRoleListMatchingInExtAuthAndLocal = new ArrayList<>();
1314 userRoleListMatchingInExtAuthAndLocal.addAll(newUpdatedRoles);
1316 userRoleListMatchingInExtAuthAndLocal = new ArrayList<>();
1317 currentUserRolesToUpdate = new HashMap<>();
1322 userRoleListMatchingInExtAuthAndLocal = new ArrayList<>();
1323 currentUserRolesToUpdate = new HashMap<>();
1328 // Check if user roles does not exists in local but still there in External Central Auth System delete them all
1329 for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
1330 if (!(currentUserRolesToUpdate
1331 .containsKey(userRole.getName().substring(app.getNameSpace().length() + 1)))) {
1332 HttpEntity<String> entity = new HttpEntity<>(headers);
1333 logger.debug(EELFLoggerDelegate.debugLogger,
1334 "updateUserRolesInExternalSystem: Connecting to external system to DELETE user role {}",
1335 userRole.getName());
1336 ResponseEntity<String> deleteResponse = template.exchange(
1337 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1338 + "userRole/" + name + "/" + userRole.getName(),
1339 HttpMethod.DELETE, entity, String.class);
1340 logger.debug(EELFLoggerDelegate.debugLogger,
1341 "updateUserRolesInExternalSystem: Finished DELETE operation in external system for user role {} and the response is {}",
1342 userRole.getName(), deleteResponse.getBody());
1345 // Check if user roles does not exists in External Central Auth System add them all
1346 for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) {
1347 if (!(currentUserRolesInExternalSystem
1348 .containsKey(app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")))) {
1349 ExternalAccessUser extUser = new ExternalAccessUser(name,
1350 app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1351 String formattedUserRole = mapper.writeValueAsString(extUser);
1352 HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers);
1353 logger.debug(EELFLoggerDelegate.debugLogger, "updateUserRolesInExternalSystem: Connecting to external system for user {} and POST {}",
1354 name , addUserRole.getRoleName());
1355 ResponseEntity<String> addResponse = template
1356 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1357 + "userRole", HttpMethod.POST, entity, String.class);
1358 logger.debug(EELFLoggerDelegate.debugLogger,
1359 "updateUserRolesInExternalSystem: Finished adding user role in external system {} and added user role {}",
1360 addResponse.getBody(), addUserRole.getRoleName());
1361 if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 404) {
1362 logger.debug(EELFLoggerDelegate.debugLogger,
1363 "Finished POST operation in external system but unable to save user role", addResponse.getBody(),
1364 addUserRole.getRoleName());
1365 throw new Exception(addResponse.getBody());
1369 } catch (HttpClientErrorException e) {
1370 logger.error(EELFLoggerDelegate.errorLogger,
1371 "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}",
1373 if (e.getStatusCode() == HttpStatus.FORBIDDEN) {
1374 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid systemUser", orgUserId);
1375 throw new HttpClientErrorException(HttpStatus.FORBIDDEN, "Please enter the valid systemUser");
1377 if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
1378 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid role");
1379 throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "Please enter the valid role");
1381 EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
1385 catch (Exception e) {
1386 logger.error(EELFLoggerDelegate.errorLogger, "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}", app.getId(), e);
1387 EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
1393 private List<ExternalAccessUserRoleDetail> CheckIfRoleAreMatchingInUserRoleDetailList(
1394 List<ExternalAccessUserRoleDetail> userRoleDetailList, EPApp app) {
1395 Map<String, EPRole> epRoleList = externalAccessRolesService.getAppRoleNamesWithUnderscoreMap(app);
1396 //Add Account Admin role for partner app to prevent conflict
1397 if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1398 EPRole role = new EPRole();
1399 role.setName(PortalConstants.ADMIN_ROLE.replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1400 epRoleList.put(role.getName(), role);
1402 userRoleDetailList.removeIf(userRoleDetail -> !epRoleList.containsKey(userRoleDetail.getName().substring(app.getNameSpace().length()+1)));
1403 return userRoleDetailList;
1410 * @param applicationsRestClientService
1411 * @param searchService
1415 protected void createNewUserOnRemoteApp(String userId, EPApp app,
1416 ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
1417 ObjectMapper mapper, boolean postOpenSource) throws Exception {
1420 EPUser client = searchService.searchUserByUserId(userId);
1422 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1424 if (client == null) {
1425 String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook.";
1426 logger.error(EELFLoggerDelegate.errorLogger, msg);
1427 throw new Exception(msg);
1430 client.setLoginId(userId);
1431 client.setActive(true);
1433 String userInString = null;
1434 userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
1435 logger.debug(EELFLoggerDelegate.debugLogger,
1436 "about to post new client to remote application, users json = " + userInString);
1437 applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user", userId));
1441 @SuppressWarnings("unchecked")
1442 protected void applyChangesToAppRolesRequest(Long appId, Long userId, String updateStatus, EPUserAppRolesRequest epUserAppRolesRequest) {
1443 final Map<String, Long> epRequestParams = new HashMap<>();
1445 EPUserAppRolesRequest epAppRolesRequestData = epUserAppRolesRequest;
1446 epAppRolesRequestData.setUpdatedDate(new Date());
1447 epAppRolesRequestData.setRequestStatus(updateStatus);
1448 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1449 addiotonalUpdateParam.put("userId", userId);
1450 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1451 epRequestParams.put("reqId", epUserAppRolesRequest.getId());
1452 List<EPUserAppRolesRequestDetail> epUserAppRolessDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1453 epUserAppRolessDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1454 epRequestParams, null);
1455 if (epUserAppRolessDetailList.size() > 0) {
1456 for (EPUserAppRolesRequestDetail epRequestUpdateData : epUserAppRolessDetailList) {
1457 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateData;
1458 epAppRoleDetailData.setReqType(updateStatus);
1459 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1460 HashMap<String, Long> updateDetailsParam = new HashMap<String, Long>();
1461 addiotonalUpdateParam.put("reqId", epUserAppRolesRequest.getId());
1462 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParam);
1465 logger.debug(EELFLoggerDelegate.debugLogger, "The request is set to complete");
1467 } catch (Exception e) {
1468 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToAppRolesRequest failed", e);
1472 @SuppressWarnings("unchecked")
1473 public void applyChangesToUserAppRolesForMyLoginsRequest(EPUser user, Long appId) {
1474 final Map<String, Long> params = new HashMap<>();
1475 final Map<String, Long> epDetailParams = new HashMap<>();
1476 List<EPUserAppRolesRequest> epRequestIdVal = new ArrayList<EPUserAppRolesRequest>();
1477 params.put("appId", appId);
1478 params.put("userId", user.getId());
1480 epRequestIdVal = (List<EPUserAppRolesRequest>) dataAccessService
1481 .executeNamedQuery("userAppRolesRequestList", params, null);
1482 if (epRequestIdVal.size() > 0) {
1483 EPUserAppRolesRequest epAppRolesRequestData = epRequestIdVal.get(0);
1484 epAppRolesRequestData.setUpdatedDate(new Date());
1485 epAppRolesRequestData.setRequestStatus("O");
1486 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1487 addiotonalUpdateParam.put("userId", user.getId());
1488 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1489 epDetailParams.put("reqId", epAppRolesRequestData.getId());
1490 List<EPUserAppRolesRequestDetail> epUserAppRolesDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1491 epUserAppRolesDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1492 epDetailParams, null);
1493 if (epUserAppRolesDetailList.size() > 0) {
1494 for (EPUserAppRolesRequestDetail epRequestUpdateList : epUserAppRolesDetailList) {
1495 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateList;
1496 epAppRoleDetailData.setReqType("O");
1497 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1498 HashMap<String, Long> updateDetailsParams = new HashMap<String, Long>();
1499 addiotonalUpdateParam.put("reqId", epAppRolesRequestData.getId());
1500 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParams);
1502 logger.debug(EELFLoggerDelegate.debugLogger, "User App roles request from User Page is overridden");
1506 } catch (Exception e) {
1507 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e);
1512 * Pushes specified user details to the specified remote app.
1515 * OrgUserId identifying user at remote app in REST endpoint path
1517 * User details to be pushed
1520 * @param applicationsRestClientService
1521 * @throws HTTPException
1523 protected void postUserToRemoteApp(String userId, EPUser user, EPApp app,
1524 ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
1526 getUser(userId, app, applicationsRestClientService);
1531 * It returns user details for single org user id
1535 * if user exists it returns list of user details otherwise empty value
1537 @SuppressWarnings("unchecked")
1538 private List<EPUser> checkIfUserExists(Map<String, String> userParams){
1539 return (List<EPUser>)dataAccessService.executeNamedQuery("epUserAppId", userParams, null);
1543 * It checks whether the new user is valid or not otherwise throws exception
1548 * Checks if user is valid and returns message otherwise throws exception
1551 private String validateNewUser(String orgUserId, EPApp app) throws Exception {
1552 EPUser epUser = searchService.searchUserByUserId(orgUserId);
1553 if (epUser == null) {
1554 throw new Exception("User does not exist");
1555 } else if (!epUser.getOrgUserId().equals(orgUserId)) {
1556 throw new Exception("User does not exist");
1557 } else if (app == null) {
1558 throw new Exception("Application does not exist");
1560 return "Saved Successfully";
1564 * Checks if the fields exists or not
1567 * contains user information
1571 * throws exception if the field is not valid
1573 private void validateExternalRequestFields(List<EPUser> userList, EPApp app) throws Exception{
1574 if (userList.size() == 0 || userList.isEmpty() ) {
1575 throw new Exception("User does not exist");
1576 } else if(app == null) {
1577 throw new Exception("Application does not exist");
1578 } else if(!app.getEnabled() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1579 throw new Exception(app.getMlAppName()+" application is unavailable");
1583 @SuppressWarnings("unchecked")
1584 public ExternalRequestFieldsValidator setExternalRequestUserAppRole(ExternalSystemUser newAppRolesForUser, String reqType) {
1585 boolean result = false;
1586 boolean externalSystemRequest = true;
1587 final Map<String, Long> params = new HashMap<>();
1588 final Map<String, String> userParams = new HashMap<>();
1589 List<EPUser> userInfo = null;
1591 List<EPUserAppRolesRequest> epRequestId = null;
1592 String orgUserId = "";
1593 String updateStatus = "";
1594 String reqMessage = "";
1596 if (newAppRolesForUser != null && newAppRolesForUser.getLoginId() != null) {
1597 orgUserId = newAppRolesForUser.getLoginId().trim();
1599 String appName = newAppRolesForUser.getApplicationName();
1600 String logMessage = ("DELETE").equals(reqType) ? "Deleting": "Assigning/Updating" ;
1601 if (orgUserId.length() > 0) {
1602 ObjectMapper mapper = new ObjectMapper();
1603 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1604 int epRequestIdSize = 0;
1606 app = appsService.getAppDetail(appName);
1607 userParams.put("orgUserIdValue", orgUserId);
1608 userInfo = checkIfUserExists(userParams);
1609 reqMessage = "Updated Successfully";
1610 if (!reqType.equals("DELETE") && (userInfo.size() == 0 || userInfo.isEmpty())) {
1611 reqMessage = validateNewUser(orgUserId, app);
1613 if (userInfo.size() != 0 || !userInfo.isEmpty()) {
1614 validateExternalRequestFields(userInfo, app);
1615 user = userInfo.get(0);
1616 params.put("appId", app.getId());
1617 params.put("userId", user.getId());
1618 epRequestId = (List<EPUserAppRolesRequest>) dataAccessService
1619 .executeNamedQuery("userAppRolesRequestList", params, null);
1620 epRequestIdSize = epRequestId.size();
1623 //If Non-Centralized app make sure you sync app roles before assigning to user
1624 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !app.getRolesInAAF()) {
1625 logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Starting GET roles for app {}",app.getId());
1626 EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, app.getId(), "/roles");
1627 logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Finshed GET roles for app {} and payload {}",app.getId(), appRoles);
1628 if (appRoles.length > 0) {
1629 syncAppRoles(sessionFactory, app.getId(), appRoles);
1632 List<RoleInAppForUser> roleInAppForUserList = roleInAppForUserList(newAppRolesForUser.getRoles(),
1633 app.getId(), app.getMlAppName());
1634 List<EcompUserAppRoles> userRoleList = null;
1635 if(!userInfo.isEmpty()){
1636 final Map<String, Long> appParams = new HashMap<>();
1637 appParams.put("userId", user.getId());
1638 appParams.put("appId", app.getId());
1639 userRoleList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", appParams, null);
1641 // Check if list contains just account admin role
1642 boolean checkIfAdminRoleExists = false;
1643 if (reqType.equals("DELETE") && userRoleList!=null) {
1644 checkIfAdminRoleExists = userRoleList.stream()
1645 .anyMatch(userRole -> userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1647 checkIfAdminRoleExists = roleInAppForUserList.stream()
1648 .anyMatch(roleList -> roleList.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1650 // if Centralized app
1651 if (app.getRolesInAAF()) {
1652 // We should add If user does not exist in remote application
1654 // If adding just account admin role dont make remote application user call or
1655 // if request has only single non admin role then make remote call
1656 if (!(app.getId().equals(PortalConstants.PORTAL_APP_ID) && reqType.equals("DELETE"))
1657 && (app.getAppAck() != null && app.getAppAck())
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;
1668 pushRemoteUser(remoteUserRoles, orgUserIdNewOrExist , app, mapper, searchService,
1669 applicationsRestClientService,true);
1671 } catch (Exception e) {
1672 reqMessage = e.getMessage();
1673 logger.error(EELFLoggerDelegate.errorLogger, "setExternalRequestUserAppRole: Failed to added remote user", e);
1674 throw new Exception(reqMessage);
1676 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1677 applicationsRestClientService, app.getId(), orgUserId);
1678 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1679 userRolesInLocalApp);
1680 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1681 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
1683 if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1684 // Apply changes in external Access system
1685 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, externalSystemRequest,false,rolesGotDeletedByApprover,false);
1687 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
1688 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1689 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,false,rolesGotDeletedByApprover,false);
1691 // If local application is not centralized
1692 else if(!app.getRolesInAAF() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1693 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1694 applicationsRestClientService, app.getId(), orgUserId);
1695 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1696 userRolesInLocalApp);
1697 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
1699 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,false,rolesGotDeletedByApprover,false);
1700 } else {// remote app
1701 // If adding just account admin role don't do remote application user call
1702 if (!((roleInAppForUserList.size() == 1 || reqType.equals("DELETE")) && checkIfAdminRoleExists)) {
1703 EPUser remoteAppUser = null;
1704 remoteAppUser = checkIfRemoteUserExits(orgUserId, app, applicationsRestClientService);
1705 if (remoteAppUser == null) {
1706 addRemoteUser(roleInAppForUserList, orgUserId, app, mapper, searchService,
1707 applicationsRestClientService);
1708 reqMessage = "Saved Successfully";
1711 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
1712 applicationsRestClientService, app.getId(), orgUserId,false);
1714 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1715 userRolesInRemoteApp);
1716 logger.info(EELFLoggerDelegate.debugLogger,
1717 "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
1718 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1719 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
1721 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1722 reqType,false,rolesGotDeletedByApprover,false);
1723 // If no roles remain, request app to set user inactive.
1725 * if (userRolesInRemoteApp.size() == 0) {
1726 * logger.debug(EELFLoggerDelegate.debugLogger,
1727 * "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive"
1728 * , app, orgUserId); //TODO Need to fix the logged in user is not set to
1729 * inactive remoteAppUser.setActive(false); postUserToRemoteApp(orgUserId, user,
1730 * app, applicationsRestClientService); }
1734 // Here we are adding only we have single account admin in roleInAppForUserList and this should not add in remote
1735 if(!(reqType.equals("DELETE")) && userInfo.isEmpty()){
1736 reqMessage = "Saved Successfully";
1738 Set<EcompRole> userRolesInRemoteApp = constructUsersEcompRoles(roleInAppForUserList);
1740 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1741 userRolesInRemoteApp);
1742 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}",
1743 logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1744 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
1746 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1747 reqType,false,rolesGotDeletedByApprover,false);
1750 reqMessage = "Failed to save the user app role(s)";
1752 if (epRequestIdSize > 0 && !userInfo.isEmpty()) {
1754 applyChangesToAppRolesRequest(app.getId(), user.getId(), updateStatus, epRequestId.get(0));
1757 } catch (Exception e) {
1758 String message = String.format("setExternalRequestUserAppRole: Failed to create user or update user roles for User %s, AppId %s",
1759 orgUserId, appName);
1760 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1762 reqMessage = e.getMessage();
1763 if(epRequestIdSize > 0 && userInfo!=null && !userInfo.isEmpty()){
1765 applyChangesToAppRolesRequest(app.getId(), user.getId(),
1766 updateStatus, epRequestId.get(0));
1771 return new ExternalRequestFieldsValidator(result, reqMessage);
1776 * @param roleInAppForUserList
1778 * @param applicationsRestClientService
1781 * @return Set<EcompRole>
1782 * @throws JsonProcessingException
1783 * @throws HTTPException
1785 private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
1786 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
1787 throws JsonProcessingException, HTTPException {
1788 Set<EcompRole> updatedUserRoles = constructUsersEcompRoles(roleInAppForUserList);
1789 return updatedUserRoles;
1793 * It constructs and returns list of user app roles when the external API role approval system calls
1796 * @param roleInAppForUserList
1798 * @return list of user app roles
1800 * throws exceptions if role id does not exits
1802 private List<RoleInAppForUser> roleInAppForUserList(List<ExternalSystemRoleApproval> roleInAppForUserList,
1803 Long appId, String appName) throws Exception {
1804 List<RoleInAppForUser> existingUserRoles = new ArrayList<RoleInAppForUser>();
1805 EPRole existingAppRole = null;
1806 for (ExternalSystemRoleApproval roleInAppForUser : roleInAppForUserList) {
1807 RoleInAppForUser ecompRole = new RoleInAppForUser();
1808 existingAppRole = epRoleService.getAppRole(roleInAppForUser.getRoleName(), appId);
1809 if (existingAppRole == null) {
1810 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1811 roleInAppForUserList);
1812 throw new Exception("'" +roleInAppForUser.getRoleName() + "'" +" role does not exist for " + appName + " application");
1814 if (!existingAppRole.getActive()) {
1815 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1816 roleInAppForUserList);
1817 throw new Exception(roleInAppForUser.getRoleName() + " role is unavailable for "+ appName + " application");
1820 List<EPRole> roleInfo = externalAccessRolesService.getPortalAppRoleInfo(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
1821 EPRole adminRole = new EPRole();
1822 if(roleInfo.size()>0)
1824 adminRole = roleInfo.get(0);
1825 logger.debug(EELFLoggerDelegate.debugLogger, "Admin RoleName form DB: " + adminRole.getName());
1827 ecompRole.roleId = (appId == 1 || roleInAppForUser.getRoleName().equals(adminRole.getName())) ? existingAppRole.getId() : existingAppRole.getAppRoleId();
1828 ecompRole.roleName = roleInAppForUser.getRoleName();
1829 ecompRole.isApplied = true;
1830 existingUserRoles.add(ecompRole);
1833 return existingUserRoles;
1842 * @param applicationsRestClientService
1844 * @throws HTTPException
1846 protected EPUser getUserFromApp(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1847 throws HTTPException {
1849 if (app.getId() == PortalConstants.PORTAL_APP_ID) {
1850 // Map<String,String> params = new HashMap<String,String>();
1851 // params.put("sbcid",userId);
1852 @SuppressWarnings("unchecked")
1853 List<EPUser> userList = (List<EPUser>) dataAccessService
1854 .executeQuery("from EPUser where orgUserId='" + userId + "'", null);
1855 if (userList != null && !userList.isEmpty())
1856 return userList.get(0);
1862 return getUser(userId, app, applicationsRestClientService);
1865 protected EPUser getUser(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1866 throws HTTPException {
1867 return applicationsRestClientService.get(EPUser.class, app.getId(), String.format("/user/%s", userId), true);
1871 protected boolean isAppUpgradeVersion(EPApp app){
1876 public ExternalSystemAccess getExternalRequestAccess(){
1877 ExternalSystemAccess res = null;
1879 res = new ExternalSystemAccess(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE,
1880 Boolean.parseBoolean(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE)));
1881 } catch (Exception e) {
1882 logger.error(EELFLoggerDelegate.errorLogger, "getExternalRequestAccess failed" + e.getMessage());
1890 * @see org.onap.portalapp.portal.service.UserRolesService#
1891 * getAppRolesForUser(java.lang.Long, java.lang.String)
1893 @SuppressWarnings("unchecked")
1894 public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId, Boolean extRequestValue,EPUser user) {
1895 List<RoleInAppForUser> rolesInAppForUser = null;
1896 EPApp app = appsService.getApp(appId);
1897 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - app = {}", app);
1899 // for onap portal app, no need to make a remote call
1900 List<Role> roleList = new ArrayList<>();
1901 if (appId == PortalConstants.PORTAL_APP_ID) {
1902 if(app.getRolesInAAF()){
1903 List<CentralV2Role> cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey());
1904 for(CentralV2Role cenRole : cenRoleList){
1905 Role role = new Role();
1906 role.setActive(cenRole.getActive());
1907 role.setId(cenRole.getId());
1908 role.setName(cenRole.getName());
1909 role.setPriority(cenRole.getPriority());
1913 roleList = roleService.getAvailableRoles(userId);
1915 List<Role> activeRoleList = new ArrayList<Role>();
1916 for(Role role: roleList) {
1917 if(role.getActive()) {
1918 if(role.getId() != 1){ // prevent portal admin from being added
1919 activeRoleList.add(role);
1920 } else if(extRequestValue){
1921 activeRoleList.add(role);
1926 EPUser localUser = getUserFromApp(userId, app, applicationsRestClientService);
1927 // If localUser does not exists return roles
1928 Set<EPRole> roleSet = null;
1929 EPRole[] roleSetList = null;
1930 if(localUser != null){
1931 roleSet = localUser.getAppEPRoles(app);
1932 roleSetList = roleSet.toArray(new EPRole[0]);
1934 rolesInAppForUser = constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue);
1935 return rolesInAppForUser;
1938 EcompRole[] appRoles = null;
1939 boolean checkIfUserisApplicationAccAdmin = false;
1940 List<EcompRole> roles = new ArrayList<>();
1941 if (app.getRolesInAAF()) {
1942 final Map<String, Long> appParams = new HashMap<>();
1943 appParams.put("appId", app.getId());
1944 List<EPRole> applicationRoles = dataAccessService.executeNamedQuery("getActiveRolesOfApplication",
1947 EPApp application = appService.getApp(appId);
1948 checkIfUserisApplicationAccAdmin = adminRolesService.isAccountAdminOfApplication(user,
1951 List<EPRole> rolesetwithfunctioncds = new ArrayList<EPRole>();
1952 for (EPRole role : applicationRoles) {
1953 Map<String, Long> params = new HashMap<>();
1954 params.put("roleId", role.getId());
1955 params.put(APP_ID, app.getId());
1956 List<CentralV2RoleFunction> cenRoleFuncList = dataAccessService
1957 .executeNamedQuery("getAppRoleFunctionList", params, null);
1959 // SortedSet<CentralV2RoleFunction> roleFunctionSet =
1961 SortedSet<RoleFunction> roleFunctionSet = new TreeSet<>();
1962 for (CentralV2RoleFunction roleFunc : cenRoleFuncList) {
1964 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1965 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
1966 String type = externalAccessRolesService.getFunctionCodeType(roleFunc.getCode());
1967 String action = externalAccessRolesService.getFunctionCodeAction(roleFunc.getCode());
1968 String name = roleFunc.getName();
1970 RoleFunction function = new RoleFunction();
1971 function.setAction(action);
1972 function.setType(type);
1973 function.setCode(functionCode);
1974 function.setName(name);
1975 roleFunctionSet.add(function);
1976 role.setRoleFunctions(roleFunctionSet);
1979 rolesetwithfunctioncds.add(role);
1984 for (EPRole role1 : rolesetwithfunctioncds) {
1985 EcompRole ecompRole = new EcompRole();
1986 ecompRole.setId(role1.getId());
1987 ecompRole.setName(role1.getName());
1988 ecompRole.setRoleFunctions(role1.getRoleFunctions());
1989 roles.add(ecompRole);
1992 if (checkIfUserisApplicationAccAdmin) {
1993 appRoles = roles.toArray(new EcompRole[roles.size()]);
1994 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() If Logged in user checkIfUserisApplicationAccAdmin- appRoles = {}", appRoles);
1995 } else if (adminRolesService.isRoleAdmin(user) && !checkIfUserisApplicationAccAdmin) {
1996 List<EcompRole> roleAdminAppRoles = new ArrayList<>();
1997 List<String> roleAdminAppRolesNames = new ArrayList<>();
1998 final Map<String, Long> userParams = new HashMap<>();
1999 userParams.put("userId", user.getId());
2000 List<String> getUserApproverRoles = dataAccessService.executeNamedQuery("getUserApproverRoles", userParams, null);
2002 List<EcompRole> userapproverRolesList = new ArrayList<>();
2003 for (String str : getUserApproverRoles) {
2004 EcompRole epRole = roles.stream().filter(x -> str.equals(x.getName())).findAny().orElse(null);
2006 userapproverRolesList.add(epRole);
2008 // roles.removeAll(userapproverRolesList);
2009 for (EcompRole role : userapproverRolesList) {
2011 List<RoleFunction> roleFunList = new ArrayList<>();
2012 roleFunList.addAll(role.getRoleFunctions());
2013 boolean checkIfFunctionsExits = roleFunList.stream()
2014 .anyMatch(roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
2015 if (checkIfFunctionsExits) {
2016 roleAdminAppRoles.add(role);
2017 List<RoleFunction> filteredList = roleFunList.stream()
2018 .filter(x -> "Approver".equalsIgnoreCase(x.getType())).collect(Collectors.toList());
2019 roleAdminAppRolesNames.addAll(filteredList.stream().map(RoleFunction::getCode)
2020 .collect(Collectors.toList()));
2021 // roleAdminAppRolesNames = filteredList.stream().map(RoleFunction::getCode)
2022 // .collect(Collectors.toList());
2025 for (String name : roleAdminAppRolesNames) {
2026 EcompRole ecompRole = roles.stream().filter(x -> name.equals(x.getName())).findAny()
2028 if (ecompRole != null)
2029 roleAdminAppRoles.add(ecompRole);
2032 appRoles = roleAdminAppRoles.toArray(new EcompRole[roleAdminAppRoles.size()]);
2036 appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
2038 // Test this error case, for generating an internal ONAP Portal
2040 // EcompRole[] appRoles = null;
2041 // If there is an exception in the rest client api, then null will
2043 if (appRoles != null) {
2044 if(!app.getRolesInAAF()) {
2045 syncAppRoles(sessionFactory, appId, appRoles);
2047 EcompRole[] userAppRoles = null;
2051 if(app.getRolesInAAF()){
2052 final Map<String, String> params = new HashMap<>();
2053 final Map<String, Long> userParams = new HashMap<>();
2054 params.put("orgUserIdValue", userId);
2055 List<EPUser> actualUser = dataAccessService.executeNamedQuery("epUserAppId", params, null);
2056 userParams.put("appId", app.getId());
2057 userParams.put("userId", actualUser.get(0).getId());
2058 List<EPUserAppCurrentRoles> userAppsRolesList = dataAccessService.executeNamedQuery("getUserAppCurrentRoles", userParams, null);
2060 List<EcompRole> setUserRoles = new ArrayList<>();
2061 for(EPUserAppCurrentRoles role : userAppsRolesList){
2062 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - userAppsRolesList get userRolename = {}", role.getRoleName());
2063 EcompRole ecompRole = new EcompRole();
2064 ecompRole.setId(role.getRoleId());
2065 ecompRole.setName(role.getRoleName());
2066 setUserRoles.add(ecompRole);
2069 boolean checkIfUserisAccAdmin = setUserRoles.stream()
2070 .anyMatch(ecompRole -> ecompRole.getId() == 999L);
2072 if (!checkIfUserisAccAdmin) {
2073 List<EcompRole> userApplicationRolesList = setUserRoles;
2074 List<EcompRole> appRolesList = Arrays.asList(appRoles);
2075 Set<EcompRole> finalUserAppRolesList = new HashSet<>();
2077 List<String> roleNames = new ArrayList<>();
2078 for (EcompRole role : userApplicationRolesList) {
2079 EcompRole epRole = appRolesList.stream()
2080 .filter(x -> role.getName().equals(x.getName())).findAny().orElse(null);
2081 List<RoleFunction> roleFunList = new ArrayList<>();
2083 if (epRole != null) {
2084 if (epRole.getRoleFunctions().size() > 0)
2085 roleFunList.addAll(epRole.getRoleFunctions());
2086 boolean checkIfFunctionsExits = roleFunList.stream().anyMatch(
2087 roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
2088 if (checkIfFunctionsExits) {
2089 finalUserAppRolesList.add(role);
2090 List<RoleFunction> filteredList = roleFunList.stream()
2091 .filter(x -> "Approver".equalsIgnoreCase(x.getType()))
2092 .collect(Collectors.toList());
2093 roleNames = filteredList.stream().map(RoleFunction::getCode)
2094 .collect(Collectors.toList());
2096 roleNames.add(epRole.getName());
2099 for (String name : roleNames) {
2100 EcompRole ecompRole = appRolesList.stream()
2101 .filter(x -> name.equals(x.getName())).findAny().orElse(null);
2102 if (ecompRole != null)
2103 finalUserAppRolesList.add(ecompRole);
2108 for (String name : roleNames) {
2110 boolean checkIfFunctionsExits = userAppsRolesList.stream().anyMatch(
2111 role -> role.getRoleName().equalsIgnoreCase(name));
2112 if(checkIfFunctionsExits)
2114 EcompRole epRole = appRolesList.stream().filter(x -> name.equals(x.getName()))
2115 .findAny().orElse(null);
2117 setUserRoles.add(epRole);
2121 userAppRoles = setUserRoles.toArray(new EcompRole[setUserRoles.size()]);
2124 userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
2125 String.format("/user/%s/roles", userId));
2127 } catch (HTTPException e) {
2128 // Some apps are returning 400 if user is not found.
2129 if (e.getResponseCode() == 400) {
2130 logger.debug(EELFLoggerDelegate.debugLogger,
2131 "getAppRolesForUser caught exception with response code 400; continuing", e);
2133 // Other response code, let it come thru.
2137 if (userAppRoles == null) {
2138 if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
2139 EcompPortalUtils.setExternalAppResponseCode(200);
2140 String message = String.format(
2141 "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
2142 + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
2143 + "Overriding to 200 until framework SDK returns a useful response.",
2144 Long.toString(appId), userId);
2145 logger.warn(EELFLoggerDelegate.applicationLogger, message);
2149 HashMap<Long, EcompRole> appRolesActiveMap =hashMapFromEcompRoles(appRoles);
2150 ArrayList<EcompRole> activeRoles = new ArrayList<EcompRole>();
2151 if(userAppRoles != null){
2152 for (int i = 0; i < userAppRoles.length; i++) {
2153 if (appRolesActiveMap.containsKey(userAppRoles[i].getId())) {
2154 EcompRole role = new EcompRole();
2155 role.setId(userAppRoles[i].getId());
2156 role.setName(userAppRoles[i].getName());
2157 activeRoles.add(role);
2161 EcompRole[] userAppRolesActive = activeRoles.toArray(new EcompRole[activeRoles.size()]);
2164 boolean checkIfUserisRoleAdmin = adminRolesService.isRoleAdmin(user) && !checkIfUserisApplicationAccAdmin;
2166 // If the remote application isn't down we MUST sync user
2167 // roles here in case we have this user here!
2168 syncUserRoles(sessionFactory, userId, appId, userAppRolesActive, extRequestValue, null,checkIfUserisRoleAdmin,appRoles);
2169 } catch (Exception e) {
2170 // TODO: we may need to check if user exists, maybe remote
2172 String message = String.format(
2173 "getAppRolesForUser: user %s does not exist in remote application %s", userId,
2174 Long.toString(appId));
2175 logger.error(EELFLoggerDelegate.errorLogger, message, e);
2176 userAppRoles = new EcompRole[0];
2178 rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
2180 } catch (Exception e) {
2181 String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
2182 Long.toString(appId));
2183 logger.error(EELFLoggerDelegate.errorLogger, message, e);
2185 return rolesInAppForUser;
2188 private boolean postUserRolesToMylogins(AppWithRolesForUser userAppRolesData,
2189 ApplicationsRestClientService applicationsRestClientService, Long appId, Long userId)
2190 throws JsonProcessingException, HTTPException {
2191 boolean result = false;
2192 ObjectMapper mapper = new ObjectMapper();
2193 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
2194 String userRolesAsString = mapper.writeValueAsString(userAppRolesData);
2195 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, as the endpoint is not defined yet from the Mylogins");
2196 applicationsRestClientService.post(AppWithRolesForUser.class, appId, userRolesAsString, String.format("/user/%s/myLoginroles", userId));
2200 @SuppressWarnings("unchecked")
2201 public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser userAppRolesData, EPUser user) {
2202 FieldsValidator fieldsValidator = new FieldsValidator();
2203 final Map<String, Long> params = new HashMap<>();
2204 List<EPUserAppRoles> appRole= null;
2206 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, still the endpoint is yet to be defined");
2207 boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService,
2208 userAppRolesData.getAppId(), user.getId());
2209 logger.debug(EELFLoggerDelegate.debugLogger,"putUserAppRolesRequest: result {}", result);
2211 params.put("appId", userAppRolesData.getAppId());
2212 EPUserAppRolesRequest epAppRolesRequestData = new EPUserAppRolesRequest();
2213 epAppRolesRequestData.setCreatedDate(new Date());
2214 epAppRolesRequestData.setUpdatedDate(new Date());
2215 epAppRolesRequestData.setUserId(user.getId());
2216 epAppRolesRequestData.setAppId(userAppRolesData.getAppId());
2217 epAppRolesRequestData.setRequestStatus("P");
2218 List<RoleInAppForUser> appRoleIdList = userAppRolesData.getAppRoles();
2219 Set<EPUserAppRolesRequestDetail> appRoleDetails = new LinkedHashSet<EPUserAppRolesRequestDetail>();
2220 dataAccessService.saveDomainObject(epAppRolesRequestData, null);
2221 for (RoleInAppForUser userAppRoles : appRoleIdList) {
2222 Boolean isAppliedVal = userAppRoles.isApplied;
2223 params.put("appRoleId", userAppRoles.roleId);
2225 appRole = (List<EPUserAppRoles>) dataAccessService.executeNamedQuery("appRoles", params, null);
2226 if (!appRole.isEmpty()) {
2227 EPUserAppRolesRequestDetail epAppRoleDetail = new EPUserAppRolesRequestDetail();
2228 epAppRoleDetail.setReqRoleId(appRole.get(0).getRoleId());
2229 epAppRoleDetail.setReqType("P");
2230 epAppRoleDetail.setEpRequestIdData(epAppRolesRequestData);
2231 dataAccessService.saveDomainObject(epAppRoleDetail, null);
2235 epAppRolesRequestData.setEpRequestIdDetail(appRoleDetails);
2236 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
2238 } catch (Exception e) {
2239 logger.error(EELFLoggerDelegate.errorLogger, "putUserAppRolesRequest failed", e);
2240 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
2242 return fieldsValidator;
2245 public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(EPUser userid, String appName) {
2246 Map<String, String> params = new HashMap<>();
2247 params.put("userid", userid.getId().toString());
2248 //params.put("appid", appid);
2249 params.put("appName", appName);
2251 @SuppressWarnings("unchecked")
2252 List<EPUserAppCatalogRoles> userAppRoles = (List<EPUserAppCatalogRoles>) dataAccessService
2253 .executeNamedQuery("userAppCatalogRoles", params, null);
2254 return userAppRoles;
2257 public String updateRemoteUserProfile(String orgUserId, Long appId) {
2258 ObjectMapper mapper = new ObjectMapper();
2259 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
2260 EPUser client = searchService.searchUserByUserId(orgUserId);
2261 EPUser newUser = new EPUser();
2262 newUser.setActive(client.getActive());
2263 newUser.setFirstName(client.getFirstName());
2264 newUser.setLastName(client.getLastName());
2265 newUser.setLoginId(client.getLoginId());
2266 newUser.setLoginPwd(client.getLoginPwd());
2267 newUser.setMiddleInitial(client.getMiddleInitial());
2268 newUser.setEmail(client.getEmail());
2269 newUser.setOrgUserId(client.getLoginId());
2271 String userAsString = mapper.writeValueAsString(newUser);
2272 List<EPApp> appList = appsService.getUserRemoteApps(client.getId().toString());
2273 // applicationsRestClientService.post(EPUser.class, appId,
2274 // userAsString, String.format("/user", orgUserId));
2275 for (EPApp eachApp : appList) {
2277 applicationsRestClientService.post(EPUser.class, eachApp.getId(), userAsString,
2278 String.format("/user/%s", orgUserId));
2279 } catch (Exception e) {
2280 logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId()
2281 + " in remote app. appId = " + eachApp.getId());
2284 } catch (Exception e) {
2285 logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
2296 * @see org.onap.portalapp.portal.service.UserRolesService#
2297 * getCachedAppRolesForUser(java.lang.Long, java.lang.Long)
2299 @SuppressWarnings("deprecation")
2300 public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId) {
2301 // Find the records for this user-app combo, if any
2302 String filter = " where user_id = " + Long.toString(userId) + " and app_id = " + Long.toString(appId);
2303 @SuppressWarnings("unchecked")
2304 List<EPUserApp> roleList = dataAccessService.getList(EPUserApp.class, filter, null, null);
2305 logger.debug(EELFLoggerDelegate.debugLogger, "getCachedAppRolesForUser: list size is {}", roleList.size());
2310 * It retrieves and returns list of user app roles for local and remote applications based app id
2313 * @return list of user app roles
2314 * @throws HTTPException
2316 public List<UserApplicationRoles> getUsersFromAppEndpoint(Long appId) throws HTTPException {
2317 ArrayList<UserApplicationRoles> userApplicationRoles = new ArrayList<UserApplicationRoles>();
2319 EPApp app = appsService.getApp(appId);
2320 //If local or centralized application
2321 if (appId == PortalConstants.PORTAL_APP_ID || app.getRolesInAAF()) {
2322 Map<String, Object> params = new HashMap<>();
2323 params.put("id", app.getId());
2324 params.put("active", true);
2325 @SuppressWarnings("unchecked")
2326 //List<EPUser> userList = (List<EPUser>) dataAccessService.executeNamedQuery("getActiveUsers", null, null);
2327 //List<Object[]> userList = (List<Object[]>) dataAccessService.executeNamedQuery("getActiveUsersForApp", params, null);
2328 List<EPUser> userList = (List<EPUser>) dataAccessService.executeNamedQuery("getActiveUsersForApp", params, null);
2329 for (EPUser user : userList) {
2330 UserApplicationRoles userWithAppRoles = convertToUserApplicationRoles(user, app.getId());
2331 if (userWithAppRoles.getRoles() != null && userWithAppRoles.getRoles().size() > 0)
2332 userApplicationRoles.add(userWithAppRoles);
2338 RemoteUserWithRoles[] remoteUsers = null;
2339 String remoteUsersString = applicationsRestClientService.getIncomingJsonString(appId, "/users");
2341 remoteUsers = doGetUsers(isAppUpgradeVersion(app), remoteUsersString);
2343 userApplicationRoles = new ArrayList<UserApplicationRoles>();
2344 for (RemoteUserWithRoles remoteUser : remoteUsers) {
2345 UserApplicationRoles userWithRemoteAppRoles = convertToUserApplicationRoles(appId, remoteUser);
2346 if (userWithRemoteAppRoles.getRoles() != null && userWithRemoteAppRoles.getRoles().size() > 0) {
2347 userApplicationRoles.add(userWithRemoteAppRoles);
2349 logger.debug(EELFLoggerDelegate.debugLogger,
2350 "User " + userWithRemoteAppRoles.getOrgUserId() + " doesn't have any roles assigned to any app.");
2355 return userApplicationRoles;
2364 private UserApplicationRoles convertToUserApplicationRoles(EPUser user, Long appId) {
2365 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
2366 userWithRemoteAppRoles.setAppId(appId);
2367 userWithRemoteAppRoles.setOrgUserId(user.getOrgUserId());
2368 userWithRemoteAppRoles.setFirstName(user.getFirstName());
2369 userWithRemoteAppRoles.setLastName(user.getLastName());
2370 List<RemoteRole> roleList = new ArrayList<RemoteRole>();
2371 for(EPUserApp userApp :user.getEPUserApps()) {
2372 RemoteRole remoteRole = new RemoteRole();
2373 remoteRole.setName(userApp.getRole().getName());
2374 remoteRole.setId(userApp.getRole().getId());
2375 roleList.add(remoteRole);
2377 userWithRemoteAppRoles.setRoles(roleList);
2378 return userWithRemoteAppRoles;
2385 * @param appgetUsersFromAppEndpoint
2388 private UserApplicationRoles convertToUserApplicationRoles(Long appId, EPUser user, EPApp app) {
2389 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
2390 userWithRemoteAppRoles.setAppId(appId);
2391 userWithRemoteAppRoles.setOrgUserId(user.getOrgUserId());
2392 userWithRemoteAppRoles.setFirstName(user.getFirstName());
2393 userWithRemoteAppRoles.setLastName(user.getLastName());
2394 userWithRemoteAppRoles.setRoles(convertToRemoteRoleList(user, app));
2395 return userWithRemoteAppRoles;
2404 @SuppressWarnings("unchecked")
2405 private List<RemoteRole> convertToRemoteRoleList(EPUser user, EPApp app) {
2406 List<RemoteRole> roleList = new ArrayList<RemoteRole>();
2407 SortedSet<EPRole> roleSet = user.getAppEPRoles(app);
2408 for (EPRole role : roleSet) {
2409 logger.debug(EELFLoggerDelegate.debugLogger, "In convertToRemoteRoleList() - for user {}, found Name {}", user.getOrgUserId(), role.getName());
2410 RemoteRole rRole = new RemoteRole();
2411 rRole.setId(role.getId());
2412 rRole.setName(role.getName());
2413 roleList.add(rRole);
2416 //Get the active roles of user for that application using query
2417 List<EPRole> userEpRoleList = new ArrayList<>();
2418 final Map<String, Long> params = new HashMap<>();
2419 params.put("appId", app.getId());
2420 params.put("userId", user.getId());
2421 userEpRoleList = dataAccessService.executeNamedQuery("getUserRoleOnUserIdAndAppId", params, null);
2423 for (EPRole remoteUserRoleList : userEpRoleList) {
2425 RemoteRole remoteRoleListId = roleList.stream().filter(x -> remoteUserRoleList.getId().equals(x.getId()))
2426 .findAny().orElse(null);
2427 if (remoteRoleListId == null) {
2428 logger.debug(EELFLoggerDelegate.debugLogger,
2429 "Adding the role to the rolelist () - for user {}, found Name {}", user.getOrgUserId(),
2431 remoteUserRoleList.getName());
2432 RemoteRole role = new RemoteRole();
2433 role.setId(remoteUserRoleList.getId());
2434 role.setName(remoteUserRoleList.getName());
2441 logger.debug(EELFLoggerDelegate.debugLogger, "rolelist size of the USER() - for user {}, found RoleListSize {}", user.getOrgUserId(), roleList.size());
2449 public RemoteUserWithRoles[] doGetUsers(boolean postOpenSource, String remoteUsersString) {
2451 ObjectMapper mapper = new ObjectMapper();
2453 return mapper.readValue(remoteUsersString, RemoteUserWithRoles[].class);
2454 } catch (IOException e) {
2455 logger.error(EELFLoggerDelegate.errorLogger,
2456 "doGetUsers : Failed : Unexpected property in incoming JSON",
2458 logger.error(EELFLoggerDelegate.errorLogger,
2459 "doGetUsers : Incoming JSON that caused it --> " + remoteUsersString);
2462 return new RemoteUserWithRoles[0];
2465 @SuppressWarnings("unchecked")
2466 public List<EPUserApp> getEPUserAppList(Long appId, Long userId, Long roleId) {
2467 List<EPUserApp> userRoleList = new ArrayList<EPUserApp>();
2468 final Map<String, Long> params = new HashMap<>();
2469 params.put("appId", appId);
2470 params.put("userId", userId);
2471 params.put("roleId", roleId);
2472 userRoleList = dataAccessService.executeNamedQuery("getUserRoleOnUserIdAndRoleIdAndAppId", params, null);
2473 return userRoleList;
2477 /*public static void main(String[] args) {
2478 List<EcompRole> str1 = new ArrayList<String>();
2484 List<String> str2 = new ArrayList<String>();
2488 List<EcompRole> userApplicationRolesList = setUserRoles;
2489 List<EcompRole> appRolesList = Arrays.asList(appRoles);