2 * ================================================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ================================================================================
21 package org.openecomp.portalapp.portal.service;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.Collection;
26 import java.util.Date;
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.LinkedHashSet;
30 import java.util.List;
33 import java.util.TreeSet;
35 import javax.servlet.http.HttpServletResponse;
37 import org.apache.commons.lang.StringUtils;
38 import org.apache.cxf.transport.http.HTTPException;
39 import org.hibernate.Query;
40 import org.hibernate.SQLQuery;
41 import org.hibernate.Session;
42 import org.hibernate.SessionFactory;
43 import org.hibernate.Transaction;
44 import org.openecomp.portalapp.externalsystemapproval.model.ExternalSystemRoleApproval;
45 import org.openecomp.portalapp.externalsystemapproval.model.ExternalSystemUser;
46 import org.openecomp.portalapp.portal.domain.EPApp;
47 import org.openecomp.portalapp.portal.domain.EPRole;
48 import org.openecomp.portalapp.portal.domain.EPUser;
49 import org.openecomp.portalapp.portal.domain.EPUserApp;
50 import org.openecomp.portalapp.portal.domain.EPUserAppCatalogRoles;
51 import org.openecomp.portalapp.portal.domain.EPUserAppRolesRequest;
52 import org.openecomp.portalapp.portal.domain.EPUserAppRolesRequestDetail;
53 import org.openecomp.portalapp.portal.domain.EpUserAppRoles;
54 import org.openecomp.portalapp.portal.domain.ExternalSystemAccess;
55 import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
56 import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
57 import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
58 import org.openecomp.portalapp.portal.transport.AppWithRolesForUser;
59 import org.openecomp.portalapp.portal.transport.ExternalRequestFieldsValidator;
60 import org.openecomp.portalapp.portal.transport.FieldsValidator;
61 import org.openecomp.portalapp.portal.transport.FunctionalMenuItem;
62 import org.openecomp.portalapp.portal.transport.FunctionalMenuRole;
63 import org.openecomp.portalapp.portal.transport.RemoteUserWithRoles;
64 import org.openecomp.portalapp.portal.transport.RoleInAppForUser;
65 import org.openecomp.portalapp.portal.transport.RolesInAppForUser;
66 import org.openecomp.portalapp.portal.transport.UserApplicationRoles;
67 import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
68 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
69 import org.openecomp.portalapp.portal.utils.PortalConstants;
70 import org.openecomp.portalsdk.core.domain.Role;
71 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
72 import org.openecomp.portalsdk.core.restful.domain.EcompRole;
73 import org.openecomp.portalsdk.core.service.DataAccessService;
74 import org.openecomp.portalsdk.core.service.RoleService;
75 import org.openecomp.portalsdk.core.util.SystemProperties;
76 import org.springframework.beans.factory.annotation.Autowired;
78 import com.fasterxml.jackson.core.JsonProcessingException;
79 import com.fasterxml.jackson.databind.DeserializationFeature;
80 import com.fasterxml.jackson.databind.ObjectMapper;
83 public class UserRolesCommonServiceImpl {
85 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesCommonServiceImpl.class);
87 private static final Object syncRests = new Object();
90 private DataAccessService dataAccessService;
92 private SessionFactory sessionFactory;
94 private SearchService searchService;
96 private EPAppService appsService;
98 private ApplicationsRestClientService applicationsRestClientService;
100 private EPRoleService epRoleService;
102 private RoleService roleService;
107 * @return HashMap<Long, EcompRole>
109 private static HashMap<Long, EcompRole> hashMapFromEcompRoles(EcompRole[] ecompRoles) {
110 HashMap<Long, EcompRole> result = new HashMap<Long, EcompRole>();
111 if (ecompRoles != null) {
112 for (int i = 0; i < ecompRoles.length; i++) {
113 if (ecompRoles[i].getId() != null) {
114 result.put(ecompRoles[i].getId(), ecompRoles[i]);
125 protected void createLocalUserIfNecessary(String userId) {
126 if (StringUtils.isEmpty(userId)) {
127 logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty userId!");
130 Session localSession = null;
131 Transaction transaction = null;
133 localSession = sessionFactory.openSession();
134 transaction = localSession.beginTransaction();
135 @SuppressWarnings("unchecked")
136 List<EPUser> userList = localSession
137 .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + userId + "'").list();
138 if (userList.size() == 0) {
139 EPUser client = searchService.searchUserByUserId(userId);
140 if (client == null) {
141 String msg = "createLocalUserIfNecessary: cannot create user " + userId
142 + ", because not found in phonebook";
143 logger.error(EELFLoggerDelegate.errorLogger, msg);
145 client.setLoginId(userId);
146 client.setActive(true);
147 localSession.save(client);
150 transaction.commit();
151 } catch (Exception e) {
152 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
153 EcompPortalUtils.rollbackTransaction(transaction, "searchOrCreateUser rollback, exception = " + e);
155 EcompPortalUtils.closeLocalSession(localSession, "searchOrCreateUser");
160 * This method return nothing and remove roles before adding any roles for an app
163 * @param localSession
164 * @param userAppRoles
165 * @param newUserAppRolesMap
167 private static void syncUserRolesExtension(EPUserApp userRole, Long appId, Session localSession, EcompRole[] userAppRoles, HashMap<Long, EcompRole> newUserAppRolesMap) {
169 Long userAppRoleId = 0L;
170 if (appId == PortalConstants.PORTAL_APP_ID) { // local app
171 userAppRoleId = userRole.getRoleId();
172 } else { // remote app
173 userAppRoleId = userRole.getAppRoleId();
176 if (!newUserAppRolesMap.containsKey(userAppRoleId)) {
177 localSession.delete(userRole);
179 newUserAppRolesMap.remove(userAppRoleId);
184 * Checks whether the role is inactive
188 * if role is inactive, throws exception
190 private void checkIfRoleInactive(EPRole epRole) throws Exception{
191 if(!epRole.getActive()){
192 throw new Exception(epRole.getName()+ " role is unavailable");
198 * @param sessionFactory
201 * @param userAppRoles
202 * @param extRequestValue
203 * set to false if request is from users page otherwise true
206 protected void syncUserRoles(SessionFactory sessionFactory, String userId, Long appId,
207 EcompRole[] userAppRoles, Boolean extRequestValue, String reqType) throws Exception {
208 boolean result = false;
209 Session localSession = null;
210 Transaction transaction = null;
211 String roleActive = null;
212 final Map<String, String> userAppParams = new HashMap<>();
213 final Map<String, String> appParams = new HashMap<>();
214 HashMap<Long, EcompRole> newUserAppRolesMap = hashMapFromEcompRoles(userAppRoles);
217 localSession = sessionFactory.openSession();
218 transaction = localSession.beginTransaction();
219 @SuppressWarnings("unchecked")
220 List<EPUser> userList = localSession
221 .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + userId + "'").list();
222 if (userList.size() > 0) {
223 EPUser client = userList.get(0);
224 roleActive = ("DELETE".equals(reqType)) ? "" : " and role.active = 'Y'";
225 @SuppressWarnings("unchecked")
226 List<EPUserApp> userRoles = localSession.createQuery("from " + EPUserApp.class.getName()
227 + " where app.id=" + appId + roleActive + " and userId=" + client.getId()).list();
229 if ("DELETE".equals(reqType)) {
230 for (EPUserApp userAppRoleList : userRoles) {
231 userAppParams.put("roleName", String.valueOf(userAppRoleList.getRole().getName()));
232 userAppParams.put("appId", String.valueOf(appId));
233 appParams.put("appRoleName", userAppRoleList.getRole().getName());
234 @SuppressWarnings("unchecked")
235 List<EPRole> rolesList = (!userAppRoleList.getRole().getName().equals(PortalConstants.ADMIN_ROLE)) ? (List<EPRole>) dataAccessService.executeNamedQuery("getAppRoles", userAppParams, null) : (List<EPRole>) dataAccessService.executeNamedQuery("getPortalAppRoles", appParams, null);
236 if(rolesList.size() > 0 || !rolesList.isEmpty()){
237 checkIfRoleInactive(rolesList.get(0));
242 for (EPUserApp userRole : userRoles) {
243 if (!userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && userRole.getRoleId() != PortalConstants.SYS_ADMIN_ROLE_ID && !extRequestValue){
244 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
246 else if (extRequestValue){
247 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
250 Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values();
251 if (newRolesToAdd.size() > 0) {
252 EPApp app = (EPApp) localSession.get(EPApp.class, appId);
254 HashMap<Long, EPRole> rolesMap = new HashMap<Long, EPRole>();
255 if (appId == PortalConstants.PORTAL_APP_ID) { // local app
256 String appIdValue = null;
257 if(!extRequestValue){
258 appIdValue = "and id != " + PortalConstants.PORTAL_APP_ID;
262 @SuppressWarnings("unchecked")
263 List<EPRole> roles = localSession
264 .createQuery("from " + EPRole.class.getName() + " where appId is null " + appIdValue).list();
265 for (EPRole role : roles) {
267 rolesMap.put(role.getId(), role);
269 } else { // remote app
270 @SuppressWarnings("unchecked")
271 List<EPRole> roles = localSession
272 .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list();
273 for (EPRole role : roles) {
274 rolesMap.put(role.getAppRoleId(), role);
278 for (EcompRole userRole : newRolesToAdd) {
279 if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName().equals(PortalConstants.ADMIN_ROLE)) {
280 role = (EPRole) localSession.get(EPRole.class, new Long(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
281 } else if (userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && !extRequestValue){
284 EPUserApp userApp = new EPUserApp();
285 userApp.setUserId(client.getId());
287 userApp.setRole(("PUT".equals(reqType) || "POST".equals(reqType) && userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) ? role : rolesMap.get(userRole.getId()));
288 localSession.save(userApp);
289 localSession.flush();
292 if (appId == PortalConstants.PORTAL_APP_ID) {
294 * for local app -- hack - always make sure fn_role
295 * table's app_id is null and not 1 for primary app in
296 * this case being ecomp portal app; reason: hibernate
297 * is rightly setting this to 1 while persisting to
298 * fn_role as per the mapping but SDK role management
299 * code expects the app_id to be null as there is no
300 * concept of App_id in SDK
302 SQLQuery sqlQuery = localSession
303 .createSQLQuery("update fn_role set app_id = null where app_id = 1 ");
304 sqlQuery.executeUpdate();
310 transaction.commit();
312 } catch (Exception e) {
313 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
314 EcompPortalUtils.rollbackTransaction(transaction,
315 "Exception occurred in syncUserRoles, Details: " + EcompPortalUtils.getStackTrace(e));
316 if("DELETE".equals(reqType)){
317 throw new Exception(e.getMessage());
320 localSession.close();
321 if (!result && !"DELETE".equals(reqType)) {
323 "Exception occurred in syncUserRoles while closing database session for app: '" + appId + "'.");
329 * Called when getting the list of roles for the user
332 * @param userAppRoles
333 * @return List<RoleInAppForUser>
335 protected List<RoleInAppForUser> constructRolesInAppForUserGet(EcompRole[] appRoles, EcompRole[] userAppRoles) {
336 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
338 Set<Long> userAppRolesMap = new HashSet<Long>();
339 if (userAppRoles != null) {
340 for (EcompRole ecompRole : userAppRoles) {
341 userAppRolesMap.add(ecompRole.getId());
344 logger.error(EELFLoggerDelegate.errorLogger,
345 "constructRolesInAppForUserGet has received userAppRoles list empty");
348 if (appRoles != null) {
349 for (EcompRole ecompRole : appRoles) {
350 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
351 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
352 rolesInAppForUser.add(roleForUser);
355 logger.error(EELFLoggerDelegate.errorLogger, "constructRolesInAppForUser has received appRoles list empty");
357 return rolesInAppForUser;
361 * Called when getting the list of roles for the user
364 * @param userAppRoles
365 * @param extRequestValue
366 * set to false if request is from users page otherwise true
367 * @return List<RoleInAppForUser>
369 protected List<RoleInAppForUser> constructRolesInAppForUserGet(List<Role> appRoles, EPRole[] userAppRoles, Boolean extRequestValue) {
370 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
372 Set<Long> userAppRolesMap = new HashSet<Long>();
373 if (userAppRoles != null) {
374 for (EPRole ecompRole : userAppRoles) {
375 userAppRolesMap.add(ecompRole.getId());
378 logger.error(EELFLoggerDelegate.errorLogger,
379 "constructRolesInAppForUserGet has received userAppRoles list empty.");
382 if (appRoles != null) {
383 for (Role ecompRole : appRoles) {
384 if (ecompRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && !extRequestValue)
386 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
387 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
388 rolesInAppForUser.add(roleForUser);
391 logger.error(EELFLoggerDelegate.errorLogger,
392 "constructRolesInAppForUser has received appRoles list empty.");
394 return rolesInAppForUser;
399 * copies of methods in GetAppsWithUserRoleState
401 * @param sessionFactory
406 protected void syncAppRoles(SessionFactory sessionFactory, Long appId, EcompRole[] appRoles) throws Exception {
407 logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId);
408 HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles);
409 boolean result = false;
410 Session localSession = null;
411 Transaction transaction = null;
414 localSession = sessionFactory.openSession();
415 transaction = localSession.beginTransaction();
416 // Attention! All roles from remote application supposed to be
418 @SuppressWarnings("unchecked")
419 List<EPRole> currentAppRoles = localSession
420 .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list();
421 List<EPRole> obsoleteRoles = new ArrayList<EPRole>();
422 for (int i = 0; i < currentAppRoles.size(); i++) {
423 EPRole oldAppRole = currentAppRoles.get(i);
424 if (oldAppRole.getAppRoleId() != null) {
425 EcompRole role = null;
426 role = newRolesMap.get(oldAppRole.getAppRoleId());
428 if (!(role.getName() == null || oldAppRole.getName().equals(role.getName()))) {
429 oldAppRole.setName(role.getName());
430 localSession.update(oldAppRole);
432 newRolesMap.remove(oldAppRole.getAppRoleId());
434 obsoleteRoles.add(oldAppRole);
437 obsoleteRoles.add(oldAppRole);
440 Collection<EcompRole> newRolesToAdd = newRolesMap.values();
441 for (EcompRole role : newRolesToAdd) {
442 logger.debug(EELFLoggerDelegate.debugLogger, "about to add missing role: " + role.toString());
443 EPRole newRole = new EPRole();
444 // Attention! All roles from remote application supposed to be
446 newRole.setActive(true);
447 newRole.setName(role.getName());
448 newRole.setAppId(appId);
449 newRole.setAppRoleId(role.getId());
450 localSession.save(newRole);
452 if (obsoleteRoles.size() > 0) {
453 logger.debug(EELFLoggerDelegate.debugLogger, "we have obsolete roles to delete");
454 for (EPRole role : obsoleteRoles) {
455 logger.debug(EELFLoggerDelegate.debugLogger, "obsolete role: " + role.toString());
456 Long roleId = role.getId();
457 // delete obsolete roles here
458 // Must delete all records with foreign key constraints on
460 // fn_user_role, fn_role_composite, fn_role_function,
461 // fn_user_pseudo_role, fn_menu_functional_roles.
462 // And for fn_menu_functional, if no other roles for that
463 // menu item, remove the url.
465 // Delete from fn_user_role
466 @SuppressWarnings("unchecked")
467 List<EPUserApp> userRoles = localSession.createQuery(
468 "from " + EPUserApp.class.getName() + " where app.id=" + appId + " and role_id=" + roleId)
471 logger.debug(EELFLoggerDelegate.debugLogger, "number of userRoles to delete: " + userRoles.size());
472 for (EPUserApp userRole : userRoles) {
473 logger.debug(EELFLoggerDelegate.debugLogger,
474 "about to delete userRole: " + userRole.toString());
475 localSession.delete(userRole);
476 logger.debug(EELFLoggerDelegate.debugLogger,
477 "finished deleting userRole: " + userRole.toString());
480 // Delete from fn_menu_functional_roles
481 @SuppressWarnings("unchecked")
482 List<FunctionalMenuRole> funcMenuRoles = localSession
483 .createQuery("from " + FunctionalMenuRole.class.getName() + " where roleId=" + roleId)
485 int numMenuRoles = funcMenuRoles.size();
486 logger.debug(EELFLoggerDelegate.debugLogger,
487 "number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles);
488 for (FunctionalMenuRole funcMenuRole : funcMenuRoles) {
489 Long menuId = funcMenuRole.menuId;
490 // If this is the only role for this menu item, then the
491 // app and roles will be gone,
492 // so must null out the url too, to be consistent
493 @SuppressWarnings("unchecked")
494 List<FunctionalMenuRole> funcMenuRoles2 = localSession
495 .createQuery("from " + FunctionalMenuRole.class.getName() + " where menuId=" + menuId)
497 int numMenuRoles2 = funcMenuRoles2.size();
498 logger.debug(EELFLoggerDelegate.debugLogger,
499 "number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2);
500 localSession.delete(funcMenuRole);
501 if (numMenuRoles2 == 1) {
502 // If this is the only role for this menu item, then
503 // the app and roles will be gone,
504 // so must null out the url too, to be consistent
505 logger.debug(EELFLoggerDelegate.debugLogger,
506 "There is exactly 1 menu item for this role, so emptying the url");
507 @SuppressWarnings("unchecked")
508 List<FunctionalMenuItem> funcMenuItems = localSession
510 "from " + FunctionalMenuItem.class.getName() + " where menuId=" + menuId)
512 if (funcMenuItems.size() > 0) {
513 logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item");
514 FunctionalMenuItem funcMenuItem = funcMenuItems.get(0);
515 funcMenuItem.url = "";
516 localSession.update(funcMenuItem);
521 // Delete from fn_role_function
522 String sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
523 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
524 Query query = localSession.createSQLQuery(sql);
525 query.executeUpdate();
527 // Delete from ep_role_notification
528 sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
529 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
530 query = localSession.createSQLQuery(sql);
531 query.executeUpdate();
533 // Delete from fn_role_composite
534 sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id="
536 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
537 query = localSession.createSQLQuery(sql);
538 query.executeUpdate();
540 // Delete from fn_user_pseudo_role
541 sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
542 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
543 query = localSession.createSQLQuery(sql);
544 query.executeUpdate();
546 logger.debug(EELFLoggerDelegate.debugLogger, "about to delete the role: " + role.toString());
547 localSession.delete(role);
548 logger.debug(EELFLoggerDelegate.debugLogger, "deleted the role");
551 logger.debug(EELFLoggerDelegate.debugLogger, "about to commit the transaction");
552 transaction.commit();
553 logger.debug(EELFLoggerDelegate.debugLogger, "committed the transaction");
555 } catch (Exception e) {
556 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
557 EcompPortalUtils.rollbackTransaction(transaction,
558 "Exception occurred in syncAppRoles, Details: " + EcompPortalUtils.getStackTrace(e));
560 localSession.close();
563 "Exception occurred in syncAppRoles while closing database session for app: '" + appId + "'.");
569 * Called when updating the list of roles for the user
573 * @param userRolesInRemoteApp
574 * @return RolesInAppForUser
576 protected RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId,
577 Set<EcompRole> userRolesInRemoteApp) {
578 RolesInAppForUser result;
579 result = new RolesInAppForUser();
580 result.appId = appId;
581 result.orgUserId = userId;
582 for (EcompRole role : userRolesInRemoteApp) {
583 RoleInAppForUser roleInAppForUser = new RoleInAppForUser();
584 roleInAppForUser.roleId = role.getId();
585 roleInAppForUser.roleName = role.getName();
586 roleInAppForUser.isApplied = new Boolean(true);
587 result.roles.add(roleInAppForUser);
594 * @param roleInAppForUserList
597 protected boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) {
598 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
599 if (roleInAppForUser.isApplied.booleanValue()) {
607 * Builds JSON and posts it to a remote application to update user roles.
609 * @param roleInAppForUserList
611 * @param applicationsRestClientService
614 * @return Set of roles as sent; NOT the response from the app.
615 * @throws JsonProcessingException
616 * @throws HTTPException
618 protected Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
619 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
620 throws JsonProcessingException, HTTPException {
621 Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList);
622 Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList);
623 String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote);
624 applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString,
625 String.format("/user/%s/roles", userId));
626 // TODO: We should add code that verifies that the post operation did
627 // succeed. Because the SDK may still return 200 OK with an html page
628 // even when it fails!
629 return updateUserRolesInEcomp;
634 * @param roleInAppForUserList
635 * @return Set<EcompRole>
637 protected Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) {
638 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
639 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
640 if (roleInAppForUser.isApplied) {
641 EcompRole ecompRole = new EcompRole();
642 ecompRole.setId(roleInAppForUser.roleId);
643 ecompRole.setName(roleInAppForUser.roleName);
644 existingUserRoles.add(ecompRole);
647 return existingUserRoles;
651 * Constructs user app roles excluding Account Administrator role
653 * @param roleInAppForUserList
655 * List of roles with Role name, Role Id
657 protected Set<EcompRole> constructUsersRemoteAppRoles(List<RoleInAppForUser> roleInAppForUserList) {
658 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
659 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
660 if (roleInAppForUser.isApplied && !roleInAppForUser.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
661 EcompRole ecompRole = new EcompRole();
662 ecompRole.setId(roleInAppForUser.roleId);
663 ecompRole.setName(roleInAppForUser.roleName);
664 existingUserRoles.add(ecompRole);
667 return existingUserRoles;
671 * This is for a single app
673 * @param rolesInAppForUser
674 * @param externalSystemRequest
675 * set to false if requests from Users page otherwise true
676 * @return true on success, false otherwise
678 protected boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser, boolean externalSystemRequest, String reqType) throws Exception {
679 boolean result = false;
680 String userId = rolesInAppForUser.orgUserId;
681 Long appId = rolesInAppForUser.appId;
682 synchronized (syncRests) {
683 if (rolesInAppForUser != null) {
684 createLocalUserIfNecessary(userId);
687 if (rolesInAppForUser != null) {
688 EcompRole[] userAppRoles = new EcompRole[rolesInAppForUser.roles.size()];
689 for (int i = 0; i < rolesInAppForUser.roles.size(); i++) {
690 RoleInAppForUser roleInAppForUser = rolesInAppForUser.roles.get(i);
691 EcompRole role = new EcompRole();
692 role.setId(roleInAppForUser.roleId);
693 role.setName(roleInAppForUser.roleName);
694 userAppRoles[i] = role;
697 syncUserRoles(sessionFactory, userId, appId, userAppRoles, externalSystemRequest, reqType);
699 } catch (Exception e) {
700 logger.error(EELFLoggerDelegate.errorLogger,
701 "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for attuid " + userId, e);
702 if("DELETE".equals(reqType)){
703 throw new Exception(e.getMessage());
715 * @return UserApplicationRoles
717 protected UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) {
718 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
719 userWithRemoteAppRoles.setAppId(appId);
720 userWithRemoteAppRoles.setOrgUserId(remoteUser.getOrgUserId());
721 userWithRemoteAppRoles.setFirstName(remoteUser.getFirstName());
722 userWithRemoteAppRoles.setLastName(remoteUser.getLastName());
723 userWithRemoteAppRoles.setRoles(remoteUser.getRoles());
724 return userWithRemoteAppRoles;
730 * @see org.openecomp.portalapp.portal.service.UserRolesService#
731 * importRolesFromRemoteApplication(java.lang.Long)
733 public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException {
734 EPRole[] appRolesFull = applicationsRestClientService.get(EPRole[].class, appId, "/rolesFull");
735 List<EPRole> rolesList = Arrays.asList(appRolesFull);
736 for (EPRole externalAppRole : rolesList) {
738 // Try to find an existing extern role for the app in the local
739 // ecomp DB. If so, then use its id to update the existing external
740 // application role record.
741 Long externAppId = externalAppRole.getId();
742 EPRole existingAppRole = epRoleService.getRole(appId, externAppId);
743 if (existingAppRole != null) {
744 logger.debug(EELFLoggerDelegate.debugLogger,
745 String.format("ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.",
746 appId, externAppId));
749 // persistExternalRoleInEcompDb(externalAppRole, appId,
759 * @see org.openecomp.portalapp.portal.service.UserRolesService#
760 * setAppWithUserRoleStateForUser(org.openecomp.portalapp.portal.domain.
761 * EPUser, org.openecomp.portalapp.portal.transport.AppWithRolesForUser)
763 public boolean setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser) {
764 boolean result = false;
765 boolean epRequestValue = false;
767 if (newAppRolesForUser != null && newAppRolesForUser.orgUserId != null) {
768 userId = newAppRolesForUser.orgUserId.trim();
770 Long appId = newAppRolesForUser.appId;
771 List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.appRoles;
772 if (userId.length() > 0) {
773 ObjectMapper mapper = new ObjectMapper();
774 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
777 EPApp app = appsService.getApp(appId);
778 applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
781 if (appId == PortalConstants.PORTAL_APP_ID) {
782 // EPUser localUser = getUserFromApp(userId, app, applicationsRestClientService);
783 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
784 applicationsRestClientService, appId, userId);
785 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
786 userRolesInLocalApp);
787 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null);
789 } else {// remote app
790 EPUser remoteAppUser = null;
792 remoteAppUser = getUserFromApp(userId, app, applicationsRestClientService);
793 } catch (HTTPException e) {
794 // Some apps are returning 400 if user is not found.
795 if (e.getResponseCode() == 400) {
796 logger.debug(EELFLoggerDelegate.debugLogger,
797 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing",
800 // Other response code, let it come thru.
804 if (remoteAppUser == null) {
805 if (remoteUserShouldBeCreated(roleInAppForUserList)) {
807 createNewUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper, isAppUpgradeVersion(app));
808 // If we succeed, we know that the new user was
809 // persisted on remote app.
810 remoteAppUser = getUserFromApp(userId, app, applicationsRestClientService);
811 if (remoteAppUser == null) {
812 logger.error(EELFLoggerDelegate.errorLogger,
813 "Failed to persist new user: " + userId + " in remote app. appId = " + appId);
818 if (remoteAppUser != null) {
819 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
820 applicationsRestClientService, appId, userId);
821 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
822 userRolesInRemoteApp);
823 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null);
825 // If no roles remain, request app to set user inactive.
826 if (userRolesInRemoteApp.size() == 0) {
827 logger.debug(EELFLoggerDelegate.debugLogger,
828 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
830 remoteAppUser.setActive(false);
831 postUserToRemoteApp(userId, user, app, applicationsRestClientService);
835 } catch (Exception e) {
836 String message = String.format(
837 "Failed to create user or update user roles for User %s, AppId %s",
838 userId, Long.toString(appId));
839 logger.error(EELFLoggerDelegate.errorLogger, message, e);
851 * @param applicationsRestClientService
852 * @param searchService
856 protected void createNewUserOnRemoteApp(String userId, EPApp app,
857 ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
858 ObjectMapper mapper, boolean postOpenSource) throws Exception {
861 EPUser client = searchService.searchUserByUserId(userId);
863 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
865 if (client == null) {
866 String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook.";
867 logger.error(EELFLoggerDelegate.errorLogger, msg);
868 throw new Exception(msg);
871 client.setLoginId(userId);
872 client.setActive(true);
874 String userInString = null;
875 userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
876 logger.debug(EELFLoggerDelegate.debugLogger,
877 "about to post new client to remote application, users json = " + userInString);
878 applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user", userId));
882 @SuppressWarnings("unchecked")
883 protected void applyChangesToAppRolesRequest(Long appId, Long userId, String updateStatus, EPUserAppRolesRequest epUserAppRolesRequest) {
884 final Map<String, Long> epRequestParams = new HashMap<>();
886 EPUserAppRolesRequest epAppRolesRequestData = epUserAppRolesRequest;
887 epAppRolesRequestData.setUpdatedDate(new Date());
888 epAppRolesRequestData.setRequestStatus(updateStatus);
889 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
890 addiotonalUpdateParam.put("userId", userId);
891 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
892 epRequestParams.put("reqId", epUserAppRolesRequest.getId());
893 List<EPUserAppRolesRequestDetail> epUserAppRolessDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
894 epUserAppRolessDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
895 epRequestParams, null);
896 if (epUserAppRolessDetailList.size() > 0) {
897 for (EPUserAppRolesRequestDetail epRequestUpdateData : epUserAppRolessDetailList) {
898 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateData;
899 epAppRoleDetailData.setReqType(updateStatus);
900 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
901 HashMap<String, Long> updateDetailsParam = new HashMap<String, Long>();
902 addiotonalUpdateParam.put("reqId", epUserAppRolesRequest.getId());
903 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParam);
906 logger.debug(EELFLoggerDelegate.debugLogger, "The request is set to complete");
908 } catch (Exception e) {
909 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToAppRolesRequest failed", e);
913 @SuppressWarnings("unchecked")
914 public void applyChangesToUserAppRolesForMyLoginsRequest(EPUser user, Long appId) {
915 final Map<String, Long> params = new HashMap<>();
916 final Map<String, Long> epDetailParams = new HashMap<>();
917 List<EPUserAppRolesRequest> epRequestIdVal = new ArrayList<EPUserAppRolesRequest>();
918 params.put("appId", appId);
919 params.put("userId", user.getId());
921 epRequestIdVal = (List<EPUserAppRolesRequest>) dataAccessService
922 .executeNamedQuery("userAppRolesRequestList", params, null);
923 if (epRequestIdVal.size() > 0) {
924 EPUserAppRolesRequest epAppRolesRequestData = epRequestIdVal.get(0);
925 epAppRolesRequestData.setUpdatedDate(new Date());
926 epAppRolesRequestData.setRequestStatus("O");
927 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
928 addiotonalUpdateParam.put("userId", user.getId());
929 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
930 epDetailParams.put("reqId", epAppRolesRequestData.getId());
931 List<EPUserAppRolesRequestDetail> epUserAppRolesDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
932 epUserAppRolesDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
933 epDetailParams, null);
934 if (epUserAppRolesDetailList.size() > 0) {
935 for (EPUserAppRolesRequestDetail epRequestUpdateList : epUserAppRolesDetailList) {
936 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateList;
937 epAppRoleDetailData.setReqType("O");
938 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
939 HashMap<String, Long> updateDetailsParams = new HashMap<String, Long>();
940 addiotonalUpdateParam.put("reqId", epAppRolesRequestData.getId());
941 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParams);
943 logger.debug(EELFLoggerDelegate.debugLogger, "User App roles request from User Page is overridden");
947 } catch (Exception e) {
948 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e);
953 * Pushes specified user details to the specified remote app.
956 * ATT UID identifying user at remote app in REST endpoint path
958 * User details to be pushed
961 * @param applicationsRestClientService
962 * @throws HTTPException
964 protected void postUserToRemoteApp(String userId, EPUser user, EPApp app,
965 ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
967 getUser(userId, app, applicationsRestClientService);
972 * It returns user details for single org user id
976 * if user exists it returns list of user details otherwise empty value
978 @SuppressWarnings("unchecked")
979 private List<EPUser> checkIfUserExists(Map<String, String> userParams){
980 return (List<EPUser>)dataAccessService.executeNamedQuery("epUserAppId", userParams, null);
984 * It checks whether the new user is valid or not otherwise throws exception
989 * Checks if user is valid and returns message otherwise throws exception
992 private String validateNewUser(String orgUserId, EPApp app) throws Exception {
993 EPUser epUser = searchService.searchUserByUserId(orgUserId);
994 if (epUser == null) {
995 throw new Exception("User does not exist");
996 } else if (!epUser.getOrgUserId().equals(orgUserId)) {
997 throw new Exception("User does not exist");
998 } else if (app == null) {
999 throw new Exception("Application does not exist");
1001 return "Saved Successfully";
1005 * Checks if the fields exists or not
1008 * contains user information
1012 * throws exception if the field is not valid
1014 private void validateExternalRequestFields(List<EPUser> userList, EPApp app) throws Exception{
1015 if (userList.size() == 0 || userList.isEmpty() ) {
1016 throw new Exception("User does not exist");
1017 } else if(app == null) {
1018 throw new Exception("Application does not exist");
1019 } else if(!app.getEnabled() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1020 throw new Exception(app.getMlAppName()+" application is unavailable");
1024 @SuppressWarnings("unchecked")
1025 public ExternalRequestFieldsValidator setExternalRequestUserAppRole(ExternalSystemUser newAppRolesForUser, String reqType) {
1026 boolean result = false;
1027 boolean externalSystemRequest = true;
1028 final Map<String, Long> params = new HashMap<>();
1029 final Map<String, String> userParams = new HashMap<>();
1030 List<EPUser> userInfo = null;
1031 EPUser userId = null;
1032 List<EPUserAppRolesRequest> epRequestId = null;
1033 String orgUserId = "";
1034 String updateStatus = "";
1035 String reqMessage = "";
1037 if (newAppRolesForUser != null && newAppRolesForUser.getLoginId() != null) {
1038 orgUserId = newAppRolesForUser.getLoginId().trim();
1040 String appName = newAppRolesForUser.getApplicationName();
1041 String logMessage = ("DELETE").equals(reqType) ? "Deleting": "Assigning/Updating" ;
1042 if (orgUserId.length() > 0) {
1043 ObjectMapper mapper = new ObjectMapper();
1044 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1045 int epRequestIdSize = 0;
1047 app = appsService.getAppDetail(appName);
1048 userParams.put("orgUserIdValue", orgUserId);
1049 userInfo = checkIfUserExists(userParams);
1050 reqMessage = "Updated Successfully";
1051 if (!reqType.equals("DELETE") && (userInfo.size() == 0 || userInfo.isEmpty())) {
1052 reqMessage = validateNewUser(orgUserId, app);
1054 if (userInfo.size() != 0 || !userInfo.isEmpty()) {
1055 validateExternalRequestFields(userInfo, app);
1056 userId = userInfo.get(0);
1057 params.put("appId", app.getId());
1058 params.put("userId", userId.getId());
1059 epRequestId = (List<EPUserAppRolesRequest>) dataAccessService
1060 .executeNamedQuery("userAppRolesRequestList", params, null);
1061 epRequestIdSize = epRequestId.size();
1063 if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1064 EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, app.getId(), "/roles");
1065 syncAppRoles(sessionFactory, app.getId(), appRoles);
1068 List<RoleInAppForUser> roleInAppForUserList = roleInAppForUserList(newAppRolesForUser.getRoles(),
1069 app.getId(), app.getMlAppName());
1071 if (app.getId() == PortalConstants.PORTAL_APP_ID) {
1072 // EPUser localUser = getUserFromApp(orgUserId, app, applicationsRestClientService);
1073 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1074 applicationsRestClientService, app.getId(), orgUserId);
1075 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1076 userRolesInLocalApp);
1077 logger.info(EELFLoggerDelegate.debugLogger, "{} user app roles: for app {}, user {}",
1078 logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1079 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType);
1080 } else {// remote app
1081 EPUser remoteAppUser = null;
1083 remoteAppUser = getUserFromApp(orgUserId, app, applicationsRestClientService);
1084 } catch (HTTPException e) {
1085 // Some apps are returning 400 if user is not found.
1086 if (e.getResponseCode() == 400) {
1087 logger.debug(EELFLoggerDelegate.debugLogger,
1088 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing",
1091 // Other response code, let it come thru.
1095 if (remoteAppUser == null) {
1096 createNewUserOnRemoteApp(orgUserId, app, applicationsRestClientService, searchService, mapper,
1097 isAppUpgradeVersion(app));
1098 // If we succeed, we know that the new user was
1099 // persisted on remote app.
1100 remoteAppUser = getUserFromApp(orgUserId, app, applicationsRestClientService);
1101 if (remoteAppUser == null) {
1102 logger.error(EELFLoggerDelegate.errorLogger, "Failed to persist new user: " + orgUserId
1103 + " in remote app. appId = " + app.getId());
1106 reqMessage = "Saved Successfully";
1108 if (remoteAppUser != null) {
1109 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList,
1110 mapper, applicationsRestClientService, app.getId(), orgUserId);
1112 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId,
1113 app.getId(), userRolesInRemoteApp);
1114 logger.info(EELFLoggerDelegate.debugLogger, "{} user app roles: for app {}, user {}",
1115 logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1116 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType);
1117 // If no roles remain, request app to set user inactive.
1118 /*if (userRolesInRemoteApp.size() == 0) {
1119 logger.debug(EELFLoggerDelegate.debugLogger,
1120 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
1122 //TODO Need to fix the logged in user is not set to inactive
1123 remoteAppUser.setActive(false);
1124 postUserToRemoteApp(attuid, user, app, applicationsRestClientService);
1129 reqMessage = "Failed to save the user app role(s)";
1131 if (epRequestIdSize > 0 && !userInfo.isEmpty()) {
1133 applyChangesToAppRolesRequest(app.getId(), userId.getId(), updateStatus, epRequestId.get(0));
1137 } catch (Exception e) {
1138 String message = String.format("Failed to create user or update user roles for User %s, AppId %s",
1139 orgUserId, appName);
1140 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1142 reqMessage = e.getMessage();
1143 if(epRequestIdSize > 0 && !userInfo.isEmpty()){
1145 applyChangesToAppRolesRequest(app.getId(), userId.getId(),
1146 updateStatus, epRequestId.get(0));
1151 return new ExternalRequestFieldsValidator(result, reqMessage);
1156 * @param roleInAppForUserList
1158 * @param applicationsRestClientService
1161 * @return Set<EcompRole>
1162 * @throws JsonProcessingException
1163 * @throws HTTPException
1165 private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
1166 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
1167 throws JsonProcessingException, HTTPException {
1168 Set<EcompRole> updatedUserRoles = constructUsersEcompRoles(roleInAppForUserList);
1169 return updatedUserRoles;
1173 * It constructs and returns list of user app roles when the external API role approval system calls
1176 * @param roleInAppForUserList
1178 * @return list of user app roles
1180 * throws exceptions if role id does not exits
1182 private List<RoleInAppForUser> roleInAppForUserList(List<ExternalSystemRoleApproval> roleInAppForUserList,
1183 Long appId, String appName) throws Exception {
1184 List<RoleInAppForUser> existingUserRoles = new ArrayList<RoleInAppForUser>();
1185 EPRole existingAppRole = null;
1186 for (ExternalSystemRoleApproval roleInAppForUser : roleInAppForUserList) {
1187 RoleInAppForUser ecompRole = new RoleInAppForUser();
1188 existingAppRole = epRoleService.getAppRole(roleInAppForUser.getRoleName(), appId);
1189 if (existingAppRole == null) {
1190 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1191 roleInAppForUserList);
1192 throw new Exception("'" +roleInAppForUser.getRoleName() + "'" +" role does not exist for" + appName + " application");
1194 if (!existingAppRole.getActive()) {
1195 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1196 roleInAppForUserList);
1197 throw new Exception(roleInAppForUser.getRoleName() + " role is unavailable for "+ appName + " application");
1199 ecompRole.roleId = (appId == 1 || roleInAppForUser.getRoleName().equals(PortalConstants.ADMIN_ROLE)) ? existingAppRole.getId() : existingAppRole.getAppRoleId();
1200 ecompRole.roleName = roleInAppForUser.getRoleName();
1201 ecompRole.isApplied = true;
1202 existingUserRoles.add(ecompRole);
1205 return existingUserRoles;
1214 * @param applicationsRestClientService
1216 * @throws HTTPException
1218 protected EPUser getUserFromApp(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1219 throws HTTPException {
1221 if (app.getId() == PortalConstants.PORTAL_APP_ID) {
1222 // Map<String,String> params = new HashMap<String,String>();
1223 // params.put("sbcid",userId);
1224 @SuppressWarnings("unchecked")
1225 List<EPUser> userList = (List<EPUser>) dataAccessService
1226 .executeQuery("from EPUser where orgUserId='" + userId + "'", null);
1227 if (userList != null && !userList.isEmpty())
1228 return userList.get(0);
1234 return getUser(userId, app, applicationsRestClientService);
1237 protected EPUser getUser(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1238 throws HTTPException {
1239 return applicationsRestClientService.get(EPUser.class, app.getId(), String.format("/user/%s", userId), true);
1243 protected boolean isAppUpgradeVersion(EPApp app){
1248 public ExternalSystemAccess getExternalRequestAccess(){
1249 ExternalSystemAccess res = null;
1251 res = new ExternalSystemAccess(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE,
1252 Boolean.parseBoolean(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE)));
1253 } catch (Exception e) {
1254 logger.error(EELFLoggerDelegate.errorLogger, "getExternalRequestAccess failed" + e.getMessage());
1262 * @see org.openecomp.portalapp.portal.service.UserRolesService#
1263 * getAppRolesForUser(java.lang.Long, java.lang.String)
1265 public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId, Boolean extRequestValue) {
1267 List<RoleInAppForUser> rolesInAppForUser = null;
1270 // for ecomp portal app, no need to make a remote call
1271 if (appId == PortalConstants.PORTAL_APP_ID) {
1273 List<Role> roleList = roleService.getAvailableRoles();
1274 List<Role> activeRoleList = new ArrayList<Role>();
1275 for(Role role: roleList) {
1276 if(role.getActive()) {
1277 if(role.getId() != 1){ // prevent portal admin from being added
1278 activeRoleList.add(role);
1279 } else if(extRequestValue){
1280 activeRoleList.add(role);
1286 EPApp app = appsService.getApp(appId);
1287 EPUser localUser = getUserFromApp(userId, app, applicationsRestClientService);
1288 Set<EPRole> roleSet = localUser.getAppEPRoles(app);
1289 rolesInAppForUser = constructRolesInAppForUserGet(activeRoleList, roleSet.toArray(new EPRole[0]), extRequestValue);
1290 return rolesInAppForUser;
1293 EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
1295 // Test this error case, for generating an internal Ecomp Portal
1297 // EcompRole[] appRoles = null;
1298 // If there is an exception in the rest client api, then null will
1300 if (appRoles != null) {
1301 syncAppRoles(sessionFactory, appId, appRoles);
1302 EcompRole[] userAppRoles = null;
1305 userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
1306 String.format("/user/%s/roles", userId));
1307 } catch (HTTPException e) {
1308 // Some apps are returning 400 if user is not found.
1309 if (e.getResponseCode() == 400) {
1310 logger.debug(EELFLoggerDelegate.debugLogger,
1311 "getAppRolesForUser caught exception with response code 400; continuing", e);
1313 // Other response code, let it come thru.
1317 if (userAppRoles == null) {
1318 if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
1319 EcompPortalUtils.setExternalAppResponseCode(200);
1320 String message = String.format(
1321 "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
1322 + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
1323 + "Overriding to 200 until framework SDK returns a useful response.",
1324 Long.toString(appId), userId);
1325 logger.warn(EELFLoggerDelegate.applicationLogger, message);
1329 HashMap<Long, EcompRole> appRolesActiveMap =hashMapFromEcompRoles(appRoles);
1330 ArrayList<EcompRole> activeRoles = new ArrayList<EcompRole>();
1331 for (int i = 0; i < userAppRoles.length; i++) {
1332 if (appRolesActiveMap.containsKey(userAppRoles[i].getId())) {
1333 EcompRole role = new EcompRole();
1334 role.setId(userAppRoles[i].getId());
1335 role.setName(userAppRoles[i].getName());
1336 activeRoles.add(role);
1339 EcompRole[] userAppRolesActive = activeRoles.toArray(new EcompRole[activeRoles.size()]);
1341 // If the remote application isn't down we MUST sync user
1342 // roles here in case we have this user here!
1343 syncUserRoles(sessionFactory, userId, appId, userAppRolesActive, extRequestValue, null);
1344 } catch (Exception e) {
1345 // TODO: we may need to check if user exists, maybe remote
1347 String message = String.format(
1348 "getAppRolesForUser: user %s does not exist in remote application %s", userId,
1349 Long.toString(appId));
1350 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1351 userAppRoles = new EcompRole[0];
1353 rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
1355 } catch (Exception e) {
1356 String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
1357 Long.toString(appId));
1358 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1360 return rolesInAppForUser;
1364 private boolean postUserRolesToMylogins(AppWithRolesForUser userAppRolesData,
1365 ApplicationsRestClientService applicationsRestClientService, Long appId, Long userId)
1366 throws JsonProcessingException, HTTPException {
1367 boolean result = false;
1368 ObjectMapper mapper = new ObjectMapper();
1369 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1370 String userRolesAsString = mapper.writeValueAsString(userAppRolesData);
1371 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, as the endpoint is not defined yet from the Mylogins");
1372 applicationsRestClientService.post(AppWithRolesForUser.class, appId, userRolesAsString, String.format("/user/%s/myLoginroles", userId));
1376 public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser userAppRolesData, EPUser user) {
1377 FieldsValidator fieldsValidator = new FieldsValidator();
1378 final Map<String, Long> params = new HashMap<>();
1379 EpUserAppRoles appRole= new EpUserAppRoles();
1381 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, still the endpoint is yet to be defined");
1382 boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService, userAppRolesData.appId, user.getId());
1384 params.put("appId", userAppRolesData.appId);
1385 EPUserAppRolesRequest epAppRolesRequestData = new EPUserAppRolesRequest();
1386 epAppRolesRequestData.setCreatedDate(new Date());
1387 epAppRolesRequestData.setUpdatedDate(new Date());
1388 epAppRolesRequestData.setUserId(user.getId());
1389 epAppRolesRequestData.setAppId(userAppRolesData.appId);
1390 epAppRolesRequestData.setRequestStatus("P");
1391 List<RoleInAppForUser> appRoleIdList = userAppRolesData.appRoles;
1392 Set<EPUserAppRolesRequestDetail> appRoleDetails = new LinkedHashSet<EPUserAppRolesRequestDetail>();
1393 dataAccessService.saveDomainObject(epAppRolesRequestData, null);
1394 for (RoleInAppForUser userAppRoles : appRoleIdList) {
1395 Boolean isAppliedVal = userAppRoles.isApplied;
1396 params.put("appRoleId", userAppRoles.roleId);
1398 appRole = (EpUserAppRoles) dataAccessService.executeNamedQuery("appRoles", params, null).get(0);
1399 EPUserAppRolesRequestDetail epAppRoleDetail = new EPUserAppRolesRequestDetail();
1400 epAppRoleDetail.setReqRoleId(appRole.getRoleId());
1401 epAppRoleDetail.setReqType("P");
1402 epAppRoleDetail.setEpRequestIdData(epAppRolesRequestData);
1403 dataAccessService.saveDomainObject(epAppRoleDetail, null);
1406 epAppRolesRequestData.setEpRequestIdDetail(appRoleDetails);
1407 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
1409 } catch (Exception e) {
1410 logger.error(EELFLoggerDelegate.errorLogger, "putUserAppRolesRequest failed", e);
1411 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1413 return fieldsValidator;
1416 public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(EPUser userid, String appName) {
1417 Map<String, String> params = new HashMap<>();
1418 params.put("userid", userid.getId().toString());
1419 //params.put("appid", appid);
1420 params.put("appName", appName);
1422 @SuppressWarnings("unchecked")
1423 List<EPUserAppCatalogRoles> userAppRoles = (List<EPUserAppCatalogRoles>) dataAccessService
1424 .executeNamedQuery("userAppCatalogRoles", params, null);
1425 return userAppRoles;
1428 public String updateRemoteUserProfile(String orgUserId, Long appId) {
1429 ObjectMapper mapper = new ObjectMapper();
1430 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1431 EPUser client = searchService.searchUserByUserId(orgUserId);
1432 EPUser newUser = new EPUser();
1433 newUser.setActive(client.getActive());
1434 newUser.setFirstName(client.getFirstName());
1435 newUser.setLastName(client.getLastName());
1436 newUser.setLoginId(client.getLoginId());
1437 newUser.setLoginPwd(client.getLoginPwd());
1438 newUser.setMiddleInitial(client.getMiddleInitial());
1439 newUser.setEmail(client.getEmail());
1440 newUser.setOrgUserId(client.getLoginId());
1442 String userAsString = mapper.writeValueAsString(newUser);
1443 List<EPApp> appList = appsService.getUserRemoteApps(client.getId().toString());
1444 // applicationsRestClientService.post(EPUser.class, appId,
1445 // userAsString, String.format("/user", orgUserId));
1446 for (EPApp eachApp : appList) {
1448 applicationsRestClientService.post(EPUser.class, eachApp.getId(), userAsString,
1449 String.format("/user/%s", orgUserId));
1450 } catch (Exception e) {
1451 logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId()
1452 + " in remote app. appId = " + eachApp.getId());
1455 } catch (Exception e) {
1456 logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
1467 * @see org.openecomp.portalapp.portal.service.UserRolesService#
1468 * getCachedAppRolesForUser(java.lang.Long, java.lang.Long)
1470 public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId) {
1471 // Find the records for this user-app combo, if any
1472 String filter = " where user_id = " + Long.toString(userId) + " and app_id = " + Long.toString(appId);
1473 @SuppressWarnings("unchecked")
1474 List<EPUserApp> roleList = dataAccessService.getList(EPUserApp.class, filter, null, null);
1475 logger.debug(EELFLoggerDelegate.debugLogger, "getCachedAppRolesForUser: list size is {}", roleList.size());