2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2017-2018 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.EPApp;
69 import org.onap.portalapp.portal.domain.EPRole;
70 import org.onap.portalapp.portal.domain.EPUser;
71 import org.onap.portalapp.portal.domain.EPUserApp;
72 import org.onap.portalapp.portal.domain.EPUserAppCatalogRoles;
73 import org.onap.portalapp.portal.domain.EPUserAppRoles;
74 import org.onap.portalapp.portal.domain.EPUserAppRolesRequest;
75 import org.onap.portalapp.portal.domain.EPUserAppRolesRequestDetail;
76 import org.onap.portalapp.portal.domain.ExternalSystemAccess;
77 import org.onap.portalapp.portal.exceptions.SyncUserRolesException;
78 import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
79 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
80 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
81 import org.onap.portalapp.portal.transport.AppWithRolesForUser;
82 import org.onap.portalapp.portal.transport.CentralV2Role;
83 import org.onap.portalapp.portal.transport.EPUserAppCurrentRoles;
84 import org.onap.portalapp.portal.transport.EcompUserAppRoles;
85 import org.onap.portalapp.portal.transport.ExternalAccessUser;
86 import org.onap.portalapp.portal.transport.ExternalAccessUserRoleDetail;
87 import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator;
88 import org.onap.portalapp.portal.transport.ExternalRoleDescription;
89 import org.onap.portalapp.portal.transport.FieldsValidator;
90 import org.onap.portalapp.portal.transport.FunctionalMenuItem;
91 import org.onap.portalapp.portal.transport.FunctionalMenuRole;
92 import org.onap.portalapp.portal.transport.RemoteRole;
93 import org.onap.portalapp.portal.transport.RemoteRoleV1;
94 import org.onap.portalapp.portal.transport.RemoteUserWithRoles;
95 import org.onap.portalapp.portal.transport.RoleInAppForUser;
96 import org.onap.portalapp.portal.transport.RolesInAppForUser;
97 import org.onap.portalapp.portal.transport.UserApplicationRoles;
98 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
99 import org.onap.portalapp.portal.utils.EcompPortalUtils;
100 import org.onap.portalapp.portal.utils.PortalConstants;
101 import org.onap.portalapp.util.SystemType;
102 import org.onap.portalsdk.core.domain.Role;
103 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
104 import org.onap.portalsdk.core.restful.domain.EcompRole;
105 import org.onap.portalsdk.core.service.DataAccessService;
106 import org.onap.portalsdk.core.service.RoleService;
107 import org.onap.portalsdk.core.util.SystemProperties;
108 import org.springframework.beans.factory.annotation.Autowired;
109 import org.springframework.http.HttpEntity;
110 import org.springframework.http.HttpHeaders;
111 import org.springframework.http.HttpMethod;
112 import org.springframework.http.HttpStatus;
113 import org.springframework.http.ResponseEntity;
114 import org.springframework.web.client.RestTemplate;
116 import com.fasterxml.jackson.core.JsonProcessingException;
117 import com.fasterxml.jackson.databind.DeserializationFeature;
118 import com.fasterxml.jackson.databind.ObjectMapper;
121 public class UserRolesCommonServiceImpl {
123 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesCommonServiceImpl.class);
125 private static final Object syncRests = new Object();
128 private DataAccessService dataAccessService;
130 private SessionFactory sessionFactory;
132 private SearchService searchService;
134 private EPAppService appsService;
136 private ApplicationsRestClientService applicationsRestClientService;
138 private EPRoleService epRoleService;
140 private RoleService roleService;
143 private ExternalAccessRolesService externalAccessRolesService;
146 private AppsCacheService appsCacheService;
148 RestTemplate template = new RestTemplate();
153 * @return HashMap<Long, EcompRole>
155 private static HashMap<Long, EcompRole> hashMapFromEcompRoles(EcompRole[] ecompRoles) {
156 HashMap<Long, EcompRole> result = new HashMap<Long, EcompRole>();
157 if (ecompRoles != null) {
158 for (int i = 0; i < ecompRoles.length; i++) {
159 if (ecompRoles[i].getId() != null) {
160 result.put(ecompRoles[i].getId(), ecompRoles[i]);
171 protected void createLocalUserIfNecessary(String userId) {
172 if (StringUtils.isEmpty(userId)) {
173 logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty userId!");
176 Session localSession = null;
177 Transaction transaction = null;
179 localSession = sessionFactory.openSession();
180 transaction = localSession.beginTransaction();
181 @SuppressWarnings("unchecked")
182 List<EPUser> userList = localSession
183 .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + userId + "'").list();
184 if (userList.size() == 0) {
185 EPUser client = searchService.searchUserByUserId(userId);
186 if (client == null) {
187 String msg = "createLocalUserIfNecessary: cannot create user " + userId
188 + ", because not found in phonebook";
189 logger.error(EELFLoggerDelegate.errorLogger, msg);
191 client.setLoginId(userId);
192 client.setActive(true);
193 localSession.save(client);
196 transaction.commit();
197 } catch (Exception e) {
198 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
199 EcompPortalUtils.rollbackTransaction(transaction, "searchOrCreateUser rollback, exception = " + e);
201 EcompPortalUtils.closeLocalSession(localSession, "searchOrCreateUser");
206 * This method return nothing and remove roles before adding any roles for an app
209 * @param localSession
210 * @param userAppRoles
211 * @param newUserAppRolesMap
213 private static void syncUserRolesExtension(EPUserApp userRole, Long appId, Session localSession, EcompRole[] userAppRoles, HashMap<Long, EcompRole> newUserAppRolesMap) {
215 Long userAppRoleId = 0L;
216 if (appId == PortalConstants.PORTAL_APP_ID) { // local app
217 userAppRoleId = userRole.getRoleId();
218 } else { // remote app
219 userAppRoleId = userRole.getAppRoleId();
222 if (!newUserAppRolesMap.containsKey(userAppRoleId)) {
223 localSession.delete(userRole);
225 newUserAppRolesMap.remove(userAppRoleId);
230 * Checks whether the role is inactive
234 * if role is inactive, throws exception
236 private void checkIfRoleInactive(EPRole epRole) throws Exception{
237 if(!epRole.getActive()){
238 throw new Exception(epRole.getName()+ " role is unavailable");
244 * @param sessionFactory
247 * @param userAppRoles
248 * @param extRequestValue
249 * set to false if request is from users page otherwise true
252 protected void syncUserRoles(SessionFactory sessionFactory, String userId, Long appId,
253 EcompRole[] userAppRoles, Boolean extRequestValue, String reqType) throws Exception {
254 Session localSession = null;
255 Transaction transaction = null;
256 String roleActive = null;
257 final Map<String, String> userAppParams = new HashMap<>();
258 final Map<String, String> appParams = new HashMap<>();
259 HashMap<Long, EcompRole> newUserAppRolesMap = hashMapFromEcompRoles(userAppRoles);
262 localSession = sessionFactory.openSession();
263 transaction = localSession.beginTransaction();
264 @SuppressWarnings("unchecked")
265 List<EPUser> userList = localSession
266 .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + userId + "'").list();
267 if (userList.size() > 0) {
268 EPUser client = userList.get(0);
269 roleActive = ("DELETE".equals(reqType)) ? "" : " and role.active = 'Y'";
270 @SuppressWarnings("unchecked")
271 List<EPUserApp> userRoles = localSession.createQuery("from " + EPUserApp.class.getName()
272 + " where app.id=" + appId + roleActive + " and userId=" + client.getId()).list();
274 if ("DELETE".equals(reqType)) {
275 for (EPUserApp userAppRoleList : userRoles) {
276 userAppParams.put("roleName", String.valueOf(userAppRoleList.getRole().getName()));
277 userAppParams.put("appId", String.valueOf(appId));
278 appParams.put("appRoleName", userAppRoleList.getRole().getName());
279 @SuppressWarnings("unchecked")
280 List<EPRole> rolesList = (!userAppRoleList.getRole().getName().equals(PortalConstants.ADMIN_ROLE)) ? (List<EPRole>) dataAccessService.executeNamedQuery("getAppRoles", userAppParams, null) : (List<EPRole>) dataAccessService.executeNamedQuery("getPortalAppRoles", appParams, null);
281 if(rolesList.size() > 0 || !rolesList.isEmpty()){
282 checkIfRoleInactive(rolesList.get(0));
287 for (EPUserApp userRole : userRoles) {
288 if (!userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && userRole.getRoleId() != PortalConstants.SYS_ADMIN_ROLE_ID && !extRequestValue){
289 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
291 else if (extRequestValue && ("PUT".equals(reqType) || "POST".equals(reqType) || "DELETE".equals(reqType))){
292 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
294 else if (extRequestValue && !userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)){
295 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
298 Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values();
299 if (newRolesToAdd.size() > 0) {
300 EPApp app = (EPApp) localSession.get(EPApp.class, appId);
302 HashMap<Long, EPRole> rolesMap = new HashMap<Long, EPRole>();
303 if (appId.equals(PortalConstants.PORTAL_APP_ID)) { // local app
304 String appIdValue = "";
305 if(!extRequestValue){
306 appIdValue = "and id != " + PortalConstants.SYS_ADMIN_ROLE_ID;
308 @SuppressWarnings("unchecked")
309 List<EPRole> roles = localSession
310 .createQuery("from " + EPRole.class.getName() + " where appId is null " + appIdValue).list();
311 for (EPRole role : roles) {
313 rolesMap.put(role.getId(), role);
315 } else { // remote app
316 @SuppressWarnings("unchecked")
317 List<EPRole> roles = localSession
318 .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list();
319 for (EPRole role : roles) {
320 if (!extRequestValue && app.getCentralAuth()) {
321 rolesMap.put(role.getId(), role);
323 rolesMap.put(role.getAppRoleId(), role);
329 for (EcompRole userRole : newRolesToAdd) {
330 EPUserApp userApp = new EPUserApp();
331 if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName().equals(PortalConstants.ADMIN_ROLE)) {
332 role = (EPRole) localSession.get(EPRole.class, new Long(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
333 userApp.setRole(role);
334 } else if ((userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) && !extRequestValue){
336 }else if((userRole.getId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)) && app.getId().equals(PortalConstants.PORTAL_APP_ID) && !extRequestValue){
340 userApp.setRole(rolesMap.get(userRole.getId()));
343 userApp.setUserId(client.getId());
345 localSession.save(userApp);
346 localSession.flush();
349 if (appId == PortalConstants.PORTAL_APP_ID) {
351 * for local app -- hack - always make sure fn_role
352 * table's app_id is null and not 1 for primary app in
353 * this case being onap portal app; reason: hibernate
354 * is rightly setting this to 1 while persisting to
355 * fn_role as per the mapping but SDK role management
356 * code expects the app_id to be null as there is no
357 * concept of App_id in SDK
359 localSession.flush();
360 SQLQuery sqlQuery = localSession
361 .createSQLQuery("update fn_role set app_id = null where app_id = 1 ");
362 sqlQuery.executeUpdate();
367 transaction.commit();
368 } catch (Exception e) {
369 logger.error(EELFLoggerDelegate.errorLogger, "syncUserRoles failed", e);
370 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
371 EcompPortalUtils.rollbackTransaction(transaction,
372 "Exception occurred in syncUserRoles, Details: " + e.toString());
373 if("DELETE".equals(reqType)){
374 throw new SyncUserRolesException(e.getMessage());
377 if(localSession != null)
378 localSession.close();
383 * Called when getting the list of roles for the user
386 * @param userAppRoles
387 * @return List<RoleInAppForUser>
389 protected List<RoleInAppForUser> constructRolesInAppForUserGet(EcompRole[] appRoles, EcompRole[] userAppRoles) {
390 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
392 Set<Long> userAppRolesMap = new HashSet<Long>();
393 if (userAppRoles != null) {
394 for (EcompRole ecompRole : userAppRoles) {
395 userAppRolesMap.add(ecompRole.getId());
398 logger.error(EELFLoggerDelegate.errorLogger,
399 "constructRolesInAppForUserGet has received userAppRoles list empty");
402 if (appRoles != null) {
403 for (EcompRole ecompRole : appRoles) {
404 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
405 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
406 rolesInAppForUser.add(roleForUser);
409 logger.error(EELFLoggerDelegate.errorLogger, "constructRolesInAppForUser has received appRoles list empty");
411 return rolesInAppForUser;
415 * Called when getting the list of roles for the user
418 * @param userAppRoles
419 * @param extRequestValue
420 * set to false if request is from users page otherwise true
421 * @return List<RoleInAppForUser>
423 protected List<RoleInAppForUser> constructRolesInAppForUserGet(List<Role> appRoles, EPRole[] userAppRoles, Boolean extRequestValue) {
424 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
426 Set<Long> userAppRolesMap = new HashSet<Long>();
427 if (userAppRoles != null) {
428 for (EPRole ecompRole : userAppRoles) {
429 userAppRolesMap.add(ecompRole.getId());
432 logger.error(EELFLoggerDelegate.errorLogger,
433 "constructRolesInAppForUserGet has received userAppRoles list empty.");
436 if (appRoles != null) {
437 for (Role ecompRole : appRoles) {
438 if (ecompRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && !extRequestValue)
440 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
441 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
442 rolesInAppForUser.add(roleForUser);
445 logger.error(EELFLoggerDelegate.errorLogger,
446 "constructRolesInAppForUser has received appRoles list empty.");
448 return rolesInAppForUser;
453 * copies of methods in GetAppsWithUserRoleState
455 * @param sessionFactory
460 protected void syncAppRoles(SessionFactory sessionFactory, Long appId, EcompRole[] appRoles) throws Exception {
461 logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId);
462 HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles);
463 Session localSession = null;
464 Transaction transaction = null;
467 localSession = sessionFactory.openSession();
468 transaction = localSession.beginTransaction();
469 // Attention! All roles from remote application supposed to be
471 @SuppressWarnings("unchecked")
472 List<EPRole> currentAppRoles = localSession
473 .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list();
474 List<EPRole> obsoleteRoles = new ArrayList<EPRole>();
475 for (int i = 0; i < currentAppRoles.size(); i++) {
476 EPRole oldAppRole = currentAppRoles.get(i);
477 if (oldAppRole.getAppRoleId() != null) {
478 EcompRole role = null;
479 role = newRolesMap.get(oldAppRole.getAppRoleId());
481 if (!(role.getName() == null || oldAppRole.getName().equals(role.getName()))) {
482 oldAppRole.setName(role.getName());
483 localSession.update(oldAppRole);
485 oldAppRole.setActive(true);
486 newRolesMap.remove(oldAppRole.getAppRoleId());
488 obsoleteRoles.add(oldAppRole);
491 obsoleteRoles.add(oldAppRole);
494 Collection<EcompRole> newRolesToAdd = newRolesMap.values();
495 if (obsoleteRoles.size() > 0) {
496 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: we have obsolete roles to delete");
497 for (EPRole role : obsoleteRoles) {
498 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: obsolete role: " + role.toString());
499 Long roleId = role.getId();
500 // delete obsolete roles here
501 // Must delete all records with foreign key constraints on
503 // fn_user_role, fn_role_composite, fn_role_function,
504 // fn_user_pseudo_role, fn_menu_functional_roles.
505 // And for fn_menu_functional, if no other roles for that
506 // menu item, remove the url.
508 // Delete from fn_user_role
509 @SuppressWarnings("unchecked")
510 List<EPUserApp> userRoles = localSession.createQuery(
511 "from " + EPUserApp.class.getName() + " where app.id=" + appId + " and role_id=" + roleId)
514 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: number of userRoles to delete: " + userRoles.size());
515 for (EPUserApp userRole : userRoles) {
516 logger.debug(EELFLoggerDelegate.debugLogger,
517 "syncAppRoles: about to delete userRole: " + userRole.toString());
518 localSession.delete(userRole);
519 logger.debug(EELFLoggerDelegate.debugLogger,
520 "syncAppRoles: finished deleting userRole: " + userRole.toString());
523 // Delete from fn_menu_functional_roles
524 @SuppressWarnings("unchecked")
525 List<FunctionalMenuRole> funcMenuRoles = localSession
526 .createQuery("from " + FunctionalMenuRole.class.getName() + " where roleId=" + roleId)
528 int numMenuRoles = funcMenuRoles.size();
529 logger.debug(EELFLoggerDelegate.debugLogger,
530 "syncAppRoles: number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles);
531 for (FunctionalMenuRole funcMenuRole : funcMenuRoles) {
532 Long menuId = funcMenuRole.menuId;
533 // If this is the only role for this menu item, then the
534 // app and roles will be gone,
535 // so must null out the url too, to be consistent
536 @SuppressWarnings("unchecked")
537 List<FunctionalMenuRole> funcMenuRoles2 = localSession
538 .createQuery("from " + FunctionalMenuRole.class.getName() + " where menuId=" + menuId)
540 int numMenuRoles2 = funcMenuRoles2.size();
541 logger.debug(EELFLoggerDelegate.debugLogger,
542 "syncAppRoles: number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2);
543 localSession.delete(funcMenuRole);
544 if (numMenuRoles2 == 1) {
545 // If this is the only role for this menu item, then
546 // the app and roles will be gone,
547 // so must null out the url too, to be consistent
548 logger.debug(EELFLoggerDelegate.debugLogger,
549 "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url");
550 @SuppressWarnings("unchecked")
551 List<FunctionalMenuItem> funcMenuItems = localSession
553 "from " + FunctionalMenuItem.class.getName() + " where menuId=" + menuId)
555 if (funcMenuItems.size() > 0) {
556 logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item");
557 FunctionalMenuItem funcMenuItem = funcMenuItems.get(0);
558 funcMenuItem.url = "";
559 localSession.update(funcMenuItem);
563 boolean isPortalRequest = true;
564 externalAccessRolesService.deleteRoleDependencyRecords(localSession, roleId, appId, isPortalRequest);
565 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to delete the role: " + role.toString());
566 localSession.delete(role);
567 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: deleted the role");
570 for (EcompRole role : newRolesToAdd) {
571 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to add missing role: " + role.toString());
572 EPRole newRole = new EPRole();
573 // Attention! All roles from remote application supposed to be
575 newRole.setActive(true);
576 newRole.setName(role.getName());
577 newRole.setAppId(appId);
578 newRole.setAppRoleId(role.getId());
579 localSession.save(newRole);
581 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to commit the transaction");
582 transaction.commit();
583 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: committed the transaction");
584 } catch (Exception e) {
585 logger.error(EELFLoggerDelegate.errorLogger, "syncAppRoles failed", e);
586 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
587 EcompPortalUtils.rollbackTransaction(transaction,
588 "Exception occurred in syncAppRoles, Details: " + e.toString());
589 throw new Exception(e);
591 localSession.close();
600 * Called when updating the list of roles for the user
604 * @param userRolesInRemoteApp
605 * @return RolesInAppForUser
607 protected RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId,
608 Set<EcompRole> userRolesInRemoteApp) {
609 RolesInAppForUser result;
610 result = new RolesInAppForUser();
611 result.appId = appId;
612 result.orgUserId = userId;
613 for (EcompRole role : userRolesInRemoteApp) {
614 RoleInAppForUser roleInAppForUser = new RoleInAppForUser();
615 roleInAppForUser.roleId = role.getId();
616 roleInAppForUser.roleName = role.getName();
617 roleInAppForUser.isApplied = new Boolean(true);
618 result.roles.add(roleInAppForUser);
625 * @param roleInAppForUserList
628 protected boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) {
629 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
630 if (roleInAppForUser.isApplied.booleanValue()) {
638 * Builds JSON and posts it to a remote application to update user roles.
640 * @param roleInAppForUserList
642 * @param applicationsRestClientService
645 * @return Set of roles as sent; NOT the response from the app.
646 * @throws JsonProcessingException
647 * @throws HTTPException
649 protected Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
650 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
651 throws JsonProcessingException, HTTPException {
652 Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList);
653 Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList);
654 String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote);
655 EPApp externalApp = null;
656 SystemType type = SystemType.APPLICATION;
657 externalApp = appsCacheService.getApp(appId);
658 String appBaseUri = null;
659 Set<RemoteRoleV1> updatedUserRolesinRemoteV1 = new TreeSet<>();
660 if (externalApp != null) {
661 appBaseUri = (type == SystemType.APPLICATION) ? externalApp.getAppRestEndpoint() : "";
663 if(appBaseUri != null && appBaseUri.endsWith("/api")){
664 for(EcompRole eprole :updatedUserRolesinRemote)
666 RemoteRoleV1 role = new RemoteRoleV1();
667 role.setId(eprole.getId());
668 role.setName(eprole.getName());
669 updatedUserRolesinRemoteV1.add(role);
671 userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemoteV1);
673 applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString,
674 String.format("/user/%s/roles", userId));
675 // TODO: We should add code that verifies that the post operation did
676 // succeed. Because the SDK may still return 200 OK with an html page
677 // even when it fails!
678 return updateUserRolesInEcomp;
683 * @param roleInAppForUserList
684 * @return Set<EcompRole>
686 protected Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) {
687 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
688 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
689 if (roleInAppForUser.isApplied) {
690 EcompRole ecompRole = new EcompRole();
691 ecompRole.setId(roleInAppForUser.roleId);
692 ecompRole.setName(roleInAppForUser.roleName);
693 existingUserRoles.add(ecompRole);
696 return existingUserRoles;
700 * Constructs user app roles excluding Account Administrator role
702 * @param roleInAppForUserList
704 * List of roles with Role name, Role Id
706 protected Set<EcompRole> constructUsersRemoteAppRoles(List<RoleInAppForUser> roleInAppForUserList) {
707 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
708 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
709 if (roleInAppForUser.isApplied && !roleInAppForUser.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
710 EcompRole ecompRole = new EcompRole();
711 ecompRole.setId(roleInAppForUser.roleId);
712 ecompRole.setName(roleInAppForUser.roleName);
713 existingUserRoles.add(ecompRole);
716 return existingUserRoles;
720 * This is for a single app
722 * @param rolesInAppForUser
723 * @param externalSystemRequest
724 * set to false if requests from Users page otherwise true
725 * @return true on success, false otherwise
727 protected boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser, boolean externalSystemRequest, String reqType) throws Exception {
728 boolean result = false;
729 String userId = rolesInAppForUser.orgUserId;
730 Long appId = rolesInAppForUser.appId;
731 synchronized (syncRests) {
732 if (rolesInAppForUser != null) {
733 createLocalUserIfNecessary(userId);
736 if (rolesInAppForUser != null) {
737 EcompRole[] userAppRoles = new EcompRole[rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size()];
738 for (int i = 0; i < rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size(); i++) {
739 RoleInAppForUser roleInAppForUser = rolesInAppForUser.roles.get(i);
740 EcompRole role = new EcompRole();
741 role.setId(roleInAppForUser.roleId);
742 role.setName(roleInAppForUser.roleName);
743 userAppRoles[i] = role;
746 syncUserRoles(sessionFactory, userId, appId, userAppRoles, externalSystemRequest, reqType);
748 } catch (Exception e) {
749 logger.error(EELFLoggerDelegate.errorLogger,
750 "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for orgUserId " + userId, e);
751 if("DELETE".equals(reqType)){
752 throw new Exception(e.getMessage());
764 * @return UserApplicationRoles
766 protected UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) {
767 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
768 userWithRemoteAppRoles.setAppId(appId);
769 userWithRemoteAppRoles.setOrgUserId(remoteUser.getOrgUserId());
770 userWithRemoteAppRoles.setFirstName(remoteUser.getFirstName());
771 userWithRemoteAppRoles.setLastName(remoteUser.getLastName());
772 userWithRemoteAppRoles.setRoles(remoteUser.getRoles());
773 return userWithRemoteAppRoles;
779 * @see org.onap.portalapp.portal.service.UserRolesService#
780 * importRolesFromRemoteApplication(java.lang.Long)
782 public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException {
783 EPRole[] appRolesFull = applicationsRestClientService.get(EPRole[].class, appId, "/rolesFull");
784 List<EPRole> rolesList = Arrays.asList(appRolesFull);
785 for (EPRole externalAppRole : rolesList) {
787 // Try to find an existing extern role for the app in the local
788 // onap DB. If so, then use its id to update the existing external
789 // application role record.
790 Long externAppId = externalAppRole.getId();
791 EPRole existingAppRole = epRoleService.getRole(appId, externAppId);
792 if (existingAppRole != null) {
793 logger.debug(EELFLoggerDelegate.debugLogger,
794 String.format("ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.",
795 appId, externAppId));
798 // persistExternalRoleInEcompDb(externalAppRole, appId,
806 * It adds new user for remote application
808 * @param roleInAppForUserList
809 * @param remoteAppUser
813 * @param searchService
814 * @param applicationsRestClientService
818 private EPUser addRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app, ObjectMapper mapper, SearchService searchService, ApplicationsRestClientService applicationsRestClientService) throws Exception{
819 EPUser addRemoteUser = null;
820 if (remoteUserShouldBeCreated(roleInAppForUserList)) {
821 createNewUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper, isAppUpgradeVersion(app));
823 return addRemoteUser;
827 * It checks whether the remote user exists or not
828 * if exits returns user object else null
832 * @param applicationsRestClientService
834 * @throws HTTPException
836 private EPUser checkIfRemoteUserExits(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService) throws HTTPException{
837 EPUser checkRemoteUser = null;
839 checkRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
840 } catch (HTTPException e) {
841 // Some apps are returning 400 if user is not found.
842 if (e.getResponseCode() == 400) {
843 logger.debug(EELFLoggerDelegate.debugLogger,
844 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing",
846 } else if(e.getResponseCode() == 404) {
847 logger.debug(EELFLoggerDelegate.debugLogger,
848 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 404; continuing",
851 // Other response code, let it come thru.
855 return checkRemoteUser;
862 * @see org.onap.portalapp.portal.service.UserRolesService#
863 * setAppWithUserRoleStateForUser(org.onap.portalapp.portal.domain.
864 * EPUser, org.onap.portalapp.portal.transport.AppWithRolesForUser)
866 public boolean setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser) {
867 boolean result = false;
868 boolean epRequestValue = false;
870 if (newAppRolesForUser != null && newAppRolesForUser.orgUserId != null) {
871 userId = newAppRolesForUser.orgUserId.trim();
873 Long appId = newAppRolesForUser.appId;
874 List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.appRoles;
875 if (userId.length() > 0) {
876 ObjectMapper mapper = new ObjectMapper();
877 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
880 EPApp app = appsService.getApp(appId);
881 applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
883 // if centralized app
884 if (app.getCentralAuth()) {
885 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
887 addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService,
888 applicationsRestClientService);
889 } catch (Exception e) {
890 String message=e.getMessage();
891 logger.error(EELFLoggerDelegate.errorLogger, message, e);
895 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
896 applicationsRestClientService, appId, userId);
897 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
898 userRolesInLocalApp);
899 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
900 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
901 // Apply changes in external Access system
902 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList,
905 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal");
907 // In case if portal is not centralized then follow existing approach
908 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
909 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
910 applicationsRestClientService, appId, userId);
911 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
912 userRolesInLocalApp);
913 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal");
915 EPUser remoteAppUser = null;
916 if(!app.getCentralAuth() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)){
918 remoteAppUser = checkIfRemoteUserExits(userId, app, applicationsRestClientService);
920 if (remoteAppUser == null) {
921 remoteAppUser = addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService, applicationsRestClientService);
923 if (remoteAppUser != null) {
924 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
925 applicationsRestClientService, appId, userId);
926 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
927 userRolesInRemoteApp);
928 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null);
930 // If no roles remain, request app to set user inactive.
931 if (userRolesInRemoteApp.size() == 0) {
932 logger.debug(EELFLoggerDelegate.debugLogger,
933 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
935 remoteAppUser.setActive(false);
936 postUserToRemoteApp(userId, user, app, applicationsRestClientService);
941 } catch (Exception e) {
942 String message = String.format(
943 "Failed to create user or update user roles for User %s, AppId %s",
944 userId, Long.toString(appId));
945 logger.error(EELFLoggerDelegate.errorLogger, message, e);
953 * It adds user roles in External system and also make data consistent in both local and in External System
957 * @param roleInAppUser Contains list of active roles
959 @SuppressWarnings("unchecked")
960 private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser, boolean isPortalRequest) throws Exception
963 // check if user exists
964 final Map<String, String> userParams = new HashMap<>();
965 userParams.put("orgUserIdValue", orgUserId);
966 List<EPUser> userInfo = checkIfUserExists(userParams);
967 if (userInfo.isEmpty()) {
968 createLocalUserIfNecessary(orgUserId);
971 if (EPCommonSystemProperties
972 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
974 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
976 ObjectMapper mapper = new ObjectMapper();
977 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
978 HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
979 ResponseEntity<String> getResponse = externalAccessRolesService.getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
980 List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
981 String res = getResponse.getBody();
982 JSONObject jsonObj = null;
983 JSONArray extRoles = null;
984 if (!res.equals("{}")) {
985 jsonObj = new JSONObject(res);
986 extRoles = jsonObj.getJSONArray("role");
988 ExternalAccessUserRoleDetail userRoleDetail = null;
989 if (extRoles != null) {
990 for (int i = 0; i < extRoles.length(); i++) {
991 if (extRoles.getJSONObject(i).getString("name").startsWith(app.getNameSpace() + ".")
992 && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".admin")
993 && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".owner")) {
994 ObjectMapper descMapper = new ObjectMapper();
995 if (extRoles.getJSONObject(i).has("description") && EcompPortalUtils.isJSONValid(extRoles.getJSONObject(i).getString("description"))) {
996 ExternalRoleDescription desc = descMapper.readValue(
997 extRoles.getJSONObject(i).getString("description"), ExternalRoleDescription.class);
998 userRoleDetail = new ExternalAccessUserRoleDetail(
999 extRoles.getJSONObject(i).getString("name"), desc);
1000 userRoleDetailList.add(userRoleDetail);
1002 userRoleDetail = new ExternalAccessUserRoleDetail(
1003 extRoles.getJSONObject(i).getString("name"), null);
1004 userRoleDetailList.add(userRoleDetail);
1011 List<ExternalAccessUserRoleDetail> userRoleListMatchingInExtAuthAndLocal = CheckIfRoleAreMatchingInUserRoleDetailList(userRoleDetailList,app);
1013 // If request coming from portal not from external role approval system then we have to check if user already
1014 // have account admin or system admin as GUI will not send these roles
1015 if (!isPortalRequest) {
1016 final Map<String, String> loginIdParams = new HashMap<>();
1017 loginIdParams.put("orgUserIdValue", orgUserId);
1018 EPUser user = (EPUser) dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null).get(0);
1019 final Map<String, Long> params = new HashMap<>();
1020 params.put("appId", app.getId());
1021 params.put("userId", user.getId());
1022 List<EcompUserAppRoles> userAppList = dataAccessService.executeNamedQuery("getUserAppExistingRoles",
1024 if (!roleInAppUser.isEmpty()) {
1025 for (EcompUserAppRoles userApp : userAppList) {
1026 if (userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)
1027 || userApp.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
1028 RoleInAppForUser addSpecialRole = new RoleInAppForUser();
1029 addSpecialRole.setIsApplied(true);
1030 addSpecialRole.setRoleId(userApp.getRoleId());
1031 addSpecialRole.setRoleName(userApp.getRoleName());
1032 roleInAppUser.add(addSpecialRole);
1037 List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct()
1038 .collect(Collectors.toList());
1039 final Map<String, RoleInAppForUser> currentUserRolesToUpdate = new HashMap<>();
1040 for (RoleInAppForUser roleInAppUserNew : roleInAppUserNonDupls) {
1041 currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), roleInAppUserNew);
1043 final Map<String, ExternalAccessUserRoleDetail> currentUserRolesInExternalSystem = new HashMap<>();
1044 for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleListMatchingInExtAuthAndLocal) {
1045 currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole);
1047 // Check if user roles does not exists in local but still there in External Central Auth System delete them all
1048 for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
1049 if (!(currentUserRolesToUpdate
1050 .containsKey(userRole.getName().substring(app.getNameSpace().length() + 1)))) {
1051 HttpEntity<String> entity = new HttpEntity<>(headers);
1052 logger.debug(EELFLoggerDelegate.debugLogger,
1053 "updateUserRolesInExternalSystem: Connecting to external system to DELETE user role {}",
1054 userRole.getName());
1055 ResponseEntity<String> deleteResponse = template.exchange(
1056 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1057 + "userRole/" + name + "/" + userRole.getName(),
1058 HttpMethod.DELETE, entity, String.class);
1059 logger.debug(EELFLoggerDelegate.debugLogger,
1060 "updateUserRolesInExternalSystem: Finished DELETE operation in external system for user role {} and the response is {}",
1061 userRole.getName(), deleteResponse.getBody());
1064 // Check if user roles does not exists in External Central Auth System add them all
1065 for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) {
1066 if (!(currentUserRolesInExternalSystem
1067 .containsKey(app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")))) {
1068 ExternalAccessUser extUser = new ExternalAccessUser(name,
1069 app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1070 String formattedUserRole = mapper.writeValueAsString(extUser);
1071 HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers);
1072 logger.debug(EELFLoggerDelegate.debugLogger, "updateUserRolesInExternalSystem: Connecting to external system for user {} and POST {}",
1073 name , addUserRole.getRoleName());
1074 ResponseEntity<String> addResponse = template
1075 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1076 + "userRole", HttpMethod.POST, entity, String.class);
1077 logger.debug(EELFLoggerDelegate.debugLogger,
1078 "updateUserRolesInExternalSystem: Finished adding user role in external system {} and added user role {}",
1079 addResponse.getBody(), addUserRole.getRoleName());
1080 if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 404) {
1081 logger.debug(EELFLoggerDelegate.debugLogger,
1082 "Finished POST operation in external system but unable to save user role", addResponse.getBody(),
1083 addUserRole.getRoleName());
1084 throw new Exception(addResponse.getBody());
1088 } catch (Exception e) {
1089 logger.error(EELFLoggerDelegate.errorLogger, "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}", app.getId(), e);
1090 EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
1096 private List<ExternalAccessUserRoleDetail> CheckIfRoleAreMatchingInUserRoleDetailList(
1097 List<ExternalAccessUserRoleDetail> userRoleDetailList, EPApp app) {
1098 Map<String, EPRole> epRoleList = externalAccessRolesService.getCurrentRolesInDB(app);
1099 //Add Account Admin role for partner app to prevent conflict
1100 if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1101 EPRole role = new EPRole();
1102 role.setName(PortalConstants.ADMIN_ROLE.replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1103 epRoleList.put(role.getName(), role);
1105 userRoleDetailList.removeIf(userRoleDetail -> !epRoleList.containsKey(userRoleDetail.getName().substring(app.getNameSpace().length()+1)));
1106 return userRoleDetailList;
1113 * @param applicationsRestClientService
1114 * @param searchService
1118 protected void createNewUserOnRemoteApp(String userId, EPApp app,
1119 ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
1120 ObjectMapper mapper, boolean postOpenSource) throws Exception {
1123 EPUser client = searchService.searchUserByUserId(userId);
1125 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1127 if (client == null) {
1128 String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook.";
1129 logger.error(EELFLoggerDelegate.errorLogger, msg);
1130 throw new Exception(msg);
1133 client.setLoginId(userId);
1134 client.setActive(true);
1136 String userInString = null;
1137 userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
1138 logger.debug(EELFLoggerDelegate.debugLogger,
1139 "about to post new client to remote application, users json = " + userInString);
1140 applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user", userId));
1144 @SuppressWarnings("unchecked")
1145 protected void applyChangesToAppRolesRequest(Long appId, Long userId, String updateStatus, EPUserAppRolesRequest epUserAppRolesRequest) {
1146 final Map<String, Long> epRequestParams = new HashMap<>();
1148 EPUserAppRolesRequest epAppRolesRequestData = epUserAppRolesRequest;
1149 epAppRolesRequestData.setUpdatedDate(new Date());
1150 epAppRolesRequestData.setRequestStatus(updateStatus);
1151 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1152 addiotonalUpdateParam.put("userId", userId);
1153 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1154 epRequestParams.put("reqId", epUserAppRolesRequest.getId());
1155 List<EPUserAppRolesRequestDetail> epUserAppRolessDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1156 epUserAppRolessDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1157 epRequestParams, null);
1158 if (epUserAppRolessDetailList.size() > 0) {
1159 for (EPUserAppRolesRequestDetail epRequestUpdateData : epUserAppRolessDetailList) {
1160 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateData;
1161 epAppRoleDetailData.setReqType(updateStatus);
1162 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1163 HashMap<String, Long> updateDetailsParam = new HashMap<String, Long>();
1164 addiotonalUpdateParam.put("reqId", epUserAppRolesRequest.getId());
1165 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParam);
1168 logger.debug(EELFLoggerDelegate.debugLogger, "The request is set to complete");
1170 } catch (Exception e) {
1171 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToAppRolesRequest failed", e);
1175 @SuppressWarnings("unchecked")
1176 public void applyChangesToUserAppRolesForMyLoginsRequest(EPUser user, Long appId) {
1177 final Map<String, Long> params = new HashMap<>();
1178 final Map<String, Long> epDetailParams = new HashMap<>();
1179 List<EPUserAppRolesRequest> epRequestIdVal = new ArrayList<EPUserAppRolesRequest>();
1180 params.put("appId", appId);
1181 params.put("userId", user.getId());
1183 epRequestIdVal = (List<EPUserAppRolesRequest>) dataAccessService
1184 .executeNamedQuery("userAppRolesRequestList", params, null);
1185 if (epRequestIdVal.size() > 0) {
1186 EPUserAppRolesRequest epAppRolesRequestData = epRequestIdVal.get(0);
1187 epAppRolesRequestData.setUpdatedDate(new Date());
1188 epAppRolesRequestData.setRequestStatus("O");
1189 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1190 addiotonalUpdateParam.put("userId", user.getId());
1191 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1192 epDetailParams.put("reqId", epAppRolesRequestData.getId());
1193 List<EPUserAppRolesRequestDetail> epUserAppRolesDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1194 epUserAppRolesDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1195 epDetailParams, null);
1196 if (epUserAppRolesDetailList.size() > 0) {
1197 for (EPUserAppRolesRequestDetail epRequestUpdateList : epUserAppRolesDetailList) {
1198 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateList;
1199 epAppRoleDetailData.setReqType("O");
1200 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1201 HashMap<String, Long> updateDetailsParams = new HashMap<String, Long>();
1202 addiotonalUpdateParam.put("reqId", epAppRolesRequestData.getId());
1203 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParams);
1205 logger.debug(EELFLoggerDelegate.debugLogger, "User App roles request from User Page is overridden");
1209 } catch (Exception e) {
1210 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e);
1215 * Pushes specified user details to the specified remote app.
1218 * OrgUserId identifying user at remote app in REST endpoint path
1220 * User details to be pushed
1223 * @param applicationsRestClientService
1224 * @throws HTTPException
1226 protected void postUserToRemoteApp(String userId, EPUser user, EPApp app,
1227 ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
1229 getUser(userId, app, applicationsRestClientService);
1234 * It returns user details for single org user id
1238 * if user exists it returns list of user details otherwise empty value
1240 @SuppressWarnings("unchecked")
1241 private List<EPUser> checkIfUserExists(Map<String, String> userParams){
1242 return (List<EPUser>)dataAccessService.executeNamedQuery("epUserAppId", userParams, null);
1246 * It checks whether the new user is valid or not otherwise throws exception
1251 * Checks if user is valid and returns message otherwise throws exception
1254 private String validateNewUser(String orgUserId, EPApp app) throws Exception {
1255 EPUser epUser = searchService.searchUserByUserId(orgUserId);
1256 if (epUser == null) {
1257 throw new Exception("User does not exist");
1258 } else if (!epUser.getOrgUserId().equals(orgUserId)) {
1259 throw new Exception("User does not exist");
1260 } else if (app == null) {
1261 throw new Exception("Application does not exist");
1263 return "Saved Successfully";
1267 * Checks if the fields exists or not
1270 * contains user information
1274 * throws exception if the field is not valid
1276 private void validateExternalRequestFields(List<EPUser> userList, EPApp app) throws Exception{
1277 if (userList.size() == 0 || userList.isEmpty() ) {
1278 throw new Exception("User does not exist");
1279 } else if(app == null) {
1280 throw new Exception("Application does not exist");
1281 } else if(!app.getEnabled() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1282 throw new Exception(app.getMlAppName()+" application is unavailable");
1286 @SuppressWarnings("unchecked")
1287 public ExternalRequestFieldsValidator setExternalRequestUserAppRole(ExternalSystemUser newAppRolesForUser, String reqType) {
1288 boolean result = false;
1289 boolean externalSystemRequest = true;
1290 final Map<String, Long> params = new HashMap<>();
1291 final Map<String, String> userParams = new HashMap<>();
1292 List<EPUser> userInfo = null;
1293 EPUser userId = null;
1294 List<EPUserAppRolesRequest> epRequestId = null;
1295 String orgUserId = "";
1296 String updateStatus = "";
1297 String reqMessage = "";
1299 if (newAppRolesForUser != null && newAppRolesForUser.getLoginId() != null) {
1300 orgUserId = newAppRolesForUser.getLoginId().trim();
1302 String appName = newAppRolesForUser.getApplicationName();
1303 String logMessage = ("DELETE").equals(reqType) ? "Deleting": "Assigning/Updating" ;
1304 if (orgUserId.length() > 0) {
1305 ObjectMapper mapper = new ObjectMapper();
1306 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1307 int epRequestIdSize = 0;
1309 app = appsService.getAppDetail(appName);
1310 userParams.put("orgUserIdValue", orgUserId);
1311 userInfo = checkIfUserExists(userParams);
1312 reqMessage = "Updated Successfully";
1313 if (!reqType.equals("DELETE") && (userInfo.size() == 0 || userInfo.isEmpty())) {
1314 reqMessage = validateNewUser(orgUserId, app);
1316 if (userInfo.size() != 0 || !userInfo.isEmpty()) {
1317 validateExternalRequestFields(userInfo, app);
1318 userId = userInfo.get(0);
1319 params.put("appId", app.getId());
1320 params.put("userId", userId.getId());
1321 epRequestId = (List<EPUserAppRolesRequest>) dataAccessService
1322 .executeNamedQuery("userAppRolesRequestList", params, null);
1323 epRequestIdSize = epRequestId.size();
1326 //If Non-Centralized app make sure you sync app roles before assigning to user
1327 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !app.getCentralAuth()) {
1328 logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Starting GET roles for app {}",app.getId());
1329 EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, app.getId(), "/roles");
1330 logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Finshed GET roles for app {} and payload {}",app.getId(), appRoles);
1331 if (appRoles.length > 0) {
1332 syncAppRoles(sessionFactory, app.getId(), appRoles);
1335 List<RoleInAppForUser> roleInAppForUserList = roleInAppForUserList(newAppRolesForUser.getRoles(),
1336 app.getId(), app.getMlAppName());
1337 List<EcompUserAppRoles> userRoleList = null;
1338 if(!userInfo.isEmpty()){
1339 final Map<String, Long> appParams = new HashMap<>();
1340 appParams.put("userId", userId.getId());
1341 appParams.put("appId", app.getId());
1342 userRoleList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", appParams, null);
1344 // Check if list contains just account admin role
1345 boolean checkIfAdminRoleExists = false;
1346 if (reqType.equals("DELETE") && userRoleList!=null) {
1347 checkIfAdminRoleExists = userRoleList.stream()
1348 .anyMatch(userRole -> userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1350 checkIfAdminRoleExists = roleInAppForUserList.stream()
1351 .anyMatch(roleList -> roleList.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1353 // if Centralized app
1354 if (app.getCentralAuth()) {
1355 // We should add If user does not exist in remote application
1357 // If adding just account admin role dont make remote application user call
1358 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !(checkIfAdminRoleExists
1359 && reqType.equals("DELETE")) && roleInAppForUserList.size() > 1) {
1360 EPUser remoteAppUser = null;
1361 remoteAppUser = checkIfRemoteUserExits(orgUserId, app,
1362 applicationsRestClientService);
1363 if (remoteAppUser == null) {
1364 addRemoteUser(roleInAppForUserList, orgUserId, app, mapper, searchService,
1365 applicationsRestClientService);
1366 reqMessage = "Saved Successfully";
1369 } catch (Exception e) {
1370 reqMessage = e.getMessage();
1371 logger.error(EELFLoggerDelegate.errorLogger, "setExternalRequestUserAppRole: Failed to added remote user", e);
1372 throw new Exception(reqMessage);
1374 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1375 applicationsRestClientService, app.getId(), orgUserId);
1376 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1377 userRolesInLocalApp);
1378 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1379 if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1380 // Apply changes in external Access system
1381 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, externalSystemRequest);
1383 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
1384 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1385 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType);
1387 // If local application is not centralized
1388 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1389 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1390 applicationsRestClientService, app.getId(), orgUserId);
1391 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1392 userRolesInLocalApp);
1393 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType);
1394 } else {// remote app
1395 // If adding just account admin role don't do remote application user call
1396 if(!((roleInAppForUserList.size() == 1 || reqType.equals("DELETE")) && checkIfAdminRoleExists)){
1397 EPUser remoteAppUser = null;
1398 remoteAppUser = checkIfRemoteUserExits(orgUserId, app, applicationsRestClientService);
1399 if (remoteAppUser == null) {
1400 remoteAppUser = addRemoteUser(roleInAppForUserList, orgUserId, app, mapper, searchService, applicationsRestClientService);
1401 reqMessage = "Saved Successfully";
1403 if (remoteAppUser != null) {
1404 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList,
1405 mapper, applicationsRestClientService, app.getId(), orgUserId);
1407 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId,
1408 app.getId(), userRolesInRemoteApp);
1409 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}",
1410 logMessage, newAppRolesForUser.getApplicationName(),
1411 newAppRolesForUser.getLoginId());
1412 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1414 // If no roles remain, request app to set user inactive.
1415 /*if (userRolesInRemoteApp.size() == 0) {
1416 logger.debug(EELFLoggerDelegate.debugLogger,
1417 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
1419 //TODO Need to fix the logged in user is not set to inactive
1420 remoteAppUser.setActive(false);
1421 postUserToRemoteApp(orgUserId, user, app, applicationsRestClientService);
1425 // Here we are adding only we have single account admin in roleInAppForUserList and this should not add in remote
1426 if(!(reqType.equals("DELETE")) && userInfo.isEmpty()){
1427 reqMessage = "Saved Successfully";
1429 Set<EcompRole> userRolesInRemoteApp = constructUsersEcompRoles(roleInAppForUserList);
1431 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1432 userRolesInRemoteApp);
1433 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}",
1434 logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1435 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1439 reqMessage = "Failed to save the user app role(s)";
1441 if (epRequestIdSize > 0 && !userInfo.isEmpty()) {
1443 applyChangesToAppRolesRequest(app.getId(), userId.getId(), updateStatus, epRequestId.get(0));
1446 } catch (Exception e) {
1447 String message = String.format("setExternalRequestUserAppRole: Failed to create user or update user roles for User %s, AppId %s",
1448 orgUserId, appName);
1449 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1451 reqMessage = e.getMessage();
1452 if(epRequestIdSize > 0 && userInfo!=null && !userInfo.isEmpty()){
1454 applyChangesToAppRolesRequest(app.getId(), userId.getId(),
1455 updateStatus, epRequestId.get(0));
1460 return new ExternalRequestFieldsValidator(result, reqMessage);
1465 * @param roleInAppForUserList
1467 * @param applicationsRestClientService
1470 * @return Set<EcompRole>
1471 * @throws JsonProcessingException
1472 * @throws HTTPException
1474 private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
1475 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
1476 throws JsonProcessingException, HTTPException {
1477 Set<EcompRole> updatedUserRoles = constructUsersEcompRoles(roleInAppForUserList);
1478 return updatedUserRoles;
1482 * It constructs and returns list of user app roles when the external API role approval system calls
1485 * @param roleInAppForUserList
1487 * @return list of user app roles
1489 * throws exceptions if role id does not exits
1491 private List<RoleInAppForUser> roleInAppForUserList(List<ExternalSystemRoleApproval> roleInAppForUserList,
1492 Long appId, String appName) throws Exception {
1493 List<RoleInAppForUser> existingUserRoles = new ArrayList<RoleInAppForUser>();
1494 EPRole existingAppRole = null;
1495 for (ExternalSystemRoleApproval roleInAppForUser : roleInAppForUserList) {
1496 RoleInAppForUser ecompRole = new RoleInAppForUser();
1497 existingAppRole = epRoleService.getAppRole(roleInAppForUser.getRoleName(), appId);
1498 if (existingAppRole == null) {
1499 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1500 roleInAppForUserList);
1501 throw new Exception("'" +roleInAppForUser.getRoleName() + "'" +" role does not exist for " + appName + " application");
1503 if (!existingAppRole.getActive()) {
1504 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1505 roleInAppForUserList);
1506 throw new Exception(roleInAppForUser.getRoleName() + " role is unavailable for "+ appName + " application");
1508 ecompRole.roleId = (appId == 1 || roleInAppForUser.getRoleName().equals(PortalConstants.ADMIN_ROLE)) ? existingAppRole.getId() : existingAppRole.getAppRoleId();
1509 ecompRole.roleName = roleInAppForUser.getRoleName();
1510 ecompRole.isApplied = true;
1511 existingUserRoles.add(ecompRole);
1514 return existingUserRoles;
1523 * @param applicationsRestClientService
1525 * @throws HTTPException
1527 protected EPUser getUserFromApp(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1528 throws HTTPException {
1530 if (app.getId() == PortalConstants.PORTAL_APP_ID) {
1531 // Map<String,String> params = new HashMap<String,String>();
1532 // params.put("sbcid",userId);
1533 @SuppressWarnings("unchecked")
1534 List<EPUser> userList = (List<EPUser>) dataAccessService
1535 .executeQuery("from EPUser where orgUserId='" + userId + "'", null);
1536 if (userList != null && !userList.isEmpty())
1537 return userList.get(0);
1543 return getUser(userId, app, applicationsRestClientService);
1546 protected EPUser getUser(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1547 throws HTTPException {
1548 return applicationsRestClientService.get(EPUser.class, app.getId(), String.format("/user/%s", userId), true);
1552 protected boolean isAppUpgradeVersion(EPApp app){
1557 public ExternalSystemAccess getExternalRequestAccess(){
1558 ExternalSystemAccess res = null;
1560 res = new ExternalSystemAccess(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE,
1561 Boolean.parseBoolean(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE)));
1562 } catch (Exception e) {
1563 logger.error(EELFLoggerDelegate.errorLogger, "getExternalRequestAccess failed" + e.getMessage());
1571 * @see org.onap.portalapp.portal.service.UserRolesService#
1572 * getAppRolesForUser(java.lang.Long, java.lang.String)
1574 @SuppressWarnings("unchecked")
1575 public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId, Boolean extRequestValue) {
1577 List<RoleInAppForUser> rolesInAppForUser = null;
1578 EPApp app = appsService.getApp(appId);
1580 // for onap portal app, no need to make a remote call
1581 List<Role> roleList = new ArrayList<>();
1582 if (appId == PortalConstants.PORTAL_APP_ID) {
1583 if(app.getCentralAuth()){
1584 List<CentralV2Role> cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey());
1585 for(CentralV2Role cenRole : cenRoleList){
1586 Role role = new Role();
1587 role.setActive(cenRole.getActive());
1588 role.setId(cenRole.getId());
1589 role.setName(cenRole.getName());
1590 role.setPriority(cenRole.getPriority());
1594 roleList = roleService.getAvailableRoles(userId);
1596 List<Role> activeRoleList = new ArrayList<Role>();
1597 for(Role role: roleList) {
1598 if(role.getActive()) {
1599 if(role.getId() != 1){ // prevent portal admin from being added
1600 activeRoleList.add(role);
1601 } else if(extRequestValue){
1602 activeRoleList.add(role);
1607 EPUser localUser = getUserFromApp(userId, app, applicationsRestClientService);
1608 // If localUser does not exists return roles
1609 Set<EPRole> roleSet = null;
1610 EPRole[] roleSetList = null;
1611 if(localUser != null){
1612 roleSet = localUser.getAppEPRoles(app);
1613 roleSetList = roleSet.toArray(new EPRole[0]);
1615 rolesInAppForUser = constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue);
1616 return rolesInAppForUser;
1619 EcompRole[] appRoles = null;
1620 List<EcompRole> roles = new ArrayList<>();
1621 if(app.getCentralAuth()){
1622 final Map<String, Long> appParams = new HashMap<>();
1623 appParams.put("appId", app.getId());
1624 List<EPRole> applicationRoles = dataAccessService.executeNamedQuery("getActiveRolesOfApplication", appParams, null);
1625 for(EPRole role : applicationRoles){
1626 EcompRole ecompRole = new EcompRole();
1627 ecompRole.setId(role.getId());
1628 ecompRole.setName(role.getName());
1629 roles.add(ecompRole);
1631 appRoles = roles.toArray(new EcompRole[roles.size()]);
1633 appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
1635 // Test this error case, for generating an internal ONAP Portal
1637 // EcompRole[] appRoles = null;
1638 // If there is an exception in the rest client api, then null will
1640 if (appRoles != null) {
1641 if(!app.getCentralAuth()) {
1642 syncAppRoles(sessionFactory, appId, appRoles);
1644 EcompRole[] userAppRoles = null;
1647 if(app.getCentralAuth()){
1648 final Map<String, String> params = new HashMap<>();
1649 final Map<String, Long> userParams = new HashMap<>();
1650 params.put("orgUserIdValue", userId);
1651 List<EPUser> user = dataAccessService.executeNamedQuery("epUserAppId", params, null);
1652 userParams.put("appId", app.getId());
1653 userParams.put("userId", user.get(0).getId());
1654 List<EPUserAppCurrentRoles> userAppsRolesList = dataAccessService.executeNamedQuery("getUserAppCurrentRoles", userParams, null);
1655 List<EcompRole> setUserRoles = new ArrayList<>();
1656 for(EPUserAppCurrentRoles role : userAppsRolesList){
1657 EcompRole ecompRole = new EcompRole();
1658 ecompRole.setId(role.getRoleId());
1659 ecompRole.setName(role.getRoleName());
1660 setUserRoles.add(ecompRole);
1662 userAppRoles = setUserRoles.toArray(new EcompRole[setUserRoles.size()]);
1663 rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
1664 return rolesInAppForUser;
1666 userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
1667 String.format("/user/%s/roles", userId));
1669 } catch (HTTPException e) {
1670 // Some apps are returning 400 if user is not found.
1671 if (e.getResponseCode() == 400) {
1672 logger.debug(EELFLoggerDelegate.debugLogger,
1673 "getAppRolesForUser caught exception with response code 400; continuing", e);
1675 // Other response code, let it come thru.
1679 if (userAppRoles == null) {
1680 if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
1681 EcompPortalUtils.setExternalAppResponseCode(200);
1682 String message = String.format(
1683 "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
1684 + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
1685 + "Overriding to 200 until framework SDK returns a useful response.",
1686 Long.toString(appId), userId);
1687 logger.warn(EELFLoggerDelegate.applicationLogger, message);
1691 HashMap<Long, EcompRole> appRolesActiveMap =hashMapFromEcompRoles(appRoles);
1692 ArrayList<EcompRole> activeRoles = new ArrayList<EcompRole>();
1693 if(userAppRoles != null){
1694 for (int i = 0; i < userAppRoles.length; i++) {
1695 if (appRolesActiveMap.containsKey(userAppRoles[i].getId())) {
1696 EcompRole role = new EcompRole();
1697 role.setId(userAppRoles[i].getId());
1698 role.setName(userAppRoles[i].getName());
1699 activeRoles.add(role);
1703 EcompRole[] userAppRolesActive = activeRoles.toArray(new EcompRole[activeRoles.size()]);
1705 // If the remote application isn't down we MUST sync user
1706 // roles here in case we have this user here!
1707 syncUserRoles(sessionFactory, userId, appId, userAppRolesActive, extRequestValue, null);
1708 } catch (Exception e) {
1709 // TODO: we may need to check if user exists, maybe remote
1711 String message = String.format(
1712 "getAppRolesForUser: user %s does not exist in remote application %s", userId,
1713 Long.toString(appId));
1714 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1715 userAppRoles = new EcompRole[0];
1717 rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
1719 } catch (Exception e) {
1720 String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
1721 Long.toString(appId));
1722 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1724 return rolesInAppForUser;
1728 private boolean postUserRolesToMylogins(AppWithRolesForUser userAppRolesData,
1729 ApplicationsRestClientService applicationsRestClientService, Long appId, Long userId)
1730 throws JsonProcessingException, HTTPException {
1731 boolean result = false;
1732 ObjectMapper mapper = new ObjectMapper();
1733 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1734 String userRolesAsString = mapper.writeValueAsString(userAppRolesData);
1735 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, as the endpoint is not defined yet from the Mylogins");
1736 applicationsRestClientService.post(AppWithRolesForUser.class, appId, userRolesAsString, String.format("/user/%s/myLoginroles", userId));
1740 @SuppressWarnings("unchecked")
1741 public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser userAppRolesData, EPUser user) {
1742 FieldsValidator fieldsValidator = new FieldsValidator();
1743 final Map<String, Long> params = new HashMap<>();
1744 List<EPUserAppRoles> appRole= null;
1746 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, still the endpoint is yet to be defined");
1747 boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService, userAppRolesData.appId, user.getId());
1748 logger.debug(EELFLoggerDelegate.debugLogger,"putUserAppRolesRequest: result {}", result);
1750 params.put("appId", userAppRolesData.appId);
1751 EPUserAppRolesRequest epAppRolesRequestData = new EPUserAppRolesRequest();
1752 epAppRolesRequestData.setCreatedDate(new Date());
1753 epAppRolesRequestData.setUpdatedDate(new Date());
1754 epAppRolesRequestData.setUserId(user.getId());
1755 epAppRolesRequestData.setAppId(userAppRolesData.appId);
1756 epAppRolesRequestData.setRequestStatus("P");
1757 List<RoleInAppForUser> appRoleIdList = userAppRolesData.appRoles;
1758 Set<EPUserAppRolesRequestDetail> appRoleDetails = new LinkedHashSet<EPUserAppRolesRequestDetail>();
1759 dataAccessService.saveDomainObject(epAppRolesRequestData, null);
1760 for (RoleInAppForUser userAppRoles : appRoleIdList) {
1761 Boolean isAppliedVal = userAppRoles.isApplied;
1762 params.put("appRoleId", userAppRoles.roleId);
1764 appRole = (List<EPUserAppRoles>) dataAccessService.executeNamedQuery("appRoles", params, null);
1765 if (!appRole.isEmpty()) {
1766 EPUserAppRolesRequestDetail epAppRoleDetail = new EPUserAppRolesRequestDetail();
1767 epAppRoleDetail.setReqRoleId(appRole.get(0).getRoleId());
1768 epAppRoleDetail.setReqType("P");
1769 epAppRoleDetail.setEpRequestIdData(epAppRolesRequestData);
1770 dataAccessService.saveDomainObject(epAppRoleDetail, null);
1774 epAppRolesRequestData.setEpRequestIdDetail(appRoleDetails);
1775 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1777 } catch (Exception e) {
1778 logger.error(EELFLoggerDelegate.errorLogger, "putUserAppRolesRequest failed", e);
1779 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1781 return fieldsValidator;
1784 public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(EPUser userid, String appName) {
1785 Map<String, String> params = new HashMap<>();
1786 params.put("userid", userid.getId().toString());
1787 //params.put("appid", appid);
1788 params.put("appName", appName);
1790 @SuppressWarnings("unchecked")
1791 List<EPUserAppCatalogRoles> userAppRoles = (List<EPUserAppCatalogRoles>) dataAccessService
1792 .executeNamedQuery("userAppCatalogRoles", params, null);
1793 return userAppRoles;
1796 public String updateRemoteUserProfile(String orgUserId, Long appId) {
1797 ObjectMapper mapper = new ObjectMapper();
1798 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1799 EPUser client = searchService.searchUserByUserId(orgUserId);
1800 EPUser newUser = new EPUser();
1801 newUser.setActive(client.getActive());
1802 newUser.setFirstName(client.getFirstName());
1803 newUser.setLastName(client.getLastName());
1804 newUser.setLoginId(client.getLoginId());
1805 newUser.setLoginPwd(client.getLoginPwd());
1806 newUser.setMiddleInitial(client.getMiddleInitial());
1807 newUser.setEmail(client.getEmail());
1808 newUser.setOrgUserId(client.getLoginId());
1810 String userAsString = mapper.writeValueAsString(newUser);
1811 List<EPApp> appList = appsService.getUserRemoteApps(client.getId().toString());
1812 // applicationsRestClientService.post(EPUser.class, appId,
1813 // userAsString, String.format("/user", orgUserId));
1814 for (EPApp eachApp : appList) {
1816 applicationsRestClientService.post(EPUser.class, eachApp.getId(), userAsString,
1817 String.format("/user/%s", orgUserId));
1818 } catch (Exception e) {
1819 logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId()
1820 + " in remote app. appId = " + eachApp.getId());
1823 } catch (Exception e) {
1824 logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
1835 * @see org.onap.portalapp.portal.service.UserRolesService#
1836 * getCachedAppRolesForUser(java.lang.Long, java.lang.Long)
1838 @SuppressWarnings("deprecation")
1839 public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId) {
1840 // Find the records for this user-app combo, if any
1841 String filter = " where user_id = " + Long.toString(userId) + " and app_id = " + Long.toString(appId);
1842 @SuppressWarnings("unchecked")
1843 List<EPUserApp> roleList = dataAccessService.getList(EPUserApp.class, filter, null, null);
1844 logger.debug(EELFLoggerDelegate.debugLogger, "getCachedAppRolesForUser: list size is {}", roleList.size());
1849 * It retrieves and returns list of user app roles for local and remote applications based app id
1852 * @return list of user app roles
1853 * @throws HTTPException
1855 public List<UserApplicationRoles> getUsersFromAppEndpoint(Long appId) throws HTTPException {
1856 ArrayList<UserApplicationRoles> userApplicationRoles = new ArrayList<UserApplicationRoles>();
1858 EPApp app = appsService.getApp(appId);
1859 //If local or centralized application
1860 if (appId == PortalConstants.PORTAL_APP_ID || app.getCentralAuth()) {
1861 @SuppressWarnings("unchecked")
1862 List<EPUser> userList = (List<EPUser>) dataAccessService.executeNamedQuery("getActiveUsers", null, null);
1863 for (EPUser user : userList) {
1864 UserApplicationRoles userWithAppRoles = convertToUserApplicationRoles(appId, user, app);
1865 if (userWithAppRoles.getRoles() != null && userWithAppRoles.getRoles().size() > 0)
1866 userApplicationRoles.add(userWithAppRoles);
1872 RemoteUserWithRoles[] remoteUsers = null;
1873 String remoteUsersString = applicationsRestClientService.getIncomingJsonString(appId, "/users");
1875 remoteUsers = doGetUsers(isAppUpgradeVersion(app), remoteUsersString);
1877 userApplicationRoles = new ArrayList<UserApplicationRoles>();
1878 for (RemoteUserWithRoles remoteUser : remoteUsers) {
1879 UserApplicationRoles userWithRemoteAppRoles = convertToUserApplicationRoles(appId, remoteUser);
1880 if (userWithRemoteAppRoles.getRoles() != null && userWithRemoteAppRoles.getRoles().size() > 0) {
1881 userApplicationRoles.add(userWithRemoteAppRoles);
1883 logger.debug(EELFLoggerDelegate.debugLogger,
1884 "User " + userWithRemoteAppRoles.getOrgUserId() + " doesn't have any roles assigned to any app.");
1889 return userApplicationRoles;
1896 * @param appgetUsersFromAppEndpoint
1899 private UserApplicationRoles convertToUserApplicationRoles(Long appId, EPUser user, EPApp app) {
1900 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
1901 userWithRemoteAppRoles.setAppId(appId);
1902 userWithRemoteAppRoles.setOrgUserId(user.getOrgUserId());
1903 userWithRemoteAppRoles.setFirstName(user.getFirstName());
1904 userWithRemoteAppRoles.setLastName(user.getLastName());
1905 userWithRemoteAppRoles.setRoles(convertToRemoteRoleList(user, app));
1906 return userWithRemoteAppRoles;
1915 private List<RemoteRole> convertToRemoteRoleList(EPUser user, EPApp app) {
1916 List<RemoteRole> roleList = new ArrayList<RemoteRole>();
1917 SortedSet<EPRole> roleSet = user.getAppEPRoles(app);
1918 for (EPRole role : roleSet) {
1919 RemoteRole rRole = new RemoteRole();
1920 rRole.setId(role.getId());
1921 rRole.setName(role.getName());
1922 roleList.add(rRole);
1927 public RemoteUserWithRoles[] doGetUsers(boolean postOpenSource, String remoteUsersString) {
1929 ObjectMapper mapper = new ObjectMapper();
1931 return mapper.readValue(remoteUsersString, RemoteUserWithRoles[].class);
1932 } catch (IOException e) {
1933 logger.error(EELFLoggerDelegate.errorLogger,
1934 "doGetUsers : Failed : Unexpected property in incoming JSON",
1936 logger.error(EELFLoggerDelegate.errorLogger,
1937 "doGetUsers : Incoming JSON that caused it --> " + remoteUsersString);
1940 return new RemoteUserWithRoles[0];
1943 @SuppressWarnings("unchecked")
1944 public List<EPUserApp> getEPUserAppList(Long appId, Long userId, Long roleId) {
1945 List<EPUserApp> userRoleList = new ArrayList<EPUserApp>();
1946 final Map<String, Long> params = new HashMap<>();
1947 params.put("appId", appId);
1948 params.put("userId", userId);
1949 params.put("roleId", roleId);
1950 userRoleList = dataAccessService.executeNamedQuery("getUserRoleOnUserIdAndRoleIdAndAppId", params, null);
1951 return userRoleList;