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.portal.service.SearchService;
67 import org.onap.portalapp.externalsystemapproval.model.ExternalSystemRoleApproval;
68 import org.onap.portalapp.externalsystemapproval.model.ExternalSystemUser;
69 import org.onap.portalapp.portal.domain.EPApp;
70 import org.onap.portalapp.portal.domain.EPRole;
71 import org.onap.portalapp.portal.domain.EPUser;
72 import org.onap.portalapp.portal.domain.EPUserApp;
73 import org.onap.portalapp.portal.domain.EPUserAppCatalogRoles;
74 import org.onap.portalapp.portal.domain.EPUserAppRoles;
75 import org.onap.portalapp.portal.domain.EPUserAppRolesRequest;
76 import org.onap.portalapp.portal.domain.EPUserAppRolesRequestDetail;
77 import org.onap.portalapp.portal.domain.ExternalSystemAccess;
78 import org.onap.portalapp.portal.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 boolean result = false;
250 Session localSession = null;
251 Transaction transaction = null;
252 String roleActive = null;
253 final Map<String, String> userAppParams = new HashMap<>();
254 final Map<String, String> appParams = new HashMap<>();
255 HashMap<Long, EcompRole> newUserAppRolesMap = hashMapFromEcompRoles(userAppRoles);
258 localSession = sessionFactory.openSession();
259 transaction = localSession.beginTransaction();
260 @SuppressWarnings("unchecked")
261 List<EPUser> userList = localSession
262 .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + userId + "'").list();
263 if (userList.size() > 0) {
264 EPUser client = userList.get(0);
265 roleActive = ("DELETE".equals(reqType)) ? "" : " and role.active = 'Y'";
266 @SuppressWarnings("unchecked")
267 List<EPUserApp> userRoles = localSession.createQuery("from " + EPUserApp.class.getName()
268 + " where app.id=" + appId + roleActive + " and userId=" + client.getId()).list();
270 if ("DELETE".equals(reqType)) {
271 for (EPUserApp userAppRoleList : userRoles) {
272 userAppParams.put("roleName", String.valueOf(userAppRoleList.getRole().getName()));
273 userAppParams.put("appId", String.valueOf(appId));
274 appParams.put("appRoleName", userAppRoleList.getRole().getName());
275 @SuppressWarnings("unchecked")
276 List<EPRole> rolesList = (!userAppRoleList.getRole().getName().equals(PortalConstants.ADMIN_ROLE)) ? (List<EPRole>) dataAccessService.executeNamedQuery("getAppRoles", userAppParams, null) : (List<EPRole>) dataAccessService.executeNamedQuery("getPortalAppRoles", appParams, null);
277 if(rolesList.size() > 0 || !rolesList.isEmpty()){
278 checkIfRoleInactive(rolesList.get(0));
283 for (EPUserApp userRole : userRoles) {
284 if (!userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && userRole.getRoleId() != PortalConstants.SYS_ADMIN_ROLE_ID && !extRequestValue){
285 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
287 else if (extRequestValue && ("PUT".equals(reqType) || "POST".equals(reqType) || "DELETE".equals(reqType))){
288 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
290 else if (extRequestValue && !userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)){
291 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
294 Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values();
295 if (newRolesToAdd.size() > 0) {
296 EPApp app = (EPApp) localSession.get(EPApp.class, appId);
298 HashMap<Long, EPRole> rolesMap = new HashMap<Long, EPRole>();
299 if (appId.equals(PortalConstants.PORTAL_APP_ID)) { // local app
300 String appIdValue = "";
301 if(!extRequestValue){
302 appIdValue = "and id != " + PortalConstants.SYS_ADMIN_ROLE_ID;
304 @SuppressWarnings("unchecked")
305 List<EPRole> roles = localSession
306 .createQuery("from " + EPRole.class.getName() + " where appId is null " + appIdValue).list();
307 for (EPRole role : roles) {
309 rolesMap.put(role.getId(), role);
311 } else { // remote app
312 @SuppressWarnings("unchecked")
313 List<EPRole> roles = localSession
314 .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list();
315 for (EPRole role : roles) {
316 if (!extRequestValue && app.getCentralAuth()) {
317 rolesMap.put(role.getId(), role);
319 rolesMap.put(role.getAppRoleId(), role);
325 for (EcompRole userRole : newRolesToAdd) {
326 EPUserApp userApp = new EPUserApp();
327 if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName().equals(PortalConstants.ADMIN_ROLE)) {
328 role = (EPRole) localSession.get(EPRole.class, new Long(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
329 userApp.setRole(role);
330 } else if ((userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) && !extRequestValue){
332 }else if((userRole.getId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)) && app.getId().equals(PortalConstants.PORTAL_APP_ID) && !extRequestValue){
336 userApp.setRole(rolesMap.get(userRole.getId()));
339 userApp.setUserId(client.getId());
341 localSession.save(userApp);
342 localSession.flush();
345 if (appId == PortalConstants.PORTAL_APP_ID) {
347 * for local app -- hack - always make sure fn_role
348 * table's app_id is null and not 1 for primary app in
349 * this case being ecomp portal app; reason: hibernate
350 * is rightly setting this to 1 while persisting to
351 * fn_role as per the mapping but SDK role management
352 * code expects the app_id to be null as there is no
353 * concept of App_id in SDK
355 localSession.flush();
356 SQLQuery sqlQuery = localSession
357 .createSQLQuery("update fn_role set app_id = null where app_id = 1 ");
358 sqlQuery.executeUpdate();
363 transaction.commit();
365 } catch (Exception e) {
366 logger.error(EELFLoggerDelegate.errorLogger, "syncUserRoles failed", e);
367 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
368 EcompPortalUtils.rollbackTransaction(transaction,
369 "Exception occurred in syncUserRoles, Details: " + e.toString());
370 if("DELETE".equals(reqType)){
371 throw new Exception(e.getMessage());
374 if (localSession != null) {
375 localSession.close();
377 if (!result && !"DELETE".equals(reqType)) {
379 "Exception occurred in syncUserRoles while closing database session for app: '" + appId + "'.");
385 * Called when getting the list of roles for the user
388 * @param userAppRoles
389 * @return List<RoleInAppForUser>
391 protected List<RoleInAppForUser> constructRolesInAppForUserGet(EcompRole[] appRoles, EcompRole[] userAppRoles) {
392 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
394 Set<Long> userAppRolesMap = new HashSet<Long>();
395 if (userAppRoles != null) {
396 for (EcompRole ecompRole : userAppRoles) {
397 userAppRolesMap.add(ecompRole.getId());
400 logger.error(EELFLoggerDelegate.errorLogger,
401 "constructRolesInAppForUserGet has received userAppRoles list empty");
404 if (appRoles != null) {
405 for (EcompRole ecompRole : appRoles) {
406 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
407 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
408 rolesInAppForUser.add(roleForUser);
411 logger.error(EELFLoggerDelegate.errorLogger, "constructRolesInAppForUser has received appRoles list empty");
413 return rolesInAppForUser;
417 * Called when getting the list of roles for the user
420 * @param userAppRoles
421 * @param extRequestValue
422 * set to false if request is from users page otherwise true
423 * @return List<RoleInAppForUser>
425 protected List<RoleInAppForUser> constructRolesInAppForUserGet(List<Role> appRoles, EPRole[] userAppRoles, Boolean extRequestValue) {
426 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
428 Set<Long> userAppRolesMap = new HashSet<Long>();
429 if (userAppRoles != null) {
430 for (EPRole ecompRole : userAppRoles) {
431 userAppRolesMap.add(ecompRole.getId());
434 logger.error(EELFLoggerDelegate.errorLogger,
435 "constructRolesInAppForUserGet has received userAppRoles list empty.");
438 if (appRoles != null) {
439 for (Role ecompRole : appRoles) {
440 if (ecompRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && !extRequestValue)
442 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
443 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
444 rolesInAppForUser.add(roleForUser);
447 logger.error(EELFLoggerDelegate.errorLogger,
448 "constructRolesInAppForUser has received appRoles list empty.");
450 return rolesInAppForUser;
455 * copies of methods in GetAppsWithUserRoleState
457 * @param sessionFactory
462 protected void syncAppRoles(SessionFactory sessionFactory, Long appId, EcompRole[] appRoles) throws Exception {
463 logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId);
464 HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles);
465 Session localSession = null;
466 Transaction transaction = null;
469 localSession = sessionFactory.openSession();
470 transaction = localSession.beginTransaction();
471 // Attention! All roles from remote application supposed to be
473 @SuppressWarnings("unchecked")
474 List<EPRole> currentAppRoles = localSession
475 .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list();
476 List<EPRole> obsoleteRoles = new ArrayList<EPRole>();
477 for (int i = 0; i < currentAppRoles.size(); i++) {
478 EPRole oldAppRole = currentAppRoles.get(i);
479 if (oldAppRole.getAppRoleId() != null) {
480 EcompRole role = null;
481 role = newRolesMap.get(oldAppRole.getAppRoleId());
483 if (!(role.getName() == null || oldAppRole.getName().equals(role.getName()))) {
484 oldAppRole.setName(role.getName());
485 localSession.update(oldAppRole);
487 newRolesMap.remove(oldAppRole.getAppRoleId());
489 obsoleteRoles.add(oldAppRole);
492 obsoleteRoles.add(oldAppRole);
495 Collection<EcompRole> newRolesToAdd = newRolesMap.values();
496 if (obsoleteRoles.size() > 0) {
497 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: we have obsolete roles to delete");
498 for (EPRole role : obsoleteRoles) {
499 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: obsolete role: " + role.toString());
500 Long roleId = role.getId();
501 // delete obsolete roles here
502 // Must delete all records with foreign key constraints on
504 // fn_user_role, fn_role_composite, fn_role_function,
505 // fn_user_pseudo_role, fn_menu_functional_roles.
506 // And for fn_menu_functional, if no other roles for that
507 // menu item, remove the url.
509 // Delete from fn_user_role
510 @SuppressWarnings("unchecked")
511 List<EPUserApp> userRoles = localSession.createQuery(
512 "from " + EPUserApp.class.getName() + " where app.id=" + appId + " and role_id=" + roleId)
515 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: number of userRoles to delete: " + userRoles.size());
516 for (EPUserApp userRole : userRoles) {
517 logger.debug(EELFLoggerDelegate.debugLogger,
518 "syncAppRoles: about to delete userRole: " + userRole.toString());
519 localSession.delete(userRole);
520 logger.debug(EELFLoggerDelegate.debugLogger,
521 "syncAppRoles: finished deleting userRole: " + userRole.toString());
524 // Delete from fn_menu_functional_roles
525 @SuppressWarnings("unchecked")
526 List<FunctionalMenuRole> funcMenuRoles = localSession
527 .createQuery("from " + FunctionalMenuRole.class.getName() + " where roleId=" + roleId)
529 int numMenuRoles = funcMenuRoles.size();
530 logger.debug(EELFLoggerDelegate.debugLogger,
531 "syncAppRoles: number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles);
532 for (FunctionalMenuRole funcMenuRole : funcMenuRoles) {
533 Long menuId = funcMenuRole.menuId;
534 // If this is the only role for this menu item, then the
535 // app and roles will be gone,
536 // so must null out the url too, to be consistent
537 @SuppressWarnings("unchecked")
538 List<FunctionalMenuRole> funcMenuRoles2 = localSession
539 .createQuery("from " + FunctionalMenuRole.class.getName() + " where menuId=" + menuId)
541 int numMenuRoles2 = funcMenuRoles2.size();
542 logger.debug(EELFLoggerDelegate.debugLogger,
543 "syncAppRoles: number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2);
544 localSession.delete(funcMenuRole);
545 if (numMenuRoles2 == 1) {
546 // If this is the only role for this menu item, then
547 // the app and roles will be gone,
548 // so must null out the url too, to be consistent
549 logger.debug(EELFLoggerDelegate.debugLogger,
550 "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url");
551 @SuppressWarnings("unchecked")
552 List<FunctionalMenuItem> funcMenuItems = localSession
554 "from " + FunctionalMenuItem.class.getName() + " where menuId=" + menuId)
556 if (funcMenuItems.size() > 0) {
557 logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item");
558 FunctionalMenuItem funcMenuItem = funcMenuItems.get(0);
559 funcMenuItem.url = "";
560 localSession.update(funcMenuItem);
564 boolean isPortalRequest = true;
565 externalAccessRolesService.deleteRoleDependencyRecords(localSession, roleId, appId, isPortalRequest);
566 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to delete the role: " + role.toString());
567 localSession.delete(role);
568 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: deleted the role");
571 for (EcompRole role : newRolesToAdd) {
572 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to add missing role: " + role.toString());
573 EPRole newRole = new EPRole();
574 // Attention! All roles from remote application supposed to be
576 newRole.setActive(true);
577 newRole.setName(role.getName());
578 newRole.setAppId(appId);
579 newRole.setAppRoleId(role.getId());
580 localSession.save(newRole);
582 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to commit the transaction");
583 transaction.commit();
584 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: committed the transaction");
585 } catch (Exception e) {
586 logger.error(EELFLoggerDelegate.errorLogger, "syncAppRoles failed", e);
587 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
588 EcompPortalUtils.rollbackTransaction(transaction,
589 "Exception occurred in syncAppRoles, Details: " + e.toString());
590 throw new Exception(e);
592 localSession.close();
601 * Called when updating the list of roles for the user
605 * @param userRolesInRemoteApp
606 * @return RolesInAppForUser
608 protected RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId,
609 Set<EcompRole> userRolesInRemoteApp) {
610 RolesInAppForUser result;
611 result = new RolesInAppForUser();
612 result.appId = appId;
613 result.orgUserId = userId;
614 for (EcompRole role : userRolesInRemoteApp) {
615 RoleInAppForUser roleInAppForUser = new RoleInAppForUser();
616 roleInAppForUser.roleId = role.getId();
617 roleInAppForUser.roleName = role.getName();
618 roleInAppForUser.isApplied = new Boolean(true);
619 result.roles.add(roleInAppForUser);
626 * @param roleInAppForUserList
629 protected boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) {
630 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
631 if (roleInAppForUser.isApplied.booleanValue()) {
639 * Builds JSON and posts it to a remote application to update user roles.
641 * @param roleInAppForUserList
643 * @param applicationsRestClientService
646 * @return Set of roles as sent; NOT the response from the app.
647 * @throws JsonProcessingException
648 * @throws HTTPException
650 protected Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
651 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
652 throws JsonProcessingException, HTTPException {
653 Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList);
654 Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList);
655 String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote);
656 applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString,
657 String.format("/user/%s/roles", userId));
658 // TODO: We should add code that verifies that the post operation did
659 // succeed. Because the SDK may still return 200 OK with an html page
660 // even when it fails!
661 return updateUserRolesInEcomp;
666 * @param roleInAppForUserList
667 * @return Set<EcompRole>
669 protected Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) {
670 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
671 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
672 if (roleInAppForUser.isApplied) {
673 EcompRole ecompRole = new EcompRole();
674 ecompRole.setId(roleInAppForUser.roleId);
675 ecompRole.setName(roleInAppForUser.roleName);
676 existingUserRoles.add(ecompRole);
679 return existingUserRoles;
683 * Constructs user app roles excluding Account Administrator role
685 * @param roleInAppForUserList
687 * List of roles with Role name, Role Id
689 protected Set<EcompRole> constructUsersRemoteAppRoles(List<RoleInAppForUser> roleInAppForUserList) {
690 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
691 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
692 if (roleInAppForUser.isApplied && !roleInAppForUser.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
693 EcompRole ecompRole = new EcompRole();
694 ecompRole.setId(roleInAppForUser.roleId);
695 ecompRole.setName(roleInAppForUser.roleName);
696 existingUserRoles.add(ecompRole);
699 return existingUserRoles;
703 * This is for a single app
705 * @param rolesInAppForUser
706 * @param externalSystemRequest
707 * set to false if requests from Users page otherwise true
708 * @return true on success, false otherwise
710 protected boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser, boolean externalSystemRequest, String reqType) throws Exception {
711 boolean result = false;
712 String userId = rolesInAppForUser.orgUserId;
713 Long appId = rolesInAppForUser.appId;
714 synchronized (syncRests) {
715 if (rolesInAppForUser != null) {
716 createLocalUserIfNecessary(userId);
719 if (rolesInAppForUser != null) {
720 EcompRole[] userAppRoles = new EcompRole[rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size()];
721 for (int i = 0; i < rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size(); i++) {
722 RoleInAppForUser roleInAppForUser = rolesInAppForUser.roles.get(i);
723 EcompRole role = new EcompRole();
724 role.setId(roleInAppForUser.roleId);
725 role.setName(roleInAppForUser.roleName);
726 userAppRoles[i] = role;
729 syncUserRoles(sessionFactory, userId, appId, userAppRoles, externalSystemRequest, reqType);
731 } catch (Exception e) {
732 logger.error(EELFLoggerDelegate.errorLogger,
733 "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for orgUserId " + userId, e);
734 if("DELETE".equals(reqType)){
735 throw new Exception(e.getMessage());
747 * @return UserApplicationRoles
749 protected UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) {
750 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
751 userWithRemoteAppRoles.setAppId(appId);
752 userWithRemoteAppRoles.setOrgUserId(remoteUser.getOrgUserId());
753 userWithRemoteAppRoles.setFirstName(remoteUser.getFirstName());
754 userWithRemoteAppRoles.setLastName(remoteUser.getLastName());
755 userWithRemoteAppRoles.setRoles(remoteUser.getRoles());
756 return userWithRemoteAppRoles;
762 * @see org.openecomp.portalapp.portal.service.UserRolesService#
763 * importRolesFromRemoteApplication(java.lang.Long)
765 public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException {
766 EPRole[] appRolesFull = applicationsRestClientService.get(EPRole[].class, appId, "/rolesFull");
767 List<EPRole> rolesList = Arrays.asList(appRolesFull);
768 for (EPRole externalAppRole : rolesList) {
770 // Try to find an existing extern role for the app in the local
771 // ecomp DB. If so, then use its id to update the existing external
772 // application role record.
773 Long externAppId = externalAppRole.getId();
774 EPRole existingAppRole = epRoleService.getRole(appId, externAppId);
775 if (existingAppRole != null) {
776 logger.debug(EELFLoggerDelegate.debugLogger,
777 String.format("ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.",
778 appId, externAppId));
781 // persistExternalRoleInEcompDb(externalAppRole, appId,
789 * It adds new user for remote application
791 * @param roleInAppForUserList
792 * @param remoteAppUser
796 * @param searchService
797 * @param applicationsRestClientService
801 private EPUser addRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app, ObjectMapper mapper, SearchService searchService, ApplicationsRestClientService applicationsRestClientService) throws Exception{
802 EPUser addRemoteUser = null;
803 if (remoteUserShouldBeCreated(roleInAppForUserList)) {
805 createNewUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper, isAppUpgradeVersion(app));
806 // If we succeed, we know that the new user was
807 // persisted on remote app.
808 addRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
809 if (addRemoteUser == null) {
810 logger.error(EELFLoggerDelegate.errorLogger,
811 "Failed to persist new user: " + userId + " in remote app. appId = " + app.getId());
815 return addRemoteUser;
819 * It checks whether the remote user exists or not
820 * if exits returns user object else null
824 * @param applicationsRestClientService
826 * @throws HTTPException
828 private EPUser checkIfRemoteUserExits(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService) throws HTTPException{
829 EPUser checkRemoteUser = null;
831 checkRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
832 } catch (HTTPException e) {
833 // Some apps are returning 400 if user is not found.
834 if (e.getResponseCode() == 400) {
835 logger.debug(EELFLoggerDelegate.debugLogger,
836 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing",
838 } else if(e.getResponseCode() == 404) {
839 logger.debug(EELFLoggerDelegate.debugLogger,
840 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 404; continuing",
843 // Other response code, let it come thru.
847 return checkRemoteUser;
854 * @see org.openecomp.portalapp.portal.service.UserRolesService#
855 * setAppWithUserRoleStateForUser(org.openecomp.portalapp.portal.domain.
856 * EPUser, org.openecomp.portalapp.portal.transport.AppWithRolesForUser)
858 public boolean setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser) {
859 boolean result = false;
860 boolean epRequestValue = false;
862 if (newAppRolesForUser != null && newAppRolesForUser.orgUserId != null) {
863 userId = newAppRolesForUser.orgUserId.trim();
865 Long appId = newAppRolesForUser.appId;
866 List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.appRoles;
867 if (userId.length() > 0) {
868 ObjectMapper mapper = new ObjectMapper();
869 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
872 EPApp app = appsService.getApp(appId);
873 applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
875 // if centralized app
876 if (app.getCentralAuth()) {
877 // We should add If user does not exist in remote application
878 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
879 EPUser remoteAppUser = null;
880 remoteAppUser = checkIfRemoteUserExits(userId, app, applicationsRestClientService);
882 if (remoteAppUser == null) {
883 addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService,
884 applicationsRestClientService);
888 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
889 applicationsRestClientService, appId, userId);
890 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
891 userRolesInLocalApp);
892 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
893 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
894 // Apply changes in external Access system
895 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList,
898 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal");
900 // In case if portal is not centralized then follow existing approach
901 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
902 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
903 applicationsRestClientService, appId, userId);
904 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
905 userRolesInLocalApp);
906 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal");
908 EPUser remoteAppUser = null;
909 if(!app.getCentralAuth() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)){
911 remoteAppUser = checkIfRemoteUserExits(userId, app, applicationsRestClientService);
913 if (remoteAppUser == null) {
914 remoteAppUser = addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService, applicationsRestClientService);
916 if (remoteAppUser != null) {
917 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
918 applicationsRestClientService, appId, userId);
919 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
920 userRolesInRemoteApp);
921 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null);
923 // If no roles remain, request app to set user inactive.
924 if (userRolesInRemoteApp.size() == 0) {
925 logger.debug(EELFLoggerDelegate.debugLogger,
926 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
928 remoteAppUser.setActive(false);
929 postUserToRemoteApp(userId, user, app, applicationsRestClientService);
934 } catch (Exception e) {
935 String message = String.format(
936 "Failed to create user or update user roles for User %s, AppId %s",
937 userId, Long.toString(appId));
938 logger.error(EELFLoggerDelegate.errorLogger, message, e);
946 * It adds user roles in External system and also make data consistent in both local and in External System
950 * @param roleInAppUser Contains list of active roles
952 @SuppressWarnings("unchecked")
953 private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser, boolean isPortalRequest) throws Exception
956 // check if user exists
957 final Map<String, String> userParams = new HashMap<>();
958 userParams.put("orgUserIdValue", orgUserId);
959 List<EPUser> userInfo = checkIfUserExists(userParams);
960 if (userInfo.isEmpty()) {
961 createLocalUserIfNecessary(orgUserId);
964 if (EPCommonSystemProperties
965 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
967 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
969 ObjectMapper mapper = new ObjectMapper();
970 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
971 HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
972 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles");
973 ResponseEntity<String> getResponse = template
974 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
975 + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class);
976 if (getResponse.getStatusCode().value() == 200) {
977 logger.debug(EELFLoggerDelegate.debugLogger, "updateUserRolesInExternalSystem: Finished GET user roles from external system and received user roles {}",
978 getResponse.getBody());
981 logger.error(EELFLoggerDelegate.errorLogger, "updateUserRolesInExternalSystem: Failed GET user roles from external system and received user roles {}",getResponse.getBody() );
982 EPLogUtil.logExternalAuthAccessAlarm(logger, getResponse.getStatusCode());
984 List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
985 String res = getResponse.getBody();
986 JSONObject jsonObj = null;
987 JSONArray extRoles = null;
988 if (!res.equals("{}")) {
989 jsonObj = new JSONObject(res);
990 extRoles = jsonObj.getJSONArray("role");
992 ExternalAccessUserRoleDetail userRoleDetail = null;
993 if (extRoles != null) {
994 for (int i = 0; i < extRoles.length(); i++) {
995 if (extRoles.getJSONObject(i).getString("name").startsWith(app.getNameSpace() + ".")
996 && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".admin")
997 && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".owner")) {
998 ObjectMapper descMapper = new ObjectMapper();
999 if (extRoles.getJSONObject(i).has("description") && EcompPortalUtils.isJSONValid(extRoles.getJSONObject(i).getString("description"))) {
1000 ExternalRoleDescription desc = descMapper.readValue(
1001 extRoles.getJSONObject(i).getString("description"), ExternalRoleDescription.class);
1002 userRoleDetail = new ExternalAccessUserRoleDetail(
1003 extRoles.getJSONObject(i).getString("name"), desc);
1004 userRoleDetailList.add(userRoleDetail);
1006 userRoleDetail = new ExternalAccessUserRoleDetail(
1007 extRoles.getJSONObject(i).getString("name"), null);
1008 userRoleDetailList.add(userRoleDetail);
1015 List<ExternalAccessUserRoleDetail> userRoleListMatchingInExtAuthAndLocal = CheckIfRoleAreMatchingInUserRoleDetailList(userRoleDetailList,app);
1017 // If request coming from portal not from external role approval system then we have to check if user already
1018 // have account admin or system admin as GUI will not send these roles
1019 if (!isPortalRequest) {
1020 final Map<String, String> loginIdParams = new HashMap<>();
1021 loginIdParams.put("orgUserIdValue", orgUserId);
1022 EPUser user = (EPUser) dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null).get(0);
1023 final Map<String, Long> params = new HashMap<>();
1024 params.put("appId", app.getId());
1025 params.put("userId", user.getId());
1026 List<EcompUserAppRoles> userAppList = dataAccessService.executeNamedQuery("getUserAppExistingRoles",
1028 if (!roleInAppUser.isEmpty()) {
1029 for (EcompUserAppRoles userApp : userAppList) {
1030 if (userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)
1031 || userApp.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
1032 RoleInAppForUser addSpecialRole = new RoleInAppForUser();
1033 addSpecialRole.setIsApplied(true);
1034 addSpecialRole.setRoleId(userApp.getRoleId());
1035 addSpecialRole.setRoleName(userApp.getRoleName());
1036 roleInAppUser.add(addSpecialRole);
1041 List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct()
1042 .collect(Collectors.toList());
1043 final Map<String, RoleInAppForUser> currentUserRolesToUpdate = new HashMap<>();
1044 for (RoleInAppForUser roleInAppUserNew : roleInAppUserNonDupls) {
1045 currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), roleInAppUserNew);
1047 final Map<String, ExternalAccessUserRoleDetail> currentUserRolesInExternalSystem = new HashMap<>();
1048 for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleListMatchingInExtAuthAndLocal) {
1049 currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole);
1051 // Check if user roles does not exists in local but still there in External Central Auth System delete them all
1052 for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
1053 if (!(currentUserRolesToUpdate
1054 .containsKey(userRole.getName().substring(app.getNameSpace().length() + 1)))) {
1055 HttpEntity<String> entity = new HttpEntity<>(headers);
1056 logger.debug(EELFLoggerDelegate.debugLogger,
1057 "updateUserRolesInExternalSystem: Connecting to external system to DELETE user role {}",
1058 userRole.getName());
1059 ResponseEntity<String> deleteResponse = template.exchange(
1060 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1061 + "userRole/" + name + "/" + userRole.getName(),
1062 HttpMethod.DELETE, entity, String.class);
1063 logger.debug(EELFLoggerDelegate.debugLogger,
1064 "updateUserRolesInExternalSystem: Finished DELETE operation in external system for user role {} and the response is {}",
1065 userRole.getName(), deleteResponse.getBody());
1068 // Check if user roles does not exists in External Central Auth System add them all
1069 for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) {
1070 if (!(currentUserRolesInExternalSystem
1071 .containsKey(app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")))) {
1072 ExternalAccessUser extUser = new ExternalAccessUser(name,
1073 app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1074 String formattedUserRole = mapper.writeValueAsString(extUser);
1075 HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers);
1076 logger.debug(EELFLoggerDelegate.debugLogger, "updateUserRolesInExternalSystem: Connecting to external system for user {} and POST {}",
1077 name , addUserRole.getRoleName());
1078 ResponseEntity<String> addResponse = template
1079 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1080 + "userRole", HttpMethod.POST, entity, String.class);
1081 logger.debug(EELFLoggerDelegate.debugLogger,
1082 "updateUserRolesInExternalSystem: Finished adding user role in external system {} and added user role {}",
1083 addResponse.getBody(), addUserRole.getRoleName());
1084 if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 404) {
1085 logger.debug(EELFLoggerDelegate.debugLogger,
1086 "Finished POST operation in external system but unable to save user role", addResponse.getBody(),
1087 addUserRole.getRoleName());
1088 throw new Exception(addResponse.getBody());
1092 } catch (Exception e) {
1093 logger.error(EELFLoggerDelegate.errorLogger, "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}", app.getId(), e);
1094 EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
1100 private List<ExternalAccessUserRoleDetail> CheckIfRoleAreMatchingInUserRoleDetailList(
1101 List<ExternalAccessUserRoleDetail> userRoleDetailList, EPApp app) {
1102 Map<String, EPRole> epRoleList = externalAccessRolesService.getCurrentRolesInDB(app);
1103 //Add Account Admin role for partner app to prevent conflict
1104 if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1105 EPRole role = new EPRole();
1106 role.setName(PortalConstants.ADMIN_ROLE.replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1107 epRoleList.put(role.getName(), role);
1109 userRoleDetailList.removeIf(userRoleDetail -> !epRoleList.containsKey(userRoleDetail.getName().substring(app.getNameSpace().length()+1)));
1110 return userRoleDetailList;
1117 * @param applicationsRestClientService
1118 * @param searchService
1122 protected void createNewUserOnRemoteApp(String userId, EPApp app,
1123 ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
1124 ObjectMapper mapper, boolean postOpenSource) throws Exception {
1127 EPUser client = searchService.searchUserByUserId(userId);
1129 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1131 if (client == null) {
1132 String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook.";
1133 logger.error(EELFLoggerDelegate.errorLogger, msg);
1134 throw new Exception(msg);
1137 client.setLoginId(userId);
1138 client.setActive(true);
1140 String userInString = null;
1141 userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
1142 logger.debug(EELFLoggerDelegate.debugLogger,
1143 "about to post new client to remote application, users json = " + userInString);
1144 applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user", userId));
1148 @SuppressWarnings("unchecked")
1149 protected void applyChangesToAppRolesRequest(Long appId, Long userId, String updateStatus, EPUserAppRolesRequest epUserAppRolesRequest) {
1150 final Map<String, Long> epRequestParams = new HashMap<>();
1152 EPUserAppRolesRequest epAppRolesRequestData = epUserAppRolesRequest;
1153 epAppRolesRequestData.setUpdatedDate(new Date());
1154 epAppRolesRequestData.setRequestStatus(updateStatus);
1155 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1156 addiotonalUpdateParam.put("userId", userId);
1157 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1158 epRequestParams.put("reqId", epUserAppRolesRequest.getId());
1159 List<EPUserAppRolesRequestDetail> epUserAppRolessDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1160 epUserAppRolessDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1161 epRequestParams, null);
1162 if (epUserAppRolessDetailList.size() > 0) {
1163 for (EPUserAppRolesRequestDetail epRequestUpdateData : epUserAppRolessDetailList) {
1164 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateData;
1165 epAppRoleDetailData.setReqType(updateStatus);
1166 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1167 HashMap<String, Long> updateDetailsParam = new HashMap<String, Long>();
1168 addiotonalUpdateParam.put("reqId", epUserAppRolesRequest.getId());
1169 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParam);
1172 logger.debug(EELFLoggerDelegate.debugLogger, "The request is set to complete");
1174 } catch (Exception e) {
1175 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToAppRolesRequest failed", e);
1179 @SuppressWarnings("unchecked")
1180 public void applyChangesToUserAppRolesForMyLoginsRequest(EPUser user, Long appId) {
1181 final Map<String, Long> params = new HashMap<>();
1182 final Map<String, Long> epDetailParams = new HashMap<>();
1183 List<EPUserAppRolesRequest> epRequestIdVal = new ArrayList<EPUserAppRolesRequest>();
1184 params.put("appId", appId);
1185 params.put("userId", user.getId());
1187 epRequestIdVal = (List<EPUserAppRolesRequest>) dataAccessService
1188 .executeNamedQuery("userAppRolesRequestList", params, null);
1189 if (epRequestIdVal.size() > 0) {
1190 EPUserAppRolesRequest epAppRolesRequestData = epRequestIdVal.get(0);
1191 epAppRolesRequestData.setUpdatedDate(new Date());
1192 epAppRolesRequestData.setRequestStatus("O");
1193 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1194 addiotonalUpdateParam.put("userId", user.getId());
1195 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1196 epDetailParams.put("reqId", epAppRolesRequestData.getId());
1197 List<EPUserAppRolesRequestDetail> epUserAppRolesDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1198 epUserAppRolesDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1199 epDetailParams, null);
1200 if (epUserAppRolesDetailList.size() > 0) {
1201 for (EPUserAppRolesRequestDetail epRequestUpdateList : epUserAppRolesDetailList) {
1202 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateList;
1203 epAppRoleDetailData.setReqType("O");
1204 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1205 HashMap<String, Long> updateDetailsParams = new HashMap<String, Long>();
1206 addiotonalUpdateParam.put("reqId", epAppRolesRequestData.getId());
1207 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParams);
1209 logger.debug(EELFLoggerDelegate.debugLogger, "User App roles request from User Page is overridden");
1213 } catch (Exception e) {
1214 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e);
1219 * Pushes specified user details to the specified remote app.
1222 * OrgUserId identifying user at remote app in REST endpoint path
1224 * User details to be pushed
1227 * @param applicationsRestClientService
1228 * @throws HTTPException
1230 protected void postUserToRemoteApp(String userId, EPUser user, EPApp app,
1231 ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
1233 getUser(userId, app, applicationsRestClientService);
1238 * It returns user details for single org user id
1242 * if user exists it returns list of user details otherwise empty value
1244 @SuppressWarnings("unchecked")
1245 private List<EPUser> checkIfUserExists(Map<String, String> userParams){
1246 return (List<EPUser>)dataAccessService.executeNamedQuery("epUserAppId", userParams, null);
1250 * It checks whether the new user is valid or not otherwise throws exception
1255 * Checks if user is valid and returns message otherwise throws exception
1258 private String validateNewUser(String orgUserId, EPApp app) throws Exception {
1259 EPUser epUser = searchService.searchUserByUserId(orgUserId);
1260 if (epUser == null) {
1261 throw new Exception("User does not exist");
1262 } else if (!epUser.getOrgUserId().equals(orgUserId)) {
1263 throw new Exception("User does not exist");
1264 } else if (app == null) {
1265 throw new Exception("Application does not exist");
1267 return "Saved Successfully";
1271 * Checks if the fields exists or not
1274 * contains user information
1278 * throws exception if the field is not valid
1280 private void validateExternalRequestFields(List<EPUser> userList, EPApp app) throws Exception{
1281 if (userList.size() == 0 || userList.isEmpty() ) {
1282 throw new Exception("User does not exist");
1283 } else if(app == null) {
1284 throw new Exception("Application does not exist");
1285 } else if(!app.getEnabled() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1286 throw new Exception(app.getMlAppName()+" application is unavailable");
1290 @SuppressWarnings("unchecked")
1291 public ExternalRequestFieldsValidator setExternalRequestUserAppRole(ExternalSystemUser newAppRolesForUser, String reqType) {
1292 boolean result = false;
1293 boolean externalSystemRequest = true;
1294 final Map<String, Long> params = new HashMap<>();
1295 final Map<String, String> userParams = new HashMap<>();
1296 List<EPUser> userInfo = null;
1297 EPUser userId = null;
1298 List<EPUserAppRolesRequest> epRequestId = null;
1299 String orgUserId = "";
1300 String updateStatus = "";
1301 String reqMessage = "";
1303 if (newAppRolesForUser != null && newAppRolesForUser.getLoginId() != null) {
1304 orgUserId = newAppRolesForUser.getLoginId().trim();
1306 String appName = newAppRolesForUser.getApplicationName();
1307 String logMessage = ("DELETE").equals(reqType) ? "Deleting": "Assigning/Updating" ;
1308 if (orgUserId.length() > 0) {
1309 ObjectMapper mapper = new ObjectMapper();
1310 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1311 int epRequestIdSize = 0;
1313 app = appsService.getAppDetail(appName);
1314 userParams.put("orgUserIdValue", orgUserId);
1315 userInfo = checkIfUserExists(userParams);
1316 reqMessage = "Updated Successfully";
1317 if (!reqType.equals("DELETE") && (userInfo.size() == 0 || userInfo.isEmpty())) {
1318 reqMessage = validateNewUser(orgUserId, app);
1320 if (userInfo.size() != 0 || !userInfo.isEmpty()) {
1321 validateExternalRequestFields(userInfo, app);
1322 userId = userInfo.get(0);
1323 params.put("appId", app.getId());
1324 params.put("userId", userId.getId());
1325 epRequestId = (List<EPUserAppRolesRequest>) dataAccessService
1326 .executeNamedQuery("userAppRolesRequestList", params, null);
1327 epRequestIdSize = epRequestId.size();
1330 //If Non-Centralized app make sure you sync app roles before assigning to user
1331 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !app.getCentralAuth()) {
1332 logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Starting GET roles for app {}",app.getId());
1333 EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, app.getId(), "/roles");
1334 logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Finshed GET roles for app {} and payload {}",app.getId(), appRoles);
1335 if (appRoles.length > 0) {
1336 syncAppRoles(sessionFactory, app.getId(), appRoles);
1339 List<RoleInAppForUser> roleInAppForUserList = roleInAppForUserList(newAppRolesForUser.getRoles(),
1340 app.getId(), app.getMlAppName());
1341 List<EcompUserAppRoles> userRoleList = null;
1342 if(!userInfo.isEmpty()){
1343 final Map<String, Long> appParams = new HashMap<>();
1344 appParams.put("userId", userId.getId());
1345 appParams.put("appId", app.getId());
1346 userRoleList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", appParams, null);
1348 // Check if list contains just account admin role
1349 boolean checkIfAdminRoleExists = false;
1350 if (reqType.equals("DELETE") && userRoleList!=null) {
1351 checkIfAdminRoleExists = userRoleList.stream()
1352 .anyMatch(userRole -> userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1354 checkIfAdminRoleExists = roleInAppForUserList.stream()
1355 .anyMatch(roleList -> roleList.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1357 // if Centralized app
1358 if (app.getCentralAuth()) {
1359 // We should add If user does not exist in remote application
1361 // If adding just account admin role dont make remote application user call
1362 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !(checkIfAdminRoleExists
1363 && reqType.equals("DELETE")) && roleInAppForUserList.size() > 1) {
1364 EPUser remoteAppUser = null;
1365 remoteAppUser = checkIfRemoteUserExits(orgUserId, app,
1366 applicationsRestClientService);
1367 if (remoteAppUser == null) {
1368 addRemoteUser(roleInAppForUserList, orgUserId, app, mapper, searchService,
1369 applicationsRestClientService);
1370 reqMessage = "Saved Successfully";
1373 } catch (Exception e) {
1374 reqMessage = e.getMessage();
1375 logger.error(EELFLoggerDelegate.errorLogger, "setExternalRequestUserAppRole: Failed to added remote user", e);
1376 throw new Exception(reqMessage);
1378 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1379 applicationsRestClientService, app.getId(), orgUserId);
1380 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1381 userRolesInLocalApp);
1382 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1383 if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1384 // Apply changes in external Access system
1385 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, externalSystemRequest);
1387 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
1388 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1389 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType);
1391 // If local application is not centralized
1392 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1393 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1394 applicationsRestClientService, app.getId(), orgUserId);
1395 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1396 userRolesInLocalApp);
1397 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType);
1398 } else {// remote app
1399 // If adding just account admin role don't do remote application user call
1400 if(!((roleInAppForUserList.size() == 1 || reqType.equals("DELETE")) && checkIfAdminRoleExists)){
1401 EPUser remoteAppUser = null;
1402 remoteAppUser = checkIfRemoteUserExits(orgUserId, app, applicationsRestClientService);
1403 if (remoteAppUser == null) {
1404 remoteAppUser = addRemoteUser(roleInAppForUserList, orgUserId, app, mapper, searchService, applicationsRestClientService);
1405 reqMessage = "Saved Successfully";
1407 if (remoteAppUser != null) {
1408 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList,
1409 mapper, applicationsRestClientService, app.getId(), orgUserId);
1411 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId,
1412 app.getId(), userRolesInRemoteApp);
1413 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}",
1414 logMessage, newAppRolesForUser.getApplicationName(),
1415 newAppRolesForUser.getLoginId());
1416 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1418 // If no roles remain, request app to set user inactive.
1419 /*if (userRolesInRemoteApp.size() == 0) {
1420 logger.debug(EELFLoggerDelegate.debugLogger,
1421 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
1423 //TODO Need to fix the logged in user is not set to inactive
1424 remoteAppUser.setActive(false);
1425 postUserToRemoteApp(orgUserId, user, app, applicationsRestClientService);
1429 // Here we are adding only we have single account admin in roleInAppForUserList and this should not add in remote
1430 if(!(reqType.equals("DELETE")) && userInfo.isEmpty()){
1431 reqMessage = "Saved Successfully";
1433 Set<EcompRole> userRolesInRemoteApp = constructUsersEcompRoles(roleInAppForUserList);
1435 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1436 userRolesInRemoteApp);
1437 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}",
1438 logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1439 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1443 reqMessage = "Failed to save the user app role(s)";
1445 if (epRequestIdSize > 0 && !userInfo.isEmpty()) {
1447 applyChangesToAppRolesRequest(app.getId(), userId.getId(), updateStatus, epRequestId.get(0));
1450 } catch (Exception e) {
1451 String message = String.format("setExternalRequestUserAppRole: Failed to create user or update user roles for User %s, AppId %s",
1452 orgUserId, appName);
1453 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1455 reqMessage = e.getMessage();
1456 if(epRequestIdSize > 0 && userInfo!=null && !userInfo.isEmpty()){
1458 applyChangesToAppRolesRequest(app.getId(), userId.getId(),
1459 updateStatus, epRequestId.get(0));
1464 return new ExternalRequestFieldsValidator(result, reqMessage);
1469 * @param roleInAppForUserList
1471 * @param applicationsRestClientService
1474 * @return Set<EcompRole>
1475 * @throws JsonProcessingException
1476 * @throws HTTPException
1478 private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
1479 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
1480 throws JsonProcessingException, HTTPException {
1481 Set<EcompRole> updatedUserRoles = constructUsersEcompRoles(roleInAppForUserList);
1482 return updatedUserRoles;
1486 * It constructs and returns list of user app roles when the external API role approval system calls
1489 * @param roleInAppForUserList
1491 * @return list of user app roles
1493 * throws exceptions if role id does not exits
1495 private List<RoleInAppForUser> roleInAppForUserList(List<ExternalSystemRoleApproval> roleInAppForUserList,
1496 Long appId, String appName) throws Exception {
1497 List<RoleInAppForUser> existingUserRoles = new ArrayList<RoleInAppForUser>();
1498 EPRole existingAppRole = null;
1499 for (ExternalSystemRoleApproval roleInAppForUser : roleInAppForUserList) {
1500 RoleInAppForUser ecompRole = new RoleInAppForUser();
1501 existingAppRole = epRoleService.getAppRole(roleInAppForUser.getRoleName(), appId);
1502 if (existingAppRole == null) {
1503 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1504 roleInAppForUserList);
1505 throw new Exception("'" +roleInAppForUser.getRoleName() + "'" +" role does not exist for " + appName + " application");
1507 if (!existingAppRole.getActive()) {
1508 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1509 roleInAppForUserList);
1510 throw new Exception(roleInAppForUser.getRoleName() + " role is unavailable for "+ appName + " application");
1512 ecompRole.roleId = (appId == 1 || roleInAppForUser.getRoleName().equals(PortalConstants.ADMIN_ROLE)) ? existingAppRole.getId() : existingAppRole.getAppRoleId();
1513 ecompRole.roleName = roleInAppForUser.getRoleName();
1514 ecompRole.isApplied = true;
1515 existingUserRoles.add(ecompRole);
1518 return existingUserRoles;
1527 * @param applicationsRestClientService
1529 * @throws HTTPException
1531 protected EPUser getUserFromApp(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1532 throws HTTPException {
1534 if (app.getId() == PortalConstants.PORTAL_APP_ID) {
1535 // Map<String,String> params = new HashMap<String,String>();
1536 // params.put("sbcid",userId);
1537 @SuppressWarnings("unchecked")
1538 List<EPUser> userList = (List<EPUser>) dataAccessService
1539 .executeQuery("from EPUser where orgUserId='" + userId + "'", null);
1540 if (userList != null && !userList.isEmpty())
1541 return userList.get(0);
1547 return getUser(userId, app, applicationsRestClientService);
1550 protected EPUser getUser(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1551 throws HTTPException {
1552 return applicationsRestClientService.get(EPUser.class, app.getId(), String.format("/user/%s", userId), true);
1556 protected boolean isAppUpgradeVersion(EPApp app){
1561 public ExternalSystemAccess getExternalRequestAccess(){
1562 ExternalSystemAccess res = null;
1564 res = new ExternalSystemAccess(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE,
1565 Boolean.parseBoolean(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE)));
1566 } catch (Exception e) {
1567 logger.error(EELFLoggerDelegate.errorLogger, "getExternalRequestAccess failed" + e.getMessage());
1575 * @see org.openecomp.portalapp.portal.service.UserRolesService#
1576 * getAppRolesForUser(java.lang.Long, java.lang.String)
1578 @SuppressWarnings("unchecked")
1579 public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId, Boolean extRequestValue) {
1581 List<RoleInAppForUser> rolesInAppForUser = null;
1582 EPApp app = appsService.getApp(appId);
1584 // for ecomp portal app, no need to make a remote call
1585 List<Role> roleList = new ArrayList<>();
1586 if (appId == PortalConstants.PORTAL_APP_ID) {
1587 if(app.getCentralAuth()){
1588 List<CentralV2Role> cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey());
1589 for(CentralV2Role cenRole : cenRoleList){
1590 Role role = new Role();
1591 role.setActive(cenRole.isActive());
1592 role.setId(cenRole.getId());
1593 role.setName(cenRole.getName());
1594 role.setPriority(cenRole.getPriority());
1598 roleList = roleService.getAvailableRoles(userId);
1600 List<Role> activeRoleList = new ArrayList<Role>();
1601 for(Role role: roleList) {
1602 if(role.getActive()) {
1603 if(role.getId() != 1){ // prevent portal admin from being added
1604 activeRoleList.add(role);
1605 } else if(extRequestValue){
1606 activeRoleList.add(role);
1611 EPUser localUser = getUserFromApp(userId, app, applicationsRestClientService);
1612 // If localUser does not exists return roles
1613 Set<EPRole> roleSet = null;
1614 EPRole[] roleSetList = null;
1615 if(localUser != null){
1616 roleSet = localUser.getAppEPRoles(app);
1617 roleSetList = roleSet.toArray(new EPRole[0]);
1619 rolesInAppForUser = constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue);
1620 return rolesInAppForUser;
1623 EcompRole[] appRoles = null;
1624 List<EcompRole> roles = new ArrayList<>();
1625 if(app.getCentralAuth()){
1626 List<EPRole> applicationRoles = dataAccessService.getList(EPRole.class, " where app_id = "+app.getId()+ " and active_yn = 'Y'", null, null);;
1627 for(EPRole role : applicationRoles){
1628 EcompRole ecompRole = new EcompRole();
1629 ecompRole.setId(role.getId());
1630 ecompRole.setName(role.getName());
1631 roles.add(ecompRole);
1633 appRoles = roles.toArray(new EcompRole[roles.size()]);
1635 appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
1637 // Test this error case, for generating an internal Ecomp Portal
1639 // EcompRole[] appRoles = null;
1640 // If there is an exception in the rest client api, then null will
1642 if (appRoles != null) {
1643 if(!app.getCentralAuth()) {
1644 syncAppRoles(sessionFactory, appId, appRoles);
1646 EcompRole[] userAppRoles = null;
1649 if(app.getCentralAuth()){
1650 final Map<String, String> params = new HashMap<>();
1651 final Map<String, Long> userParams = new HashMap<>();
1652 params.put("orgUserIdValue", userId);
1653 List<EPUser> user = dataAccessService.executeNamedQuery("epUserAppId", params, null);
1654 userParams.put("appId", app.getId());
1655 userParams.put("userId", user.get(0).getId());
1656 List<EPUserAppCurrentRoles> userAppsRolesList = dataAccessService.executeNamedQuery("getUserAppCurrentRoles", userParams, null);
1657 List<EcompRole> setUserRoles = new ArrayList<>();
1658 for(EPUserAppCurrentRoles role : userAppsRolesList){
1659 EcompRole ecompRole = new EcompRole();
1660 ecompRole.setId(role.getRoleId());
1661 ecompRole.setName(role.getRoleName());
1662 setUserRoles.add(ecompRole);
1664 userAppRoles = setUserRoles.toArray(new EcompRole[setUserRoles.size()]);
1665 rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
1666 return rolesInAppForUser;
1668 userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
1669 String.format("/user/%s/roles", userId));
1671 } catch (HTTPException e) {
1672 // Some apps are returning 400 if user is not found.
1673 if (e.getResponseCode() == 400) {
1674 logger.debug(EELFLoggerDelegate.debugLogger,
1675 "getAppRolesForUser caught exception with response code 400; continuing", e);
1677 // Other response code, let it come thru.
1681 if (userAppRoles == null) {
1682 if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
1683 EcompPortalUtils.setExternalAppResponseCode(200);
1684 String message = String.format(
1685 "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
1686 + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
1687 + "Overriding to 200 until framework SDK returns a useful response.",
1688 Long.toString(appId), userId);
1689 logger.warn(EELFLoggerDelegate.applicationLogger, message);
1693 HashMap<Long, EcompRole> appRolesActiveMap =hashMapFromEcompRoles(appRoles);
1694 ArrayList<EcompRole> activeRoles = new ArrayList<EcompRole>();
1695 if(userAppRoles != null){
1696 for (int i = 0; i < userAppRoles.length; i++) {
1697 if (appRolesActiveMap.containsKey(userAppRoles[i].getId())) {
1698 EcompRole role = new EcompRole();
1699 role.setId(userAppRoles[i].getId());
1700 role.setName(userAppRoles[i].getName());
1701 activeRoles.add(role);
1705 EcompRole[] userAppRolesActive = activeRoles.toArray(new EcompRole[activeRoles.size()]);
1707 // If the remote application isn't down we MUST sync user
1708 // roles here in case we have this user here!
1709 syncUserRoles(sessionFactory, userId, appId, userAppRolesActive, extRequestValue, null);
1710 } catch (Exception e) {
1711 // TODO: we may need to check if user exists, maybe remote
1713 String message = String.format(
1714 "getAppRolesForUser: user %s does not exist in remote application %s", userId,
1715 Long.toString(appId));
1716 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1717 userAppRoles = new EcompRole[0];
1719 rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
1721 } catch (Exception e) {
1722 String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
1723 Long.toString(appId));
1724 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1726 return rolesInAppForUser;
1730 private boolean postUserRolesToMylogins(AppWithRolesForUser userAppRolesData,
1731 ApplicationsRestClientService applicationsRestClientService, Long appId, Long userId)
1732 throws JsonProcessingException, HTTPException {
1733 boolean result = false;
1734 ObjectMapper mapper = new ObjectMapper();
1735 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1736 String userRolesAsString = mapper.writeValueAsString(userAppRolesData);
1737 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, as the endpoint is not defined yet from the Mylogins");
1738 applicationsRestClientService.post(AppWithRolesForUser.class, appId, userRolesAsString, String.format("/user/%s/myLoginroles", userId));
1742 public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser userAppRolesData, EPUser user) {
1743 FieldsValidator fieldsValidator = new FieldsValidator();
1744 final Map<String, Long> params = new HashMap<>();
1745 EPUserAppRoles appRole= new EPUserAppRoles();
1747 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, still the endpoint is yet to be defined");
1748 boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService, userAppRolesData.appId, user.getId());
1749 logger.debug(EELFLoggerDelegate.debugLogger,"putUserAppRolesRequest: result {}", result);
1751 params.put("appId", userAppRolesData.appId);
1752 EPUserAppRolesRequest epAppRolesRequestData = new EPUserAppRolesRequest();
1753 epAppRolesRequestData.setCreatedDate(new Date());
1754 epAppRolesRequestData.setUpdatedDate(new Date());
1755 epAppRolesRequestData.setUserId(user.getId());
1756 epAppRolesRequestData.setAppId(userAppRolesData.appId);
1757 epAppRolesRequestData.setRequestStatus("P");
1758 List<RoleInAppForUser> appRoleIdList = userAppRolesData.appRoles;
1759 Set<EPUserAppRolesRequestDetail> appRoleDetails = new LinkedHashSet<EPUserAppRolesRequestDetail>();
1760 dataAccessService.saveDomainObject(epAppRolesRequestData, null);
1761 for (RoleInAppForUser userAppRoles : appRoleIdList) {
1762 Boolean isAppliedVal = userAppRoles.isApplied;
1763 params.put("appRoleId", userAppRoles.roleId);
1765 appRole = (EPUserAppRoles) dataAccessService.executeNamedQuery("appRoles", params, null).get(0);
1766 EPUserAppRolesRequestDetail epAppRoleDetail = new EPUserAppRolesRequestDetail();
1767 epAppRoleDetail.setReqRoleId(appRole.getRoleId());
1768 epAppRoleDetail.setReqType("P");
1769 epAppRoleDetail.setEpRequestIdData(epAppRolesRequestData);
1770 dataAccessService.saveDomainObject(epAppRoleDetail, null);
1773 epAppRolesRequestData.setEpRequestIdDetail(appRoleDetails);
1774 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1776 } catch (Exception e) {
1777 logger.error(EELFLoggerDelegate.errorLogger, "putUserAppRolesRequest failed", e);
1778 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1780 return fieldsValidator;
1783 public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(EPUser userid, String appName) {
1784 Map<String, String> params = new HashMap<>();
1785 params.put("userid", userid.getId().toString());
1786 //params.put("appid", appid);
1787 params.put("appName", appName);
1789 @SuppressWarnings("unchecked")
1790 List<EPUserAppCatalogRoles> userAppRoles = (List<EPUserAppCatalogRoles>) dataAccessService
1791 .executeNamedQuery("userAppCatalogRoles", params, null);
1792 return userAppRoles;
1795 public String updateRemoteUserProfile(String orgUserId, Long appId) {
1796 ObjectMapper mapper = new ObjectMapper();
1797 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1798 EPUser client = searchService.searchUserByUserId(orgUserId);
1799 EPUser newUser = new EPUser();
1800 newUser.setActive(client.getActive());
1801 newUser.setFirstName(client.getFirstName());
1802 newUser.setLastName(client.getLastName());
1803 newUser.setLoginId(client.getLoginId());
1804 newUser.setLoginPwd(client.getLoginPwd());
1805 newUser.setMiddleInitial(client.getMiddleInitial());
1806 newUser.setEmail(client.getEmail());
1807 newUser.setOrgUserId(client.getLoginId());
1809 String userAsString = mapper.writeValueAsString(newUser);
1810 List<EPApp> appList = appsService.getUserRemoteApps(client.getId().toString());
1811 // applicationsRestClientService.post(EPUser.class, appId,
1812 // userAsString, String.format("/user", orgUserId));
1813 for (EPApp eachApp : appList) {
1815 applicationsRestClientService.post(EPUser.class, eachApp.getId(), userAsString,
1816 String.format("/user/%s", orgUserId));
1817 } catch (Exception e) {
1818 logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId()
1819 + " in remote app. appId = " + eachApp.getId());
1822 } catch (Exception e) {
1823 logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
1834 * @see org.openecomp.portalapp.portal.service.UserRolesService#
1835 * getCachedAppRolesForUser(java.lang.Long, java.lang.Long)
1837 public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId) {
1838 // Find the records for this user-app combo, if any
1839 String filter = " where user_id = " + Long.toString(userId) + " and app_id = " + Long.toString(appId);
1840 @SuppressWarnings("unchecked")
1841 List<EPUserApp> roleList = dataAccessService.getList(EPUserApp.class, filter, null, null);
1842 logger.debug(EELFLoggerDelegate.debugLogger, "getCachedAppRolesForUser: list size is {}", roleList.size());
1847 * It retrieves and returns list of user app roles for local and remote applications based app id
1850 * @return list of user app roles
1851 * @throws HTTPException
1853 public List<UserApplicationRoles> getUsersFromAppEndpoint(Long appId) throws HTTPException {
1854 ArrayList<UserApplicationRoles> userApplicationRoles = new ArrayList<UserApplicationRoles>();
1856 EPApp app = appsService.getApp(appId);
1857 //If local or centralized application
1858 if (appId == PortalConstants.PORTAL_APP_ID || app.getCentralAuth()) {
1859 @SuppressWarnings("unchecked")
1860 List<EPUser> userList = (List<EPUser>) dataAccessService.executeNamedQuery("getActiveUsers", null, null);
1861 for (EPUser user : userList) {
1862 UserApplicationRoles userWithAppRoles = convertToUserApplicationRoles(appId, user, app);
1863 if (userWithAppRoles.getRoles() != null && userWithAppRoles.getRoles().size() > 0)
1864 userApplicationRoles.add(userWithAppRoles);
1870 RemoteUserWithRoles[] remoteUsers = null;
1871 String remoteUsersString = applicationsRestClientService.getIncomingJsonString(appId, "/users");
1873 remoteUsers = doGetUsers(isAppUpgradeVersion(app), remoteUsersString);
1875 userApplicationRoles = new ArrayList<UserApplicationRoles>();
1876 for (RemoteUserWithRoles remoteUser : remoteUsers) {
1877 UserApplicationRoles userWithRemoteAppRoles = convertToUserApplicationRoles(appId, remoteUser);
1878 if (userWithRemoteAppRoles.getRoles() != null && userWithRemoteAppRoles.getRoles().size() > 0) {
1879 userApplicationRoles.add(userWithRemoteAppRoles);
1881 logger.debug(EELFLoggerDelegate.debugLogger,
1882 "User " + userWithRemoteAppRoles.getOrgUserId() + " doesn't have any roles assigned to any app.");
1887 return userApplicationRoles;
1894 * @param appgetUsersFromAppEndpoint
1897 private UserApplicationRoles convertToUserApplicationRoles(Long appId, EPUser user, EPApp app) {
1898 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
1899 userWithRemoteAppRoles.setAppId(appId);
1900 userWithRemoteAppRoles.setOrgUserId(user.getOrgUserId());
1901 userWithRemoteAppRoles.setFirstName(user.getFirstName());
1902 userWithRemoteAppRoles.setLastName(user.getLastName());
1903 userWithRemoteAppRoles.setRoles(convertToRemoteRoleList(user, app));
1904 return userWithRemoteAppRoles;
1913 private List<RemoteRole> convertToRemoteRoleList(EPUser user, EPApp app) {
1914 List<RemoteRole> roleList = new ArrayList<RemoteRole>();
1915 SortedSet<EPRole> roleSet = user.getAppEPRoles(app);
1916 for (EPRole role : roleSet) {
1917 RemoteRole rRole = new RemoteRole();
1918 rRole.setId(role.getId());
1919 rRole.setName(role.getName());
1920 roleList.add(rRole);
1925 public RemoteUserWithRoles[] doGetUsers(boolean postOpenSource, String remoteUsersString) {
1927 ObjectMapper mapper = new ObjectMapper();
1929 return mapper.readValue(remoteUsersString, RemoteUserWithRoles[].class);
1930 } catch (IOException e) {
1931 logger.error(EELFLoggerDelegate.errorLogger,
1932 "doGetUsers : Failed : Unexpected property in incoming JSON",
1934 logger.error(EELFLoggerDelegate.errorLogger,
1935 "doGetUsers : Incoming JSON that caused it --> " + remoteUsersString);
1938 return new RemoteUserWithRoles[0];
1941 @SuppressWarnings("unchecked")
1942 public List<EPUserApp> getEPUserAppList(Long appId, Long userId, Long roleId) {
1943 List<EPUserApp> userRoleList = new ArrayList<EPUserApp>();
1944 final Map<String, Long> params = new HashMap<>();
1945 params.put("appId", appId);
1946 params.put("userId", userId);
1947 params.put("roleId", roleId);
1948 userRoleList = dataAccessService.executeNamedQuery("getUserRoleOnUserIdAndRoleIdAndAppId", params, null);
1949 return userRoleList;