2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright © 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.openecomp.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.openecomp.portalapp.externalsystemapproval.model.ExternalSystemRoleApproval;
67 import org.openecomp.portalapp.externalsystemapproval.model.ExternalSystemUser;
68 import org.openecomp.portalapp.portal.domain.EPApp;
69 import org.openecomp.portalapp.portal.domain.EPRole;
70 import org.openecomp.portalapp.portal.domain.EPUser;
71 import org.openecomp.portalapp.portal.domain.EPUserApp;
72 import org.openecomp.portalapp.portal.domain.EPUserAppCatalogRoles;
73 import org.openecomp.portalapp.portal.domain.EPUserAppRoles;
74 import org.openecomp.portalapp.portal.domain.EPUserAppRolesRequest;
75 import org.openecomp.portalapp.portal.domain.EPUserAppRolesRequestDetail;
76 import org.openecomp.portalapp.portal.domain.ExternalSystemAccess;
77 import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
78 import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
79 import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
80 import org.openecomp.portalapp.portal.transport.AppWithRolesForUser;
81 import org.openecomp.portalapp.portal.transport.CentralRole;
82 import org.openecomp.portalapp.portal.transport.EPUserAppCurrentRoles;
83 import org.openecomp.portalapp.portal.transport.EcompUserAppRoles;
84 import org.openecomp.portalapp.portal.transport.ExternalAccessUser;
85 import org.openecomp.portalapp.portal.transport.ExternalAccessUserRoleDetail;
86 import org.openecomp.portalapp.portal.transport.ExternalRequestFieldsValidator;
87 import org.openecomp.portalapp.portal.transport.ExternalRoleDescription;
88 import org.openecomp.portalapp.portal.transport.FieldsValidator;
89 import org.openecomp.portalapp.portal.transport.FunctionalMenuItem;
90 import org.openecomp.portalapp.portal.transport.FunctionalMenuRole;
91 import org.openecomp.portalapp.portal.transport.RemoteRole;
92 import org.openecomp.portalapp.portal.transport.RemoteUserWithRoles;
93 import org.openecomp.portalapp.portal.transport.RoleInAppForUser;
94 import org.openecomp.portalapp.portal.transport.RolesInAppForUser;
95 import org.openecomp.portalapp.portal.transport.UserApplicationRoles;
96 import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
97 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
98 import org.openecomp.portalapp.portal.utils.PortalConstants;
99 import org.openecomp.portalsdk.core.domain.Role;
100 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
101 import org.openecomp.portalsdk.core.restful.domain.EcompRole;
102 import org.openecomp.portalsdk.core.service.DataAccessService;
103 import org.openecomp.portalsdk.core.service.RoleService;
104 import org.openecomp.portalsdk.core.util.SystemProperties;
105 import org.springframework.beans.factory.annotation.Autowired;
106 import org.springframework.http.HttpEntity;
107 import org.springframework.http.HttpHeaders;
108 import org.springframework.http.HttpMethod;
109 import org.springframework.http.ResponseEntity;
110 import org.springframework.web.client.RestTemplate;
112 import com.fasterxml.jackson.core.JsonProcessingException;
113 import com.fasterxml.jackson.databind.DeserializationFeature;
114 import com.fasterxml.jackson.databind.ObjectMapper;
117 public class UserRolesCommonServiceImpl {
119 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesCommonServiceImpl.class);
121 private static final Object syncRests = new Object();
124 private DataAccessService dataAccessService;
126 private SessionFactory sessionFactory;
128 private SearchService searchService;
130 private EPAppService appsService;
132 private ApplicationsRestClientService applicationsRestClientService;
134 private EPRoleService epRoleService;
136 private RoleService roleService;
139 private ExternalAccessRolesService externalAccessRolesService;
141 RestTemplate template = new RestTemplate();
146 * @return HashMap<Long, EcompRole>
148 private static HashMap<Long, EcompRole> hashMapFromEcompRoles(EcompRole[] ecompRoles) {
149 HashMap<Long, EcompRole> result = new HashMap<Long, EcompRole>();
150 if (ecompRoles != null) {
151 for (int i = 0; i < ecompRoles.length; i++) {
152 if (ecompRoles[i].getId() != null) {
153 result.put(ecompRoles[i].getId(), ecompRoles[i]);
164 protected void createLocalUserIfNecessary(String userId) {
165 if (StringUtils.isEmpty(userId)) {
166 logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty userId!");
169 Session localSession = null;
170 Transaction transaction = null;
172 localSession = sessionFactory.openSession();
173 transaction = localSession.beginTransaction();
174 @SuppressWarnings("unchecked")
175 List<EPUser> userList = localSession
176 .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + userId + "'").list();
177 if (userList.size() == 0) {
178 EPUser client = searchService.searchUserByUserId(userId);
179 if (client == null) {
180 String msg = "createLocalUserIfNecessary: cannot create user " + userId
181 + ", because not found in phonebook";
182 logger.error(EELFLoggerDelegate.errorLogger, msg);
184 client.setLoginId(userId);
185 client.setActive(true);
186 localSession.save(client);
189 transaction.commit();
190 } catch (Exception e) {
191 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
192 EcompPortalUtils.rollbackTransaction(transaction, "searchOrCreateUser rollback, exception = " + e);
194 EcompPortalUtils.closeLocalSession(localSession, "searchOrCreateUser");
199 * This method return nothing and remove roles before adding any roles for an
204 * @param localSession
205 * @param userAppRoles
206 * @param newUserAppRolesMap
208 private static void syncUserRolesExtension(EPUserApp userRole, Long appId, Session localSession,
209 EcompRole[] userAppRoles, HashMap<Long, EcompRole> newUserAppRolesMap) {
211 Long userAppRoleId = 0L;
212 if (appId == PortalConstants.PORTAL_APP_ID) { // local app
213 userAppRoleId = userRole.getRoleId();
214 } else { // remote app
215 userAppRoleId = userRole.getAppRoleId();
218 if (!newUserAppRolesMap.containsKey(userAppRoleId)) {
219 localSession.delete(userRole);
221 newUserAppRolesMap.remove(userAppRoleId);
226 * Checks whether the role is inactive
230 * if role is inactive, throws exception
232 private void checkIfRoleInactive(EPRole epRole) throws Exception {
233 if (!epRole.getActive()) {
234 throw new Exception(epRole.getName() + " role is unavailable");
240 * @param sessionFactory
243 * @param userAppRoles
244 * @param extRequestValue
245 * set to false if request is from users page otherwise true
248 protected void syncUserRoles(SessionFactory sessionFactory, String userId, Long appId, EcompRole[] userAppRoles,
249 Boolean extRequestValue, String reqType) throws Exception {
250 boolean result = false;
251 Session localSession = null;
252 Transaction transaction = null;
253 String roleActive = null;
254 final Map<String, String> userAppParams = new HashMap<>();
255 final Map<String, String> appParams = new HashMap<>();
256 HashMap<Long, EcompRole> newUserAppRolesMap = hashMapFromEcompRoles(userAppRoles);
259 localSession = sessionFactory.openSession();
260 transaction = localSession.beginTransaction();
261 @SuppressWarnings("unchecked")
262 List<EPUser> userList = localSession
263 .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + userId + "'").list();
264 if (userList.size() > 0) {
265 EPUser client = userList.get(0);
266 roleActive = ("DELETE".equals(reqType)) ? "" : " and role.active = 'Y'";
267 @SuppressWarnings("unchecked")
268 List<EPUserApp> userRoles = localSession.createQuery("from " + EPUserApp.class.getName()
269 + " where app.id=" + appId + roleActive + " and userId=" + client.getId()).list();
271 if ("DELETE".equals(reqType)) {
272 for (EPUserApp userAppRoleList : userRoles) {
273 userAppParams.put("roleName", String.valueOf(userAppRoleList.getRole().getName()));
274 userAppParams.put("appId", String.valueOf(appId));
275 appParams.put("appRoleName", userAppRoleList.getRole().getName());
276 @SuppressWarnings("unchecked")
277 List<EPRole> rolesList = (!userAppRoleList.getRole().getName()
278 .equals(PortalConstants.ADMIN_ROLE))
279 ? (List<EPRole>) dataAccessService.executeNamedQuery("getAppRoles",
281 : (List<EPRole>) dataAccessService.executeNamedQuery("getPortalAppRoles",
283 if (rolesList.size() > 0 || !rolesList.isEmpty()) {
284 checkIfRoleInactive(rolesList.get(0));
289 for (EPUserApp userRole : userRoles) {
290 if (!userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)
291 && userRole.getRoleId() != PortalConstants.SYS_ADMIN_ROLE_ID && !extRequestValue) {
292 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
293 } else if (extRequestValue
294 && ("PUT".equals(reqType) || "POST".equals(reqType) || "DELETE".equals(reqType))) {
295 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
296 } else if (extRequestValue && !userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
297 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
300 Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values();
301 if (newRolesToAdd.size() > 0) {
302 EPApp app = (EPApp) localSession.get(EPApp.class, appId);
304 HashMap<Long, EPRole> rolesMap = new HashMap<Long, EPRole>();
305 if (appId.equals(PortalConstants.PORTAL_APP_ID)) { // local app
306 String appIdValue = "";
307 if (!extRequestValue) {
308 appIdValue = "and id != " + PortalConstants.SYS_ADMIN_ROLE_ID;
310 @SuppressWarnings("unchecked")
311 List<EPRole> roles = localSession
312 .createQuery("from " + EPRole.class.getName() + " where appId is null " + appIdValue)
314 for (EPRole role : roles) {
316 rolesMap.put(role.getId(), role);
318 } else { // remote app
319 @SuppressWarnings("unchecked")
320 List<EPRole> roles = localSession
321 .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list();
322 for (EPRole role : roles) {
323 if (!extRequestValue && app.getCentralAuth()) {
324 rolesMap.put(role.getId(), role);
326 rolesMap.put(role.getAppRoleId(), role);
332 for (EcompRole userRole : newRolesToAdd) {
333 EPUserApp userApp = new EPUserApp();
334 if (("PUT".equals(reqType) || "POST".equals(reqType))
335 && userRole.getName().equals(PortalConstants.ADMIN_ROLE)) {
336 role = (EPRole) localSession.get(EPRole.class,
337 new Long(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
338 userApp.setRole(role);
339 } else if ((userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID))
340 && !extRequestValue) {
342 } else if ((userRole.getId().equals(PortalConstants.SYS_ADMIN_ROLE_ID))
343 && app.getId().equals(PortalConstants.PORTAL_APP_ID) && !extRequestValue) {
346 userApp.setRole(rolesMap.get(userRole.getId()));
349 userApp.setUserId(client.getId());
351 localSession.save(userApp);
352 localSession.flush();
355 if (appId == PortalConstants.PORTAL_APP_ID) {
357 * for local app -- hack - always make sure fn_role table's app_id is null and
358 * not 1 for primary app in this case being ecomp portal app; reason: hibernate
359 * is rightly setting this to 1 while persisting to fn_role as per the mapping
360 * but SDK role management code expects the app_id to be null as there is no
361 * concept of App_id in SDK
363 localSession.flush();
364 SQLQuery sqlQuery = localSession
365 .createSQLQuery("update fn_role set app_id = null where app_id = 1 ");
366 sqlQuery.executeUpdate();
371 transaction.commit();
373 } catch (Exception e) {
374 logger.error(EELFLoggerDelegate.errorLogger, "syncUserRoles failed", e);
375 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
376 EcompPortalUtils.rollbackTransaction(transaction,
377 "Exception occurred in syncUserRoles, Details: " + e.toString());
378 if ("DELETE".equals(reqType)) {
379 throw new Exception(e.getMessage());
382 localSession.close();
383 if (!result && !"DELETE".equals(reqType)) {
385 "Exception occurred in syncUserRoles while closing database session for app: '" + appId + "'.");
391 * Called when getting the list of roles for the user
394 * @param userAppRoles
395 * @return List<RoleInAppForUser>
397 protected List<RoleInAppForUser> constructRolesInAppForUserGet(EcompRole[] appRoles, EcompRole[] userAppRoles) {
398 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
400 Set<Long> userAppRolesMap = new HashSet<Long>();
401 if (userAppRoles != null) {
402 for (EcompRole ecompRole : userAppRoles) {
403 userAppRolesMap.add(ecompRole.getId());
406 logger.error(EELFLoggerDelegate.errorLogger,
407 "constructRolesInAppForUserGet has received userAppRoles list empty");
410 if (appRoles != null) {
411 for (EcompRole ecompRole : appRoles) {
412 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
413 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
414 rolesInAppForUser.add(roleForUser);
417 logger.error(EELFLoggerDelegate.errorLogger, "constructRolesInAppForUser has received appRoles list empty");
419 return rolesInAppForUser;
423 * Called when getting the list of roles for the user
426 * @param userAppRoles
427 * @param extRequestValue
428 * set to false if request is from users page otherwise true
429 * @return List<RoleInAppForUser>
431 protected List<RoleInAppForUser> constructRolesInAppForUserGet(List<Role> appRoles, EPRole[] userAppRoles,
432 Boolean extRequestValue) {
433 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
435 Set<Long> userAppRolesMap = new HashSet<Long>();
436 if (userAppRoles != null) {
437 for (EPRole ecompRole : userAppRoles) {
438 userAppRolesMap.add(ecompRole.getId());
441 logger.error(EELFLoggerDelegate.errorLogger,
442 "constructRolesInAppForUserGet has received userAppRoles list empty.");
445 if (appRoles != null) {
446 for (Role ecompRole : appRoles) {
447 if (ecompRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && !extRequestValue)
449 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
450 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
451 rolesInAppForUser.add(roleForUser);
454 logger.error(EELFLoggerDelegate.errorLogger,
455 "constructRolesInAppForUser has received appRoles list empty.");
457 return rolesInAppForUser;
461 * copies of methods in GetAppsWithUserRoleState
463 * @param sessionFactory
468 protected void syncAppRoles(SessionFactory sessionFactory, Long appId, EcompRole[] appRoles) throws Exception {
469 logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId);
470 HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles);
471 Session localSession = null;
472 Transaction transaction = null;
475 localSession = sessionFactory.openSession();
476 transaction = localSession.beginTransaction();
477 // Attention! All roles from remote application supposed to be
479 @SuppressWarnings("unchecked")
480 List<EPRole> currentAppRoles = localSession
481 .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list();
482 List<EPRole> obsoleteRoles = new ArrayList<EPRole>();
483 for (int i = 0; i < currentAppRoles.size(); i++) {
484 EPRole oldAppRole = currentAppRoles.get(i);
485 if (oldAppRole.getAppRoleId() != null) {
486 EcompRole role = null;
487 role = newRolesMap.get(oldAppRole.getAppRoleId());
489 if (!(role.getName() == null || oldAppRole.getName().equals(role.getName()))) {
490 oldAppRole.setName(role.getName());
491 localSession.update(oldAppRole);
493 newRolesMap.remove(oldAppRole.getAppRoleId());
495 obsoleteRoles.add(oldAppRole);
498 obsoleteRoles.add(oldAppRole);
501 Collection<EcompRole> newRolesToAdd = newRolesMap.values();
502 if (obsoleteRoles.size() > 0) {
503 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: we have obsolete roles to delete");
504 for (EPRole role : obsoleteRoles) {
505 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: obsolete role: " + role.toString());
506 Long roleId = role.getId();
507 // delete obsolete roles here
508 // Must delete all records with foreign key constraints on
510 // fn_user_role, fn_role_composite, fn_role_function,
511 // fn_user_pseudo_role, fn_menu_functional_roles.
512 // And for fn_menu_functional, if no other roles for that
513 // menu item, remove the url.
515 // Delete from fn_user_role
516 @SuppressWarnings("unchecked")
517 List<EPUserApp> userRoles = localSession.createQuery(
518 "from " + EPUserApp.class.getName() + " where app.id=" + appId + " and role_id=" + roleId)
521 logger.debug(EELFLoggerDelegate.debugLogger,
522 "syncAppRoles: number of userRoles to delete: " + userRoles.size());
523 for (EPUserApp userRole : userRoles) {
524 logger.debug(EELFLoggerDelegate.debugLogger,
525 "syncAppRoles: about to delete userRole: " + userRole.toString());
526 localSession.delete(userRole);
527 logger.debug(EELFLoggerDelegate.debugLogger,
528 "syncAppRoles: finished deleting userRole: " + userRole.toString());
531 // Delete from fn_menu_functional_roles
532 @SuppressWarnings("unchecked")
533 List<FunctionalMenuRole> funcMenuRoles = localSession
534 .createQuery("from " + FunctionalMenuRole.class.getName() + " where roleId=" + roleId)
536 int numMenuRoles = funcMenuRoles.size();
537 logger.debug(EELFLoggerDelegate.debugLogger,
538 "syncAppRoles: number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles);
539 for (FunctionalMenuRole funcMenuRole : funcMenuRoles) {
540 Long menuId = funcMenuRole.menuId;
541 // If this is the only role for this menu item, then the
542 // app and roles will be gone,
543 // so must null out the url too, to be consistent
544 @SuppressWarnings("unchecked")
545 List<FunctionalMenuRole> funcMenuRoles2 = localSession
546 .createQuery("from " + FunctionalMenuRole.class.getName() + " where menuId=" + menuId)
548 int numMenuRoles2 = funcMenuRoles2.size();
549 logger.debug(EELFLoggerDelegate.debugLogger,
550 "syncAppRoles: number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2);
551 localSession.delete(funcMenuRole);
552 if (numMenuRoles2 == 1) {
553 // If this is the only role for this menu item, then
554 // the app and roles will be gone,
555 // so must null out the url too, to be consistent
556 logger.debug(EELFLoggerDelegate.debugLogger,
557 "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url");
558 @SuppressWarnings("unchecked")
559 List<FunctionalMenuItem> funcMenuItems = localSession
561 "from " + FunctionalMenuItem.class.getName() + " where menuId=" + menuId)
563 if (funcMenuItems.size() > 0) {
564 logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item");
565 FunctionalMenuItem funcMenuItem = funcMenuItems.get(0);
566 funcMenuItem.url = "";
567 localSession.update(funcMenuItem);
571 externalAccessRolesService.deleteRoleDependencyRecords(localSession, roleId, appId);
572 logger.debug(EELFLoggerDelegate.debugLogger,
573 "syncAppRoles: about to delete the role: " + role.toString());
574 localSession.delete(role);
575 localSession.flush();
576 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: deleted the role");
579 for (EcompRole role : newRolesToAdd) {
580 logger.debug(EELFLoggerDelegate.debugLogger,
581 "syncAppRoles: about to add missing role: " + role.toString());
582 EPRole newRole = new EPRole();
583 // Attention! All roles from remote application supposed to be
585 newRole.setActive(true);
586 newRole.setName(role.getName());
587 newRole.setAppId(appId);
588 newRole.setAppRoleId(role.getId());
589 localSession.save(newRole);
591 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to commit the transaction");
592 transaction.commit();
593 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: committed the transaction");
594 } catch (Exception e) {
595 logger.error(EELFLoggerDelegate.errorLogger, "syncAppRoles failed", e);
596 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
597 EcompPortalUtils.rollbackTransaction(transaction,
598 "Exception occurred in syncAppRoles, Details: " + e.toString());
599 throw new Exception(e);
601 localSession.close();
606 * Called when updating the list of roles for the user
610 * @param userRolesInRemoteApp
611 * @return RolesInAppForUser
613 protected RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId,
614 Set<EcompRole> userRolesInRemoteApp) {
615 RolesInAppForUser result;
616 result = new RolesInAppForUser();
617 result.appId = appId;
618 result.orgUserId = userId;
619 for (EcompRole role : userRolesInRemoteApp) {
620 RoleInAppForUser roleInAppForUser = new RoleInAppForUser();
621 roleInAppForUser.roleId = role.getId();
622 roleInAppForUser.roleName = role.getName();
623 roleInAppForUser.isApplied = new Boolean(true);
624 result.roles.add(roleInAppForUser);
631 * @param roleInAppForUserList
634 protected boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) {
635 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
636 if (roleInAppForUser.isApplied.booleanValue()) {
644 * Builds JSON and posts it to a remote application to update user roles.
646 * @param roleInAppForUserList
648 * @param applicationsRestClientService
651 * @return Set of roles as sent; NOT the response from the app.
652 * @throws JsonProcessingException
653 * @throws HTTPException
655 protected Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
656 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
657 throws JsonProcessingException, HTTPException {
658 Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList);
659 Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList);
660 String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote);
661 applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString,
662 String.format("/user/%s/roles", userId));
663 // TODO: We should add code that verifies that the post operation did
664 // succeed. Because the SDK may still return 200 OK with an html page
665 // even when it fails!
666 return updateUserRolesInEcomp;
671 * @param roleInAppForUserList
672 * @return Set<EcompRole>
674 protected Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) {
675 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
676 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
677 if (roleInAppForUser.isApplied) {
678 EcompRole ecompRole = new EcompRole();
679 ecompRole.setId(roleInAppForUser.roleId);
680 ecompRole.setName(roleInAppForUser.roleName);
681 existingUserRoles.add(ecompRole);
684 return existingUserRoles;
688 * Constructs user app roles excluding Account Administrator role
690 * @param roleInAppForUserList
691 * @return List of roles with Role name, Role Id
693 protected Set<EcompRole> constructUsersRemoteAppRoles(List<RoleInAppForUser> roleInAppForUserList) {
694 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
695 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
696 if (roleInAppForUser.isApplied
697 && !roleInAppForUser.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
698 EcompRole ecompRole = new EcompRole();
699 ecompRole.setId(roleInAppForUser.roleId);
700 ecompRole.setName(roleInAppForUser.roleName);
701 existingUserRoles.add(ecompRole);
704 return existingUserRoles;
708 * This is for a single app
710 * @param rolesInAppForUser
711 * @param externalSystemRequest
712 * set to false if requests from Users page otherwise true
713 * @return true on success, false otherwise
715 protected boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser,
716 boolean externalSystemRequest, String reqType) throws Exception {
717 boolean result = false;
718 String userId = rolesInAppForUser.orgUserId;
719 Long appId = rolesInAppForUser.appId;
720 synchronized (syncRests) {
721 if (rolesInAppForUser != null) {
722 createLocalUserIfNecessary(userId);
725 if (rolesInAppForUser != null) {
726 EcompRole[] userAppRoles = new EcompRole[rolesInAppForUser.roles.stream().distinct()
727 .collect(Collectors.toList()).size()];
728 for (int i = 0; i < rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList())
730 RoleInAppForUser roleInAppForUser = rolesInAppForUser.roles.get(i);
731 EcompRole role = new EcompRole();
732 role.setId(roleInAppForUser.roleId);
733 role.setName(roleInAppForUser.roleName);
734 userAppRoles[i] = role;
737 syncUserRoles(sessionFactory, userId, appId, userAppRoles, externalSystemRequest, reqType);
739 } catch (Exception e) {
740 logger.error(EELFLoggerDelegate.errorLogger,
741 "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for orgUserId " + userId,
743 if ("DELETE".equals(reqType)) {
744 throw new Exception(e.getMessage());
756 * @return UserApplicationRoles
758 protected UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) {
759 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
760 userWithRemoteAppRoles.setAppId(appId);
761 userWithRemoteAppRoles.setOrgUserId(remoteUser.getOrgUserId());
762 userWithRemoteAppRoles.setFirstName(remoteUser.getFirstName());
763 userWithRemoteAppRoles.setLastName(remoteUser.getLastName());
764 userWithRemoteAppRoles.setRoles(remoteUser.getRoles());
765 return userWithRemoteAppRoles;
771 * @see org.openecomp.portalapp.portal.service.UserRolesService#
772 * importRolesFromRemoteApplication(java.lang.Long)
774 public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException {
775 EPRole[] appRolesFull = applicationsRestClientService.get(EPRole[].class, appId, "/rolesFull");
776 List<EPRole> rolesList = Arrays.asList(appRolesFull);
777 for (EPRole externalAppRole : rolesList) {
779 // Try to find an existing extern role for the app in the local
780 // ecomp DB. If so, then use its id to update the existing external
781 // application role record.
782 Long externAppId = externalAppRole.getId();
783 EPRole existingAppRole = epRoleService.getRole(appId, externAppId);
784 if (existingAppRole != null) {
785 logger.debug(EELFLoggerDelegate.debugLogger,
786 String.format("ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.",
787 appId, externAppId));
790 // persistExternalRoleInEcompDb(externalAppRole, appId,
798 * It adds new user for remote application
800 * @param roleInAppForUserList
801 * @param remoteAppUser
805 * @param searchService
806 * @param applicationsRestClientService
810 private EPUser addRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app,
811 ObjectMapper mapper, SearchService searchService,
812 ApplicationsRestClientService applicationsRestClientService) throws Exception {
813 EPUser addRemoteUser = null;
814 if (remoteUserShouldBeCreated(roleInAppForUserList)) {
816 createNewUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper,
817 isAppUpgradeVersion(app));
818 // If we succeed, we know that the new user was
819 // persisted on remote app.
820 addRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
821 if (addRemoteUser == null) {
822 logger.error(EELFLoggerDelegate.errorLogger,
823 "Failed to persist new user: " + userId + " in remote app. appId = " + app.getId());
827 return addRemoteUser;
831 * It checks whether the remote user exists or not if exits returns user object
836 * @param applicationsRestClientService
838 * @throws HTTPException
840 private EPUser checkIfRemoteUserExits(String userId, EPApp app,
841 ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
842 EPUser checkRemoteUser = null;
844 checkRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
845 } catch (HTTPException e) {
846 // Some apps are returning 400 if user is not found.
847 if (e.getResponseCode() == 400) {
848 logger.debug(EELFLoggerDelegate.debugLogger,
849 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing",
851 } else if (e.getResponseCode() == 404) {
852 logger.debug(EELFLoggerDelegate.debugLogger,
853 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 404; continuing",
856 // Other response code, let it come thru.
860 return checkRemoteUser;
866 * @see org.openecomp.portalapp.portal.service.UserRolesService#
867 * setAppWithUserRoleStateForUser(org.openecomp.portalapp.portal.domain. EPUser,
868 * org.openecomp.portalapp.portal.transport.AppWithRolesForUser)
870 public boolean setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser) {
871 boolean result = false;
872 boolean epRequestValue = false;
874 if (newAppRolesForUser != null && newAppRolesForUser.orgUserId != null) {
875 userId = newAppRolesForUser.orgUserId.trim();
877 Long appId = newAppRolesForUser.appId;
878 List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.appRoles;
879 if (userId.length() > 0) {
880 ObjectMapper mapper = new ObjectMapper();
881 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
884 EPApp app = appsService.getApp(appId);
885 applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
887 // if centralized app
888 if (app.getCentralAuth()) {
889 // We should add If user does not exist in remote application
890 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
891 EPUser remoteAppUser = null;
892 remoteAppUser = checkIfRemoteUserExits(userId, app, applicationsRestClientService);
894 if (remoteAppUser == null) {
895 addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService,
896 applicationsRestClientService);
900 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
901 applicationsRestClientService, appId, userId);
902 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
903 userRolesInLocalApp);
904 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
905 // Apply changes in external Access system
906 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, epRequestValue);
907 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal");
909 // In case if portal is not centralized then follow existing approach
910 else if (!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
911 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
912 applicationsRestClientService, appId, userId);
913 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
914 userRolesInLocalApp);
915 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal");
916 } else {// remote app
917 EPUser remoteAppUser = null;
918 if (!app.getCentralAuth() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
920 remoteAppUser = checkIfRemoteUserExits(userId, app, applicationsRestClientService);
922 if (remoteAppUser == null) {
923 remoteAppUser = addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService,
924 applicationsRestClientService);
926 if (remoteAppUser != null) {
927 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList,
928 mapper, applicationsRestClientService, appId, userId);
929 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
930 userRolesInRemoteApp);
931 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null);
933 // If no roles remain, request app to set user inactive.
934 if (userRolesInRemoteApp.size() == 0) {
935 logger.debug(EELFLoggerDelegate.debugLogger,
936 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive",
938 remoteAppUser.setActive(false);
939 postUserToRemoteApp(userId, user, app, applicationsRestClientService);
944 } catch (Exception e) {
945 String message = String.format("Failed to create user or update user roles for User %s, AppId %s",
946 userId, Long.toString(appId));
947 logger.error(EELFLoggerDelegate.errorLogger, message, e);
956 * It adds user roles in External system and also make data consistent in both
957 * local and in External System
962 * @param roleInAppUser
963 * Contains list of active roles
965 @SuppressWarnings("unchecked")
966 private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser,
967 boolean isPortalRequest) {
969 // check if user exists
970 final Map<String, String> userParams = new HashMap<>();
971 userParams.put("orgUserIdValue", orgUserId);
972 List<EPUser> userInfo = checkIfUserExists(userParams);
973 if (userInfo.isEmpty()) {
974 createLocalUserIfNecessary(orgUserId);
977 if (EPCommonSystemProperties
978 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
980 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
982 ObjectMapper mapper = new ObjectMapper();
983 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
984 HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
985 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles");
986 ResponseEntity<String> getResponse = template
987 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
988 + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class);
989 if (getResponse.getStatusCode().value() == 200) {
990 logger.debug(EELFLoggerDelegate.debugLogger,
991 "updateUserRolesInExternalSystem: Finished GET user roles from external system and received user roles {}",
992 getResponse.getBody());
995 List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
996 String res = getResponse.getBody();
997 JSONObject jsonObj = null;
998 JSONArray extRoles = null;
999 if (!res.equals("{}")) {
1000 jsonObj = new JSONObject(res);
1001 extRoles = jsonObj.getJSONArray("role");
1003 ExternalAccessUserRoleDetail userRoleDetail = null;
1004 if (extRoles != null) {
1005 for (int i = 0; i < extRoles.length(); i++) {
1006 if (extRoles.getJSONObject(i).getString("name").startsWith(app.getNameSpace() + ".")
1007 && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".admin")
1008 && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".owner")) {
1009 ObjectMapper descMapper = new ObjectMapper();
1010 if (extRoles.getJSONObject(i).has("description")) {
1011 ExternalRoleDescription desc = descMapper.readValue(
1012 extRoles.getJSONObject(i).getString("description"), ExternalRoleDescription.class);
1013 userRoleDetail = new ExternalAccessUserRoleDetail(
1014 extRoles.getJSONObject(i).getString("name"), desc);
1015 userRoleDetailList.add(userRoleDetail);
1017 userRoleDetail = new ExternalAccessUserRoleDetail(
1018 extRoles.getJSONObject(i).getString("name"), null);
1019 userRoleDetailList.add(userRoleDetail);
1025 // If request coming from portal not from external role approval system then we
1026 // have to check if user already
1027 // have account admin or system admin as GUI will not send these roles
1028 if (!isPortalRequest) {
1029 final Map<String, String> loginIdParams = new HashMap<>();
1030 loginIdParams.put("orgUserIdValue", orgUserId);
1031 EPUser user = (EPUser) dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null).get(0);
1032 final Map<String, Long> params = new HashMap<>();
1033 params.put("appId", app.getId());
1034 params.put("userId", user.getId());
1035 List<EcompUserAppRoles> userAppList = dataAccessService.executeNamedQuery("getUserAppExistingRoles",
1037 if (!roleInAppUser.isEmpty()) {
1038 for (EcompUserAppRoles userApp : userAppList) {
1039 if (userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)
1040 || userApp.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
1041 RoleInAppForUser addSpecialRole = new RoleInAppForUser();
1042 addSpecialRole.setIsApplied(true);
1043 addSpecialRole.setRoleId(userApp.getRoleId());
1044 addSpecialRole.setRoleName(userApp.getRoleName());
1045 roleInAppUser.add(addSpecialRole);
1050 List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct()
1051 .collect(Collectors.toList());
1052 final Map<String, RoleInAppForUser> currentUserRolesToUpdate = new HashMap<>();
1053 for (RoleInAppForUser roleInAppUserNew : roleInAppUser) {
1054 currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName(), roleInAppUserNew);
1056 final Map<String, ExternalAccessUserRoleDetail> currentUserRolesInExternalSystem = new HashMap<>();
1057 for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleDetailList) {
1058 currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole);
1060 // Check if roles does not exists in local but still there in External Central
1061 // Auth System delete them all
1062 for (ExternalAccessUserRoleDetail userRole : userRoleDetailList) {
1063 if (!(currentUserRolesToUpdate
1064 .containsKey(userRole.getName().substring(app.getNameSpace().length() + 1).replaceAll("_", " "))
1065 || currentUserRolesToUpdate
1066 .containsKey(userRole.getName().substring(app.getNameSpace().length() + 1)))) {
1067 HttpEntity<String> entity = new HttpEntity<>(headers);
1068 logger.debug(EELFLoggerDelegate.debugLogger,
1069 "updateUserRolesInExternalSystem: Connecting to external system to DELETE user role {}",
1071 ResponseEntity<String> deleteResponse = template.exchange(
1072 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1073 + "userRole/" + name + "/" + userRole.getName(),
1074 HttpMethod.DELETE, entity, String.class);
1075 logger.debug(EELFLoggerDelegate.debugLogger,
1076 "updateUserRolesInExternalSystem: Finished DELETE operation in external system for user role {} and the response is {}",
1077 userRole, deleteResponse.getBody());
1080 // Check if user roles does not exists in External Central Auth System add them
1082 for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) {
1083 if (!(currentUserRolesInExternalSystem
1084 .containsKey(app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(" ", "_")))) {
1085 ExternalAccessUser extUser = new ExternalAccessUser(name,
1086 app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(" ", "_"));
1087 String formattedUserRole = mapper.writeValueAsString(extUser);
1088 HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers);
1089 logger.debug(EELFLoggerDelegate.debugLogger,
1090 "updateUserRolesInExternalSystem: Connecting to external system and adding user role",
1091 addUserRole.getRoleName());
1092 ResponseEntity<String> addResponse = template
1093 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1094 + "userRole", HttpMethod.POST, entity, String.class);
1095 logger.debug(EELFLoggerDelegate.debugLogger,
1096 "updateUserRolesInExternalSystem: Finished adding user role in external system {} and added user role {}",
1097 getResponse.getBody(), addUserRole.getRoleName());
1098 if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 404) {
1099 logger.debug(EELFLoggerDelegate.debugLogger,
1100 "Finished POST operation in external system but unable to save user role",
1101 getResponse.getBody(), addUserRole.getRoleName());
1102 throw new Exception(addResponse.getBody());
1106 } catch (Exception e) {
1107 logger.error(EELFLoggerDelegate.errorLogger,
1108 "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}",
1118 * @param applicationsRestClientService
1119 * @param searchService
1123 protected void createNewUserOnRemoteApp(String userId, EPApp app,
1124 ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
1125 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,
1150 EPUserAppRolesRequest epUserAppRolesRequest) {
1151 final Map<String, Long> epRequestParams = new HashMap<>();
1153 EPUserAppRolesRequest epAppRolesRequestData = epUserAppRolesRequest;
1154 epAppRolesRequestData.setUpdatedDate(new Date());
1155 epAppRolesRequestData.setRequestStatus(updateStatus);
1156 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1157 addiotonalUpdateParam.put("userId", userId);
1158 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1159 epRequestParams.put("reqId", epUserAppRolesRequest.getId());
1160 List<EPUserAppRolesRequestDetail> epUserAppRolessDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1161 epUserAppRolessDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1162 epRequestParams, null);
1163 if (epUserAppRolessDetailList.size() > 0) {
1164 for (EPUserAppRolesRequestDetail epRequestUpdateData : epUserAppRolessDetailList) {
1165 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateData;
1166 epAppRoleDetailData.setReqType(updateStatus);
1167 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1168 HashMap<String, Long> updateDetailsParam = new HashMap<String, Long>();
1169 addiotonalUpdateParam.put("reqId", epUserAppRolesRequest.getId());
1170 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParam);
1173 logger.debug(EELFLoggerDelegate.debugLogger, "The request is set to complete");
1175 } catch (Exception e) {
1176 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToAppRolesRequest failed", e);
1180 @SuppressWarnings("unchecked")
1181 public void applyChangesToUserAppRolesForMyLoginsRequest(EPUser user, Long appId) {
1182 final Map<String, Long> params = new HashMap<>();
1183 final Map<String, Long> epDetailParams = new HashMap<>();
1184 List<EPUserAppRolesRequest> epRequestIdVal = new ArrayList<EPUserAppRolesRequest>();
1185 params.put("appId", appId);
1186 params.put("userId", user.getId());
1188 epRequestIdVal = (List<EPUserAppRolesRequest>) dataAccessService
1189 .executeNamedQuery("userAppRolesRequestList", params, null);
1190 if (epRequestIdVal.size() > 0) {
1191 EPUserAppRolesRequest epAppRolesRequestData = epRequestIdVal.get(0);
1192 epAppRolesRequestData.setUpdatedDate(new Date());
1193 epAppRolesRequestData.setRequestStatus("O");
1194 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1195 addiotonalUpdateParam.put("userId", user.getId());
1196 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1197 epDetailParams.put("reqId", epAppRolesRequestData.getId());
1198 List<EPUserAppRolesRequestDetail> epUserAppRolesDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1199 epUserAppRolesDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1200 epDetailParams, null);
1201 if (epUserAppRolesDetailList.size() > 0) {
1202 for (EPUserAppRolesRequestDetail epRequestUpdateList : epUserAppRolesDetailList) {
1203 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateList;
1204 epAppRoleDetailData.setReqType("O");
1205 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1206 HashMap<String, Long> updateDetailsParams = new HashMap<String, Long>();
1207 addiotonalUpdateParam.put("reqId", epAppRolesRequestData.getId());
1208 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParams);
1210 logger.debug(EELFLoggerDelegate.debugLogger, "User App roles request from User Page is overridden");
1214 } catch (Exception e) {
1215 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e);
1220 * Pushes specified user details to the specified remote app.
1223 * OrgUserId identifying user at remote app in REST endpoint path
1225 * User details to be pushed
1228 * @param applicationsRestClientService
1229 * @throws HTTPException
1231 protected void postUserToRemoteApp(String userId, EPUser user, EPApp app,
1232 ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
1234 getUser(userId, app, applicationsRestClientService);
1239 * It returns user details for single org user id
1242 * @return 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
1254 * @return Checks if user is valid and returns message otherwise throws
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,
1293 boolean result = false;
1294 boolean externalSystemRequest = true;
1295 final Map<String, Long> params = new HashMap<>();
1296 final Map<String, String> userParams = new HashMap<>();
1297 List<EPUser> userInfo = null;
1298 EPUser userId = null;
1299 List<EPUserAppRolesRequest> epRequestId = null;
1300 String orgUserId = "";
1301 String updateStatus = "";
1302 String reqMessage = "";
1304 if (newAppRolesForUser != null && newAppRolesForUser.getLoginId() != null) {
1305 orgUserId = newAppRolesForUser.getLoginId().trim();
1307 String appName = newAppRolesForUser.getApplicationName();
1308 String logMessage = ("DELETE").equals(reqType) ? "Deleting" : "Assigning/Updating";
1309 if (orgUserId.length() > 0) {
1310 ObjectMapper mapper = new ObjectMapper();
1311 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1312 int epRequestIdSize = 0;
1314 app = appsService.getAppDetail(appName);
1315 userParams.put("orgUserIdValue", orgUserId);
1316 userInfo = checkIfUserExists(userParams);
1317 reqMessage = "Updated Successfully";
1318 if (!reqType.equals("DELETE") && (userInfo.size() == 0 || userInfo.isEmpty())) {
1319 reqMessage = validateNewUser(orgUserId, app);
1321 if (userInfo.size() != 0 || !userInfo.isEmpty()) {
1322 validateExternalRequestFields(userInfo, app);
1323 userId = userInfo.get(0);
1324 params.put("appId", app.getId());
1325 params.put("userId", userId.getId());
1326 epRequestId = (List<EPUserAppRolesRequest>) dataAccessService
1327 .executeNamedQuery("userAppRolesRequestList", params, null);
1328 epRequestIdSize = epRequestId.size();
1331 // If Non-Centralized app make sure you sync app roles before assigning to user
1332 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !app.getCentralAuth()) {
1333 EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, app.getId(), "/roles");
1334 syncAppRoles(sessionFactory, app.getId(), appRoles);
1336 List<RoleInAppForUser> roleInAppForUserList = roleInAppForUserList(newAppRolesForUser.getRoles(),
1337 app.getId(), app.getMlAppName());
1338 List<EcompUserAppRoles> userRoleList = null;
1339 if (!userInfo.isEmpty()) {
1340 final Map<String, Long> appParams = new HashMap<>();
1341 appParams.put("userId", userId.getId());
1342 appParams.put("appId", app.getId());
1343 userRoleList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", appParams, null);
1345 // Check if list contains just account admin role
1346 boolean checkIfAdminRoleExists = false;
1347 if (reqType.equals("DELETE") && userRoleList != null) {
1348 checkIfAdminRoleExists = userRoleList.stream()
1349 .anyMatch(userRole -> userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1351 checkIfAdminRoleExists = roleInAppForUserList.stream()
1352 .anyMatch(roleList -> roleList.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1354 // if Centralized app
1355 if (app.getCentralAuth()) {
1356 // We should add If user does not exist in remote application
1358 // If adding just account admin role dont make remote application user call
1359 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)
1360 && !(checkIfAdminRoleExists && reqType.equals("DELETE"))
1361 && roleInAppForUserList.size() > 1) {
1362 EPUser remoteAppUser = null;
1363 remoteAppUser = checkIfRemoteUserExits(orgUserId, app, applicationsRestClientService);
1364 if (remoteAppUser == null) {
1365 addRemoteUser(roleInAppForUserList, orgUserId, app, mapper, searchService,
1366 applicationsRestClientService);
1367 reqMessage = "Saved Successfully";
1370 } catch (Exception e) {
1371 reqMessage = e.getMessage();
1372 logger.error(EELFLoggerDelegate.errorLogger,
1373 "setExternalRequestUserAppRole: Failed to added remote user", e);
1374 throw new Exception(reqMessage);
1376 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1377 applicationsRestClientService, app.getId(), orgUserId);
1378 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1379 userRolesInLocalApp);
1380 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1381 // Apply changes in external Access system
1382 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList,
1383 externalSystemRequest);
1384 logger.info(EELFLoggerDelegate.debugLogger,
1385 "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
1386 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1387 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType);
1389 // If local application is not centralized
1390 else if (!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1391 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1392 applicationsRestClientService, app.getId(), orgUserId);
1393 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1394 userRolesInLocalApp);
1395 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType);
1396 } else {// remote app
1397 // If adding just account admin role don't do remote application user call
1398 if (!((roleInAppForUserList.size() == 1 || reqType.equals("DELETE")) && checkIfAdminRoleExists)) {
1399 EPUser remoteAppUser = null;
1400 remoteAppUser = checkIfRemoteUserExits(orgUserId, app, applicationsRestClientService);
1401 if (remoteAppUser == null) {
1402 remoteAppUser = addRemoteUser(roleInAppForUserList, orgUserId, app, mapper, searchService,
1403 applicationsRestClientService);
1404 reqMessage = "Saved Successfully";
1406 if (remoteAppUser != null) {
1407 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList,
1408 mapper, applicationsRestClientService, app.getId(), orgUserId);
1410 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId,
1411 app.getId(), userRolesInRemoteApp);
1412 logger.info(EELFLoggerDelegate.debugLogger,
1413 "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
1414 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1415 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1417 // 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"
1422 * , app, orgUserId); //TODO Need to fix the logged in user is not set to
1423 * inactive remoteAppUser.setActive(false); postUserToRemoteApp(orgUserId, user,
1424 * app, applicationsRestClientService); }
1428 // Here we are adding only we have single account admin in roleInAppForUserList
1429 // 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,
1438 "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
1439 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1440 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1444 reqMessage = "Failed to save the user app role(s)";
1446 if (epRequestIdSize > 0 && !userInfo.isEmpty()) {
1448 applyChangesToAppRolesRequest(app.getId(), userId.getId(), updateStatus, epRequestId.get(0));
1451 } catch (Exception e) {
1452 String message = String.format(
1453 "setExternalRequestUserAppRole: Failed to create user or update user roles for User %s, AppId %s",
1454 orgUserId, appName);
1455 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1457 reqMessage = e.getMessage();
1458 if (epRequestIdSize > 0 && userInfo != null && !userInfo.isEmpty()) {
1460 applyChangesToAppRolesRequest(app.getId(), userId.getId(), updateStatus, epRequestId.get(0));
1465 return new ExternalRequestFieldsValidator(result, reqMessage);
1470 * @param roleInAppForUserList
1472 * @param applicationsRestClientService
1475 * @return Set<EcompRole>
1476 * @throws JsonProcessingException
1477 * @throws HTTPException
1479 private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
1480 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
1481 throws JsonProcessingException, HTTPException {
1482 Set<EcompRole> updatedUserRoles = constructUsersEcompRoles(roleInAppForUserList);
1483 return updatedUserRoles;
1487 * It constructs and returns list of user app roles when the external API role
1488 * approval system calls this method
1490 * @param roleInAppForUserList
1492 * @return list of user app roles
1494 * throws exceptions if role id does not exits
1496 private List<RoleInAppForUser> roleInAppForUserList(List<ExternalSystemRoleApproval> roleInAppForUserList,
1497 Long appId, String appName) throws Exception {
1498 List<RoleInAppForUser> existingUserRoles = new ArrayList<RoleInAppForUser>();
1499 EPRole existingAppRole = null;
1500 for (ExternalSystemRoleApproval roleInAppForUser : roleInAppForUserList) {
1501 RoleInAppForUser ecompRole = new RoleInAppForUser();
1502 existingAppRole = epRoleService.getAppRole(roleInAppForUser.getRoleName(), appId);
1503 if (existingAppRole == null) {
1504 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1505 roleInAppForUserList);
1506 throw new Exception("'" + roleInAppForUser.getRoleName() + "'" + " role does not exist for " + appName
1509 if (!existingAppRole.getActive()) {
1510 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1511 roleInAppForUserList);
1512 throw new Exception(
1513 roleInAppForUser.getRoleName() + " role is unavailable for " + appName + " application");
1515 ecompRole.roleId = (appId == 1 || roleInAppForUser.getRoleName().equals(PortalConstants.ADMIN_ROLE))
1516 ? existingAppRole.getId()
1517 : existingAppRole.getAppRoleId();
1518 ecompRole.roleName = roleInAppForUser.getRoleName();
1519 ecompRole.isApplied = true;
1520 existingUserRoles.add(ecompRole);
1523 return existingUserRoles;
1530 * @param applicationsRestClientService
1532 * @throws HTTPException
1534 protected EPUser getUserFromApp(String userId, EPApp app,
1535 ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
1537 if (app.getId() == PortalConstants.PORTAL_APP_ID) {
1538 // Map<String,String> params = new HashMap<String,String>();
1539 // params.put("sbcid",userId);
1540 @SuppressWarnings("unchecked")
1541 List<EPUser> userList = (List<EPUser>) dataAccessService
1542 .executeQuery("from EPUser where orgUserId='" + userId + "'", null);
1543 if (userList != null && !userList.isEmpty())
1544 return userList.get(0);
1550 return getUser(userId, app, applicationsRestClientService);
1553 protected EPUser getUser(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1554 throws HTTPException {
1555 return applicationsRestClientService.get(EPUser.class, app.getId(), String.format("/user/%s", userId));
1559 protected boolean isAppUpgradeVersion(EPApp app) {
1563 public ExternalSystemAccess getExternalRequestAccess() {
1564 ExternalSystemAccess res = null;
1566 res = new ExternalSystemAccess(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE, Boolean
1567 .parseBoolean(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE)));
1568 } catch (Exception e) {
1569 logger.error(EELFLoggerDelegate.errorLogger, "getExternalRequestAccess failed" + e.getMessage());
1577 * @see org.openecomp.portalapp.portal.service.UserRolesService#
1578 * getAppRolesForUser(java.lang.Long, java.lang.String)
1580 @SuppressWarnings("unchecked")
1581 public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId, Boolean extRequestValue) {
1583 List<RoleInAppForUser> rolesInAppForUser = null;
1584 EPApp app = appsService.getApp(appId);
1586 // for ecomp portal app, no need to make a remote call
1587 List<Role> roleList = new ArrayList<>();
1588 if (appId == PortalConstants.PORTAL_APP_ID) {
1589 if (app.getCentralAuth()) {
1590 List<CentralRole> cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey());
1591 for (CentralRole cenRole : cenRoleList) {
1592 Role role = new Role();
1593 role.setActive(cenRole.isActive());
1594 role.setId(cenRole.getId());
1595 role.setName(cenRole.getName());
1596 role.setPriority(cenRole.getPriority());
1600 roleList = roleService.getAvailableRoles(userId);
1602 List<Role> activeRoleList = new ArrayList<Role>();
1603 for (Role role : roleList) {
1604 if (role.getActive()) {
1605 if (role.getId() != 1) { // prevent portal admin from being added
1606 activeRoleList.add(role);
1607 } else if (extRequestValue) {
1608 activeRoleList.add(role);
1613 EPUser localUser = getUserFromApp(userId, app, applicationsRestClientService);
1614 // If localUser does not exists return roles
1615 Set<EPRole> roleSet = null;
1616 EPRole[] roleSetList = null;
1617 if (localUser != null) {
1618 roleSet = localUser.getAppEPRoles(app);
1619 roleSetList = roleSet.toArray(new EPRole[0]);
1621 rolesInAppForUser = constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue);
1622 return rolesInAppForUser;
1625 EcompRole[] appRoles = null;
1626 List<EcompRole> roles = new ArrayList<>();
1627 if (app.getCentralAuth()) {
1628 // Sync application functions from External Access System
1629 externalAccessRolesService.syncRoleFunctionFromExternalAccessSystem(app);
1630 List<EPRole> applicationRoles = dataAccessService.getList(EPRole.class,
1631 " where app_id = " + app.getId() + " and active_yn = 'Y'", null, null);
1633 for (EPRole role : applicationRoles) {
1634 EcompRole ecompRole = new EcompRole();
1635 ecompRole.setId(role.getId());
1636 ecompRole.setName(role.getName());
1637 roles.add(ecompRole);
1639 appRoles = roles.toArray(new EcompRole[roles.size()]);
1641 appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
1643 // Test this error case, for generating an internal Ecomp Portal
1645 // EcompRole[] appRoles = null;
1646 // If there is an exception in the rest client api, then null will
1648 if (appRoles != null) {
1649 if (!app.getCentralAuth()) {
1650 syncAppRoles(sessionFactory, appId, appRoles);
1652 EcompRole[] userAppRoles = null;
1655 if (app.getCentralAuth()) {
1656 final Map<String, String> params = new HashMap<>();
1657 final Map<String, Long> userParams = new HashMap<>();
1658 params.put("orgUserIdValue", userId);
1659 List<EPUser> user = dataAccessService.executeNamedQuery("epUserAppId", params, null);
1660 userParams.put("appId", app.getId());
1661 userParams.put("userId", user.get(0).getId());
1662 List<EPUserAppCurrentRoles> userAppsRolesList = dataAccessService
1663 .executeNamedQuery("getUserAppCurrentRoles", userParams, null);
1664 List<EcompRole> setUserRoles = new ArrayList<>();
1665 for (EPUserAppCurrentRoles role : userAppsRolesList) {
1666 EcompRole ecompRole = new EcompRole();
1667 ecompRole.setId(role.getRoleId());
1668 ecompRole.setName(role.getRoleName());
1669 setUserRoles.add(ecompRole);
1671 userAppRoles = setUserRoles.toArray(new EcompRole[setUserRoles.size()]);
1672 rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
1673 return rolesInAppForUser;
1675 userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
1676 String.format("/user/%s/roles", userId));
1678 } catch (HTTPException e) {
1679 // Some apps are returning 400 if user is not found.
1680 if (e.getResponseCode() == 400) {
1681 logger.debug(EELFLoggerDelegate.debugLogger,
1682 "getAppRolesForUser caught exception with response code 400; continuing", e);
1684 // Other response code, let it come thru.
1688 if (userAppRoles == null) {
1689 if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
1690 EcompPortalUtils.setExternalAppResponseCode(200);
1691 String message = String.format(
1692 "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
1693 + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
1694 + "Overriding to 200 until framework SDK returns a useful response.",
1695 Long.toString(appId), userId);
1696 logger.warn(EELFLoggerDelegate.applicationLogger, message);
1700 HashMap<Long, EcompRole> appRolesActiveMap = hashMapFromEcompRoles(appRoles);
1701 ArrayList<EcompRole> activeRoles = new ArrayList<EcompRole>();
1702 if (userAppRoles != null) {
1703 for (int i = 0; i < userAppRoles.length; i++) {
1704 if (appRolesActiveMap.containsKey(userAppRoles[i].getId())) {
1705 EcompRole role = new EcompRole();
1706 role.setId(userAppRoles[i].getId());
1707 role.setName(userAppRoles[i].getName());
1708 activeRoles.add(role);
1712 EcompRole[] userAppRolesActive = activeRoles.toArray(new EcompRole[activeRoles.size()]);
1714 // If the remote application isn't down we MUST sync user
1715 // roles here in case we have this user here!
1716 syncUserRoles(sessionFactory, userId, appId, userAppRolesActive, extRequestValue, null);
1717 } catch (Exception e) {
1718 // TODO: we may need to check if user exists, maybe remote
1720 String message = String.format(
1721 "getAppRolesForUser: user %s does not exist in remote application %s", userId,
1722 Long.toString(appId));
1723 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1724 userAppRoles = new EcompRole[0];
1726 rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
1728 } catch (Exception e) {
1729 String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
1730 Long.toString(appId));
1731 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1733 return rolesInAppForUser;
1737 private boolean postUserRolesToMylogins(AppWithRolesForUser userAppRolesData,
1738 ApplicationsRestClientService applicationsRestClientService, Long appId, Long userId)
1739 throws JsonProcessingException, HTTPException {
1740 boolean result = false;
1741 ObjectMapper mapper = new ObjectMapper();
1742 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1743 String userRolesAsString = mapper.writeValueAsString(userAppRolesData);
1744 logger.error(EELFLoggerDelegate.errorLogger,
1745 "Should not be reached here, as the endpoint is not defined yet from the Mylogins");
1746 applicationsRestClientService.post(AppWithRolesForUser.class, appId, userRolesAsString,
1747 String.format("/user/%s/myLoginroles", userId));
1751 public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser userAppRolesData, EPUser user) {
1752 FieldsValidator fieldsValidator = new FieldsValidator();
1753 final Map<String, Long> params = new HashMap<>();
1754 EPUserAppRoles appRole = new EPUserAppRoles();
1756 logger.error(EELFLoggerDelegate.errorLogger,
1757 "Should not be reached here, still the endpoint is yet to be defined");
1758 boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService,
1759 userAppRolesData.appId, user.getId());
1760 logger.debug(EELFLoggerDelegate.debugLogger, "putUserAppRolesRequest: result {}", result);
1762 params.put("appId", userAppRolesData.appId);
1763 EPUserAppRolesRequest epAppRolesRequestData = new EPUserAppRolesRequest();
1764 epAppRolesRequestData.setCreatedDate(new Date());
1765 epAppRolesRequestData.setUpdatedDate(new Date());
1766 epAppRolesRequestData.setUserId(user.getId());
1767 epAppRolesRequestData.setAppId(userAppRolesData.appId);
1768 epAppRolesRequestData.setRequestStatus("P");
1769 List<RoleInAppForUser> appRoleIdList = userAppRolesData.appRoles;
1770 Set<EPUserAppRolesRequestDetail> appRoleDetails = new LinkedHashSet<EPUserAppRolesRequestDetail>();
1771 dataAccessService.saveDomainObject(epAppRolesRequestData, null);
1772 for (RoleInAppForUser userAppRoles : appRoleIdList) {
1773 Boolean isAppliedVal = userAppRoles.isApplied;
1774 params.put("appRoleId", userAppRoles.roleId);
1776 appRole = (EPUserAppRoles) dataAccessService.executeNamedQuery("appRoles", params, null).get(0);
1777 EPUserAppRolesRequestDetail epAppRoleDetail = new EPUserAppRolesRequestDetail();
1778 epAppRoleDetail.setReqRoleId(appRole.getRoleId());
1779 epAppRoleDetail.setReqType("P");
1780 epAppRoleDetail.setEpRequestIdData(epAppRolesRequestData);
1781 dataAccessService.saveDomainObject(epAppRoleDetail, null);
1784 epAppRolesRequestData.setEpRequestIdDetail(appRoleDetails);
1785 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1787 } catch (Exception e) {
1788 logger.error(EELFLoggerDelegate.errorLogger, "putUserAppRolesRequest failed", e);
1789 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1791 return fieldsValidator;
1794 public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(EPUser userid, String appName) {
1795 Map<String, String> params = new HashMap<>();
1796 params.put("userid", userid.getId().toString());
1797 // params.put("appid", appid);
1798 params.put("appName", appName);
1800 @SuppressWarnings("unchecked")
1801 List<EPUserAppCatalogRoles> userAppRoles = (List<EPUserAppCatalogRoles>) dataAccessService
1802 .executeNamedQuery("userAppCatalogRoles", params, null);
1803 return userAppRoles;
1806 public String updateRemoteUserProfile(String orgUserId, Long appId) {
1807 ObjectMapper mapper = new ObjectMapper();
1808 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1809 EPUser client = searchService.searchUserByUserId(orgUserId);
1810 EPUser newUser = new EPUser();
1811 newUser.setActive(client.getActive());
1812 newUser.setFirstName(client.getFirstName());
1813 newUser.setLastName(client.getLastName());
1814 newUser.setLoginId(client.getLoginId());
1815 newUser.setLoginPwd(client.getLoginPwd());
1816 newUser.setMiddleInitial(client.getMiddleInitial());
1817 newUser.setEmail(client.getEmail());
1818 newUser.setOrgUserId(client.getLoginId());
1820 String userAsString = mapper.writeValueAsString(newUser);
1821 List<EPApp> appList = appsService.getUserRemoteApps(client.getId().toString());
1822 // applicationsRestClientService.post(EPUser.class, appId,
1823 // userAsString, String.format("/user", orgUserId));
1824 for (EPApp eachApp : appList) {
1826 applicationsRestClientService.post(EPUser.class, eachApp.getId(), userAsString,
1827 String.format("/user/%s", orgUserId));
1828 } catch (Exception e) {
1829 logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId()
1830 + " in remote app. appId = " + eachApp.getId());
1833 } catch (Exception e) {
1834 logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
1844 * @see org.openecomp.portalapp.portal.service.UserRolesService#
1845 * getCachedAppRolesForUser(java.lang.Long, java.lang.Long)
1847 public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId) {
1848 // Find the records for this user-app combo, if any
1849 String filter = " where user_id = " + Long.toString(userId) + " and app_id = " + Long.toString(appId);
1850 @SuppressWarnings("unchecked")
1851 List<EPUserApp> roleList = dataAccessService.getList(EPUserApp.class, filter, null, null);
1852 logger.debug(EELFLoggerDelegate.debugLogger, "getCachedAppRolesForUser: list size is {}", roleList.size());
1857 * Retrieves and returns a list of user app roles for local and remote
1858 * applications based on the app id.
1861 * @return list of user app roles
1862 * @throws HTTPException
1864 public List<UserApplicationRoles> getUsersFromAppEndpoint(Long appId) throws HTTPException {
1865 ArrayList<UserApplicationRoles> userApplicationRoles = new ArrayList<UserApplicationRoles>();
1867 EPApp app = appsService.getApp(appId);
1868 // If local or centralized application
1869 if (appId == PortalConstants.PORTAL_APP_ID || app.getCentralAuth()) {
1870 @SuppressWarnings("unchecked")
1871 List<EPUser> userList = (List<EPUser>) dataAccessService.executeNamedQuery("getActiveUsers", null, null);
1872 for (EPUser user : userList) {
1873 UserApplicationRoles userWithAppRoles = convertToUserApplicationRoles(appId, user, app);
1874 if (userWithAppRoles.getRoles() != null && userWithAppRoles.getRoles().size() > 0)
1875 userApplicationRoles.add(userWithAppRoles);
1880 RemoteUserWithRoles[] remoteUsers = null;
1881 String remoteUsersString = applicationsRestClientService.getIncomingJsonString(appId, "/users");
1882 remoteUsers = doGetUsers(isAppUpgradeVersion(app), remoteUsersString);
1883 userApplicationRoles = new ArrayList<UserApplicationRoles>();
1884 for (RemoteUserWithRoles remoteUser : remoteUsers) {
1885 UserApplicationRoles userWithRemoteAppRoles = convertToUserApplicationRoles(appId, remoteUser);
1886 if (userWithRemoteAppRoles.getRoles() != null && userWithRemoteAppRoles.getRoles().size() > 0) {
1887 userApplicationRoles.add(userWithRemoteAppRoles);
1889 logger.debug(EELFLoggerDelegate.debugLogger, "User " + userWithRemoteAppRoles.getOrgUserId()
1890 + " doesn't have any roles assigned to any app.");
1894 return userApplicationRoles;
1901 * @param appgetUsersFromAppEndpoint
1904 private UserApplicationRoles convertToUserApplicationRoles(Long appId, EPUser user, EPApp app) {
1905 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
1906 userWithRemoteAppRoles.setAppId(appId);
1907 userWithRemoteAppRoles.setOrgUserId(user.getOrgUserId());
1908 userWithRemoteAppRoles.setFirstName(user.getFirstName());
1909 userWithRemoteAppRoles.setLastName(user.getLastName());
1910 userWithRemoteAppRoles.setRoles(convertToRemoteRoleList(user, app));
1911 return userWithRemoteAppRoles;
1920 private List<RemoteRole> convertToRemoteRoleList(EPUser user, EPApp app) {
1921 List<RemoteRole> roleList = new ArrayList<RemoteRole>();
1922 SortedSet<EPRole> roleSet = user.getAppEPRoles(app);
1923 for (EPRole role : roleSet) {
1924 RemoteRole rRole = new RemoteRole();
1925 rRole.setId(role.getId());
1926 rRole.setName(role.getName());
1927 roleList.add(rRole);
1934 * Returns RemoteUserWithRoles reading the value from remote application user in the form a string from an ObjectMapper
1935 * @param postOpenSource
1936 * @param remoteUsersString
1937 * @return RemoteUserWithRoles
1939 public RemoteUserWithRoles[] doGetUsers(boolean postOpenSource, String remoteUsersString) {
1940 ObjectMapper mapper = new ObjectMapper();
1942 return mapper.readValue(remoteUsersString, RemoteUserWithRoles[].class);
1943 } catch (IOException e) {
1944 logger.error(EELFLoggerDelegate.errorLogger, "doGetUsers : Failed : Unexpected property in incoming JSON",
1946 logger.error(EELFLoggerDelegate.errorLogger,
1947 "doGetUsers : Incoming JSON that caused it --> " + remoteUsersString);
1950 return new RemoteUserWithRoles[0];