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.id as requestedRoleId,\n"
124 + " A.requestStatus as requestStatus,\n"
125 + " A.appId.id as appId,\n"
132 + " id = B.requestedRoleId.id\n"
135 + " EpUserRolesRequest A\n"
136 + " left join EpUserRolesRequestDet B on A.reqId = B.reqId.reqId\n"
138 + " A.userId.id = :userid\n"
139 + " and A.appId IN (\n"
145 + " appName = :appName\n"
147 + " and A.requestStatus = 'P'\n";
149 private final 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 EpUserRolesRequestService epUserRolesRequestService;
156 private final EpUserRolesRequestDetService epUserRolesRequestDetService;
157 private final EntityManager entityManager;
158 private final ApplicationsRestClientService applicationsRestClientService;
161 public FnUserRoleService(FnUserRoleDao
163 FnAppService fnAppService,
164 FnRoleService fnRoleService,
165 FnUserService fnUserService,
166 EpUserRolesRequestService epUserRolesRequestService,
167 EpUserRolesRequestDetService epUserRolesRequestDetService,
168 EntityManager entityManager,
169 ApplicationsRestClientService applicationsRestClientService) {
170 this.fnUserRoleDao = fnUserRoleDao;
171 this.fnAppService = fnAppService;
172 this.fnRoleService = fnRoleService;
173 this.fnUserService = fnUserService;
174 this.epUserRolesRequestService = epUserRolesRequestService;
175 this.epUserRolesRequestDetService = epUserRolesRequestDetService;
176 this.entityManager = entityManager;
177 this.applicationsRestClientService = applicationsRestClientService;
180 public List<FnUserRole> getAdminUserRoles(final Long userId, final Long roleId, final Long appId) {
181 return fnUserRoleDao.getAdminUserRoles(userId, roleId, appId).orElse(new ArrayList<>());
184 public boolean isSuperAdmin(final String loginId, final Long roleId, final Long appId) {
185 List<FnUserRole> roles = getUserRolesForRoleIdAndAppId(roleId, appId).stream()
186 .filter(role -> role.getUserId().getOrgUserId().equals(loginId)).collect(Collectors.toList());
187 return !roles.isEmpty();
190 public List<FnUserRole> getUserRolesForRoleIdAndAppId(final Long roleId, final Long appId) {
191 return Optional.of(fnUserRoleDao.retrieveByAppIdAndRoleId(appId, roleId)).orElse(new ArrayList<>());
194 public List<FnUserRole> retrieveByUserIdAndRoleId(final Long userId, final Long roleId){
195 return Optional.of(fnUserRoleDao.retrieveByUserIdAndRoleId(userId, roleId)).orElse(new ArrayList<>());
198 public FnUserRole saveOne(final FnUserRole fnUserRole) {
199 return fnUserRoleDao.save(fnUserRole);
202 public ExternalSystemAccess getExternalRequestAccess() {
203 ExternalSystemAccess res = null;
205 res = new ExternalSystemAccess(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE,
206 Boolean.parseBoolean(
207 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE)));
208 } catch (Exception e) {
209 logger.error(EELFLoggerDelegate.errorLogger, "getExternalRequestAccess failed" + e.getMessage());
214 public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(FnUser userid, String appName) {
215 List<Tuple> tuples = entityManager.createQuery(USER_APP_CATALOG_ROLES, Tuple.class)
216 .setParameter("userid", userid.getId())
217 .setParameter("appName", appName)
219 return Optional.of(tuples.stream().map(this::tupleToEPUserAppCatalogRoles).collect(Collectors.toList()))
220 .orElse(new ArrayList<>());
223 private EPUserAppCatalogRoles tupleToEPUserAppCatalogRoles(Tuple tuple) {
224 return new EPUserAppCatalogRoles((Long) tuple.get("reqId"), (Long) tuple.get("requestedRoleId"),
225 (String) tuple.get("roleName"), (String) tuple.get("requestStatus"), (Long) tuple.get("appId"));
228 private boolean postUserRolesToMylogins(AppWithRolesForUser userAppRolesData,
229 ApplicationsRestClientService applicationsRestClientService, Long appId, Long userId)
230 throws JsonProcessingException, HTTPException {
231 boolean result = false;
232 ObjectMapper mapper = new ObjectMapper();
233 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
234 String userRolesAsString = mapper.writeValueAsString(userAppRolesData);
235 logger.error(EELFLoggerDelegate.errorLogger,
236 "Should not be reached here, as the endpoint is not defined yet from the Mylogins");
237 applicationsRestClientService.post(AppWithRolesForUser.class, appId, userRolesAsString,
238 String.format("/user/%s/myLoginroles", userId));
242 public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser newAppRolesForUser, FnUser user) {
243 FieldsValidator fieldsValidator = new FieldsValidator();
244 List<FnRole> appRole;
246 logger.error(EELFLoggerDelegate.errorLogger,
247 "Should not be reached here, still the endpoint is yet to be defined");
248 boolean result = postUserRolesToMylogins(newAppRolesForUser, applicationsRestClientService,
249 newAppRolesForUser.getAppId(), user.getId());
250 logger.debug(EELFLoggerDelegate.debugLogger, "putUserAppRolesRequest: result {}", result);
251 FnApp app = fnAppService.getById(newAppRolesForUser.getAppId());
252 EpUserRolesRequest epUserRolesRequest = new EpUserRolesRequest();
253 epUserRolesRequest.setCreatedDate(LocalDateTime.now());
254 epUserRolesRequest.setUpdatedDate(LocalDateTime.now());
255 epUserRolesRequest.setUserId(user);
256 epUserRolesRequest.setAppId(app);
257 epUserRolesRequest.setRequestStatus("P");
258 List<RoleInAppForUser> appRoleIdList = newAppRolesForUser.getAppRoles();
259 Set<EpUserRolesRequestDet> appRoleDetails = new LinkedHashSet<>();
260 epUserRolesRequestService.saveOne(epUserRolesRequest);
261 for (RoleInAppForUser userAppRoles : appRoleIdList) {
262 Boolean isAppliedVal = userAppRoles.getIsApplied();
264 appRole = fnRoleService
265 .retrieveAppRoleByAppRoleIdAndByAppId(newAppRolesForUser.getAppId(),
266 userAppRoles.getRoleId());
267 if (!appRole.isEmpty()) {
268 EpUserRolesRequestDet epAppRoleDetail = new EpUserRolesRequestDet();
269 epAppRoleDetail.setRequestedRoleId(appRole.get(0));
270 epAppRoleDetail.setRequestType("P");
271 epAppRoleDetail.setReqId(epUserRolesRequest);
272 epUserRolesRequestDetService.saveOne(epAppRoleDetail);
276 epUserRolesRequest.setEpRequestIdDetail(appRoleDetails);
277 fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_OK);
279 } catch (Exception e) {
280 logger.error(EELFLoggerDelegate.errorLogger, "putUserAppRolesRequest failed", e);
281 fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
283 return fieldsValidator;
286 public List<FnRole> importRolesFromRemoteApplication(Long appId) throws HTTPException {
287 FnRole[] appRolesFull = applicationsRestClientService.get(FnRole[].class, appId, "/rolesFull");
288 List<FnRole> rolesList = Arrays.asList(appRolesFull);
289 for (FnRole externalAppRole : rolesList) {
291 // Try to find an existing extern role for the app in the local
292 // onap DB. If so, then use its id to update the existing external
293 // application role record.
294 Long externAppId = externalAppRole.getId();
295 FnRole existingAppRole = fnRoleService.getRole(appId, externAppId);
296 if (existingAppRole != null) {
297 logger.debug(EELFLoggerDelegate.debugLogger,
299 "ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.",
300 appId, externAppId));
307 public List<UserApplicationRoles> getUsersFromAppEndpoint(Long appId) throws HTTPException {
308 ArrayList<UserApplicationRoles> userApplicationRoles = new ArrayList<>();
310 FnApp app = fnAppService.getById(appId);
311 //If local or centralized application
312 if (PortalConstants.PORTAL_APP_ID.equals(appId) || app.getAuthCentral()) {
313 List<FnUser> userList = fnUserService.getActiveUsers();
314 for (FnUser user : userList) {
315 UserApplicationRoles userWithAppRoles = convertToUserApplicationRoles(appId, user, app);
316 if (userWithAppRoles.getRoles() != null && userWithAppRoles.getRoles().size() > 0) {
317 userApplicationRoles.add(userWithAppRoles);
324 RemoteUserWithRoles[] remoteUsers;
325 String remoteUsersString = applicationsRestClientService.getIncomingJsonString(appId, "/users");
327 remoteUsers = doGetUsers(remoteUsersString);
329 userApplicationRoles = new ArrayList<>();
330 for (RemoteUserWithRoles remoteUser : remoteUsers) {
331 UserApplicationRoles userWithRemoteAppRoles = convertToUserApplicationRoles(appId,
333 if (userWithRemoteAppRoles.getRoles() != null
334 && userWithRemoteAppRoles.getRoles().size() > 0) {
335 userApplicationRoles.add(userWithRemoteAppRoles);
337 logger.debug(EELFLoggerDelegate.debugLogger,
338 "User " + userWithRemoteAppRoles.getOrgUserId()
339 + " doesn't have any roles assigned to any app.");
344 return userApplicationRoles;
347 private UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) {
348 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
349 userWithRemoteAppRoles.setAppId(appId);
350 userWithRemoteAppRoles.setOrgUserId(remoteUser.getOrgUserId());
351 userWithRemoteAppRoles.setFirstName(remoteUser.getFirstName());
352 userWithRemoteAppRoles.setLastName(remoteUser.getLastName());
353 userWithRemoteAppRoles.setRoles(remoteUser.getRoles());
354 return userWithRemoteAppRoles;
357 private RemoteUserWithRoles[] doGetUsers(String remoteUsersString) {
359 ObjectMapper mapper = new ObjectMapper();
361 return mapper.readValue(remoteUsersString, RemoteUserWithRoles[].class);
362 } catch (IOException e) {
363 logger.error(EELFLoggerDelegate.errorLogger,
364 "doGetUsers : Failed : Unexpected property in incoming JSON",
366 logger.error(EELFLoggerDelegate.errorLogger,
367 "doGetUsers : Incoming JSON that caused it --> " + remoteUsersString);
370 return new RemoteUserWithRoles[0];
373 private UserApplicationRoles convertToUserApplicationRoles(Long appId, FnUser user, FnApp app) {
374 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
375 userWithRemoteAppRoles.setAppId(appId);
376 userWithRemoteAppRoles.setOrgUserId(user.getOrgUserId());
377 userWithRemoteAppRoles.setFirstName(user.getFirstName());
378 userWithRemoteAppRoles.setLastName(user.getLastName());
379 userWithRemoteAppRoles.setRoles(convertToRemoteRoleList(user, app));
380 return userWithRemoteAppRoles;
383 private List<RemoteRole> convertToRemoteRoleList(FnUser user, FnApp app) {
384 List<RemoteRole> roleList = new ArrayList<>();
385 SortedSet<FnRole> roleSet = user.getAppEPRoles(app);
386 for (FnRole role : roleSet) {
387 logger.debug(EELFLoggerDelegate.debugLogger,
388 "In convertToRemoteRoleList() - for user {}, found Name {}", user.getOrgUserId(),
390 RemoteRole rRole = new RemoteRole();
391 rRole.setId(role.getId());
392 rRole.setName(role.getRoleName());
396 //Get the active roles of user for that application using query
397 List<FnRole> userEpRoleList = fnRoleService.getUserRoleOnUserIdAndAppId(user.getId(), app.getId());
399 for (FnRole remoteUserRoleList : userEpRoleList) {
401 RemoteRole remoteRoleListId = roleList.stream()
402 .filter(x -> remoteUserRoleList.getId().equals(x.getId()))
403 .findAny().orElse(null);
404 if (remoteRoleListId == null) {
405 logger.debug(EELFLoggerDelegate.debugLogger,
406 "Adding the role to the rolelist () - for user {}, found Name {}",
409 remoteUserRoleList.getRoleName());
410 RemoteRole role = new RemoteRole();
411 role.setId(remoteUserRoleList.getId());
412 role.setName(remoteUserRoleList.getRoleName());
419 logger.debug(EELFLoggerDelegate.debugLogger,
420 "rolelist size of the USER() - for user {}, found RoleListSize {}", user.getOrgUserId(),
425 public List getRoleFunctionsOfUserforAlltheApplications(Long userId) {
426 List<Tuple> tuples = entityManager
427 .createQuery(GET_ROLE_FUNCTIONS_OF_USERFOR_ALLTHE_APPLICATIONS, Tuple.class)
428 .setParameter("userid", userId)
430 return Optional.of(tuples.stream().map(tuple -> tuple.get("functionCd")).collect(Collectors.toList()))
431 .orElse(new ArrayList<>());
434 public List<FnUserRole> retrieveByAppIdAndUserId(final Long appId, final String userId) {
435 return Optional.of(fnUserRoleDao.retrieveByAppIdAndUserId(appId, userId)).orElse(new ArrayList<>());
438 public String updateRemoteUserProfile(String orgUserId, long appId) {
439 ObjectMapper mapper = new ObjectMapper();
440 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
441 FnUser client = fnUserService.loadUserByUsername(orgUserId);
442 FnUser newUser = new FnUser();
443 newUser.setActiveYn(client.getActiveYn());
444 newUser.setFirstName(client.getFirstName());
445 newUser.setLastName(client.getLastName());
446 newUser.setLoginId(client.getLoginId());
447 newUser.setLoginPwd(client.getLoginPwd());
448 newUser.setMiddleName(client.getMiddleName());
449 newUser.setEmail(client.getEmail());
450 newUser.setOrgUserId(client.getLoginId());
452 String userAsString = mapper.writeValueAsString(newUser);
453 List<FnApp> appList = fnAppService.getUserRemoteApps(client.getId().toString());
454 // applicationsRestClientService.post(EPUser.class, appId,
455 // userAsString, String.format("/user", orgUserId));
456 for (FnApp eachApp : appList) {
458 applicationsRestClientService.post(FnUser.class, eachApp.getId(), userAsString,
459 String.format("/user/%s", orgUserId));
460 } catch (Exception e) {
461 logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId()
462 + " in remote app. appId = " + eachApp.getId());
465 } catch (Exception e) {
466 logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
472 public void deleteById(final Long id) {
473 fnUserRoleDao.deleteById(id);
476 public List<RoleInAppForUser> constructRolesInAppForUserGet(List<Role> appRoles, FnRole[] userAppRoles,
477 Boolean extRequestValue) {
478 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<>();
480 Set<Long> userAppRolesMap = new HashSet<>();
481 if (userAppRoles != null) {
482 for (FnRole ecompRole : userAppRoles) {
483 userAppRolesMap.add(ecompRole.getAppId());
485 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - userAppRolesMap = {}",
489 logger.error(EELFLoggerDelegate.errorLogger,
490 "constructRolesInAppForUserGet has received userAppRoles list empty.");
493 if (appRoles != null) {
494 for (Role ecompRole : appRoles) {
495 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - appRoles not null = {}",
498 if (ecompRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && !extRequestValue) {
501 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getRoleName());
502 roleForUser.setIsApplied(userAppRolesMap.contains(ecompRole.getId()));
503 rolesInAppForUser.add(roleForUser);
504 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - rolesInAppForUser = {}",
509 logger.error(EELFLoggerDelegate.errorLogger,
510 "constructRolesInAppForUser has received appRoles list empty.");
512 return rolesInAppForUser;
515 public List<RoleInAppForUser> constructRolesInAppForUserGet(EcompRole[] appRoles, EcompRole[] userAppRoles) {
516 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<>();
518 Set<Long> userAppRolesMap = new HashSet<>();
519 if (userAppRoles != null) {
520 for (EcompRole ecompRole : userAppRoles) {
521 userAppRolesMap.add(ecompRole.getId());
524 logger.error(EELFLoggerDelegate.errorLogger,
525 "constructRolesInAppForUserGet has received userAppRoles list empty");
528 if (appRoles != null) {
529 for (EcompRole ecompRole : appRoles) {
530 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
531 roleForUser.setIsApplied(userAppRolesMap.contains(ecompRole.getId()));
532 rolesInAppForUser.add(roleForUser);
535 logger.error(EELFLoggerDelegate.errorLogger, "constructRolesInAppForUser has received appRoles list empty");
537 return rolesInAppForUser;