2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2017 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 newRolesMap.remove(oldAppRole.getAppRoleId());
487 obsoleteRoles.add(oldAppRole);
490 obsoleteRoles.add(oldAppRole);
493 Collection<EcompRole> newRolesToAdd = newRolesMap.values();
494 if (obsoleteRoles.size() > 0) {
495 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: we have obsolete roles to delete");
496 for (EPRole role : obsoleteRoles) {
497 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: obsolete role: " + role.toString());
498 Long roleId = role.getId();
499 // delete obsolete roles here
500 // Must delete all records with foreign key constraints on
502 // fn_user_role, fn_role_composite, fn_role_function,
503 // fn_user_pseudo_role, fn_menu_functional_roles.
504 // And for fn_menu_functional, if no other roles for that
505 // menu item, remove the url.
507 // Delete from fn_user_role
508 @SuppressWarnings("unchecked")
509 List<EPUserApp> userRoles = localSession.createQuery(
510 "from " + EPUserApp.class.getName() + " where app.id=" + appId + " and role_id=" + roleId)
513 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: number of userRoles to delete: " + userRoles.size());
514 for (EPUserApp userRole : userRoles) {
515 logger.debug(EELFLoggerDelegate.debugLogger,
516 "syncAppRoles: about to delete userRole: " + userRole.toString());
517 localSession.delete(userRole);
518 logger.debug(EELFLoggerDelegate.debugLogger,
519 "syncAppRoles: finished deleting userRole: " + userRole.toString());
522 // Delete from fn_menu_functional_roles
523 @SuppressWarnings("unchecked")
524 List<FunctionalMenuRole> funcMenuRoles = localSession
525 .createQuery("from " + FunctionalMenuRole.class.getName() + " where roleId=" + roleId)
527 int numMenuRoles = funcMenuRoles.size();
528 logger.debug(EELFLoggerDelegate.debugLogger,
529 "syncAppRoles: number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles);
530 for (FunctionalMenuRole funcMenuRole : funcMenuRoles) {
531 Long menuId = funcMenuRole.menuId;
532 // If this is the only role for this menu item, then the
533 // app and roles will be gone,
534 // so must null out the url too, to be consistent
535 @SuppressWarnings("unchecked")
536 List<FunctionalMenuRole> funcMenuRoles2 = localSession
537 .createQuery("from " + FunctionalMenuRole.class.getName() + " where menuId=" + menuId)
539 int numMenuRoles2 = funcMenuRoles2.size();
540 logger.debug(EELFLoggerDelegate.debugLogger,
541 "syncAppRoles: number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2);
542 localSession.delete(funcMenuRole);
543 if (numMenuRoles2 == 1) {
544 // If this is the only role for this menu item, then
545 // the app and roles will be gone,
546 // so must null out the url too, to be consistent
547 logger.debug(EELFLoggerDelegate.debugLogger,
548 "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url");
549 @SuppressWarnings("unchecked")
550 List<FunctionalMenuItem> funcMenuItems = localSession
552 "from " + FunctionalMenuItem.class.getName() + " where menuId=" + menuId)
554 if (funcMenuItems.size() > 0) {
555 logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item");
556 FunctionalMenuItem funcMenuItem = funcMenuItems.get(0);
557 funcMenuItem.url = "";
558 localSession.update(funcMenuItem);
562 boolean isPortalRequest = true;
563 externalAccessRolesService.deleteRoleDependencyRecords(localSession, roleId, appId, isPortalRequest);
564 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to delete the role: " + role.toString());
565 localSession.delete(role);
566 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: deleted the role");
569 for (EcompRole role : newRolesToAdd) {
570 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to add missing role: " + role.toString());
571 EPRole newRole = new EPRole();
572 // Attention! All roles from remote application supposed to be
574 newRole.setActive(true);
575 newRole.setName(role.getName());
576 newRole.setAppId(appId);
577 newRole.setAppRoleId(role.getId());
578 localSession.save(newRole);
580 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to commit the transaction");
581 transaction.commit();
582 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: committed the transaction");
583 } catch (Exception e) {
584 logger.error(EELFLoggerDelegate.errorLogger, "syncAppRoles failed", e);
585 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
586 EcompPortalUtils.rollbackTransaction(transaction,
587 "Exception occurred in syncAppRoles, Details: " + e.toString());
588 throw new Exception(e);
590 localSession.close();
599 * Called when updating the list of roles for the user
603 * @param userRolesInRemoteApp
604 * @return RolesInAppForUser
606 protected RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId,
607 Set<EcompRole> userRolesInRemoteApp) {
608 RolesInAppForUser result;
609 result = new RolesInAppForUser();
610 result.appId = appId;
611 result.orgUserId = userId;
612 for (EcompRole role : userRolesInRemoteApp) {
613 RoleInAppForUser roleInAppForUser = new RoleInAppForUser();
614 roleInAppForUser.roleId = role.getId();
615 roleInAppForUser.roleName = role.getName();
616 roleInAppForUser.isApplied = new Boolean(true);
617 result.roles.add(roleInAppForUser);
624 * @param roleInAppForUserList
627 protected boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) {
628 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
629 if (roleInAppForUser.isApplied.booleanValue()) {
637 * Builds JSON and posts it to a remote application to update user roles.
639 * @param roleInAppForUserList
641 * @param applicationsRestClientService
644 * @return Set of roles as sent; NOT the response from the app.
645 * @throws JsonProcessingException
646 * @throws HTTPException
648 protected Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
649 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
650 throws JsonProcessingException, HTTPException {
651 Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList);
652 Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList);
653 String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote);
654 EPApp externalApp = null;
655 SystemType type = SystemType.APPLICATION;
656 externalApp = appsCacheService.getApp(appId);
657 String appBaseUri = null;
658 Set<RemoteRoleV1> updatedUserRolesinRemoteV1 = new TreeSet<>();
659 if (externalApp != null) {
660 appBaseUri = (type == SystemType.APPLICATION) ? externalApp.getAppRestEndpoint() : "";
662 if(appBaseUri != null && appBaseUri.endsWith("/api")){
663 for(EcompRole eprole :updatedUserRolesinRemote)
665 RemoteRoleV1 role = new RemoteRoleV1();
666 role.setId(eprole.getId());
667 role.setName(eprole.getName());
668 updatedUserRolesinRemoteV1.add(role);
670 userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemoteV1);
672 applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString,
673 String.format("/user/%s/roles", userId));
674 // TODO: We should add code that verifies that the post operation did
675 // succeed. Because the SDK may still return 200 OK with an html page
676 // even when it fails!
677 return updateUserRolesInEcomp;
682 * @param roleInAppForUserList
683 * @return Set<EcompRole>
685 protected Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) {
686 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
687 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
688 if (roleInAppForUser.isApplied) {
689 EcompRole ecompRole = new EcompRole();
690 ecompRole.setId(roleInAppForUser.roleId);
691 ecompRole.setName(roleInAppForUser.roleName);
692 existingUserRoles.add(ecompRole);
695 return existingUserRoles;
699 * Constructs user app roles excluding Account Administrator role
701 * @param roleInAppForUserList
703 * List of roles with Role name, Role Id
705 protected Set<EcompRole> constructUsersRemoteAppRoles(List<RoleInAppForUser> roleInAppForUserList) {
706 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
707 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
708 if (roleInAppForUser.isApplied && !roleInAppForUser.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
709 EcompRole ecompRole = new EcompRole();
710 ecompRole.setId(roleInAppForUser.roleId);
711 ecompRole.setName(roleInAppForUser.roleName);
712 existingUserRoles.add(ecompRole);
715 return existingUserRoles;
719 * This is for a single app
721 * @param rolesInAppForUser
722 * @param externalSystemRequest
723 * set to false if requests from Users page otherwise true
724 * @return true on success, false otherwise
726 protected boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser, boolean externalSystemRequest, String reqType) throws Exception {
727 boolean result = false;
728 String userId = rolesInAppForUser.orgUserId;
729 Long appId = rolesInAppForUser.appId;
730 synchronized (syncRests) {
731 if (rolesInAppForUser != null) {
732 createLocalUserIfNecessary(userId);
735 if (rolesInAppForUser != null) {
736 EcompRole[] userAppRoles = new EcompRole[rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size()];
737 for (int i = 0; i < rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size(); i++) {
738 RoleInAppForUser roleInAppForUser = rolesInAppForUser.roles.get(i);
739 EcompRole role = new EcompRole();
740 role.setId(roleInAppForUser.roleId);
741 role.setName(roleInAppForUser.roleName);
742 userAppRoles[i] = role;
745 syncUserRoles(sessionFactory, userId, appId, userAppRoles, externalSystemRequest, reqType);
747 } catch (Exception e) {
748 logger.error(EELFLoggerDelegate.errorLogger,
749 "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for orgUserId " + userId, e);
750 if("DELETE".equals(reqType)){
751 throw new Exception(e.getMessage());
763 * @return UserApplicationRoles
765 protected UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) {
766 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
767 userWithRemoteAppRoles.setAppId(appId);
768 userWithRemoteAppRoles.setOrgUserId(remoteUser.getOrgUserId());
769 userWithRemoteAppRoles.setFirstName(remoteUser.getFirstName());
770 userWithRemoteAppRoles.setLastName(remoteUser.getLastName());
771 userWithRemoteAppRoles.setRoles(remoteUser.getRoles());
772 return userWithRemoteAppRoles;
778 * @see org.onap.portalapp.portal.service.UserRolesService#
779 * importRolesFromRemoteApplication(java.lang.Long)
781 public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException {
782 EPRole[] appRolesFull = applicationsRestClientService.get(EPRole[].class, appId, "/rolesFull");
783 List<EPRole> rolesList = Arrays.asList(appRolesFull);
784 for (EPRole externalAppRole : rolesList) {
786 // Try to find an existing extern role for the app in the local
787 // onap DB. If so, then use its id to update the existing external
788 // application role record.
789 Long externAppId = externalAppRole.getId();
790 EPRole existingAppRole = epRoleService.getRole(appId, externAppId);
791 if (existingAppRole != null) {
792 logger.debug(EELFLoggerDelegate.debugLogger,
793 String.format("ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.",
794 appId, externAppId));
797 // persistExternalRoleInEcompDb(externalAppRole, appId,
805 * It adds new user for remote application
807 * @param roleInAppForUserList
808 * @param remoteAppUser
812 * @param searchService
813 * @param applicationsRestClientService
817 private EPUser addRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app, ObjectMapper mapper, SearchService searchService, ApplicationsRestClientService applicationsRestClientService) throws Exception{
818 EPUser addRemoteUser = null;
819 if (remoteUserShouldBeCreated(roleInAppForUserList)) {
821 createNewUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper, isAppUpgradeVersion(app));
822 // If we succeed, we know that the new user was
823 // persisted on remote app.
824 addRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
825 if (addRemoteUser == null) {
826 logger.error(EELFLoggerDelegate.errorLogger,
827 "Failed to persist new user: " + userId + " in remote app. appId = " + app.getId());
831 return addRemoteUser;
835 * It checks whether the remote user exists or not
836 * if exits returns user object else null
840 * @param applicationsRestClientService
842 * @throws HTTPException
844 private EPUser checkIfRemoteUserExits(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService) throws HTTPException{
845 EPUser checkRemoteUser = null;
847 checkRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
848 } catch (HTTPException e) {
849 // Some apps are returning 400 if user is not found.
850 if (e.getResponseCode() == 400) {
851 logger.debug(EELFLoggerDelegate.debugLogger,
852 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing",
854 } else if(e.getResponseCode() == 404) {
855 logger.debug(EELFLoggerDelegate.debugLogger,
856 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 404; continuing",
859 // Other response code, let it come thru.
863 return checkRemoteUser;
870 * @see org.onap.portalapp.portal.service.UserRolesService#
871 * setAppWithUserRoleStateForUser(org.onap.portalapp.portal.domain.
872 * EPUser, org.onap.portalapp.portal.transport.AppWithRolesForUser)
874 public boolean setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser) {
875 boolean result = false;
876 boolean epRequestValue = false;
878 if (newAppRolesForUser != null && newAppRolesForUser.orgUserId != null) {
879 userId = newAppRolesForUser.orgUserId.trim();
881 Long appId = newAppRolesForUser.appId;
882 List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.appRoles;
883 if (userId.length() > 0) {
884 ObjectMapper mapper = new ObjectMapper();
885 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
888 EPApp app = appsService.getApp(appId);
889 applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
891 // if centralized app
892 if (app.getCentralAuth()) {
893 // We should add If user does not exist in remote application
894 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
895 EPUser remoteAppUser = null;
896 remoteAppUser = checkIfRemoteUserExits(userId, app, applicationsRestClientService);
898 if (remoteAppUser == null) {
899 addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService,
900 applicationsRestClientService);
904 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
905 applicationsRestClientService, appId, userId);
906 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
907 userRolesInLocalApp);
908 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
909 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
910 // Apply changes in external Access system
911 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList,
914 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal");
916 // In case if portal is not centralized then follow existing approach
917 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
918 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
919 applicationsRestClientService, appId, userId);
920 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
921 userRolesInLocalApp);
922 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal");
924 EPUser remoteAppUser = null;
925 if(!app.getCentralAuth() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)){
927 remoteAppUser = checkIfRemoteUserExits(userId, app, applicationsRestClientService);
929 if (remoteAppUser == null) {
930 remoteAppUser = addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService, applicationsRestClientService);
932 if (remoteAppUser != null) {
933 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
934 applicationsRestClientService, appId, userId);
935 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
936 userRolesInRemoteApp);
937 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null);
939 // If no roles remain, request app to set user inactive.
940 if (userRolesInRemoteApp.size() == 0) {
941 logger.debug(EELFLoggerDelegate.debugLogger,
942 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
944 remoteAppUser.setActive(false);
945 postUserToRemoteApp(userId, user, app, applicationsRestClientService);
950 } catch (Exception e) {
951 String message = String.format(
952 "Failed to create user or update user roles for User %s, AppId %s",
953 userId, Long.toString(appId));
954 logger.error(EELFLoggerDelegate.errorLogger, message, e);
962 * It adds user roles in External system and also make data consistent in both local and in External System
966 * @param roleInAppUser Contains list of active roles
968 @SuppressWarnings("unchecked")
969 private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser, boolean isPortalRequest) throws Exception
972 // check if user exists
973 final Map<String, String> userParams = new HashMap<>();
974 userParams.put("orgUserIdValue", orgUserId);
975 List<EPUser> userInfo = checkIfUserExists(userParams);
976 if (userInfo.isEmpty()) {
977 createLocalUserIfNecessary(orgUserId);
980 if (EPCommonSystemProperties
981 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
983 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
985 ObjectMapper mapper = new ObjectMapper();
986 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
987 HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
988 ResponseEntity<String> getResponse = externalAccessRolesService.getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
989 List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
990 String res = getResponse.getBody();
991 JSONObject jsonObj = null;
992 JSONArray extRoles = null;
993 if (!res.equals("{}")) {
994 jsonObj = new JSONObject(res);
995 extRoles = jsonObj.getJSONArray("role");
997 ExternalAccessUserRoleDetail userRoleDetail = null;
998 if (extRoles != null) {
999 for (int i = 0; i < extRoles.length(); i++) {
1000 if (extRoles.getJSONObject(i).getString("name").startsWith(app.getNameSpace() + ".")
1001 && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".admin")
1002 && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".owner")) {
1003 ObjectMapper descMapper = new ObjectMapper();
1004 if (extRoles.getJSONObject(i).has("description") && EcompPortalUtils.isJSONValid(extRoles.getJSONObject(i).getString("description"))) {
1005 ExternalRoleDescription desc = descMapper.readValue(
1006 extRoles.getJSONObject(i).getString("description"), ExternalRoleDescription.class);
1007 userRoleDetail = new ExternalAccessUserRoleDetail(
1008 extRoles.getJSONObject(i).getString("name"), desc);
1009 userRoleDetailList.add(userRoleDetail);
1011 userRoleDetail = new ExternalAccessUserRoleDetail(
1012 extRoles.getJSONObject(i).getString("name"), null);
1013 userRoleDetailList.add(userRoleDetail);
1020 List<ExternalAccessUserRoleDetail> userRoleListMatchingInExtAuthAndLocal = CheckIfRoleAreMatchingInUserRoleDetailList(userRoleDetailList,app);
1022 // If request coming from portal not from external role approval system then we have to check if user already
1023 // have account admin or system admin as GUI will not send these roles
1024 if (!isPortalRequest) {
1025 final Map<String, String> loginIdParams = new HashMap<>();
1026 loginIdParams.put("orgUserIdValue", orgUserId);
1027 EPUser user = (EPUser) dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null).get(0);
1028 final Map<String, Long> params = new HashMap<>();
1029 params.put("appId", app.getId());
1030 params.put("userId", user.getId());
1031 List<EcompUserAppRoles> userAppList = dataAccessService.executeNamedQuery("getUserAppExistingRoles",
1033 if (!roleInAppUser.isEmpty()) {
1034 for (EcompUserAppRoles userApp : userAppList) {
1035 if (userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)
1036 || userApp.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
1037 RoleInAppForUser addSpecialRole = new RoleInAppForUser();
1038 addSpecialRole.setIsApplied(true);
1039 addSpecialRole.setRoleId(userApp.getRoleId());
1040 addSpecialRole.setRoleName(userApp.getRoleName());
1041 roleInAppUser.add(addSpecialRole);
1046 List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct()
1047 .collect(Collectors.toList());
1048 final Map<String, RoleInAppForUser> currentUserRolesToUpdate = new HashMap<>();
1049 for (RoleInAppForUser roleInAppUserNew : roleInAppUserNonDupls) {
1050 currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), roleInAppUserNew);
1052 final Map<String, ExternalAccessUserRoleDetail> currentUserRolesInExternalSystem = new HashMap<>();
1053 for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleListMatchingInExtAuthAndLocal) {
1054 currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole);
1056 // Check if user roles does not exists in local but still there in External Central Auth System delete them all
1057 for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
1058 if (!(currentUserRolesToUpdate
1059 .containsKey(userRole.getName().substring(app.getNameSpace().length() + 1)))) {
1060 HttpEntity<String> entity = new HttpEntity<>(headers);
1061 logger.debug(EELFLoggerDelegate.debugLogger,
1062 "updateUserRolesInExternalSystem: Connecting to external system to DELETE user role {}",
1063 userRole.getName());
1064 ResponseEntity<String> deleteResponse = template.exchange(
1065 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1066 + "userRole/" + name + "/" + userRole.getName(),
1067 HttpMethod.DELETE, entity, String.class);
1068 logger.debug(EELFLoggerDelegate.debugLogger,
1069 "updateUserRolesInExternalSystem: Finished DELETE operation in external system for user role {} and the response is {}",
1070 userRole.getName(), deleteResponse.getBody());
1073 // Check if user roles does not exists in External Central Auth System add them all
1074 for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) {
1075 if (!(currentUserRolesInExternalSystem
1076 .containsKey(app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")))) {
1077 ExternalAccessUser extUser = new ExternalAccessUser(name,
1078 app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1079 String formattedUserRole = mapper.writeValueAsString(extUser);
1080 HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers);
1081 logger.debug(EELFLoggerDelegate.debugLogger, "updateUserRolesInExternalSystem: Connecting to external system for user {} and POST {}",
1082 name , addUserRole.getRoleName());
1083 ResponseEntity<String> addResponse = template
1084 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1085 + "userRole", HttpMethod.POST, entity, String.class);
1086 logger.debug(EELFLoggerDelegate.debugLogger,
1087 "updateUserRolesInExternalSystem: Finished adding user role in external system {} and added user role {}",
1088 addResponse.getBody(), addUserRole.getRoleName());
1089 if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 404) {
1090 logger.debug(EELFLoggerDelegate.debugLogger,
1091 "Finished POST operation in external system but unable to save user role", addResponse.getBody(),
1092 addUserRole.getRoleName());
1093 throw new Exception(addResponse.getBody());
1097 } catch (Exception e) {
1098 logger.error(EELFLoggerDelegate.errorLogger, "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}", app.getId(), e);
1099 EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
1105 private List<ExternalAccessUserRoleDetail> CheckIfRoleAreMatchingInUserRoleDetailList(
1106 List<ExternalAccessUserRoleDetail> userRoleDetailList, EPApp app) {
1107 Map<String, EPRole> epRoleList = externalAccessRolesService.getCurrentRolesInDB(app);
1108 //Add Account Admin role for partner app to prevent conflict
1109 if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1110 EPRole role = new EPRole();
1111 role.setName(PortalConstants.ADMIN_ROLE.replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1112 epRoleList.put(role.getName(), role);
1114 userRoleDetailList.removeIf(userRoleDetail -> !epRoleList.containsKey(userRoleDetail.getName().substring(app.getNameSpace().length()+1)));
1115 return userRoleDetailList;
1122 * @param applicationsRestClientService
1123 * @param searchService
1127 protected void createNewUserOnRemoteApp(String userId, EPApp app,
1128 ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
1129 ObjectMapper mapper, boolean postOpenSource) throws Exception {
1132 EPUser client = searchService.searchUserByUserId(userId);
1134 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1136 if (client == null) {
1137 String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook.";
1138 logger.error(EELFLoggerDelegate.errorLogger, msg);
1139 throw new Exception(msg);
1142 client.setLoginId(userId);
1143 client.setActive(true);
1145 String userInString = null;
1146 userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
1147 logger.debug(EELFLoggerDelegate.debugLogger,
1148 "about to post new client to remote application, users json = " + userInString);
1149 applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user", userId));
1153 @SuppressWarnings("unchecked")
1154 protected void applyChangesToAppRolesRequest(Long appId, Long userId, String updateStatus, EPUserAppRolesRequest epUserAppRolesRequest) {
1155 final Map<String, Long> epRequestParams = new HashMap<>();
1157 EPUserAppRolesRequest epAppRolesRequestData = epUserAppRolesRequest;
1158 epAppRolesRequestData.setUpdatedDate(new Date());
1159 epAppRolesRequestData.setRequestStatus(updateStatus);
1160 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1161 addiotonalUpdateParam.put("userId", userId);
1162 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1163 epRequestParams.put("reqId", epUserAppRolesRequest.getId());
1164 List<EPUserAppRolesRequestDetail> epUserAppRolessDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1165 epUserAppRolessDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1166 epRequestParams, null);
1167 if (epUserAppRolessDetailList.size() > 0) {
1168 for (EPUserAppRolesRequestDetail epRequestUpdateData : epUserAppRolessDetailList) {
1169 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateData;
1170 epAppRoleDetailData.setReqType(updateStatus);
1171 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1172 HashMap<String, Long> updateDetailsParam = new HashMap<String, Long>();
1173 addiotonalUpdateParam.put("reqId", epUserAppRolesRequest.getId());
1174 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParam);
1177 logger.debug(EELFLoggerDelegate.debugLogger, "The request is set to complete");
1179 } catch (Exception e) {
1180 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToAppRolesRequest failed", e);
1184 @SuppressWarnings("unchecked")
1185 public void applyChangesToUserAppRolesForMyLoginsRequest(EPUser user, Long appId) {
1186 final Map<String, Long> params = new HashMap<>();
1187 final Map<String, Long> epDetailParams = new HashMap<>();
1188 List<EPUserAppRolesRequest> epRequestIdVal = new ArrayList<EPUserAppRolesRequest>();
1189 params.put("appId", appId);
1190 params.put("userId", user.getId());
1192 epRequestIdVal = (List<EPUserAppRolesRequest>) dataAccessService
1193 .executeNamedQuery("userAppRolesRequestList", params, null);
1194 if (epRequestIdVal.size() > 0) {
1195 EPUserAppRolesRequest epAppRolesRequestData = epRequestIdVal.get(0);
1196 epAppRolesRequestData.setUpdatedDate(new Date());
1197 epAppRolesRequestData.setRequestStatus("O");
1198 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1199 addiotonalUpdateParam.put("userId", user.getId());
1200 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1201 epDetailParams.put("reqId", epAppRolesRequestData.getId());
1202 List<EPUserAppRolesRequestDetail> epUserAppRolesDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1203 epUserAppRolesDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1204 epDetailParams, null);
1205 if (epUserAppRolesDetailList.size() > 0) {
1206 for (EPUserAppRolesRequestDetail epRequestUpdateList : epUserAppRolesDetailList) {
1207 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateList;
1208 epAppRoleDetailData.setReqType("O");
1209 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1210 HashMap<String, Long> updateDetailsParams = new HashMap<String, Long>();
1211 addiotonalUpdateParam.put("reqId", epAppRolesRequestData.getId());
1212 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParams);
1214 logger.debug(EELFLoggerDelegate.debugLogger, "User App roles request from User Page is overridden");
1218 } catch (Exception e) {
1219 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e);
1224 * Pushes specified user details to the specified remote app.
1227 * OrgUserId identifying user at remote app in REST endpoint path
1229 * User details to be pushed
1232 * @param applicationsRestClientService
1233 * @throws HTTPException
1235 protected void postUserToRemoteApp(String userId, EPUser user, EPApp app,
1236 ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
1238 getUser(userId, app, applicationsRestClientService);
1243 * It returns user details for single org user id
1247 * if user exists it returns list of user details otherwise empty value
1249 @SuppressWarnings("unchecked")
1250 private List<EPUser> checkIfUserExists(Map<String, String> userParams){
1251 return (List<EPUser>)dataAccessService.executeNamedQuery("epUserAppId", userParams, null);
1255 * It checks whether the new user is valid or not otherwise throws exception
1260 * Checks if user is valid and returns message otherwise throws exception
1263 private String validateNewUser(String orgUserId, EPApp app) throws Exception {
1264 EPUser epUser = searchService.searchUserByUserId(orgUserId);
1265 if (epUser == null) {
1266 throw new Exception("User does not exist");
1267 } else if (!epUser.getOrgUserId().equals(orgUserId)) {
1268 throw new Exception("User does not exist");
1269 } else if (app == null) {
1270 throw new Exception("Application does not exist");
1272 return "Saved Successfully";
1276 * Checks if the fields exists or not
1279 * contains user information
1283 * throws exception if the field is not valid
1285 private void validateExternalRequestFields(List<EPUser> userList, EPApp app) throws Exception{
1286 if (userList.size() == 0 || userList.isEmpty() ) {
1287 throw new Exception("User does not exist");
1288 } else if(app == null) {
1289 throw new Exception("Application does not exist");
1290 } else if(!app.getEnabled() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1291 throw new Exception(app.getMlAppName()+" application is unavailable");
1295 @SuppressWarnings("unchecked")
1296 public ExternalRequestFieldsValidator setExternalRequestUserAppRole(ExternalSystemUser newAppRolesForUser, String reqType) {
1297 boolean result = false;
1298 boolean externalSystemRequest = true;
1299 final Map<String, Long> params = new HashMap<>();
1300 final Map<String, String> userParams = new HashMap<>();
1301 List<EPUser> userInfo = null;
1302 EPUser userId = null;
1303 List<EPUserAppRolesRequest> epRequestId = null;
1304 String orgUserId = "";
1305 String updateStatus = "";
1306 String reqMessage = "";
1308 if (newAppRolesForUser != null && newAppRolesForUser.getLoginId() != null) {
1309 orgUserId = newAppRolesForUser.getLoginId().trim();
1311 String appName = newAppRolesForUser.getApplicationName();
1312 String logMessage = ("DELETE").equals(reqType) ? "Deleting": "Assigning/Updating" ;
1313 if (orgUserId.length() > 0) {
1314 ObjectMapper mapper = new ObjectMapper();
1315 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1316 int epRequestIdSize = 0;
1318 app = appsService.getAppDetail(appName);
1319 userParams.put("orgUserIdValue", orgUserId);
1320 userInfo = checkIfUserExists(userParams);
1321 reqMessage = "Updated Successfully";
1322 if (!reqType.equals("DELETE") && (userInfo.size() == 0 || userInfo.isEmpty())) {
1323 reqMessage = validateNewUser(orgUserId, app);
1325 if (userInfo.size() != 0 || !userInfo.isEmpty()) {
1326 validateExternalRequestFields(userInfo, app);
1327 userId = userInfo.get(0);
1328 params.put("appId", app.getId());
1329 params.put("userId", userId.getId());
1330 epRequestId = (List<EPUserAppRolesRequest>) dataAccessService
1331 .executeNamedQuery("userAppRolesRequestList", params, null);
1332 epRequestIdSize = epRequestId.size();
1335 //If Non-Centralized app make sure you sync app roles before assigning to user
1336 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !app.getCentralAuth()) {
1337 logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Starting GET roles for app {}",app.getId());
1338 EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, app.getId(), "/roles");
1339 logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Finshed GET roles for app {} and payload {}",app.getId(), appRoles);
1340 if (appRoles.length > 0) {
1341 syncAppRoles(sessionFactory, app.getId(), appRoles);
1344 List<RoleInAppForUser> roleInAppForUserList = roleInAppForUserList(newAppRolesForUser.getRoles(),
1345 app.getId(), app.getMlAppName());
1346 List<EcompUserAppRoles> userRoleList = null;
1347 if(!userInfo.isEmpty()){
1348 final Map<String, Long> appParams = new HashMap<>();
1349 appParams.put("userId", userId.getId());
1350 appParams.put("appId", app.getId());
1351 userRoleList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", appParams, null);
1353 // Check if list contains just account admin role
1354 boolean checkIfAdminRoleExists = false;
1355 if (reqType.equals("DELETE") && userRoleList!=null) {
1356 checkIfAdminRoleExists = userRoleList.stream()
1357 .anyMatch(userRole -> userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1359 checkIfAdminRoleExists = roleInAppForUserList.stream()
1360 .anyMatch(roleList -> roleList.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1362 // if Centralized app
1363 if (app.getCentralAuth()) {
1364 // We should add If user does not exist in remote application
1366 // If adding just account admin role dont make remote application user call
1367 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !(checkIfAdminRoleExists
1368 && reqType.equals("DELETE")) && roleInAppForUserList.size() > 1) {
1369 EPUser remoteAppUser = null;
1370 remoteAppUser = checkIfRemoteUserExits(orgUserId, app,
1371 applicationsRestClientService);
1372 if (remoteAppUser == null) {
1373 addRemoteUser(roleInAppForUserList, orgUserId, app, mapper, searchService,
1374 applicationsRestClientService);
1375 reqMessage = "Saved Successfully";
1378 } catch (Exception e) {
1379 reqMessage = e.getMessage();
1380 logger.error(EELFLoggerDelegate.errorLogger, "setExternalRequestUserAppRole: Failed to added remote user", e);
1381 throw new Exception(reqMessage);
1383 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1384 applicationsRestClientService, app.getId(), orgUserId);
1385 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1386 userRolesInLocalApp);
1387 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1388 if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1389 // Apply changes in external Access system
1390 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, externalSystemRequest);
1392 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
1393 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1394 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType);
1396 // If local application is not centralized
1397 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1398 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1399 applicationsRestClientService, app.getId(), orgUserId);
1400 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1401 userRolesInLocalApp);
1402 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType);
1403 } else {// remote app
1404 // If adding just account admin role don't do remote application user call
1405 if(!((roleInAppForUserList.size() == 1 || reqType.equals("DELETE")) && checkIfAdminRoleExists)){
1406 EPUser remoteAppUser = null;
1407 remoteAppUser = checkIfRemoteUserExits(orgUserId, app, applicationsRestClientService);
1408 if (remoteAppUser == null) {
1409 remoteAppUser = addRemoteUser(roleInAppForUserList, orgUserId, app, mapper, searchService, applicationsRestClientService);
1410 reqMessage = "Saved Successfully";
1412 if (remoteAppUser != null) {
1413 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList,
1414 mapper, applicationsRestClientService, app.getId(), orgUserId);
1416 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId,
1417 app.getId(), userRolesInRemoteApp);
1418 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}",
1419 logMessage, newAppRolesForUser.getApplicationName(),
1420 newAppRolesForUser.getLoginId());
1421 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1423 // If no roles remain, request app to set user inactive.
1424 /*if (userRolesInRemoteApp.size() == 0) {
1425 logger.debug(EELFLoggerDelegate.debugLogger,
1426 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
1428 //TODO Need to fix the logged in user is not set to inactive
1429 remoteAppUser.setActive(false);
1430 postUserToRemoteApp(orgUserId, user, app, applicationsRestClientService);
1434 // Here we are adding only we have single account admin in roleInAppForUserList and this should not add in remote
1435 if(!(reqType.equals("DELETE")) && userInfo.isEmpty()){
1436 reqMessage = "Saved Successfully";
1438 Set<EcompRole> userRolesInRemoteApp = constructUsersEcompRoles(roleInAppForUserList);
1440 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1441 userRolesInRemoteApp);
1442 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}",
1443 logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1444 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1448 reqMessage = "Failed to save the user app role(s)";
1450 if (epRequestIdSize > 0 && !userInfo.isEmpty()) {
1452 applyChangesToAppRolesRequest(app.getId(), userId.getId(), updateStatus, epRequestId.get(0));
1455 } catch (Exception e) {
1456 String message = String.format("setExternalRequestUserAppRole: Failed to create user or update user roles for User %s, AppId %s",
1457 orgUserId, appName);
1458 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1460 reqMessage = e.getMessage();
1461 if(epRequestIdSize > 0 && userInfo!=null && !userInfo.isEmpty()){
1463 applyChangesToAppRolesRequest(app.getId(), userId.getId(),
1464 updateStatus, epRequestId.get(0));
1469 return new ExternalRequestFieldsValidator(result, reqMessage);
1474 * @param roleInAppForUserList
1476 * @param applicationsRestClientService
1479 * @return Set<EcompRole>
1480 * @throws JsonProcessingException
1481 * @throws HTTPException
1483 private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
1484 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
1485 throws JsonProcessingException, HTTPException {
1486 Set<EcompRole> updatedUserRoles = constructUsersEcompRoles(roleInAppForUserList);
1487 return updatedUserRoles;
1491 * It constructs and returns list of user app roles when the external API role approval system calls
1494 * @param roleInAppForUserList
1496 * @return list of user app roles
1498 * throws exceptions if role id does not exits
1500 private List<RoleInAppForUser> roleInAppForUserList(List<ExternalSystemRoleApproval> roleInAppForUserList,
1501 Long appId, String appName) throws Exception {
1502 List<RoleInAppForUser> existingUserRoles = new ArrayList<RoleInAppForUser>();
1503 EPRole existingAppRole = null;
1504 for (ExternalSystemRoleApproval roleInAppForUser : roleInAppForUserList) {
1505 RoleInAppForUser ecompRole = new RoleInAppForUser();
1506 existingAppRole = epRoleService.getAppRole(roleInAppForUser.getRoleName(), appId);
1507 if (existingAppRole == null) {
1508 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1509 roleInAppForUserList);
1510 throw new Exception("'" +roleInAppForUser.getRoleName() + "'" +" role does not exist for " + appName + " application");
1512 if (!existingAppRole.getActive()) {
1513 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1514 roleInAppForUserList);
1515 throw new Exception(roleInAppForUser.getRoleName() + " role is unavailable for "+ appName + " application");
1517 ecompRole.roleId = (appId == 1 || roleInAppForUser.getRoleName().equals(PortalConstants.ADMIN_ROLE)) ? existingAppRole.getId() : existingAppRole.getAppRoleId();
1518 ecompRole.roleName = roleInAppForUser.getRoleName();
1519 ecompRole.isApplied = true;
1520 existingUserRoles.add(ecompRole);
1523 return existingUserRoles;
1532 * @param applicationsRestClientService
1534 * @throws HTTPException
1536 protected EPUser getUserFromApp(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1537 throws HTTPException {
1539 if (app.getId() == PortalConstants.PORTAL_APP_ID) {
1540 // Map<String,String> params = new HashMap<String,String>();
1541 // params.put("sbcid",userId);
1542 @SuppressWarnings("unchecked")
1543 List<EPUser> userList = (List<EPUser>) dataAccessService
1544 .executeQuery("from EPUser where orgUserId='" + userId + "'", null);
1545 if (userList != null && !userList.isEmpty())
1546 return userList.get(0);
1552 return getUser(userId, app, applicationsRestClientService);
1555 protected EPUser getUser(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1556 throws HTTPException {
1557 return applicationsRestClientService.get(EPUser.class, app.getId(), String.format("/user/%s", userId), true);
1561 protected boolean isAppUpgradeVersion(EPApp app){
1566 public ExternalSystemAccess getExternalRequestAccess(){
1567 ExternalSystemAccess res = null;
1569 res = new ExternalSystemAccess(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE,
1570 Boolean.parseBoolean(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE)));
1571 } catch (Exception e) {
1572 logger.error(EELFLoggerDelegate.errorLogger, "getExternalRequestAccess failed" + e.getMessage());
1580 * @see org.onap.portalapp.portal.service.UserRolesService#
1581 * getAppRolesForUser(java.lang.Long, java.lang.String)
1583 @SuppressWarnings("unchecked")
1584 public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId, Boolean extRequestValue) {
1586 List<RoleInAppForUser> rolesInAppForUser = null;
1587 EPApp app = appsService.getApp(appId);
1589 // for onap portal app, no need to make a remote call
1590 List<Role> roleList = new ArrayList<>();
1591 if (appId == PortalConstants.PORTAL_APP_ID) {
1592 if(app.getCentralAuth()){
1593 List<CentralV2Role> cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey());
1594 for(CentralV2Role cenRole : cenRoleList){
1595 Role role = new Role();
1596 role.setActive(cenRole.getActive());
1597 role.setId(cenRole.getId());
1598 role.setName(cenRole.getName());
1599 role.setPriority(cenRole.getPriority());
1603 roleList = roleService.getAvailableRoles(userId);
1605 List<Role> activeRoleList = new ArrayList<Role>();
1606 for(Role role: roleList) {
1607 if(role.getActive()) {
1608 if(role.getId() != 1){ // prevent portal admin from being added
1609 activeRoleList.add(role);
1610 } else if(extRequestValue){
1611 activeRoleList.add(role);
1616 EPUser localUser = getUserFromApp(userId, app, applicationsRestClientService);
1617 // If localUser does not exists return roles
1618 Set<EPRole> roleSet = null;
1619 EPRole[] roleSetList = null;
1620 if(localUser != null){
1621 roleSet = localUser.getAppEPRoles(app);
1622 roleSetList = roleSet.toArray(new EPRole[0]);
1624 rolesInAppForUser = constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue);
1625 return rolesInAppForUser;
1628 EcompRole[] appRoles = null;
1629 List<EcompRole> roles = new ArrayList<>();
1630 if(app.getCentralAuth()){
1631 final Map<String, Long> appParams = new HashMap<>();
1632 appParams.put("appId", app.getId());
1633 List<EPRole> applicationRoles = dataAccessService.executeNamedQuery("getActiveRolesOfApplication", appParams, null);
1634 for(EPRole role : applicationRoles){
1635 EcompRole ecompRole = new EcompRole();
1636 ecompRole.setId(role.getId());
1637 ecompRole.setName(role.getName());
1638 roles.add(ecompRole);
1640 appRoles = roles.toArray(new EcompRole[roles.size()]);
1642 appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
1644 // Test this error case, for generating an internal ONAP Portal
1646 // EcompRole[] appRoles = null;
1647 // If there is an exception in the rest client api, then null will
1649 if (appRoles != null) {
1650 if(!app.getCentralAuth()) {
1651 syncAppRoles(sessionFactory, appId, appRoles);
1653 EcompRole[] userAppRoles = null;
1656 if(app.getCentralAuth()){
1657 final Map<String, String> params = new HashMap<>();
1658 final Map<String, Long> userParams = new HashMap<>();
1659 params.put("orgUserIdValue", userId);
1660 List<EPUser> user = dataAccessService.executeNamedQuery("epUserAppId", params, null);
1661 userParams.put("appId", app.getId());
1662 userParams.put("userId", user.get(0).getId());
1663 List<EPUserAppCurrentRoles> userAppsRolesList = dataAccessService.executeNamedQuery("getUserAppCurrentRoles", userParams, null);
1664 List<EcompRole> setUserRoles = new ArrayList<>();
1665 for(EPUserAppCurrentRoles role : userAppsRolesList){
1666 EcompRole ecompRole = new EcompRole();
1667 ecompRole.setId(role.getRoleId());
1668 ecompRole.setName(role.getRoleName());
1669 setUserRoles.add(ecompRole);
1671 userAppRoles = setUserRoles.toArray(new EcompRole[setUserRoles.size()]);
1672 rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
1673 return rolesInAppForUser;
1675 userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
1676 String.format("/user/%s/roles", userId));
1678 } catch (HTTPException e) {
1679 // Some apps are returning 400 if user is not found.
1680 if (e.getResponseCode() == 400) {
1681 logger.debug(EELFLoggerDelegate.debugLogger,
1682 "getAppRolesForUser caught exception with response code 400; continuing", e);
1684 // Other response code, let it come thru.
1688 if (userAppRoles == null) {
1689 if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
1690 EcompPortalUtils.setExternalAppResponseCode(200);
1691 String message = String.format(
1692 "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
1693 + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
1694 + "Overriding to 200 until framework SDK returns a useful response.",
1695 Long.toString(appId), userId);
1696 logger.warn(EELFLoggerDelegate.applicationLogger, message);
1700 HashMap<Long, EcompRole> appRolesActiveMap =hashMapFromEcompRoles(appRoles);
1701 ArrayList<EcompRole> activeRoles = new ArrayList<EcompRole>();
1702 if(userAppRoles != null){
1703 for (int i = 0; i < userAppRoles.length; i++) {
1704 if (appRolesActiveMap.containsKey(userAppRoles[i].getId())) {
1705 EcompRole role = new EcompRole();
1706 role.setId(userAppRoles[i].getId());
1707 role.setName(userAppRoles[i].getName());
1708 activeRoles.add(role);
1712 EcompRole[] userAppRolesActive = activeRoles.toArray(new EcompRole[activeRoles.size()]);
1714 // If the remote application isn't down we MUST sync user
1715 // roles here in case we have this user here!
1716 syncUserRoles(sessionFactory, userId, appId, userAppRolesActive, extRequestValue, null);
1717 } catch (Exception e) {
1718 // TODO: we may need to check if user exists, maybe remote
1720 String message = String.format(
1721 "getAppRolesForUser: user %s does not exist in remote application %s", userId,
1722 Long.toString(appId));
1723 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1724 userAppRoles = new EcompRole[0];
1726 rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
1728 } catch (Exception e) {
1729 String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
1730 Long.toString(appId));
1731 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1733 return rolesInAppForUser;
1737 private boolean postUserRolesToMylogins(AppWithRolesForUser userAppRolesData,
1738 ApplicationsRestClientService applicationsRestClientService, Long appId, Long userId)
1739 throws JsonProcessingException, HTTPException {
1740 boolean result = false;
1741 ObjectMapper mapper = new ObjectMapper();
1742 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1743 String userRolesAsString = mapper.writeValueAsString(userAppRolesData);
1744 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, as the endpoint is not defined yet from the Mylogins");
1745 applicationsRestClientService.post(AppWithRolesForUser.class, appId, userRolesAsString, String.format("/user/%s/myLoginroles", userId));
1749 @SuppressWarnings("unchecked")
1750 public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser userAppRolesData, EPUser user) {
1751 FieldsValidator fieldsValidator = new FieldsValidator();
1752 final Map<String, Long> params = new HashMap<>();
1753 List<EPUserAppRoles> appRole= null;
1755 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, still the endpoint is yet to be defined");
1756 boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService, userAppRolesData.appId, user.getId());
1757 logger.debug(EELFLoggerDelegate.debugLogger,"putUserAppRolesRequest: result {}", result);
1759 params.put("appId", userAppRolesData.appId);
1760 EPUserAppRolesRequest epAppRolesRequestData = new EPUserAppRolesRequest();
1761 epAppRolesRequestData.setCreatedDate(new Date());
1762 epAppRolesRequestData.setUpdatedDate(new Date());
1763 epAppRolesRequestData.setUserId(user.getId());
1764 epAppRolesRequestData.setAppId(userAppRolesData.appId);
1765 epAppRolesRequestData.setRequestStatus("P");
1766 List<RoleInAppForUser> appRoleIdList = userAppRolesData.appRoles;
1767 Set<EPUserAppRolesRequestDetail> appRoleDetails = new LinkedHashSet<EPUserAppRolesRequestDetail>();
1768 dataAccessService.saveDomainObject(epAppRolesRequestData, null);
1769 for (RoleInAppForUser userAppRoles : appRoleIdList) {
1770 Boolean isAppliedVal = userAppRoles.isApplied;
1771 params.put("appRoleId", userAppRoles.roleId);
1773 appRole = (List<EPUserAppRoles>) dataAccessService.executeNamedQuery("appRoles", params, null);
1774 if (!appRole.isEmpty()) {
1775 EPUserAppRolesRequestDetail epAppRoleDetail = new EPUserAppRolesRequestDetail();
1776 epAppRoleDetail.setReqRoleId(appRole.get(0).getRoleId());
1777 epAppRoleDetail.setReqType("P");
1778 epAppRoleDetail.setEpRequestIdData(epAppRolesRequestData);
1779 dataAccessService.saveDomainObject(epAppRoleDetail, null);
1783 epAppRolesRequestData.setEpRequestIdDetail(appRoleDetails);
1784 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1786 } catch (Exception e) {
1787 logger.error(EELFLoggerDelegate.errorLogger, "putUserAppRolesRequest failed", e);
1788 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1790 return fieldsValidator;
1793 public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(EPUser userid, String appName) {
1794 Map<String, String> params = new HashMap<>();
1795 params.put("userid", userid.getId().toString());
1796 //params.put("appid", appid);
1797 params.put("appName", appName);
1799 @SuppressWarnings("unchecked")
1800 List<EPUserAppCatalogRoles> userAppRoles = (List<EPUserAppCatalogRoles>) dataAccessService
1801 .executeNamedQuery("userAppCatalogRoles", params, null);
1802 return userAppRoles;
1805 public String updateRemoteUserProfile(String orgUserId, Long appId) {
1806 ObjectMapper mapper = new ObjectMapper();
1807 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1808 EPUser client = searchService.searchUserByUserId(orgUserId);
1809 EPUser newUser = new EPUser();
1810 newUser.setActive(client.getActive());
1811 newUser.setFirstName(client.getFirstName());
1812 newUser.setLastName(client.getLastName());
1813 newUser.setLoginId(client.getLoginId());
1814 newUser.setLoginPwd(client.getLoginPwd());
1815 newUser.setMiddleInitial(client.getMiddleInitial());
1816 newUser.setEmail(client.getEmail());
1817 newUser.setOrgUserId(client.getLoginId());
1819 String userAsString = mapper.writeValueAsString(newUser);
1820 List<EPApp> appList = appsService.getUserRemoteApps(client.getId().toString());
1821 // applicationsRestClientService.post(EPUser.class, appId,
1822 // userAsString, String.format("/user", orgUserId));
1823 for (EPApp eachApp : appList) {
1825 applicationsRestClientService.post(EPUser.class, eachApp.getId(), userAsString,
1826 String.format("/user/%s", orgUserId));
1827 } catch (Exception e) {
1828 logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId()
1829 + " in remote app. appId = " + eachApp.getId());
1832 } catch (Exception e) {
1833 logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
1844 * @see org.onap.portalapp.portal.service.UserRolesService#
1845 * getCachedAppRolesForUser(java.lang.Long, java.lang.Long)
1847 @SuppressWarnings("deprecation")
1848 public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId) {
1849 // Find the records for this user-app combo, if any
1850 String filter = " where user_id = " + Long.toString(userId) + " and app_id = " + Long.toString(appId);
1851 @SuppressWarnings("unchecked")
1852 List<EPUserApp> roleList = dataAccessService.getList(EPUserApp.class, filter, null, null);
1853 logger.debug(EELFLoggerDelegate.debugLogger, "getCachedAppRolesForUser: list size is {}", roleList.size());
1858 * It retrieves and returns list of user app roles for local and remote applications based app id
1861 * @return list of user app roles
1862 * @throws HTTPException
1864 public List<UserApplicationRoles> getUsersFromAppEndpoint(Long appId) throws HTTPException {
1865 ArrayList<UserApplicationRoles> userApplicationRoles = new ArrayList<UserApplicationRoles>();
1867 EPApp app = appsService.getApp(appId);
1868 //If local or centralized application
1869 if (appId == PortalConstants.PORTAL_APP_ID || app.getCentralAuth()) {
1870 @SuppressWarnings("unchecked")
1871 List<EPUser> userList = (List<EPUser>) dataAccessService.executeNamedQuery("getActiveUsers", null, null);
1872 for (EPUser user : userList) {
1873 UserApplicationRoles userWithAppRoles = convertToUserApplicationRoles(appId, user, app);
1874 if (userWithAppRoles.getRoles() != null && userWithAppRoles.getRoles().size() > 0)
1875 userApplicationRoles.add(userWithAppRoles);
1881 RemoteUserWithRoles[] remoteUsers = null;
1882 String remoteUsersString = applicationsRestClientService.getIncomingJsonString(appId, "/users");
1884 remoteUsers = doGetUsers(isAppUpgradeVersion(app), remoteUsersString);
1886 userApplicationRoles = new ArrayList<UserApplicationRoles>();
1887 for (RemoteUserWithRoles remoteUser : remoteUsers) {
1888 UserApplicationRoles userWithRemoteAppRoles = convertToUserApplicationRoles(appId, remoteUser);
1889 if (userWithRemoteAppRoles.getRoles() != null && userWithRemoteAppRoles.getRoles().size() > 0) {
1890 userApplicationRoles.add(userWithRemoteAppRoles);
1892 logger.debug(EELFLoggerDelegate.debugLogger,
1893 "User " + userWithRemoteAppRoles.getOrgUserId() + " doesn't have any roles assigned to any app.");
1898 return userApplicationRoles;
1905 * @param appgetUsersFromAppEndpoint
1908 private UserApplicationRoles convertToUserApplicationRoles(Long appId, EPUser user, EPApp app) {
1909 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
1910 userWithRemoteAppRoles.setAppId(appId);
1911 userWithRemoteAppRoles.setOrgUserId(user.getOrgUserId());
1912 userWithRemoteAppRoles.setFirstName(user.getFirstName());
1913 userWithRemoteAppRoles.setLastName(user.getLastName());
1914 userWithRemoteAppRoles.setRoles(convertToRemoteRoleList(user, app));
1915 return userWithRemoteAppRoles;
1924 private List<RemoteRole> convertToRemoteRoleList(EPUser user, EPApp app) {
1925 List<RemoteRole> roleList = new ArrayList<RemoteRole>();
1926 SortedSet<EPRole> roleSet = user.getAppEPRoles(app);
1927 for (EPRole role : roleSet) {
1928 RemoteRole rRole = new RemoteRole();
1929 rRole.setId(role.getId());
1930 rRole.setName(role.getName());
1931 roleList.add(rRole);
1936 public RemoteUserWithRoles[] doGetUsers(boolean postOpenSource, String remoteUsersString) {
1938 ObjectMapper mapper = new ObjectMapper();
1940 return mapper.readValue(remoteUsersString, RemoteUserWithRoles[].class);
1941 } catch (IOException e) {
1942 logger.error(EELFLoggerDelegate.errorLogger,
1943 "doGetUsers : Failed : Unexpected property in incoming JSON",
1945 logger.error(EELFLoggerDelegate.errorLogger,
1946 "doGetUsers : Incoming JSON that caused it --> " + remoteUsersString);
1949 return new RemoteUserWithRoles[0];
1952 @SuppressWarnings("unchecked")
1953 public List<EPUserApp> getEPUserAppList(Long appId, Long userId, Long roleId) {
1954 List<EPUserApp> userRoleList = new ArrayList<EPUserApp>();
1955 final Map<String, Long> params = new HashMap<>();
1956 params.put("appId", appId);
1957 params.put("userId", userId);
1958 params.put("roleId", roleId);
1959 userRoleList = dataAccessService.executeNamedQuery("getUserRoleOnUserIdAndRoleIdAndAppId", params, null);
1960 return userRoleList;