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============================================
36 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
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.RemoteUserWithRoles;
94 import org.onap.portalapp.portal.transport.RoleInAppForUser;
95 import org.onap.portalapp.portal.transport.RolesInAppForUser;
96 import org.onap.portalapp.portal.transport.UserApplicationRoles;
97 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
98 import org.onap.portalapp.portal.utils.EcompPortalUtils;
99 import org.onap.portalapp.portal.utils.PortalConstants;
100 import org.onap.portalsdk.core.domain.Role;
101 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
102 import org.onap.portalsdk.core.restful.domain.EcompRole;
103 import org.onap.portalsdk.core.service.DataAccessService;
104 import org.onap.portalsdk.core.service.RoleService;
105 import org.onap.portalsdk.core.util.SystemProperties;
106 import org.springframework.beans.factory.annotation.Autowired;
107 import org.springframework.http.HttpEntity;
108 import org.springframework.http.HttpHeaders;
109 import org.springframework.http.HttpMethod;
110 import org.springframework.http.HttpStatus;
111 import org.springframework.http.ResponseEntity;
112 import org.springframework.web.client.RestTemplate;
114 import com.fasterxml.jackson.core.JsonProcessingException;
115 import com.fasterxml.jackson.databind.DeserializationFeature;
116 import com.fasterxml.jackson.databind.ObjectMapper;
119 public class UserRolesCommonServiceImpl {
121 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesCommonServiceImpl.class);
123 private static final Object syncRests = new Object();
126 private DataAccessService dataAccessService;
128 private SessionFactory sessionFactory;
130 private SearchService searchService;
132 private EPAppService appsService;
134 private ApplicationsRestClientService applicationsRestClientService;
136 private EPRoleService epRoleService;
138 private RoleService roleService;
141 private ExternalAccessRolesService externalAccessRolesService;
143 RestTemplate template = new RestTemplate();
148 * @return HashMap<Long, EcompRole>
150 private static HashMap<Long, EcompRole> hashMapFromEcompRoles(EcompRole[] ecompRoles) {
151 HashMap<Long, EcompRole> result = new HashMap<Long, EcompRole>();
152 if (ecompRoles != null) {
153 for (int i = 0; i < ecompRoles.length; i++) {
154 if (ecompRoles[i].getId() != null) {
155 result.put(ecompRoles[i].getId(), ecompRoles[i]);
166 protected void createLocalUserIfNecessary(String userId) {
167 if (StringUtils.isEmpty(userId)) {
168 logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty userId!");
171 Session localSession = null;
172 Transaction transaction = null;
174 localSession = sessionFactory.openSession();
175 transaction = localSession.beginTransaction();
176 @SuppressWarnings("unchecked")
177 List<EPUser> userList = localSession
178 .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + userId + "'").list();
179 if (userList.size() == 0) {
180 EPUser client = searchService.searchUserByUserId(userId);
181 if (client == null) {
182 String msg = "createLocalUserIfNecessary: cannot create user " + userId
183 + ", because not found in phonebook";
184 logger.error(EELFLoggerDelegate.errorLogger, msg);
186 client.setLoginId(userId);
187 client.setActive(true);
188 localSession.save(client);
191 transaction.commit();
192 } catch (Exception e) {
193 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
194 EcompPortalUtils.rollbackTransaction(transaction, "searchOrCreateUser rollback, exception = " + e);
196 EcompPortalUtils.closeLocalSession(localSession, "searchOrCreateUser");
201 * This method return nothing and remove roles before adding any roles for an app
204 * @param localSession
205 * @param userAppRoles
206 * @param newUserAppRolesMap
208 private static void syncUserRolesExtension(EPUserApp userRole, Long appId, Session localSession, EcompRole[] userAppRoles, HashMap<Long, EcompRole> newUserAppRolesMap) {
210 Long userAppRoleId = 0L;
211 if (appId == PortalConstants.PORTAL_APP_ID) { // local app
212 userAppRoleId = userRole.getRoleId();
213 } else { // remote app
214 userAppRoleId = userRole.getAppRoleId();
217 if (!newUserAppRolesMap.containsKey(userAppRoleId)) {
218 localSession.delete(userRole);
220 newUserAppRolesMap.remove(userAppRoleId);
225 * Checks whether the role is inactive
229 * if role is inactive, throws exception
231 private void checkIfRoleInactive(EPRole epRole) throws Exception{
232 if(!epRole.getActive()){
233 throw new Exception(epRole.getName()+ " role is unavailable");
239 * @param sessionFactory
242 * @param userAppRoles
243 * @param extRequestValue
244 * set to false if request is from users page otherwise true
247 protected void syncUserRoles(SessionFactory sessionFactory, String userId, Long appId,
248 EcompRole[] userAppRoles, Boolean extRequestValue, String reqType) throws Exception {
249 Session localSession = null;
250 Transaction transaction = null;
251 String roleActive = null;
252 final Map<String, String> userAppParams = new HashMap<>();
253 final Map<String, String> appParams = new HashMap<>();
254 HashMap<Long, EcompRole> newUserAppRolesMap = hashMapFromEcompRoles(userAppRoles);
257 localSession = sessionFactory.openSession();
258 transaction = localSession.beginTransaction();
259 @SuppressWarnings("unchecked")
260 List<EPUser> userList = localSession
261 .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + userId + "'").list();
262 if (userList.size() > 0) {
263 EPUser client = userList.get(0);
264 roleActive = ("DELETE".equals(reqType)) ? "" : " and role.active = 'Y'";
265 @SuppressWarnings("unchecked")
266 List<EPUserApp> userRoles = localSession.createQuery("from " + EPUserApp.class.getName()
267 + " where app.id=" + appId + roleActive + " and userId=" + client.getId()).list();
269 if ("DELETE".equals(reqType)) {
270 for (EPUserApp userAppRoleList : userRoles) {
271 userAppParams.put("roleName", String.valueOf(userAppRoleList.getRole().getName()));
272 userAppParams.put("appId", String.valueOf(appId));
273 appParams.put("appRoleName", userAppRoleList.getRole().getName());
274 @SuppressWarnings("unchecked")
275 List<EPRole> rolesList = (!userAppRoleList.getRole().getName().equals(PortalConstants.ADMIN_ROLE)) ? (List<EPRole>) dataAccessService.executeNamedQuery("getAppRoles", userAppParams, null) : (List<EPRole>) dataAccessService.executeNamedQuery("getPortalAppRoles", appParams, null);
276 if(rolesList.size() > 0 || !rolesList.isEmpty()){
277 checkIfRoleInactive(rolesList.get(0));
282 for (EPUserApp userRole : userRoles) {
283 if (!userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && userRole.getRoleId() != PortalConstants.SYS_ADMIN_ROLE_ID && !extRequestValue){
284 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
286 else if (extRequestValue && ("PUT".equals(reqType) || "POST".equals(reqType) || "DELETE".equals(reqType))){
287 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
289 else if (extRequestValue && !userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)){
290 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
293 Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values();
294 if (newRolesToAdd.size() > 0) {
295 EPApp app = (EPApp) localSession.get(EPApp.class, appId);
297 HashMap<Long, EPRole> rolesMap = new HashMap<Long, EPRole>();
298 if (appId.equals(PortalConstants.PORTAL_APP_ID)) { // local app
299 String appIdValue = "";
300 if(!extRequestValue){
301 appIdValue = "and id != " + PortalConstants.SYS_ADMIN_ROLE_ID;
303 @SuppressWarnings("unchecked")
304 List<EPRole> roles = localSession
305 .createQuery("from " + EPRole.class.getName() + " where appId is null " + appIdValue).list();
306 for (EPRole role : roles) {
308 rolesMap.put(role.getId(), role);
310 } else { // remote app
311 @SuppressWarnings("unchecked")
312 List<EPRole> roles = localSession
313 .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list();
314 for (EPRole role : roles) {
315 if (!extRequestValue && app.getCentralAuth()) {
316 rolesMap.put(role.getId(), role);
318 rolesMap.put(role.getAppRoleId(), role);
324 for (EcompRole userRole : newRolesToAdd) {
325 EPUserApp userApp = new EPUserApp();
326 if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName().equals(PortalConstants.ADMIN_ROLE)) {
327 role = (EPRole) localSession.get(EPRole.class, new Long(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
328 userApp.setRole(role);
329 } else if ((userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) && !extRequestValue){
331 }else if((userRole.getId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)) && app.getId().equals(PortalConstants.PORTAL_APP_ID) && !extRequestValue){
335 userApp.setRole(rolesMap.get(userRole.getId()));
338 userApp.setUserId(client.getId());
340 localSession.save(userApp);
341 localSession.flush();
344 if (appId == PortalConstants.PORTAL_APP_ID) {
346 * for local app -- hack - always make sure fn_role
347 * table's app_id is null and not 1 for primary app in
348 * this case being ecomp portal app; reason: hibernate
349 * is rightly setting this to 1 while persisting to
350 * fn_role as per the mapping but SDK role management
351 * code expects the app_id to be null as there is no
352 * concept of App_id in SDK
354 localSession.flush();
355 SQLQuery sqlQuery = localSession
356 .createSQLQuery("update fn_role set app_id = null where app_id = 1 ");
357 sqlQuery.executeUpdate();
362 transaction.commit();
363 } catch (Exception e) {
364 logger.error(EELFLoggerDelegate.errorLogger, "syncUserRoles failed", e);
365 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
366 EcompPortalUtils.rollbackTransaction(transaction,
367 "Exception occurred in syncUserRoles, Details: " + e.toString());
368 if("DELETE".equals(reqType)){
369 throw new SyncUserRolesException(e.getMessage());
372 if(localSession != null)
373 localSession.close();
378 * Called when getting the list of roles for the user
381 * @param userAppRoles
382 * @return List<RoleInAppForUser>
384 protected List<RoleInAppForUser> constructRolesInAppForUserGet(EcompRole[] appRoles, EcompRole[] userAppRoles) {
385 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
387 Set<Long> userAppRolesMap = new HashSet<Long>();
388 if (userAppRoles != null) {
389 for (EcompRole ecompRole : userAppRoles) {
390 userAppRolesMap.add(ecompRole.getId());
393 logger.error(EELFLoggerDelegate.errorLogger,
394 "constructRolesInAppForUserGet has received userAppRoles list empty");
397 if (appRoles != null) {
398 for (EcompRole ecompRole : appRoles) {
399 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
400 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
401 rolesInAppForUser.add(roleForUser);
404 logger.error(EELFLoggerDelegate.errorLogger, "constructRolesInAppForUser has received appRoles list empty");
406 return rolesInAppForUser;
410 * Called when getting the list of roles for the user
413 * @param userAppRoles
414 * @param extRequestValue
415 * set to false if request is from users page otherwise true
416 * @return List<RoleInAppForUser>
418 protected List<RoleInAppForUser> constructRolesInAppForUserGet(List<Role> appRoles, EPRole[] userAppRoles, Boolean extRequestValue) {
419 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
421 Set<Long> userAppRolesMap = new HashSet<Long>();
422 if (userAppRoles != null) {
423 for (EPRole ecompRole : userAppRoles) {
424 userAppRolesMap.add(ecompRole.getId());
427 logger.error(EELFLoggerDelegate.errorLogger,
428 "constructRolesInAppForUserGet has received userAppRoles list empty.");
431 if (appRoles != null) {
432 for (Role ecompRole : appRoles) {
433 if (ecompRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && !extRequestValue)
435 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
436 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
437 rolesInAppForUser.add(roleForUser);
440 logger.error(EELFLoggerDelegate.errorLogger,
441 "constructRolesInAppForUser has received appRoles list empty.");
443 return rolesInAppForUser;
448 * copies of methods in GetAppsWithUserRoleState
450 * @param sessionFactory
455 protected void syncAppRoles(SessionFactory sessionFactory, Long appId, EcompRole[] appRoles) throws Exception {
456 logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId);
457 HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles);
458 Session localSession = null;
459 Transaction transaction = null;
462 localSession = sessionFactory.openSession();
463 transaction = localSession.beginTransaction();
464 // Attention! All roles from remote application supposed to be
466 @SuppressWarnings("unchecked")
467 List<EPRole> currentAppRoles = localSession
468 .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list();
469 List<EPRole> obsoleteRoles = new ArrayList<EPRole>();
470 for (int i = 0; i < currentAppRoles.size(); i++) {
471 EPRole oldAppRole = currentAppRoles.get(i);
472 if (oldAppRole.getAppRoleId() != null) {
473 EcompRole role = null;
474 role = newRolesMap.get(oldAppRole.getAppRoleId());
476 if (!(role.getName() == null || oldAppRole.getName().equals(role.getName()))) {
477 oldAppRole.setName(role.getName());
478 localSession.update(oldAppRole);
480 newRolesMap.remove(oldAppRole.getAppRoleId());
482 obsoleteRoles.add(oldAppRole);
485 obsoleteRoles.add(oldAppRole);
488 Collection<EcompRole> newRolesToAdd = newRolesMap.values();
489 if (obsoleteRoles.size() > 0) {
490 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: we have obsolete roles to delete");
491 for (EPRole role : obsoleteRoles) {
492 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: obsolete role: " + role.toString());
493 Long roleId = role.getId();
494 // delete obsolete roles here
495 // Must delete all records with foreign key constraints on
497 // fn_user_role, fn_role_composite, fn_role_function,
498 // fn_user_pseudo_role, fn_menu_functional_roles.
499 // And for fn_menu_functional, if no other roles for that
500 // menu item, remove the url.
502 // Delete from fn_user_role
503 @SuppressWarnings("unchecked")
504 List<EPUserApp> userRoles = localSession.createQuery(
505 "from " + EPUserApp.class.getName() + " where app.id=" + appId + " and role_id=" + roleId)
508 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: number of userRoles to delete: " + userRoles.size());
509 for (EPUserApp userRole : userRoles) {
510 logger.debug(EELFLoggerDelegate.debugLogger,
511 "syncAppRoles: about to delete userRole: " + userRole.toString());
512 localSession.delete(userRole);
513 logger.debug(EELFLoggerDelegate.debugLogger,
514 "syncAppRoles: finished deleting userRole: " + userRole.toString());
517 // Delete from fn_menu_functional_roles
518 @SuppressWarnings("unchecked")
519 List<FunctionalMenuRole> funcMenuRoles = localSession
520 .createQuery("from " + FunctionalMenuRole.class.getName() + " where roleId=" + roleId)
522 int numMenuRoles = funcMenuRoles.size();
523 logger.debug(EELFLoggerDelegate.debugLogger,
524 "syncAppRoles: number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles);
525 for (FunctionalMenuRole funcMenuRole : funcMenuRoles) {
526 Long menuId = funcMenuRole.menuId;
527 // If this is the only role for this menu item, then the
528 // app and roles will be gone,
529 // so must null out the url too, to be consistent
530 @SuppressWarnings("unchecked")
531 List<FunctionalMenuRole> funcMenuRoles2 = localSession
532 .createQuery("from " + FunctionalMenuRole.class.getName() + " where menuId=" + menuId)
534 int numMenuRoles2 = funcMenuRoles2.size();
535 logger.debug(EELFLoggerDelegate.debugLogger,
536 "syncAppRoles: number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2);
537 localSession.delete(funcMenuRole);
538 if (numMenuRoles2 == 1) {
539 // If this is the only role for this menu item, then
540 // the app and roles will be gone,
541 // so must null out the url too, to be consistent
542 logger.debug(EELFLoggerDelegate.debugLogger,
543 "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url");
544 @SuppressWarnings("unchecked")
545 List<FunctionalMenuItem> funcMenuItems = localSession
547 "from " + FunctionalMenuItem.class.getName() + " where menuId=" + menuId)
549 if (funcMenuItems.size() > 0) {
550 logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item");
551 FunctionalMenuItem funcMenuItem = funcMenuItems.get(0);
552 funcMenuItem.url = "";
553 localSession.update(funcMenuItem);
557 boolean isPortalRequest = true;
558 externalAccessRolesService.deleteRoleDependencyRecords(localSession, roleId, appId, isPortalRequest);
559 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to delete the role: " + role.toString());
560 localSession.delete(role);
561 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: deleted the role");
564 for (EcompRole role : newRolesToAdd) {
565 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to add missing role: " + role.toString());
566 EPRole newRole = new EPRole();
567 // Attention! All roles from remote application supposed to be
569 newRole.setActive(true);
570 newRole.setName(role.getName());
571 newRole.setAppId(appId);
572 newRole.setAppRoleId(role.getId());
573 localSession.save(newRole);
575 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to commit the transaction");
576 transaction.commit();
577 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: committed the transaction");
578 } catch (Exception e) {
579 logger.error(EELFLoggerDelegate.errorLogger, "syncAppRoles failed", e);
580 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
581 EcompPortalUtils.rollbackTransaction(transaction,
582 "Exception occurred in syncAppRoles, Details: " + e.toString());
583 throw new Exception(e);
585 localSession.close();
594 * Called when updating the list of roles for the user
598 * @param userRolesInRemoteApp
599 * @return RolesInAppForUser
601 protected RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId,
602 Set<EcompRole> userRolesInRemoteApp) {
603 RolesInAppForUser result;
604 result = new RolesInAppForUser();
605 result.appId = appId;
606 result.orgUserId = userId;
607 for (EcompRole role : userRolesInRemoteApp) {
608 RoleInAppForUser roleInAppForUser = new RoleInAppForUser();
609 roleInAppForUser.roleId = role.getId();
610 roleInAppForUser.roleName = role.getName();
611 roleInAppForUser.isApplied = new Boolean(true);
612 result.roles.add(roleInAppForUser);
619 * @param roleInAppForUserList
622 protected boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) {
623 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
624 if (roleInAppForUser.isApplied.booleanValue()) {
632 * Builds JSON and posts it to a remote application to update user roles.
634 * @param roleInAppForUserList
636 * @param applicationsRestClientService
639 * @return Set of roles as sent; NOT the response from the app.
640 * @throws JsonProcessingException
641 * @throws HTTPException
643 protected Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
644 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
645 throws JsonProcessingException, HTTPException {
646 Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList);
647 Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList);
648 String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote);
649 applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString,
650 String.format("/user/%s/roles", userId));
651 // TODO: We should add code that verifies that the post operation did
652 // succeed. Because the SDK may still return 200 OK with an html page
653 // even when it fails!
654 return updateUserRolesInEcomp;
659 * @param roleInAppForUserList
660 * @return Set<EcompRole>
662 protected Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) {
663 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
664 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
665 if (roleInAppForUser.isApplied) {
666 EcompRole ecompRole = new EcompRole();
667 ecompRole.setId(roleInAppForUser.roleId);
668 ecompRole.setName(roleInAppForUser.roleName);
669 existingUserRoles.add(ecompRole);
672 return existingUserRoles;
676 * Constructs user app roles excluding Account Administrator role
678 * @param roleInAppForUserList
680 * List of roles with Role name, Role Id
682 protected Set<EcompRole> constructUsersRemoteAppRoles(List<RoleInAppForUser> roleInAppForUserList) {
683 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
684 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
685 if (roleInAppForUser.isApplied && !roleInAppForUser.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
686 EcompRole ecompRole = new EcompRole();
687 ecompRole.setId(roleInAppForUser.roleId);
688 ecompRole.setName(roleInAppForUser.roleName);
689 existingUserRoles.add(ecompRole);
692 return existingUserRoles;
696 * This is for a single app
698 * @param rolesInAppForUser
699 * @param externalSystemRequest
700 * set to false if requests from Users page otherwise true
701 * @return true on success, false otherwise
703 protected boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser, boolean externalSystemRequest, String reqType) throws Exception {
704 boolean result = false;
705 String userId = rolesInAppForUser.orgUserId;
706 Long appId = rolesInAppForUser.appId;
707 synchronized (syncRests) {
708 if (rolesInAppForUser != null) {
709 createLocalUserIfNecessary(userId);
712 if (rolesInAppForUser != null) {
713 EcompRole[] userAppRoles = new EcompRole[rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size()];
714 for (int i = 0; i < rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size(); i++) {
715 RoleInAppForUser roleInAppForUser = rolesInAppForUser.roles.get(i);
716 EcompRole role = new EcompRole();
717 role.setId(roleInAppForUser.roleId);
718 role.setName(roleInAppForUser.roleName);
719 userAppRoles[i] = role;
722 syncUserRoles(sessionFactory, userId, appId, userAppRoles, externalSystemRequest, reqType);
724 } catch (Exception e) {
725 logger.error(EELFLoggerDelegate.errorLogger,
726 "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for orgUserId " + userId, e);
727 if("DELETE".equals(reqType)){
728 throw new Exception(e.getMessage());
740 * @return UserApplicationRoles
742 protected UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) {
743 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
744 userWithRemoteAppRoles.setAppId(appId);
745 userWithRemoteAppRoles.setOrgUserId(remoteUser.getOrgUserId());
746 userWithRemoteAppRoles.setFirstName(remoteUser.getFirstName());
747 userWithRemoteAppRoles.setLastName(remoteUser.getLastName());
748 userWithRemoteAppRoles.setRoles(remoteUser.getRoles());
749 return userWithRemoteAppRoles;
755 * @see org.onap.portalapp.portal.service.UserRolesService#
756 * importRolesFromRemoteApplication(java.lang.Long)
758 public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException {
759 EPRole[] appRolesFull = applicationsRestClientService.get(EPRole[].class, appId, "/rolesFull");
760 List<EPRole> rolesList = Arrays.asList(appRolesFull);
761 for (EPRole externalAppRole : rolesList) {
763 // Try to find an existing extern role for the app in the local
764 // ecomp DB. If so, then use its id to update the existing external
765 // application role record.
766 Long externAppId = externalAppRole.getId();
767 EPRole existingAppRole = epRoleService.getRole(appId, externAppId);
768 if (existingAppRole != null) {
769 logger.debug(EELFLoggerDelegate.debugLogger,
770 String.format("ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.",
771 appId, externAppId));
774 // persistExternalRoleInEcompDb(externalAppRole, appId,
782 * It adds new user for remote application
784 * @param roleInAppForUserList
785 * @param remoteAppUser
789 * @param searchService
790 * @param applicationsRestClientService
794 private EPUser addRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app, ObjectMapper mapper, SearchService searchService, ApplicationsRestClientService applicationsRestClientService) throws Exception{
795 EPUser addRemoteUser = null;
796 if (remoteUserShouldBeCreated(roleInAppForUserList)) {
798 createNewUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper, isAppUpgradeVersion(app));
799 // If we succeed, we know that the new user was
800 // persisted on remote app.
801 addRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
802 if (addRemoteUser == null) {
803 logger.error(EELFLoggerDelegate.errorLogger,
804 "Failed to persist new user: " + userId + " in remote app. appId = " + app.getId());
808 return addRemoteUser;
812 * It checks whether the remote user exists or not
813 * if exits returns user object else null
817 * @param applicationsRestClientService
819 * @throws HTTPException
821 private EPUser checkIfRemoteUserExits(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService) throws HTTPException{
822 EPUser checkRemoteUser = null;
824 checkRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
825 } catch (HTTPException e) {
826 // Some apps are returning 400 if user is not found.
827 if (e.getResponseCode() == 400) {
828 logger.debug(EELFLoggerDelegate.debugLogger,
829 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing",
831 } else if(e.getResponseCode() == 404) {
832 logger.debug(EELFLoggerDelegate.debugLogger,
833 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 404; continuing",
836 // Other response code, let it come thru.
840 return checkRemoteUser;
847 * @see org.onap.portalapp.portal.service.UserRolesService#
848 * setAppWithUserRoleStateForUser(org.onap.portalapp.portal.domain.
849 * EPUser, org.onap.portalapp.portal.transport.AppWithRolesForUser)
851 public boolean setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser) {
852 boolean result = false;
853 boolean epRequestValue = false;
855 if (newAppRolesForUser != null && newAppRolesForUser.orgUserId != null) {
856 userId = newAppRolesForUser.orgUserId.trim();
858 Long appId = newAppRolesForUser.appId;
859 List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.appRoles;
860 if (userId.length() > 0) {
861 ObjectMapper mapper = new ObjectMapper();
862 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
865 EPApp app = appsService.getApp(appId);
866 applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
868 // if centralized app
869 if (app.getCentralAuth()) {
870 // We should add If user does not exist in remote application
871 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
872 EPUser remoteAppUser = null;
873 remoteAppUser = checkIfRemoteUserExits(userId, app, applicationsRestClientService);
875 if (remoteAppUser == null) {
876 addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService,
877 applicationsRestClientService);
881 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
882 applicationsRestClientService, appId, userId);
883 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
884 userRolesInLocalApp);
885 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
886 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
887 // Apply changes in external Access system
888 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList,
891 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal");
893 // In case if portal is not centralized then follow existing approach
894 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
895 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
896 applicationsRestClientService, appId, userId);
897 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
898 userRolesInLocalApp);
899 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal");
901 EPUser remoteAppUser = null;
902 if(!app.getCentralAuth() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)){
904 remoteAppUser = checkIfRemoteUserExits(userId, app, applicationsRestClientService);
906 if (remoteAppUser == null) {
907 remoteAppUser = addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService, applicationsRestClientService);
909 if (remoteAppUser != null) {
910 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
911 applicationsRestClientService, appId, userId);
912 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
913 userRolesInRemoteApp);
914 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null);
916 // If no roles remain, request app to set user inactive.
917 if (userRolesInRemoteApp.size() == 0) {
918 logger.debug(EELFLoggerDelegate.debugLogger,
919 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
921 remoteAppUser.setActive(false);
922 postUserToRemoteApp(userId, user, app, applicationsRestClientService);
927 } catch (Exception e) {
928 String message = String.format(
929 "Failed to create user or update user roles for User %s, AppId %s",
930 userId, Long.toString(appId));
931 logger.error(EELFLoggerDelegate.errorLogger, message, e);
939 * It adds user roles in External system and also make data consistent in both local and in External System
943 * @param roleInAppUser Contains list of active roles
945 @SuppressWarnings("unchecked")
946 private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser, boolean isPortalRequest) throws Exception
949 // check if user exists
950 final Map<String, String> userParams = new HashMap<>();
951 userParams.put("orgUserIdValue", orgUserId);
952 List<EPUser> userInfo = checkIfUserExists(userParams);
953 if (userInfo.isEmpty()) {
954 createLocalUserIfNecessary(orgUserId);
957 if (EPCommonSystemProperties
958 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
960 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
962 ObjectMapper mapper = new ObjectMapper();
963 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
964 HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
965 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles");
966 ResponseEntity<String> getResponse = template
967 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
968 + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class);
969 if (getResponse.getStatusCode().value() == 200) {
970 logger.debug(EELFLoggerDelegate.debugLogger, "updateUserRolesInExternalSystem: Finished GET user roles from external system and received user roles {}",
971 getResponse.getBody());
974 logger.error(EELFLoggerDelegate.errorLogger, "updateUserRolesInExternalSystem: Failed GET user roles from external system and received user roles {}",getResponse.getBody() );
975 EPLogUtil.logExternalAuthAccessAlarm(logger, getResponse.getStatusCode());
977 List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
978 String res = getResponse.getBody();
979 JSONObject jsonObj = null;
980 JSONArray extRoles = null;
981 if (!res.equals("{}")) {
982 jsonObj = new JSONObject(res);
983 extRoles = jsonObj.getJSONArray("role");
985 ExternalAccessUserRoleDetail userRoleDetail = null;
986 if (extRoles != null) {
987 for (int i = 0; i < extRoles.length(); i++) {
988 if (extRoles.getJSONObject(i).getString("name").startsWith(app.getNameSpace() + ".")
989 && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".admin")
990 && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".owner")) {
991 ObjectMapper descMapper = new ObjectMapper();
992 if (extRoles.getJSONObject(i).has("description") && EcompPortalUtils.isJSONValid(extRoles.getJSONObject(i).getString("description"))) {
993 ExternalRoleDescription desc = descMapper.readValue(
994 extRoles.getJSONObject(i).getString("description"), ExternalRoleDescription.class);
995 userRoleDetail = new ExternalAccessUserRoleDetail(
996 extRoles.getJSONObject(i).getString("name"), desc);
997 userRoleDetailList.add(userRoleDetail);
999 userRoleDetail = new ExternalAccessUserRoleDetail(
1000 extRoles.getJSONObject(i).getString("name"), null);
1001 userRoleDetailList.add(userRoleDetail);
1008 List<ExternalAccessUserRoleDetail> userRoleListMatchingInExtAuthAndLocal = CheckIfRoleAreMatchingInUserRoleDetailList(userRoleDetailList,app);
1010 // If request coming from portal not from external role approval system then we have to check if user already
1011 // have account admin or system admin as GUI will not send these roles
1012 if (!isPortalRequest) {
1013 final Map<String, String> loginIdParams = new HashMap<>();
1014 loginIdParams.put("orgUserIdValue", orgUserId);
1015 EPUser user = (EPUser) dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null).get(0);
1016 final Map<String, Long> params = new HashMap<>();
1017 params.put("appId", app.getId());
1018 params.put("userId", user.getId());
1019 List<EcompUserAppRoles> userAppList = dataAccessService.executeNamedQuery("getUserAppExistingRoles",
1021 if (!roleInAppUser.isEmpty()) {
1022 for (EcompUserAppRoles userApp : userAppList) {
1023 if (userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)
1024 || userApp.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
1025 RoleInAppForUser addSpecialRole = new RoleInAppForUser();
1026 addSpecialRole.setIsApplied(true);
1027 addSpecialRole.setRoleId(userApp.getRoleId());
1028 addSpecialRole.setRoleName(userApp.getRoleName());
1029 roleInAppUser.add(addSpecialRole);
1034 List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct()
1035 .collect(Collectors.toList());
1036 final Map<String, RoleInAppForUser> currentUserRolesToUpdate = new HashMap<>();
1037 for (RoleInAppForUser roleInAppUserNew : roleInAppUserNonDupls) {
1038 currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), roleInAppUserNew);
1040 final Map<String, ExternalAccessUserRoleDetail> currentUserRolesInExternalSystem = new HashMap<>();
1041 for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleListMatchingInExtAuthAndLocal) {
1042 currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole);
1044 // Check if user roles does not exists in local but still there in External Central Auth System delete them all
1045 for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
1046 if (!(currentUserRolesToUpdate
1047 .containsKey(userRole.getName().substring(app.getNameSpace().length() + 1)))) {
1048 HttpEntity<String> entity = new HttpEntity<>(headers);
1049 logger.debug(EELFLoggerDelegate.debugLogger,
1050 "updateUserRolesInExternalSystem: Connecting to external system to DELETE user role {}",
1051 userRole.getName());
1052 ResponseEntity<String> deleteResponse = template.exchange(
1053 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1054 + "userRole/" + name + "/" + userRole.getName(),
1055 HttpMethod.DELETE, entity, String.class);
1056 logger.debug(EELFLoggerDelegate.debugLogger,
1057 "updateUserRolesInExternalSystem: Finished DELETE operation in external system for user role {} and the response is {}",
1058 userRole.getName(), deleteResponse.getBody());
1061 // Check if user roles does not exists in External Central Auth System add them all
1062 for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) {
1063 if (!(currentUserRolesInExternalSystem
1064 .containsKey(app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")))) {
1065 ExternalAccessUser extUser = new ExternalAccessUser(name,
1066 app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1067 String formattedUserRole = mapper.writeValueAsString(extUser);
1068 HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers);
1069 logger.debug(EELFLoggerDelegate.debugLogger, "updateUserRolesInExternalSystem: Connecting to external system for user {} and POST {}",
1070 name , addUserRole.getRoleName());
1071 ResponseEntity<String> addResponse = template
1072 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1073 + "userRole", HttpMethod.POST, entity, String.class);
1074 logger.debug(EELFLoggerDelegate.debugLogger,
1075 "updateUserRolesInExternalSystem: Finished adding user role in external system {} and added user role {}",
1076 addResponse.getBody(), addUserRole.getRoleName());
1077 if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 404) {
1078 logger.debug(EELFLoggerDelegate.debugLogger,
1079 "Finished POST operation in external system but unable to save user role", addResponse.getBody(),
1080 addUserRole.getRoleName());
1081 throw new Exception(addResponse.getBody());
1085 } catch (Exception e) {
1086 logger.error(EELFLoggerDelegate.errorLogger, "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}", app.getId(), e);
1087 EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
1093 private List<ExternalAccessUserRoleDetail> CheckIfRoleAreMatchingInUserRoleDetailList(
1094 List<ExternalAccessUserRoleDetail> userRoleDetailList, EPApp app) {
1095 Map<String, EPRole> epRoleList = externalAccessRolesService.getCurrentRolesInDB(app);
1096 //Add Account Admin role for partner app to prevent conflict
1097 if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1098 EPRole role = new EPRole();
1099 role.setName(PortalConstants.ADMIN_ROLE.replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1100 epRoleList.put(role.getName(), role);
1102 userRoleDetailList.removeIf(userRoleDetail -> !epRoleList.containsKey(userRoleDetail.getName().substring(app.getNameSpace().length()+1)));
1103 return userRoleDetailList;
1110 * @param applicationsRestClientService
1111 * @param searchService
1115 protected void createNewUserOnRemoteApp(String userId, EPApp app,
1116 ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
1117 ObjectMapper mapper, boolean postOpenSource) throws Exception {
1120 EPUser client = searchService.searchUserByUserId(userId);
1122 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1124 if (client == null) {
1125 String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook.";
1126 logger.error(EELFLoggerDelegate.errorLogger, msg);
1127 throw new Exception(msg);
1130 client.setLoginId(userId);
1131 client.setActive(true);
1133 String userInString = null;
1134 userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
1135 logger.debug(EELFLoggerDelegate.debugLogger,
1136 "about to post new client to remote application, users json = " + userInString);
1137 applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user", userId));
1141 @SuppressWarnings("unchecked")
1142 protected void applyChangesToAppRolesRequest(Long appId, Long userId, String updateStatus, EPUserAppRolesRequest epUserAppRolesRequest) {
1143 final Map<String, Long> epRequestParams = new HashMap<>();
1145 EPUserAppRolesRequest epAppRolesRequestData = epUserAppRolesRequest;
1146 epAppRolesRequestData.setUpdatedDate(new Date());
1147 epAppRolesRequestData.setRequestStatus(updateStatus);
1148 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1149 addiotonalUpdateParam.put("userId", userId);
1150 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1151 epRequestParams.put("reqId", epUserAppRolesRequest.getId());
1152 List<EPUserAppRolesRequestDetail> epUserAppRolessDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1153 epUserAppRolessDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1154 epRequestParams, null);
1155 if (epUserAppRolessDetailList.size() > 0) {
1156 for (EPUserAppRolesRequestDetail epRequestUpdateData : epUserAppRolessDetailList) {
1157 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateData;
1158 epAppRoleDetailData.setReqType(updateStatus);
1159 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1160 HashMap<String, Long> updateDetailsParam = new HashMap<String, Long>();
1161 addiotonalUpdateParam.put("reqId", epUserAppRolesRequest.getId());
1162 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParam);
1165 logger.debug(EELFLoggerDelegate.debugLogger, "The request is set to complete");
1167 } catch (Exception e) {
1168 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToAppRolesRequest failed", e);
1172 @SuppressWarnings("unchecked")
1173 public void applyChangesToUserAppRolesForMyLoginsRequest(EPUser user, Long appId) {
1174 final Map<String, Long> params = new HashMap<>();
1175 final Map<String, Long> epDetailParams = new HashMap<>();
1176 List<EPUserAppRolesRequest> epRequestIdVal = new ArrayList<EPUserAppRolesRequest>();
1177 params.put("appId", appId);
1178 params.put("userId", user.getId());
1180 epRequestIdVal = (List<EPUserAppRolesRequest>) dataAccessService
1181 .executeNamedQuery("userAppRolesRequestList", params, null);
1182 if (epRequestIdVal.size() > 0) {
1183 EPUserAppRolesRequest epAppRolesRequestData = epRequestIdVal.get(0);
1184 epAppRolesRequestData.setUpdatedDate(new Date());
1185 epAppRolesRequestData.setRequestStatus("O");
1186 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1187 addiotonalUpdateParam.put("userId", user.getId());
1188 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1189 epDetailParams.put("reqId", epAppRolesRequestData.getId());
1190 List<EPUserAppRolesRequestDetail> epUserAppRolesDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1191 epUserAppRolesDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1192 epDetailParams, null);
1193 if (epUserAppRolesDetailList.size() > 0) {
1194 for (EPUserAppRolesRequestDetail epRequestUpdateList : epUserAppRolesDetailList) {
1195 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateList;
1196 epAppRoleDetailData.setReqType("O");
1197 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1198 HashMap<String, Long> updateDetailsParams = new HashMap<String, Long>();
1199 addiotonalUpdateParam.put("reqId", epAppRolesRequestData.getId());
1200 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParams);
1202 logger.debug(EELFLoggerDelegate.debugLogger, "User App roles request from User Page is overridden");
1206 } catch (Exception e) {
1207 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e);
1212 * Pushes specified user details to the specified remote app.
1215 * OrgUserId identifying user at remote app in REST endpoint path
1217 * User details to be pushed
1220 * @param applicationsRestClientService
1221 * @throws HTTPException
1223 protected void postUserToRemoteApp(String userId, EPUser user, EPApp app,
1224 ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
1226 getUser(userId, app, applicationsRestClientService);
1231 * It returns user details for single org user id
1235 * if user exists it returns list of user details otherwise empty value
1237 @SuppressWarnings("unchecked")
1238 private List<EPUser> checkIfUserExists(Map<String, String> userParams){
1239 return (List<EPUser>)dataAccessService.executeNamedQuery("epUserAppId", userParams, null);
1243 * It checks whether the new user is valid or not otherwise throws exception
1248 * Checks if user is valid and returns message otherwise throws exception
1251 private String validateNewUser(String orgUserId, EPApp app) throws Exception {
1252 EPUser epUser = searchService.searchUserByUserId(orgUserId);
1253 if (epUser == null) {
1254 throw new Exception("User does not exist");
1255 } else if (!epUser.getOrgUserId().equals(orgUserId)) {
1256 throw new Exception("User does not exist");
1257 } else if (app == null) {
1258 throw new Exception("Application does not exist");
1260 return "Saved Successfully";
1264 * Checks if the fields exists or not
1267 * contains user information
1271 * throws exception if the field is not valid
1273 private void validateExternalRequestFields(List<EPUser> userList, EPApp app) throws Exception{
1274 if (userList.size() == 0 || userList.isEmpty() ) {
1275 throw new Exception("User does not exist");
1276 } else if(app == null) {
1277 throw new Exception("Application does not exist");
1278 } else if(!app.getEnabled() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1279 throw new Exception(app.getMlAppName()+" application is unavailable");
1283 @SuppressWarnings("unchecked")
1284 public ExternalRequestFieldsValidator setExternalRequestUserAppRole(ExternalSystemUser newAppRolesForUser, String reqType) {
1285 boolean result = false;
1286 boolean externalSystemRequest = true;
1287 final Map<String, Long> params = new HashMap<>();
1288 final Map<String, String> userParams = new HashMap<>();
1289 List<EPUser> userInfo = null;
1290 EPUser userId = null;
1291 List<EPUserAppRolesRequest> epRequestId = null;
1292 String orgUserId = "";
1293 String updateStatus = "";
1294 String reqMessage = "";
1296 if (newAppRolesForUser != null && newAppRolesForUser.getLoginId() != null) {
1297 orgUserId = newAppRolesForUser.getLoginId().trim();
1299 String appName = newAppRolesForUser.getApplicationName();
1300 String logMessage = ("DELETE").equals(reqType) ? "Deleting": "Assigning/Updating" ;
1301 if (orgUserId.length() > 0) {
1302 ObjectMapper mapper = new ObjectMapper();
1303 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1304 int epRequestIdSize = 0;
1306 app = appsService.getAppDetail(appName);
1307 userParams.put("orgUserIdValue", orgUserId);
1308 userInfo = checkIfUserExists(userParams);
1309 reqMessage = "Updated Successfully";
1310 if (!reqType.equals("DELETE") && (userInfo.size() == 0 || userInfo.isEmpty())) {
1311 reqMessage = validateNewUser(orgUserId, app);
1313 if (userInfo.size() != 0 || !userInfo.isEmpty()) {
1314 validateExternalRequestFields(userInfo, app);
1315 userId = userInfo.get(0);
1316 params.put("appId", app.getId());
1317 params.put("userId", userId.getId());
1318 epRequestId = (List<EPUserAppRolesRequest>) dataAccessService
1319 .executeNamedQuery("userAppRolesRequestList", params, null);
1320 epRequestIdSize = epRequestId.size();
1323 //If Non-Centralized app make sure you sync app roles before assigning to user
1324 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !app.getCentralAuth()) {
1325 logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Starting GET roles for app {}",app.getId());
1326 EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, app.getId(), "/roles");
1327 logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Finshed GET roles for app {} and payload {}",app.getId(), appRoles);
1328 if (appRoles.length > 0) {
1329 syncAppRoles(sessionFactory, app.getId(), appRoles);
1332 List<RoleInAppForUser> roleInAppForUserList = roleInAppForUserList(newAppRolesForUser.getRoles(),
1333 app.getId(), app.getMlAppName());
1334 List<EcompUserAppRoles> userRoleList = null;
1335 if(!userInfo.isEmpty()){
1336 final Map<String, Long> appParams = new HashMap<>();
1337 appParams.put("userId", userId.getId());
1338 appParams.put("appId", app.getId());
1339 userRoleList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", appParams, null);
1341 // Check if list contains just account admin role
1342 boolean checkIfAdminRoleExists = false;
1343 if (reqType.equals("DELETE") && userRoleList!=null) {
1344 checkIfAdminRoleExists = userRoleList.stream()
1345 .anyMatch(userRole -> userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1347 checkIfAdminRoleExists = roleInAppForUserList.stream()
1348 .anyMatch(roleList -> roleList.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1350 // if Centralized app
1351 if (app.getCentralAuth()) {
1352 // We should add If user does not exist in remote application
1354 // If adding just account admin role dont make remote application user call
1355 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !(checkIfAdminRoleExists
1356 && reqType.equals("DELETE")) && roleInAppForUserList.size() > 1) {
1357 EPUser remoteAppUser = null;
1358 remoteAppUser = checkIfRemoteUserExits(orgUserId, app,
1359 applicationsRestClientService);
1360 if (remoteAppUser == null) {
1361 addRemoteUser(roleInAppForUserList, orgUserId, app, mapper, searchService,
1362 applicationsRestClientService);
1363 reqMessage = "Saved Successfully";
1366 } catch (Exception e) {
1367 reqMessage = e.getMessage();
1368 logger.error(EELFLoggerDelegate.errorLogger, "setExternalRequestUserAppRole: Failed to added remote user", e);
1369 throw new Exception(reqMessage);
1371 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1372 applicationsRestClientService, app.getId(), orgUserId);
1373 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1374 userRolesInLocalApp);
1375 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1376 if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1377 // Apply changes in external Access system
1378 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, externalSystemRequest);
1380 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
1381 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1382 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType);
1384 // If local application is not centralized
1385 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1386 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1387 applicationsRestClientService, app.getId(), orgUserId);
1388 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1389 userRolesInLocalApp);
1390 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType);
1391 } else {// remote app
1392 // If adding just account admin role don't do remote application user call
1393 if(!((roleInAppForUserList.size() == 1 || reqType.equals("DELETE")) && checkIfAdminRoleExists)){
1394 EPUser remoteAppUser = null;
1395 remoteAppUser = checkIfRemoteUserExits(orgUserId, app, applicationsRestClientService);
1396 if (remoteAppUser == null) {
1397 remoteAppUser = addRemoteUser(roleInAppForUserList, orgUserId, app, mapper, searchService, applicationsRestClientService);
1398 reqMessage = "Saved Successfully";
1400 if (remoteAppUser != null) {
1401 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList,
1402 mapper, applicationsRestClientService, app.getId(), orgUserId);
1404 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId,
1405 app.getId(), userRolesInRemoteApp);
1406 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}",
1407 logMessage, newAppRolesForUser.getApplicationName(),
1408 newAppRolesForUser.getLoginId());
1409 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1411 // If no roles remain, request app to set user inactive.
1412 /*if (userRolesInRemoteApp.size() == 0) {
1413 logger.debug(EELFLoggerDelegate.debugLogger,
1414 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
1416 //TODO Need to fix the logged in user is not set to inactive
1417 remoteAppUser.setActive(false);
1418 postUserToRemoteApp(orgUserId, user, app, applicationsRestClientService);
1422 // Here we are adding only we have single account admin in roleInAppForUserList and this should not add in remote
1423 if(!(reqType.equals("DELETE")) && userInfo.isEmpty()){
1424 reqMessage = "Saved Successfully";
1426 Set<EcompRole> userRolesInRemoteApp = constructUsersEcompRoles(roleInAppForUserList);
1428 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1429 userRolesInRemoteApp);
1430 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}",
1431 logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1432 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1436 reqMessage = "Failed to save the user app role(s)";
1438 if (epRequestIdSize > 0 && !userInfo.isEmpty()) {
1440 applyChangesToAppRolesRequest(app.getId(), userId.getId(), updateStatus, epRequestId.get(0));
1443 } catch (Exception e) {
1444 String message = String.format("setExternalRequestUserAppRole: Failed to create user or update user roles for User %s, AppId %s",
1445 orgUserId, appName);
1446 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1448 reqMessage = e.getMessage();
1449 if(epRequestIdSize > 0 && userInfo!=null && !userInfo.isEmpty()){
1451 applyChangesToAppRolesRequest(app.getId(), userId.getId(),
1452 updateStatus, epRequestId.get(0));
1457 return new ExternalRequestFieldsValidator(result, reqMessage);
1462 * @param roleInAppForUserList
1464 * @param applicationsRestClientService
1467 * @return Set<EcompRole>
1468 * @throws JsonProcessingException
1469 * @throws HTTPException
1471 private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
1472 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
1473 throws JsonProcessingException, HTTPException {
1474 Set<EcompRole> updatedUserRoles = constructUsersEcompRoles(roleInAppForUserList);
1475 return updatedUserRoles;
1479 * It constructs and returns list of user app roles when the external API role approval system calls
1482 * @param roleInAppForUserList
1484 * @return list of user app roles
1486 * throws exceptions if role id does not exits
1488 private List<RoleInAppForUser> roleInAppForUserList(List<ExternalSystemRoleApproval> roleInAppForUserList,
1489 Long appId, String appName) throws Exception {
1490 List<RoleInAppForUser> existingUserRoles = new ArrayList<RoleInAppForUser>();
1491 EPRole existingAppRole = null;
1492 for (ExternalSystemRoleApproval roleInAppForUser : roleInAppForUserList) {
1493 RoleInAppForUser ecompRole = new RoleInAppForUser();
1494 existingAppRole = epRoleService.getAppRole(roleInAppForUser.getRoleName(), appId);
1495 if (existingAppRole == null) {
1496 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1497 roleInAppForUserList);
1498 throw new Exception("'" +roleInAppForUser.getRoleName() + "'" +" role does not exist for " + appName + " application");
1500 if (!existingAppRole.getActive()) {
1501 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1502 roleInAppForUserList);
1503 throw new Exception(roleInAppForUser.getRoleName() + " role is unavailable for "+ appName + " application");
1505 ecompRole.roleId = (appId == 1 || roleInAppForUser.getRoleName().equals(PortalConstants.ADMIN_ROLE)) ? existingAppRole.getId() : existingAppRole.getAppRoleId();
1506 ecompRole.roleName = roleInAppForUser.getRoleName();
1507 ecompRole.isApplied = true;
1508 existingUserRoles.add(ecompRole);
1511 return existingUserRoles;
1520 * @param applicationsRestClientService
1522 * @throws HTTPException
1524 protected EPUser getUserFromApp(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1525 throws HTTPException {
1527 if (app.getId() == PortalConstants.PORTAL_APP_ID) {
1528 // Map<String,String> params = new HashMap<String,String>();
1529 // params.put("sbcid",userId);
1530 @SuppressWarnings("unchecked")
1531 List<EPUser> userList = (List<EPUser>) dataAccessService
1532 .executeQuery("from EPUser where orgUserId='" + userId + "'", null);
1533 if (userList != null && !userList.isEmpty())
1534 return userList.get(0);
1540 return getUser(userId, app, applicationsRestClientService);
1543 protected EPUser getUser(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1544 throws HTTPException {
1545 return applicationsRestClientService.get(EPUser.class, app.getId(), String.format("/user/%s", userId), true);
1549 protected boolean isAppUpgradeVersion(EPApp app){
1554 public ExternalSystemAccess getExternalRequestAccess(){
1555 ExternalSystemAccess res = null;
1557 res = new ExternalSystemAccess(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE,
1558 Boolean.parseBoolean(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE)));
1559 } catch (Exception e) {
1560 logger.error(EELFLoggerDelegate.errorLogger, "getExternalRequestAccess failed" + e.getMessage());
1568 * @see org.onap.portalapp.portal.service.UserRolesService#
1569 * getAppRolesForUser(java.lang.Long, java.lang.String)
1571 @SuppressWarnings("unchecked")
1572 public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId, Boolean extRequestValue) {
1574 List<RoleInAppForUser> rolesInAppForUser = null;
1575 EPApp app = appsService.getApp(appId);
1577 // for ecomp portal app, no need to make a remote call
1578 List<Role> roleList = new ArrayList<>();
1579 if (appId == PortalConstants.PORTAL_APP_ID) {
1580 if(app.getCentralAuth()){
1581 List<CentralV2Role> cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey());
1582 for(CentralV2Role cenRole : cenRoleList){
1583 Role role = new Role();
1584 role.setActive(cenRole.isActive());
1585 role.setId(cenRole.getId());
1586 role.setName(cenRole.getName());
1587 role.setPriority(cenRole.getPriority());
1591 roleList = roleService.getAvailableRoles(userId);
1593 List<Role> activeRoleList = new ArrayList<Role>();
1594 for(Role role: roleList) {
1595 if(role.getActive()) {
1596 if(role.getId() != 1){ // prevent portal admin from being added
1597 activeRoleList.add(role);
1598 } else if(extRequestValue){
1599 activeRoleList.add(role);
1604 EPUser localUser = getUserFromApp(userId, app, applicationsRestClientService);
1605 // If localUser does not exists return roles
1606 Set<EPRole> roleSet = null;
1607 EPRole[] roleSetList = null;
1608 if(localUser != null){
1609 roleSet = localUser.getAppEPRoles(app);
1610 roleSetList = roleSet.toArray(new EPRole[0]);
1612 rolesInAppForUser = constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue);
1613 return rolesInAppForUser;
1616 EcompRole[] appRoles = null;
1617 List<EcompRole> roles = new ArrayList<>();
1618 if(app.getCentralAuth()){
1619 final Map<String, Long> appParams = new HashMap<>();
1620 appParams.put("appId", app.getId());
1621 List<EPRole> applicationRoles = dataAccessService.executeNamedQuery("getActiveRolesOfApplication", appParams, null);
1622 for(EPRole role : applicationRoles){
1623 EcompRole ecompRole = new EcompRole();
1624 ecompRole.setId(role.getId());
1625 ecompRole.setName(role.getName());
1626 roles.add(ecompRole);
1628 appRoles = roles.toArray(new EcompRole[roles.size()]);
1630 appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
1632 // Test this error case, for generating an internal Ecomp Portal
1634 // EcompRole[] appRoles = null;
1635 // If there is an exception in the rest client api, then null will
1637 if (appRoles != null) {
1638 if(!app.getCentralAuth()) {
1639 syncAppRoles(sessionFactory, appId, appRoles);
1641 EcompRole[] userAppRoles = null;
1644 if(app.getCentralAuth()){
1645 final Map<String, String> params = new HashMap<>();
1646 final Map<String, Long> userParams = new HashMap<>();
1647 params.put("orgUserIdValue", userId);
1648 List<EPUser> user = dataAccessService.executeNamedQuery("epUserAppId", params, null);
1649 userParams.put("appId", app.getId());
1650 userParams.put("userId", user.get(0).getId());
1651 List<EPUserAppCurrentRoles> userAppsRolesList = dataAccessService.executeNamedQuery("getUserAppCurrentRoles", userParams, null);
1652 List<EcompRole> setUserRoles = new ArrayList<>();
1653 for(EPUserAppCurrentRoles role : userAppsRolesList){
1654 EcompRole ecompRole = new EcompRole();
1655 ecompRole.setId(role.getRoleId());
1656 ecompRole.setName(role.getRoleName());
1657 setUserRoles.add(ecompRole);
1659 userAppRoles = setUserRoles.toArray(new EcompRole[setUserRoles.size()]);
1660 rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
1661 return rolesInAppForUser;
1663 userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
1664 String.format("/user/%s/roles", userId));
1666 } catch (HTTPException e) {
1667 // Some apps are returning 400 if user is not found.
1668 if (e.getResponseCode() == 400) {
1669 logger.debug(EELFLoggerDelegate.debugLogger,
1670 "getAppRolesForUser caught exception with response code 400; continuing", e);
1672 // Other response code, let it come thru.
1676 if (userAppRoles == null) {
1677 if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
1678 EcompPortalUtils.setExternalAppResponseCode(200);
1679 String message = String.format(
1680 "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
1681 + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
1682 + "Overriding to 200 until framework SDK returns a useful response.",
1683 Long.toString(appId), userId);
1684 logger.warn(EELFLoggerDelegate.applicationLogger, message);
1688 HashMap<Long, EcompRole> appRolesActiveMap =hashMapFromEcompRoles(appRoles);
1689 ArrayList<EcompRole> activeRoles = new ArrayList<EcompRole>();
1690 if(userAppRoles != null){
1691 for (int i = 0; i < userAppRoles.length; i++) {
1692 if (appRolesActiveMap.containsKey(userAppRoles[i].getId())) {
1693 EcompRole role = new EcompRole();
1694 role.setId(userAppRoles[i].getId());
1695 role.setName(userAppRoles[i].getName());
1696 activeRoles.add(role);
1700 EcompRole[] userAppRolesActive = activeRoles.toArray(new EcompRole[activeRoles.size()]);
1702 // If the remote application isn't down we MUST sync user
1703 // roles here in case we have this user here!
1704 syncUserRoles(sessionFactory, userId, appId, userAppRolesActive, extRequestValue, null);
1705 } catch (Exception e) {
1706 // TODO: we may need to check if user exists, maybe remote
1708 String message = String.format(
1709 "getAppRolesForUser: user %s does not exist in remote application %s", userId,
1710 Long.toString(appId));
1711 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1712 userAppRoles = new EcompRole[0];
1714 rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
1716 } catch (Exception e) {
1717 String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
1718 Long.toString(appId));
1719 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1721 return rolesInAppForUser;
1725 private boolean postUserRolesToMylogins(AppWithRolesForUser userAppRolesData,
1726 ApplicationsRestClientService applicationsRestClientService, Long appId, Long userId)
1727 throws JsonProcessingException, HTTPException {
1728 boolean result = false;
1729 ObjectMapper mapper = new ObjectMapper();
1730 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1731 String userRolesAsString = mapper.writeValueAsString(userAppRolesData);
1732 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, as the endpoint is not defined yet from the Mylogins");
1733 applicationsRestClientService.post(AppWithRolesForUser.class, appId, userRolesAsString, String.format("/user/%s/myLoginroles", userId));
1737 @SuppressWarnings("unchecked")
1738 public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser userAppRolesData, EPUser user) {
1739 FieldsValidator fieldsValidator = new FieldsValidator();
1740 final Map<String, Long> params = new HashMap<>();
1741 List<EPUserAppRoles> appRole= null;
1743 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, still the endpoint is yet to be defined");
1744 boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService, userAppRolesData.appId, user.getId());
1745 logger.debug(EELFLoggerDelegate.debugLogger,"putUserAppRolesRequest: result {}", result);
1747 params.put("appId", userAppRolesData.appId);
1748 EPUserAppRolesRequest epAppRolesRequestData = new EPUserAppRolesRequest();
1749 epAppRolesRequestData.setCreatedDate(new Date());
1750 epAppRolesRequestData.setUpdatedDate(new Date());
1751 epAppRolesRequestData.setUserId(user.getId());
1752 epAppRolesRequestData.setAppId(userAppRolesData.appId);
1753 epAppRolesRequestData.setRequestStatus("P");
1754 List<RoleInAppForUser> appRoleIdList = userAppRolesData.appRoles;
1755 Set<EPUserAppRolesRequestDetail> appRoleDetails = new LinkedHashSet<EPUserAppRolesRequestDetail>();
1756 dataAccessService.saveDomainObject(epAppRolesRequestData, null);
1757 for (RoleInAppForUser userAppRoles : appRoleIdList) {
1758 Boolean isAppliedVal = userAppRoles.isApplied;
1759 params.put("appRoleId", userAppRoles.roleId);
1761 appRole = (List<EPUserAppRoles>) dataAccessService.executeNamedQuery("appRoles", params, null);
1762 if (!appRole.isEmpty()) {
1763 EPUserAppRolesRequestDetail epAppRoleDetail = new EPUserAppRolesRequestDetail();
1764 epAppRoleDetail.setReqRoleId(appRole.get(0).getRoleId());
1765 epAppRoleDetail.setReqType("P");
1766 epAppRoleDetail.setEpRequestIdData(epAppRolesRequestData);
1767 dataAccessService.saveDomainObject(epAppRoleDetail, null);
1771 epAppRolesRequestData.setEpRequestIdDetail(appRoleDetails);
1772 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1774 } catch (Exception e) {
1775 logger.error(EELFLoggerDelegate.errorLogger, "putUserAppRolesRequest failed", e);
1776 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1778 return fieldsValidator;
1781 public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(EPUser userid, String appName) {
1782 Map<String, String> params = new HashMap<>();
1783 params.put("userid", userid.getId().toString());
1784 //params.put("appid", appid);
1785 params.put("appName", appName);
1787 @SuppressWarnings("unchecked")
1788 List<EPUserAppCatalogRoles> userAppRoles = (List<EPUserAppCatalogRoles>) dataAccessService
1789 .executeNamedQuery("userAppCatalogRoles", params, null);
1790 return userAppRoles;
1793 public String updateRemoteUserProfile(String orgUserId, Long appId) {
1794 ObjectMapper mapper = new ObjectMapper();
1795 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1796 EPUser client = searchService.searchUserByUserId(orgUserId);
1797 EPUser newUser = new EPUser();
1798 newUser.setActive(client.getActive());
1799 newUser.setFirstName(client.getFirstName());
1800 newUser.setLastName(client.getLastName());
1801 newUser.setLoginId(client.getLoginId());
1802 newUser.setLoginPwd(client.getLoginPwd());
1803 newUser.setMiddleInitial(client.getMiddleInitial());
1804 newUser.setEmail(client.getEmail());
1805 newUser.setOrgUserId(client.getLoginId());
1807 String userAsString = mapper.writeValueAsString(newUser);
1808 List<EPApp> appList = appsService.getUserRemoteApps(client.getId().toString());
1809 // applicationsRestClientService.post(EPUser.class, appId,
1810 // userAsString, String.format("/user", orgUserId));
1811 for (EPApp eachApp : appList) {
1813 applicationsRestClientService.post(EPUser.class, eachApp.getId(), userAsString,
1814 String.format("/user/%s", orgUserId));
1815 } catch (Exception e) {
1816 logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId()
1817 + " in remote app. appId = " + eachApp.getId());
1820 } catch (Exception e) {
1821 logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
1832 * @see org.onap.portalapp.portal.service.UserRolesService#
1833 * getCachedAppRolesForUser(java.lang.Long, java.lang.Long)
1835 public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId) {
1836 // Find the records for this user-app combo, if any
1837 String filter = " where user_id = " + Long.toString(userId) + " and app_id = " + Long.toString(appId);
1838 @SuppressWarnings("unchecked")
1839 List<EPUserApp> roleList = dataAccessService.getList(EPUserApp.class, filter, null, null);
1840 logger.debug(EELFLoggerDelegate.debugLogger, "getCachedAppRolesForUser: list size is {}", roleList.size());
1845 * It retrieves and returns list of user app roles for local and remote applications based app id
1848 * @return list of user app roles
1849 * @throws HTTPException
1851 public List<UserApplicationRoles> getUsersFromAppEndpoint(Long appId) throws HTTPException {
1852 ArrayList<UserApplicationRoles> userApplicationRoles = new ArrayList<UserApplicationRoles>();
1854 EPApp app = appsService.getApp(appId);
1855 //If local or centralized application
1856 if (appId == PortalConstants.PORTAL_APP_ID || app.getCentralAuth()) {
1857 @SuppressWarnings("unchecked")
1858 List<EPUser> userList = (List<EPUser>) dataAccessService.executeNamedQuery("getActiveUsers", null, null);
1859 for (EPUser user : userList) {
1860 UserApplicationRoles userWithAppRoles = convertToUserApplicationRoles(appId, user, app);
1861 if (userWithAppRoles.getRoles() != null && userWithAppRoles.getRoles().size() > 0)
1862 userApplicationRoles.add(userWithAppRoles);
1868 RemoteUserWithRoles[] remoteUsers = null;
1869 String remoteUsersString = applicationsRestClientService.getIncomingJsonString(appId, "/users");
1871 remoteUsers = doGetUsers(isAppUpgradeVersion(app), remoteUsersString);
1873 userApplicationRoles = new ArrayList<UserApplicationRoles>();
1874 for (RemoteUserWithRoles remoteUser : remoteUsers) {
1875 UserApplicationRoles userWithRemoteAppRoles = convertToUserApplicationRoles(appId, remoteUser);
1876 if (userWithRemoteAppRoles.getRoles() != null && userWithRemoteAppRoles.getRoles().size() > 0) {
1877 userApplicationRoles.add(userWithRemoteAppRoles);
1879 logger.debug(EELFLoggerDelegate.debugLogger,
1880 "User " + userWithRemoteAppRoles.getOrgUserId() + " doesn't have any roles assigned to any app.");
1885 return userApplicationRoles;
1892 * @param appgetUsersFromAppEndpoint
1895 private UserApplicationRoles convertToUserApplicationRoles(Long appId, EPUser user, EPApp app) {
1896 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
1897 userWithRemoteAppRoles.setAppId(appId);
1898 userWithRemoteAppRoles.setOrgUserId(user.getOrgUserId());
1899 userWithRemoteAppRoles.setFirstName(user.getFirstName());
1900 userWithRemoteAppRoles.setLastName(user.getLastName());
1901 userWithRemoteAppRoles.setRoles(convertToRemoteRoleList(user, app));
1902 return userWithRemoteAppRoles;
1911 private List<RemoteRole> convertToRemoteRoleList(EPUser user, EPApp app) {
1912 List<RemoteRole> roleList = new ArrayList<RemoteRole>();
1913 SortedSet<EPRole> roleSet = user.getAppEPRoles(app);
1914 for (EPRole role : roleSet) {
1915 RemoteRole rRole = new RemoteRole();
1916 rRole.setId(role.getId());
1917 rRole.setName(role.getName());
1918 roleList.add(rRole);
1923 public RemoteUserWithRoles[] doGetUsers(boolean postOpenSource, String remoteUsersString) {
1925 ObjectMapper mapper = new ObjectMapper();
1927 return mapper.readValue(remoteUsersString, RemoteUserWithRoles[].class);
1928 } catch (IOException e) {
1929 logger.error(EELFLoggerDelegate.errorLogger,
1930 "doGetUsers : Failed : Unexpected property in incoming JSON",
1932 logger.error(EELFLoggerDelegate.errorLogger,
1933 "doGetUsers : Incoming JSON that caused it --> " + remoteUsersString);
1936 return new RemoteUserWithRoles[0];
1939 @SuppressWarnings("unchecked")
1940 public List<EPUserApp> getEPUserAppList(Long appId, Long userId, Long roleId) {
1941 List<EPUserApp> userRoleList = new ArrayList<EPUserApp>();
1942 final Map<String, Long> params = new HashMap<>();
1943 params.put("appId", appId);
1944 params.put("userId", userId);
1945 params.put("roleId", roleId);
1946 userRoleList = dataAccessService.executeNamedQuery("getUserRoleOnUserIdAndRoleIdAndAppId", params, null);
1947 return userRoleList;