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.fn;
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.dao.fn.FnUserRoleDao;
62 import org.onap.portal.domain.db.ep.EpUserRolesRequest;
63 import org.onap.portal.domain.db.ep.EpUserRolesRequestDet;
64 import org.onap.portal.domain.db.fn.FnApp;
65 import org.onap.portal.domain.db.fn.FnRole;
66 import org.onap.portal.domain.db.fn.FnUser;
67 import org.onap.portal.domain.db.fn.FnUserRole;
68 import org.onap.portal.domain.dto.ecomp.EPUserAppCatalogRoles;
69 import org.onap.portal.domain.dto.ecomp.ExternalSystemAccess;
70 import org.onap.portal.domain.dto.transport.AppWithRolesForUser;
71 import org.onap.portal.domain.dto.transport.FieldsValidator;
72 import org.onap.portal.domain.dto.transport.RemoteRole;
73 import org.onap.portal.domain.dto.transport.RemoteUserWithRoles;
74 import org.onap.portal.domain.dto.transport.Role;
75 import org.onap.portal.domain.dto.transport.RoleInAppForUser;
76 import org.onap.portal.domain.dto.transport.UserApplicationRoles;
77 import org.onap.portal.service.ApplicationsRestClientService;
78 import org.onap.portal.service.ep.EpAppFunctionService;
79 import org.onap.portal.service.ep.EpUserRolesRequestDetService;
80 import org.onap.portal.service.ep.EpUserRolesRequestService;
81 import org.onap.portal.utils.EPCommonSystemProperties;
82 import org.onap.portal.utils.PortalConstants;
83 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
84 import org.onap.portalsdk.core.restful.domain.EcompRole;
85 import org.onap.portalsdk.core.util.SystemProperties;
86 import org.springframework.beans.factory.annotation.Autowired;
87 import org.springframework.stereotype.Service;
88 import org.springframework.transaction.annotation.Transactional;
92 public class FnUserRoleService {
94 private static final String GET_ROLE_FUNCTIONS_OF_USERFOR_ALLTHE_APPLICATIONS =
96 + " distinct ep.function_cd functionCd\n"
98 + " fn_user_role fu,\n"
99 + " ep_app_role_function ep,\n"
100 + " ep_app_function ea\n"
102 + " fu.role_id = ep.role_id\n"
103 + " and fu.app_id = ep.app_id\n"
104 + " and fu.user_id = 'userId'\n"
105 + " and ea.function_cd = ep.function_cd\n"
111 + " fn_user_role ur,\n"
114 + " fu.user_id = 'userId'\n"
115 + " and fu.user_id = ur.user_id\n"
116 + " and ur.app_id = fa.app_id\n"
117 + " and fa.enabled = 'Y'\n"
120 private static final String USER_APP_CATALOG_ROLES =
122 + " A.reqId as reqId,\n"
123 + " B.requestedRoleId.roleId as requestedRoleId,\n"
124 + " A.requestStatus as requestStatus,\n"
125 + " A.appId.appId as appId,\n"
132 + " roleId = B.requestedRoleId.roleId\n"
135 + " EpUserRolesRequest A\n"
136 + " left join EpUserRolesRequestDet B on A.reqId = B.reqId.reqId\n"
138 + " A.userId.userId = :userid\n"
139 + " and A.appId IN (\n"
145 + " appName = :appName\n"
147 + " and A.requestStatus = 'P'\n";
149 private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FnUserRoleService.class);
151 private final FnUserRoleDao fnUserRoleDao;
152 private final FnAppService fnAppService;
153 private final FnRoleService fnRoleService;
154 private final FnUserService fnUserService;
155 private final EpAppFunctionService epAppFunctionService;
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 EpAppFunctionService epAppFunctionService,
168 EpUserRolesRequestService epUserRolesRequestService,
169 EpUserRolesRequestDetService epUserRolesRequestDetService,
170 EntityManager entityManager,
171 ApplicationsRestClientService applicationsRestClientService) {
172 this.fnUserRoleDao = fnUserRoleDao;
173 this.fnAppService = fnAppService;
174 this.fnRoleService = fnRoleService;
175 this.fnUserService = fnUserService;
176 this.epAppFunctionService = epAppFunctionService;
177 this.epUserRolesRequestService = epUserRolesRequestService;
178 this.epUserRolesRequestDetService = epUserRolesRequestDetService;
179 this.entityManager = entityManager;
180 this.applicationsRestClientService = applicationsRestClientService;
183 public List<FnUserRole> retrieveByAppIdAndRoleId(final Long appId, final Long roleId) {
184 return Optional.of(fnUserRoleDao.retrieveByAppIdAndRoleId(appId, roleId)).orElse(new ArrayList<>());
187 public List<FnUserRole> getAdminUserRoles(final Long userId, final Long roleId, final Long appId) {
188 return fnUserRoleDao.getAdminUserRoles(userId, roleId, appId).orElse(new ArrayList<>());
191 public boolean isSuperAdmin(final String orgUserId, final Long roleId, final Long appId) {
192 List<FnUserRole> roles = getUserRolesForRoleIdAndAppId(roleId, appId).stream()
193 .filter(role -> role.getUserId().getOrgUserId().equals(orgUserId)).collect(Collectors.toList());
194 return !roles.isEmpty();
197 private List<FnUserRole> getUserRolesForRoleIdAndAppId(final Long roleId, final Long appId) {
198 return Optional.of(fnUserRoleDao.getUserRolesForRoleIdAndAppId(roleId, appId)).orElse(new ArrayList<>());
201 public FnUserRole saveOne(final FnUserRole fnUserRole) {
202 return fnUserRoleDao.save(fnUserRole);
205 public ExternalSystemAccess getExternalRequestAccess() {
206 ExternalSystemAccess res = null;
208 res = new ExternalSystemAccess(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE,
209 Boolean.parseBoolean(
210 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE)));
211 } catch (Exception e) {
212 logger.error(EELFLoggerDelegate.errorLogger, "getExternalRequestAccess failed" + e.getMessage());
217 public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(FnUser userid, String appName) {
218 List<Tuple> tuples = entityManager.createQuery(USER_APP_CATALOG_ROLES, Tuple.class)
219 .setParameter("userid", userid.getUserId())
220 .setParameter("appName", appName)
222 return Optional.of(tuples.stream().map(this::tupleToEPUserAppCatalogRoles).collect(Collectors.toList()))
223 .orElse(new ArrayList<>());
226 private EPUserAppCatalogRoles tupleToEPUserAppCatalogRoles(Tuple tuple) {
227 return new EPUserAppCatalogRoles((Long) tuple.get("reqId"), (Long) tuple.get("requestedRoleId"),
228 (String) tuple.get("roleName"), (String) tuple.get("requestStatus"), (Long) tuple.get("appId"));
231 private boolean postUserRolesToMylogins(AppWithRolesForUser userAppRolesData,
232 ApplicationsRestClientService applicationsRestClientService, Long appId, Long userId)
233 throws JsonProcessingException, HTTPException {
234 boolean result = false;
235 ObjectMapper mapper = new ObjectMapper();
236 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
237 String userRolesAsString = mapper.writeValueAsString(userAppRolesData);
238 logger.error(EELFLoggerDelegate.errorLogger,
239 "Should not be reached here, as the endpoint is not defined yet from the Mylogins");
240 applicationsRestClientService.post(AppWithRolesForUser.class, appId, userRolesAsString,
241 String.format("/user/%s/myLoginroles", userId));
245 public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser newAppRolesForUser, FnUser user) {
246 FieldsValidator fieldsValidator = new FieldsValidator();
247 List<FnRole> appRole;
249 logger.error(EELFLoggerDelegate.errorLogger,
250 "Should not be reached here, still the endpoint is yet to be defined");
251 boolean result = postUserRolesToMylogins(newAppRolesForUser, applicationsRestClientService,
252 newAppRolesForUser.getAppId(), user.getId());
253 logger.debug(EELFLoggerDelegate.debugLogger, "putUserAppRolesRequest: result {}", result);
254 FnApp app = fnAppService.getById(newAppRolesForUser.getAppId());
255 EpUserRolesRequest epUserRolesRequest = new EpUserRolesRequest();
256 epUserRolesRequest.setCreatedDate(LocalDateTime.now());
257 epUserRolesRequest.setUpdatedDate(LocalDateTime.now());
258 epUserRolesRequest.setUserId(user);
259 epUserRolesRequest.setAppId(app);
260 epUserRolesRequest.setRequestStatus("P");
261 List<RoleInAppForUser> appRoleIdList = newAppRolesForUser.getAppRoles();
262 Set<EpUserRolesRequestDet> appRoleDetails = new LinkedHashSet<>();
263 epUserRolesRequestService.saveOne(epUserRolesRequest);
264 for (RoleInAppForUser userAppRoles : appRoleIdList) {
265 Boolean isAppliedVal = userAppRoles.getIsApplied();
267 appRole = fnRoleService
268 .retrieveAppRoleByAppRoleIdAndByAppId(newAppRolesForUser.getAppId(),
269 userAppRoles.getRoleId());
270 if (!appRole.isEmpty()) {
271 EpUserRolesRequestDet epAppRoleDetail = new EpUserRolesRequestDet();
272 epAppRoleDetail.setRequestedRoleId(appRole.get(0));
273 epAppRoleDetail.setRequestType("P");
274 epAppRoleDetail.setReqId(epUserRolesRequest);
275 epUserRolesRequestDetService.saveOne(epAppRoleDetail);
279 epUserRolesRequest.setEpRequestIdDetail(appRoleDetails);
280 fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_OK);
282 } catch (Exception e) {
283 logger.error(EELFLoggerDelegate.errorLogger, "putUserAppRolesRequest failed", e);
284 fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
286 return fieldsValidator;
289 public List<FnRole> importRolesFromRemoteApplication(Long appId) throws HTTPException {
290 FnRole[] appRolesFull = applicationsRestClientService.get(FnRole[].class, appId, "/rolesFull");
291 List<FnRole> rolesList = Arrays.asList(appRolesFull);
292 for (FnRole externalAppRole : rolesList) {
294 // Try to find an existing extern role for the app in the local
295 // onap DB. If so, then use its id to update the existing external
296 // application role record.
297 Long externAppId = externalAppRole.getId();
298 FnRole existingAppRole = fnRoleService.getRole(appId, externAppId);
299 if (existingAppRole != null) {
300 logger.debug(EELFLoggerDelegate.debugLogger,
302 "ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.",
303 appId, externAppId));
310 public List<UserApplicationRoles> getUsersFromAppEndpoint(Long appId) throws HTTPException {
311 ArrayList<UserApplicationRoles> userApplicationRoles = new ArrayList<>();
313 FnApp app = fnAppService.getById(appId);
314 //If local or centralized application
315 if (PortalConstants.PORTAL_APP_ID.equals(appId) || app.getAuthCentral()) {
316 List<FnUser> userList = fnUserService.getActiveUsers();
317 for (FnUser user : userList) {
318 UserApplicationRoles userWithAppRoles = convertToUserApplicationRoles(appId, user, app);
319 if (userWithAppRoles.getRoles() != null && userWithAppRoles.getRoles().size() > 0) {
320 userApplicationRoles.add(userWithAppRoles);
327 RemoteUserWithRoles[] remoteUsers;
328 String remoteUsersString = applicationsRestClientService.getIncomingJsonString(appId, "/users");
330 remoteUsers = doGetUsers(remoteUsersString);
332 userApplicationRoles = new ArrayList<>();
333 for (RemoteUserWithRoles remoteUser : remoteUsers) {
334 UserApplicationRoles userWithRemoteAppRoles = convertToUserApplicationRoles(appId,
336 if (userWithRemoteAppRoles.getRoles() != null
337 && userWithRemoteAppRoles.getRoles().size() > 0) {
338 userApplicationRoles.add(userWithRemoteAppRoles);
340 logger.debug(EELFLoggerDelegate.debugLogger,
341 "User " + userWithRemoteAppRoles.getOrgUserId()
342 + " doesn't have any roles assigned to any app.");
347 return userApplicationRoles;
350 private UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) {
351 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
352 userWithRemoteAppRoles.setAppId(appId);
353 userWithRemoteAppRoles.setOrgUserId(remoteUser.getOrgUserId());
354 userWithRemoteAppRoles.setFirstName(remoteUser.getFirstName());
355 userWithRemoteAppRoles.setLastName(remoteUser.getLastName());
356 userWithRemoteAppRoles.setRoles(remoteUser.getRoles());
357 return userWithRemoteAppRoles;
360 private RemoteUserWithRoles[] doGetUsers(String remoteUsersString) {
362 ObjectMapper mapper = new ObjectMapper();
364 return mapper.readValue(remoteUsersString, RemoteUserWithRoles[].class);
365 } catch (IOException e) {
366 logger.error(EELFLoggerDelegate.errorLogger,
367 "doGetUsers : Failed : Unexpected property in incoming JSON",
369 logger.error(EELFLoggerDelegate.errorLogger,
370 "doGetUsers : Incoming JSON that caused it --> " + remoteUsersString);
373 return new RemoteUserWithRoles[0];
376 private UserApplicationRoles convertToUserApplicationRoles(Long appId, FnUser user, FnApp app) {
377 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
378 userWithRemoteAppRoles.setAppId(appId);
379 userWithRemoteAppRoles.setOrgUserId(user.getOrgUserId());
380 userWithRemoteAppRoles.setFirstName(user.getFirstName());
381 userWithRemoteAppRoles.setLastName(user.getLastName());
382 userWithRemoteAppRoles.setRoles(convertToRemoteRoleList(user, app));
383 return userWithRemoteAppRoles;
386 private List<RemoteRole> convertToRemoteRoleList(FnUser user, FnApp app) {
387 List<RemoteRole> roleList = new ArrayList<>();
388 SortedSet<FnRole> roleSet = user.getAppEPRoles(app);
389 for (FnRole role : roleSet) {
390 logger.debug(EELFLoggerDelegate.debugLogger,
391 "In convertToRemoteRoleList() - for user {}, found Name {}", user.getOrgUserId(),
393 RemoteRole rRole = new RemoteRole();
394 rRole.setId(role.getId());
395 rRole.setName(role.getRoleName());
399 //Get the active roles of user for that application using query
400 List<FnRole> userEpRoleList = fnRoleService.getUserRoleOnUserIdAndAppId(user.getId(), app.getId());
402 for (FnRole remoteUserRoleList : userEpRoleList) {
404 RemoteRole remoteRoleListId = roleList.stream()
405 .filter(x -> remoteUserRoleList.getId().equals(x.getId()))
406 .findAny().orElse(null);
407 if (remoteRoleListId == null) {
408 logger.debug(EELFLoggerDelegate.debugLogger,
409 "Adding the role to the rolelist () - for user {}, found Name {}",
412 remoteUserRoleList.getRoleName());
413 RemoteRole role = new RemoteRole();
414 role.setId(remoteUserRoleList.getId());
415 role.setName(remoteUserRoleList.getRoleName());
422 logger.debug(EELFLoggerDelegate.debugLogger,
423 "rolelist size of the USER() - for user {}, found RoleListSize {}", user.getOrgUserId(),
428 public List getRoleFunctionsOfUserforAlltheApplications(Long userId) {
429 List<Tuple> tuples = entityManager
430 .createQuery(GET_ROLE_FUNCTIONS_OF_USERFOR_ALLTHE_APPLICATIONS, Tuple.class)
431 .setParameter("userid", userId)
433 return Optional.of(tuples.stream().map(tuple -> tuple.get("functionCd")).collect(Collectors.toList()))
434 .orElse(new ArrayList<>());
437 public List<FnUserRole> retrieveByAppIdAndUserId(final Long appId, final String userId) {
438 return Optional.of(fnUserRoleDao.retrieveByAppIdAndUserId(appId, userId)).orElse(new ArrayList<>());
441 public String updateRemoteUserProfile(String orgUserId, long appId) {
442 ObjectMapper mapper = new ObjectMapper();
443 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
444 FnUser client = fnUserService.loadUserByUsername(orgUserId);
445 FnUser newUser = new FnUser();
446 newUser.setActiveYn(client.getActiveYn());
447 newUser.setFirstName(client.getFirstName());
448 newUser.setLastName(client.getLastName());
449 newUser.setLoginId(client.getLoginId());
450 newUser.setLoginPwd(client.getLoginPwd());
451 newUser.setMiddleName(client.getMiddleName());
452 newUser.setEmail(client.getEmail());
453 newUser.setOrgUserId(client.getLoginId());
455 String userAsString = mapper.writeValueAsString(newUser);
456 List<FnApp> appList = fnAppService.getUserRemoteApps(client.getId().toString());
457 // applicationsRestClientService.post(EPUser.class, appId,
458 // userAsString, String.format("/user", orgUserId));
459 for (FnApp eachApp : appList) {
461 applicationsRestClientService.post(FnUser.class, eachApp.getId(), userAsString,
462 String.format("/user/%s", orgUserId));
463 } catch (Exception e) {
464 logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId()
465 + " in remote app. appId = " + eachApp.getId());
468 } catch (Exception e) {
469 logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
475 public void deleteById(final Long id) {
476 fnUserRoleDao.deleteById(id);
479 public List<RoleInAppForUser> constructRolesInAppForUserGet(List<Role> appRoles, FnRole[] userAppRoles,
480 Boolean extRequestValue) {
481 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<>();
483 Set<Long> userAppRolesMap = new HashSet<>();
484 if (userAppRoles != null) {
485 for (FnRole ecompRole : userAppRoles) {
486 userAppRolesMap.add(ecompRole.getAppId());
488 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - userAppRolesMap = {}",
492 logger.error(EELFLoggerDelegate.errorLogger,
493 "constructRolesInAppForUserGet has received userAppRoles list empty.");
496 if (appRoles != null) {
497 for (Role ecompRole : appRoles) {
498 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - appRoles not null = {}",
501 if (ecompRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && !extRequestValue) {
504 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
505 roleForUser.setIsApplied(userAppRolesMap.contains(ecompRole.getId()));
506 rolesInAppForUser.add(roleForUser);
507 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - rolesInAppForUser = {}",
512 logger.error(EELFLoggerDelegate.errorLogger,
513 "constructRolesInAppForUser has received appRoles list empty.");
515 return rolesInAppForUser;
518 public List<RoleInAppForUser> constructRolesInAppForUserGet(EcompRole[] appRoles, EcompRole[] userAppRoles) {
519 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<>();
521 Set<Long> userAppRolesMap = new HashSet<>();
522 if (userAppRoles != null) {
523 for (EcompRole ecompRole : userAppRoles) {
524 userAppRolesMap.add(ecompRole.getId());
527 logger.error(EELFLoggerDelegate.errorLogger,
528 "constructRolesInAppForUserGet has received userAppRoles list empty");
531 if (appRoles != null) {
532 for (EcompRole ecompRole : appRoles) {
533 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
534 roleForUser.setIsApplied(userAppRolesMap.contains(ecompRole.getId()));
535 rolesInAppForUser.add(roleForUser);
538 logger.error(EELFLoggerDelegate.errorLogger, "constructRolesInAppForUser has received appRoles list empty");
540 return rolesInAppForUser;