2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
7 * Modifications Copyright (c) 2019 Samsung
8 * ===================================================================
10 * Unless otherwise specified, all software contained herein is licensed
11 * under the Apache License, Version 2.0 (the "License");
12 * you may not use this software except in compliance with the License.
13 * You may obtain a copy of the License at
15 * http://www.apache.org/licenses/LICENSE-2.0
17 * Unless required by applicable law or agreed to in writing, software
18 * distributed under the License is distributed on an "AS IS" BASIS,
19 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 * See the License for the specific language governing permissions and
21 * limitations under the License.
23 * Unless otherwise specified, all documentation contained herein is licensed
24 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
25 * you may not use this documentation except in compliance with the License.
26 * You may obtain a copy of the License at
28 * https://creativecommons.org/licenses/by/4.0/
30 * Unless required by applicable law or agreed to in writing, documentation
31 * distributed under the License is distributed on an "AS IS" BASIS,
32 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
33 * See the License for the specific language governing permissions and
34 * limitations under the License.
36 * ============LICENSE_END============================================
41 package org.onap.portal.service.userRole;
43 import com.fasterxml.jackson.core.JsonProcessingException;
44 import com.fasterxml.jackson.databind.DeserializationFeature;
45 import com.fasterxml.jackson.databind.ObjectMapper;
46 import java.io.IOException;
47 import java.time.LocalDateTime;
48 import java.util.ArrayList;
49 import java.util.Arrays;
50 import java.util.HashSet;
51 import java.util.LinkedHashSet;
52 import java.util.List;
53 import java.util.Optional;
55 import java.util.SortedSet;
56 import java.util.stream.Collectors;
57 import javax.persistence.EntityManager;
58 import javax.persistence.Tuple;
59 import javax.servlet.http.HttpServletResponse;
60 import org.apache.cxf.transport.http.HTTPException;
61 import org.onap.portal.domain.db.ep.EpUserRolesRequest;
62 import org.onap.portal.domain.db.ep.EpUserRolesRequestDet;
63 import org.onap.portal.domain.db.fn.FnApp;
64 import org.onap.portal.domain.db.fn.FnRole;
65 import org.onap.portal.domain.db.fn.FnUser;
66 import org.onap.portal.domain.db.fn.FnUserRole;
67 import org.onap.portal.domain.dto.ecomp.EPUserAppCatalogRoles;
68 import org.onap.portal.domain.dto.ecomp.ExternalSystemAccess;
69 import org.onap.portal.domain.dto.transport.AppWithRolesForUser;
70 import org.onap.portal.domain.dto.transport.FieldsValidator;
71 import org.onap.portal.domain.dto.transport.RemoteRole;
72 import org.onap.portal.domain.dto.transport.RemoteUserWithRoles;
73 import org.onap.portal.domain.dto.transport.Role;
74 import org.onap.portal.domain.dto.transport.RoleInAppForUser;
75 import org.onap.portal.domain.dto.transport.UserApplicationRoles;
76 import org.onap.portal.service.ApplicationsRestClientService;
77 import org.onap.portal.service.userRolesRequestDet.EpUserRolesRequestDetService;
78 import org.onap.portal.service.userRolesRequest.EpUserRolesRequestService;
79 import org.onap.portal.service.app.FnAppService;
80 import org.onap.portal.service.role.FnRoleService;
81 import org.onap.portal.service.user.FnUserService;
82 import org.onap.portal.utils.EPCommonSystemProperties;
83 import org.onap.portal.utils.PortalConstants;
84 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
85 import org.onap.portalsdk.core.restful.domain.EcompRole;
86 import org.onap.portalsdk.core.util.SystemProperties;
87 import org.springframework.beans.factory.annotation.Autowired;
88 import org.springframework.stereotype.Service;
89 import org.springframework.transaction.annotation.Transactional;
93 public class FnUserRoleService {
95 private static final String GET_ROLE_FUNCTIONS_OF_USERFOR_ALLTHE_APPLICATIONS =
97 + " distinct ep.function_cd functionCd\n"
99 + " fn_user_role fu,\n"
100 + " ep_app_role_function ep,\n"
101 + " ep_app_function ea\n"
103 + " fu.role_id = ep.role_id\n"
104 + " and fu.app_id = ep.app_id\n"
105 + " and fu.user_id = 'userId'\n"
106 + " and ea.function_cd = ep.function_cd\n"
112 + " fn_user_role ur,\n"
115 + " fu.user_id = 'userId'\n"
116 + " and fu.user_id = ur.user_id\n"
117 + " and ur.app_id = fa.app_id\n"
118 + " and fa.enabled = 'Y'\n"
121 private static final String USER_APP_CATALOG_ROLES =
123 + " A.reqId as reqId,\n"
124 + " B.requestedRoleId.id as requestedRoleId,\n"
125 + " A.requestStatus as requestStatus,\n"
126 + " A.appId.id as appId,\n"
133 + " id = B.requestedRoleId.id\n"
136 + " EpUserRolesRequest A\n"
137 + " left join EpUserRolesRequestDet B on A.reqId = B.reqId.reqId\n"
139 + " A.userId.id = :userid\n"
140 + " and A.appId IN (\n"
146 + " appName = :appName\n"
148 + " and A.requestStatus = 'P'\n";
150 private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FnUserRoleService.class);
152 private final FnUserRoleDao fnUserRoleDao;
153 private final FnAppService fnAppService;
154 private final FnRoleService fnRoleService;
155 private final FnUserService fnUserService;
156 private final EpUserRolesRequestService epUserRolesRequestService;
157 private final EpUserRolesRequestDetService epUserRolesRequestDetService;
158 private final EntityManager entityManager;
159 private final ApplicationsRestClientService applicationsRestClientService;
162 public FnUserRoleService(FnUserRoleDao
164 FnAppService fnAppService,
165 FnRoleService fnRoleService,
166 FnUserService fnUserService,
167 EpUserRolesRequestService epUserRolesRequestService,
168 EpUserRolesRequestDetService epUserRolesRequestDetService,
169 EntityManager entityManager,
170 ApplicationsRestClientService applicationsRestClientService) {
171 this.fnUserRoleDao = fnUserRoleDao;
172 this.fnAppService = fnAppService;
173 this.fnRoleService = fnRoleService;
174 this.fnUserService = fnUserService;
175 this.epUserRolesRequestService = epUserRolesRequestService;
176 this.epUserRolesRequestDetService = epUserRolesRequestDetService;
177 this.entityManager = entityManager;
178 this.applicationsRestClientService = applicationsRestClientService;
181 public List<FnUserRole> getAdminUserRoles(final Long userId, final Long roleId, final Long appId) {
182 return fnUserRoleDao.getAdminUserRoles(userId, roleId, appId).orElse(new ArrayList<>());
185 public boolean isSuperAdmin(final String loginId, final Long roleId, final Long appId) {
186 List<FnUserRole> roles = getUserRolesForRoleIdAndAppId(roleId, appId).stream()
187 .filter(role -> role.getUserId().getOrgUserId().equals(loginId)).collect(Collectors.toList());
188 return !roles.isEmpty();
191 public List<FnUserRole> getUserRolesForRoleIdAndAppId(final Long roleId, final Long appId) {
192 return Optional.of(fnUserRoleDao.retrieveByAppIdAndRoleId(appId, roleId)).orElse(new ArrayList<>());
195 public List<FnUserRole> retrieveByUserIdAndRoleId(final Long userId, final Long roleId){
196 return Optional.of(fnUserRoleDao.retrieveByUserIdAndRoleId(userId, roleId)).orElse(new ArrayList<>());
199 public FnUserRole saveOne(final FnUserRole fnUserRole) {
200 return fnUserRoleDao.save(fnUserRole);
203 public ExternalSystemAccess getExternalRequestAccess() {
204 ExternalSystemAccess res = null;
206 res = new ExternalSystemAccess(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE,
207 Boolean.parseBoolean(
208 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE)));
209 } catch (Exception e) {
210 logger.error(EELFLoggerDelegate.errorLogger, "getExternalRequestAccess failed" + e.getMessage());
215 public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(FnUser userid, String appName) {
216 List<Tuple> tuples = entityManager.createQuery(USER_APP_CATALOG_ROLES, Tuple.class)
217 .setParameter("userid", userid.getId())
218 .setParameter("appName", appName)
220 return Optional.of(tuples.stream().map(this::tupleToEPUserAppCatalogRoles).collect(Collectors.toList()))
221 .orElse(new ArrayList<>());
224 private EPUserAppCatalogRoles tupleToEPUserAppCatalogRoles(Tuple tuple) {
225 return new EPUserAppCatalogRoles((Long) tuple.get("reqId"), (Long) tuple.get("requestedRoleId"),
226 (String) tuple.get("roleName"), (String) tuple.get("requestStatus"), (Long) tuple.get("appId"));
229 private boolean postUserRolesToMylogins(AppWithRolesForUser userAppRolesData,
230 ApplicationsRestClientService applicationsRestClientService, Long appId, Long userId)
231 throws JsonProcessingException, HTTPException {
232 boolean result = false;
233 ObjectMapper mapper = new ObjectMapper();
234 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
235 String userRolesAsString = mapper.writeValueAsString(userAppRolesData);
236 logger.error(EELFLoggerDelegate.errorLogger,
237 "Should not be reached here, as the endpoint is not defined yet from the Mylogins");
238 applicationsRestClientService.post(AppWithRolesForUser.class, appId, userRolesAsString,
239 String.format("/user/%s/myLoginroles", userId));
243 public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser newAppRolesForUser, FnUser user) {
244 FieldsValidator fieldsValidator = new FieldsValidator();
245 List<FnRole> appRole;
247 logger.error(EELFLoggerDelegate.errorLogger,
248 "Should not be reached here, still the endpoint is yet to be defined");
249 boolean result = postUserRolesToMylogins(newAppRolesForUser, applicationsRestClientService,
250 newAppRolesForUser.getAppId(), user.getId());
251 logger.debug(EELFLoggerDelegate.debugLogger, "putUserAppRolesRequest: result {}", result);
252 FnApp app = fnAppService.getById(newAppRolesForUser.getAppId());
253 EpUserRolesRequest epUserRolesRequest = new EpUserRolesRequest();
254 epUserRolesRequest.setCreatedDate(LocalDateTime.now());
255 epUserRolesRequest.setUpdatedDate(LocalDateTime.now());
256 epUserRolesRequest.setUserId(user);
257 epUserRolesRequest.setAppId(app);
258 epUserRolesRequest.setRequestStatus("P");
259 List<RoleInAppForUser> appRoleIdList = newAppRolesForUser.getAppRoles();
260 Set<EpUserRolesRequestDet> appRoleDetails = new LinkedHashSet<>();
261 epUserRolesRequestService.saveOne(epUserRolesRequest);
262 for (RoleInAppForUser userAppRoles : appRoleIdList) {
263 Boolean isAppliedVal = userAppRoles.getIsApplied();
265 appRole = fnRoleService
266 .retrieveAppRoleByAppRoleIdAndByAppId(newAppRolesForUser.getAppId(),
267 userAppRoles.getRoleId());
268 if (!appRole.isEmpty()) {
269 EpUserRolesRequestDet epAppRoleDetail = new EpUserRolesRequestDet();
270 epAppRoleDetail.setRequestedRoleId(appRole.get(0));
271 epAppRoleDetail.setRequestType("P");
272 epAppRoleDetail.setReqId(epUserRolesRequest);
273 epUserRolesRequestDetService.saveOne(epAppRoleDetail);
277 epUserRolesRequest.setEpRequestIdDetail(appRoleDetails);
278 fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_OK);
280 } catch (Exception e) {
281 logger.error(EELFLoggerDelegate.errorLogger, "putUserAppRolesRequest failed", e);
282 fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
284 return fieldsValidator;
287 public List<FnRole> importRolesFromRemoteApplication(Long appId) throws HTTPException {
288 FnRole[] appRolesFull = applicationsRestClientService.get(FnRole[].class, appId, "/rolesFull");
289 List<FnRole> rolesList = Arrays.asList(appRolesFull);
290 for (FnRole externalAppRole : rolesList) {
292 // Try to find an existing extern role for the app in the local
293 // onap DB. If so, then use its id to update the existing external
294 // application role record.
295 Long externAppId = externalAppRole.getId();
296 FnRole existingAppRole = fnRoleService.getRole(appId, externAppId);
297 if (existingAppRole != null) {
298 logger.debug(EELFLoggerDelegate.debugLogger,
300 "ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.",
301 appId, externAppId));
308 public List<UserApplicationRoles> getUsersFromAppEndpoint(Long appId) throws HTTPException {
309 ArrayList<UserApplicationRoles> userApplicationRoles = new ArrayList<>();
311 FnApp app = fnAppService.getById(appId);
312 //If local or centralized application
313 if (PortalConstants.PORTAL_APP_ID.equals(appId) || app.getAuthCentral()) {
314 List<FnUser> userList = fnUserService.getActiveUsers();
315 for (FnUser user : userList) {
316 UserApplicationRoles userWithAppRoles = convertToUserApplicationRoles(appId, user, app);
317 if (userWithAppRoles.getRoles() != null && userWithAppRoles.getRoles().size() > 0) {
318 userApplicationRoles.add(userWithAppRoles);
325 RemoteUserWithRoles[] remoteUsers;
326 String remoteUsersString = applicationsRestClientService.getIncomingJsonString(appId, "/users");
328 remoteUsers = doGetUsers(remoteUsersString);
330 userApplicationRoles = new ArrayList<>();
331 for (RemoteUserWithRoles remoteUser : remoteUsers) {
332 UserApplicationRoles userWithRemoteAppRoles = convertToUserApplicationRoles(appId,
334 if (userWithRemoteAppRoles.getRoles() != null
335 && userWithRemoteAppRoles.getRoles().size() > 0) {
336 userApplicationRoles.add(userWithRemoteAppRoles);
338 logger.debug(EELFLoggerDelegate.debugLogger,
339 "User " + userWithRemoteAppRoles.getOrgUserId()
340 + " doesn't have any roles assigned to any app.");
345 return userApplicationRoles;
348 private UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) {
349 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
350 userWithRemoteAppRoles.setAppId(appId);
351 userWithRemoteAppRoles.setOrgUserId(remoteUser.getOrgUserId());
352 userWithRemoteAppRoles.setFirstName(remoteUser.getFirstName());
353 userWithRemoteAppRoles.setLastName(remoteUser.getLastName());
354 userWithRemoteAppRoles.setRoles(remoteUser.getRoles());
355 return userWithRemoteAppRoles;
358 private RemoteUserWithRoles[] doGetUsers(String remoteUsersString) {
360 ObjectMapper mapper = new ObjectMapper();
362 return mapper.readValue(remoteUsersString, RemoteUserWithRoles[].class);
363 } catch (IOException e) {
364 logger.error(EELFLoggerDelegate.errorLogger,
365 "doGetUsers : Failed : Unexpected property in incoming JSON",
367 logger.error(EELFLoggerDelegate.errorLogger,
368 "doGetUsers : Incoming JSON that caused it --> " + remoteUsersString);
371 return new RemoteUserWithRoles[0];
374 private UserApplicationRoles convertToUserApplicationRoles(Long appId, FnUser user, FnApp app) {
375 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
376 userWithRemoteAppRoles.setAppId(appId);
377 userWithRemoteAppRoles.setOrgUserId(user.getOrgUserId());
378 userWithRemoteAppRoles.setFirstName(user.getFirstName());
379 userWithRemoteAppRoles.setLastName(user.getLastName());
380 userWithRemoteAppRoles.setRoles(convertToRemoteRoleList(user, app));
381 return userWithRemoteAppRoles;
384 private List<RemoteRole> convertToRemoteRoleList(FnUser user, FnApp app) {
385 List<RemoteRole> roleList = new ArrayList<>();
386 SortedSet<FnRole> roleSet = user.getAppEPRoles(app);
387 for (FnRole role : roleSet) {
388 logger.debug(EELFLoggerDelegate.debugLogger,
389 "In convertToRemoteRoleList() - for user {}, found Name {}", user.getOrgUserId(),
391 RemoteRole rRole = new RemoteRole();
392 rRole.setId(role.getId());
393 rRole.setName(role.getRoleName());
397 //Get the active roles of user for that application using query
398 List<FnRole> userEpRoleList = fnRoleService.getUserRoleOnUserIdAndAppId(user.getId(), app.getId());
400 for (FnRole remoteUserRoleList : userEpRoleList) {
402 RemoteRole remoteRoleListId = roleList.stream()
403 .filter(x -> remoteUserRoleList.getId().equals(x.getId()))
404 .findAny().orElse(null);
405 if (remoteRoleListId == null) {
406 logger.debug(EELFLoggerDelegate.debugLogger,
407 "Adding the role to the rolelist () - for user {}, found Name {}",
410 remoteUserRoleList.getRoleName());
411 RemoteRole role = new RemoteRole();
412 role.setId(remoteUserRoleList.getId());
413 role.setName(remoteUserRoleList.getRoleName());
420 logger.debug(EELFLoggerDelegate.debugLogger,
421 "rolelist size of the USER() - for user {}, found RoleListSize {}", user.getOrgUserId(),
426 public List getRoleFunctionsOfUserforAlltheApplications(Long userId) {
427 List<Tuple> tuples = entityManager
428 .createQuery(GET_ROLE_FUNCTIONS_OF_USERFOR_ALLTHE_APPLICATIONS, Tuple.class)
429 .setParameter("userid", userId)
431 return Optional.of(tuples.stream().map(tuple -> tuple.get("functionCd")).collect(Collectors.toList()))
432 .orElse(new ArrayList<>());
435 public List<FnUserRole> retrieveByAppIdAndUserId(final Long appId, final String userId) {
436 return Optional.of(fnUserRoleDao.retrieveByAppIdAndUserId(appId, userId)).orElse(new ArrayList<>());
439 public String updateRemoteUserProfile(String orgUserId, long appId) {
440 ObjectMapper mapper = new ObjectMapper();
441 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
442 FnUser client = fnUserService.loadUserByUsername(orgUserId);
443 FnUser newUser = new FnUser();
444 newUser.setActiveYn(client.getActiveYn());
445 newUser.setFirstName(client.getFirstName());
446 newUser.setLastName(client.getLastName());
447 newUser.setLoginId(client.getLoginId());
448 newUser.setLoginPwd(client.getLoginPwd());
449 newUser.setMiddleName(client.getMiddleName());
450 newUser.setEmail(client.getEmail());
451 newUser.setOrgUserId(client.getLoginId());
453 String userAsString = mapper.writeValueAsString(newUser);
454 List<FnApp> appList = fnAppService.getUserRemoteApps(client.getId().toString());
455 // applicationsRestClientService.post(EPUser.class, appId,
456 // userAsString, String.format("/user", orgUserId));
457 for (FnApp eachApp : appList) {
459 applicationsRestClientService.post(FnUser.class, eachApp.getId(), userAsString,
460 String.format("/user/%s", orgUserId));
461 } catch (Exception e) {
462 logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId()
463 + " in remote app. appId = " + eachApp.getId());
466 } catch (Exception e) {
467 logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
473 public void deleteById(final Long id) {
474 fnUserRoleDao.deleteById(id);
477 public List<RoleInAppForUser> constructRolesInAppForUserGet(List<Role> appRoles, FnRole[] userAppRoles,
478 Boolean extRequestValue) {
479 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<>();
481 Set<Long> userAppRolesMap = new HashSet<>();
482 if (userAppRoles != null) {
483 for (FnRole ecompRole : userAppRoles) {
484 userAppRolesMap.add(ecompRole.getAppId());
486 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - userAppRolesMap = {}",
490 logger.error(EELFLoggerDelegate.errorLogger,
491 "constructRolesInAppForUserGet has received userAppRoles list empty.");
494 if (appRoles != null) {
495 for (Role ecompRole : appRoles) {
496 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - appRoles not null = {}",
499 if (ecompRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && !extRequestValue) {
502 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getRoleName());
503 roleForUser.setIsApplied(userAppRolesMap.contains(ecompRole.getId()));
504 rolesInAppForUser.add(roleForUser);
505 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - rolesInAppForUser = {}",
510 logger.error(EELFLoggerDelegate.errorLogger,
511 "constructRolesInAppForUser has received appRoles list empty.");
513 return rolesInAppForUser;
516 public List<RoleInAppForUser> constructRolesInAppForUserGet(EcompRole[] appRoles, EcompRole[] userAppRoles) {
517 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<>();
519 Set<Long> userAppRolesMap = new HashSet<>();
520 if (userAppRoles != null) {
521 for (EcompRole ecompRole : userAppRoles) {
522 userAppRolesMap.add(ecompRole.getId());
525 logger.error(EELFLoggerDelegate.errorLogger,
526 "constructRolesInAppForUserGet has received userAppRoles list empty");
529 if (appRoles != null) {
530 for (EcompRole ecompRole : appRoles) {
531 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
532 roleForUser.setIsApplied(userAppRolesMap.contains(ecompRole.getId()));
533 rolesInAppForUser.add(roleForUser);
536 logger.error(EELFLoggerDelegate.errorLogger, "constructRolesInAppForUser has received appRoles list empty");
538 return rolesInAppForUser;
541 public List<FnUserRole> saveAll(List<FnUserRole> userRoles) {
542 return fnUserRoleDao.saveAll(userRoles);