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.Collection;
51 import java.util.HashMap;
52 import java.util.LinkedHashSet;
53 import java.util.List;
55 import java.util.Optional;
57 import java.util.SortedSet;
58 import java.util.stream.Collectors;
59 import javax.persistence.EntityManager;
60 import javax.persistence.Query;
61 import javax.persistence.Tuple;
62 import javax.servlet.http.HttpServletResponse;
63 import org.apache.commons.lang.StringUtils;
64 import org.apache.cxf.transport.http.HTTPException;
65 import org.hibernate.Session;
66 import org.hibernate.SessionFactory;
67 import org.hibernate.Transaction;
68 import org.onap.portal.dao.fn.FnUserRoleDao;
69 import org.onap.portal.domain.db.ep.EpUserRolesRequest;
70 import org.onap.portal.domain.db.ep.EpUserRolesRequestDet;
71 import org.onap.portal.domain.db.fn.FnApp;
72 import org.onap.portal.domain.db.fn.FnRole;
73 import org.onap.portal.domain.db.fn.FnUser;
74 import org.onap.portal.domain.db.fn.FnUserRole;
75 import org.onap.portal.domain.dto.ecomp.EPUserAppCatalogRoles;
76 import org.onap.portal.domain.dto.ecomp.ExternalSystemAccess;
77 import org.onap.portal.domain.dto.transport.AppWithRolesForUser;
78 import org.onap.portal.domain.dto.transport.ExternalAccessUserRoleDetail;
79 import org.onap.portal.domain.dto.transport.FieldsValidator;
80 import org.onap.portal.domain.dto.transport.RemoteRole;
81 import org.onap.portal.domain.dto.transport.RemoteUserWithRoles;
82 import org.onap.portal.domain.dto.transport.RoleInAppForUser;
83 import org.onap.portal.domain.dto.transport.UserApplicationRoles;
84 import org.onap.portal.exception.SyncUserRolesException;
85 import org.onap.portal.logging.format.EPAppMessagesEnum;
86 import org.onap.portal.logging.logic.EPLogUtil;
87 import org.onap.portal.service.ApplicationsRestClientService;
88 import org.onap.portal.service.ExternalAccessRolesService;
89 import org.onap.portal.service.ep.EpUserRolesRequestDetService;
90 import org.onap.portal.service.ep.EpUserRolesRequestService;
91 import org.onap.portal.utils.EPCommonSystemProperties;
92 import org.onap.portal.utils.EcompPortalUtils;
93 import org.onap.portal.utils.PortalConstants;
94 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
95 import org.onap.portalsdk.core.restful.domain.EcompRole;
96 import org.onap.portalsdk.core.util.SystemProperties;
97 import org.springframework.beans.factory.annotation.Autowired;
98 import org.springframework.stereotype.Service;
99 import org.springframework.transaction.annotation.Transactional;
100 import org.springframework.web.client.RestTemplate;
104 public class FnUserRoleService {
106 private static final String GET_ROLE_FUNCTIONS_OF_USERFOR_ALLTHE_APPLICATIONS =
108 + " distinct ep.function_cd functionCd\n"
110 + " fn_user_role fu,\n"
111 + " ep_app_role_function ep,\n"
112 + " ep_app_function ea\n"
114 + " fu.role_id = ep.role_id\n"
115 + " and fu.app_id = ep.app_id\n"
116 + " and fu.user_id = 'userId'\n"
117 + " and ea.function_cd = ep.function_cd\n"
123 + " fn_user_role ur,\n"
126 + " fu.user_id = 'userId'\n"
127 + " and fu.user_id = ur.user_id\n"
128 + " and ur.app_id = fa.app_id\n"
129 + " and fa.enabled = 'Y'\n"
132 private static final String USER_APP_CATALOG_ROLES =
134 + " A.reqId as reqId,\n"
135 + " B.requestedRoleId.roleId as requestedRoleId,\n"
136 + " A.requestStatus as requestStatus,\n"
137 + " A.appId.appId as appId,\n"
144 + " roleId = B.requestedRoleId.roleId\n"
147 + " EpUserRolesRequest A\n"
148 + " left join EpUserRolesRequestDet B on A.reqId = B.reqId.reqId\n"
150 + " A.userId.userId = :userid\n"
151 + " and A.appId IN (\n"
157 + " appName = :appName\n"
159 + " and A.requestStatus = 'P'\n";
161 private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FnUserRoleService.class);
163 private final FnUserRoleDao fnUserRoleDao;
164 private final FnAppService fnAppService;
165 private final FnRoleService fnRoleService;
166 private final FnUserService fnUserService;
167 private final EpUserRolesRequestService epUserRolesRequestService;
168 private final EpUserRolesRequestDetService epUserRolesRequestDetService;
169 private final EntityManager entityManager;
170 private final ApplicationsRestClientService applicationsRestClientService;
173 public FnUserRoleService(FnUserRoleDao
175 FnAppService fnAppService,
176 FnRoleService fnRoleService,
177 FnUserService fnUserService,
178 EpUserRolesRequestService epUserRolesRequestService,
179 EpUserRolesRequestDetService epUserRolesRequestDetService,
180 EntityManager entityManager,
181 ApplicationsRestClientService applicationsRestClientService) {
182 this.fnUserRoleDao = fnUserRoleDao;
183 this.fnAppService = fnAppService;
184 this.fnRoleService = fnRoleService;
185 this.fnUserService = fnUserService;
186 this.epUserRolesRequestService = epUserRolesRequestService;
187 this.epUserRolesRequestDetService = epUserRolesRequestDetService;
188 this.entityManager = entityManager;
189 this.applicationsRestClientService = applicationsRestClientService;
192 public List<FnUserRole> getAdminUserRoles(final Long userId, final Long roleId, final Long appId) {
193 return fnUserRoleDao.getAdminUserRoles(userId, roleId, appId).orElse(new ArrayList<>());
196 public boolean isSuperAdmin(final String orgUserId, final Long roleId, final Long appId) {
197 List<FnUserRole> roles = getUserRolesForRoleIdAndAppId(roleId, appId).stream()
198 .filter(role -> role.getUserId().getOrgUserId().equals(orgUserId)).collect(Collectors.toList());
199 return !roles.isEmpty();
202 private List<FnUserRole> getUserRolesForRoleIdAndAppId(final Long roleId, final Long appId) {
203 return Optional.of(fnUserRoleDao.getUserRolesForRoleIdAndAppId(roleId, appId)).orElse(new ArrayList<>());
206 public FnUserRole saveOne(final FnUserRole fnUserRole) {
207 return fnUserRoleDao.save(fnUserRole);
210 public ExternalSystemAccess getExternalRequestAccess() {
211 ExternalSystemAccess res = null;
213 res = new ExternalSystemAccess(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE,
214 Boolean.parseBoolean(
215 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE)));
216 } catch (Exception e) {
217 logger.error(EELFLoggerDelegate.errorLogger, "getExternalRequestAccess failed" + e.getMessage());
222 public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(FnUser userid, String appName) {
223 List<Tuple> tuples = entityManager.createQuery(USER_APP_CATALOG_ROLES, Tuple.class)
224 .setParameter("userid", userid.getUserId())
225 .setParameter("appName", appName)
227 return Optional.of(tuples.stream().map(this::tupleToEPUserAppCatalogRoles).collect(Collectors.toList()))
228 .orElse(new ArrayList<>());
231 private EPUserAppCatalogRoles tupleToEPUserAppCatalogRoles(Tuple tuple) {
232 return new EPUserAppCatalogRoles((Long) tuple.get("reqId"), (Long) tuple.get("requestedRoleId"),
233 (String) tuple.get("roleName"), (String) tuple.get("requestStatus"), (Long) tuple.get("appId"));
236 private boolean postUserRolesToMylogins(AppWithRolesForUser userAppRolesData,
237 ApplicationsRestClientService applicationsRestClientService, Long appId, Long userId)
238 throws JsonProcessingException, HTTPException {
239 boolean result = false;
240 ObjectMapper mapper = new ObjectMapper();
241 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
242 String userRolesAsString = mapper.writeValueAsString(userAppRolesData);
243 logger.error(EELFLoggerDelegate.errorLogger,
244 "Should not be reached here, as the endpoint is not defined yet from the Mylogins");
245 applicationsRestClientService.post(AppWithRolesForUser.class, appId, userRolesAsString,
246 String.format("/user/%s/myLoginroles", userId));
250 public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser newAppRolesForUser, FnUser user) {
251 FieldsValidator fieldsValidator = new FieldsValidator();
252 List<FnRole> appRole;
254 logger.error(EELFLoggerDelegate.errorLogger,
255 "Should not be reached here, still the endpoint is yet to be defined");
256 boolean result = postUserRolesToMylogins(newAppRolesForUser, applicationsRestClientService,
257 newAppRolesForUser.getAppId(), user.getId());
258 logger.debug(EELFLoggerDelegate.debugLogger, "putUserAppRolesRequest: result {}", result);
259 FnApp app = fnAppService.getById(newAppRolesForUser.getAppId());
260 EpUserRolesRequest epUserRolesRequest = new EpUserRolesRequest();
261 epUserRolesRequest.setCreatedDate(LocalDateTime.now());
262 epUserRolesRequest.setUpdatedDate(LocalDateTime.now());
263 epUserRolesRequest.setUserId(user);
264 epUserRolesRequest.setAppId(app);
265 epUserRolesRequest.setRequestStatus("P");
266 List<RoleInAppForUser> appRoleIdList = newAppRolesForUser.getAppRoles();
267 Set<EpUserRolesRequestDet> appRoleDetails = new LinkedHashSet<>();
268 epUserRolesRequestService.saveOne(epUserRolesRequest);
269 for (RoleInAppForUser userAppRoles : appRoleIdList) {
270 Boolean isAppliedVal = userAppRoles.getIsApplied();
272 appRole = fnRoleService
273 .retrieveAppRoleByAppRoleIdAndByAppId(newAppRolesForUser.getAppId(),
274 userAppRoles.getRoleId());
275 if (!appRole.isEmpty()) {
276 EpUserRolesRequestDet epAppRoleDetail = new EpUserRolesRequestDet();
277 epAppRoleDetail.setRequestedRoleId(appRole.get(0));
278 epAppRoleDetail.setRequestType("P");
279 epAppRoleDetail.setReqId(epUserRolesRequest);
280 epUserRolesRequestDetService.saveOne(epAppRoleDetail);
284 epUserRolesRequest.setEpRequestIdDetail(appRoleDetails);
285 fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_OK);
287 } catch (Exception e) {
288 logger.error(EELFLoggerDelegate.errorLogger, "putUserAppRolesRequest failed", e);
289 fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
291 return fieldsValidator;
294 public List<FnRole> importRolesFromRemoteApplication(Long appId) throws HTTPException {
295 FnRole[] appRolesFull = applicationsRestClientService.get(FnRole[].class, appId, "/rolesFull");
296 List<FnRole> rolesList = Arrays.asList(appRolesFull);
297 for (FnRole externalAppRole : rolesList) {
299 // Try to find an existing extern role for the app in the local
300 // onap DB. If so, then use its id to update the existing external
301 // application role record.
302 Long externAppId = externalAppRole.getId();
303 FnRole existingAppRole = fnRoleService.getRole(appId, externAppId);
304 if (existingAppRole != null) {
305 logger.debug(EELFLoggerDelegate.debugLogger,
307 "ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.",
308 appId, externAppId));
315 public List<UserApplicationRoles> getUsersFromAppEndpoint(Long appId) throws HTTPException {
316 ArrayList<UserApplicationRoles> userApplicationRoles = new ArrayList<>();
318 FnApp app = fnAppService.getById(appId);
319 //If local or centralized application
320 if (PortalConstants.PORTAL_APP_ID.equals(appId) || app.getAuthCentral()) {
321 List<FnUser> userList = fnUserService.getActiveUsers();
322 for (FnUser user : userList) {
323 UserApplicationRoles userWithAppRoles = convertToUserApplicationRoles(appId, user, app);
324 if (userWithAppRoles.getRoles() != null && userWithAppRoles.getRoles().size() > 0) {
325 userApplicationRoles.add(userWithAppRoles);
332 RemoteUserWithRoles[] remoteUsers;
333 String remoteUsersString = applicationsRestClientService.getIncomingJsonString(appId, "/users");
335 remoteUsers = doGetUsers(remoteUsersString);
337 userApplicationRoles = new ArrayList<>();
338 for (RemoteUserWithRoles remoteUser : remoteUsers) {
339 UserApplicationRoles userWithRemoteAppRoles = convertToUserApplicationRoles(appId,
341 if (userWithRemoteAppRoles.getRoles() != null
342 && userWithRemoteAppRoles.getRoles().size() > 0) {
343 userApplicationRoles.add(userWithRemoteAppRoles);
345 logger.debug(EELFLoggerDelegate.debugLogger,
346 "User " + userWithRemoteAppRoles.getOrgUserId()
347 + " doesn't have any roles assigned to any app.");
352 return userApplicationRoles;
355 private UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) {
356 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
357 userWithRemoteAppRoles.setAppId(appId);
358 userWithRemoteAppRoles.setOrgUserId(remoteUser.getOrgUserId());
359 userWithRemoteAppRoles.setFirstName(remoteUser.getFirstName());
360 userWithRemoteAppRoles.setLastName(remoteUser.getLastName());
361 userWithRemoteAppRoles.setRoles(remoteUser.getRoles());
362 return userWithRemoteAppRoles;
365 private RemoteUserWithRoles[] doGetUsers(String remoteUsersString) {
367 ObjectMapper mapper = new ObjectMapper();
369 return mapper.readValue(remoteUsersString, RemoteUserWithRoles[].class);
370 } catch (IOException e) {
371 logger.error(EELFLoggerDelegate.errorLogger,
372 "doGetUsers : Failed : Unexpected property in incoming JSON",
374 logger.error(EELFLoggerDelegate.errorLogger,
375 "doGetUsers : Incoming JSON that caused it --> " + remoteUsersString);
378 return new RemoteUserWithRoles[0];
381 private UserApplicationRoles convertToUserApplicationRoles(Long appId, FnUser user, FnApp app) {
382 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
383 userWithRemoteAppRoles.setAppId(appId);
384 userWithRemoteAppRoles.setOrgUserId(user.getOrgUserId());
385 userWithRemoteAppRoles.setFirstName(user.getFirstName());
386 userWithRemoteAppRoles.setLastName(user.getLastName());
387 userWithRemoteAppRoles.setRoles(convertToRemoteRoleList(user, app));
388 return userWithRemoteAppRoles;
391 private List<RemoteRole> convertToRemoteRoleList(FnUser user, FnApp app) {
392 List<RemoteRole> roleList = new ArrayList<>();
393 SortedSet<FnRole> roleSet = user.getAppEPRoles(app);
394 for (FnRole role : roleSet) {
395 logger.debug(EELFLoggerDelegate.debugLogger,
396 "In convertToRemoteRoleList() - for user {}, found Name {}", user.getOrgUserId(),
398 RemoteRole rRole = new RemoteRole();
399 rRole.setId(role.getId());
400 rRole.setName(role.getRoleName());
404 //Get the active roles of user for that application using query
405 List<FnRole> userEpRoleList = fnRoleService.getUserRoleOnUserIdAndAppId(user.getId(), app.getId());
407 for (FnRole remoteUserRoleList : userEpRoleList) {
409 RemoteRole remoteRoleListId = roleList.stream()
410 .filter(x -> remoteUserRoleList.getId().equals(x.getId()))
411 .findAny().orElse(null);
412 if (remoteRoleListId == null) {
413 logger.debug(EELFLoggerDelegate.debugLogger,
414 "Adding the role to the rolelist () - for user {}, found Name {}",
417 remoteUserRoleList.getRoleName());
418 RemoteRole role = new RemoteRole();
419 role.setId(remoteUserRoleList.getId());
420 role.setName(remoteUserRoleList.getRoleName());
427 logger.debug(EELFLoggerDelegate.debugLogger,
428 "rolelist size of the USER() - for user {}, found RoleListSize {}", user.getOrgUserId(),
433 public List getRoleFunctionsOfUserforAlltheApplications(Long userId) {
434 List<Tuple> tuples = entityManager
435 .createQuery(GET_ROLE_FUNCTIONS_OF_USERFOR_ALLTHE_APPLICATIONS, Tuple.class)
436 .setParameter("userid", userId)
438 return Optional.of(tuples.stream().map(tuple -> tuple.get("functionCd")).collect(Collectors.toList()))
439 .orElse(new ArrayList<>());
442 public List<FnUserRole> retrieveByAppIdAndUserId(final Long appId, final String userId) {
443 return Optional.of(fnUserRoleDao.retrieveByAppIdAndUserId(appId, userId)).orElse(new ArrayList<>());
446 public String updateRemoteUserProfile(String orgUserId, long appId) {
447 ObjectMapper mapper = new ObjectMapper();
448 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
449 FnUser client = fnUserService.loadUserByUsername(orgUserId);
450 FnUser newUser = new FnUser();
451 newUser.setActiveYn(client.getActiveYn());
452 newUser.setFirstName(client.getFirstName());
453 newUser.setLastName(client.getLastName());
454 newUser.setLoginId(client.getLoginId());
455 newUser.setLoginPwd(client.getLoginPwd());
456 newUser.setMiddleName(client.getMiddleName());
457 newUser.setEmail(client.getEmail());
458 newUser.setOrgUserId(client.getLoginId());
460 String userAsString = mapper.writeValueAsString(newUser);
461 List<FnApp> appList = fnAppService.getUserRemoteApps(client.getId().toString());
462 // applicationsRestClientService.post(EPUser.class, appId,
463 // userAsString, String.format("/user", orgUserId));
464 for (FnApp eachApp : appList) {
466 applicationsRestClientService.post(FnUser.class, eachApp.getId(), userAsString,
467 String.format("/user/%s", orgUserId));
468 } catch (Exception e) {
469 logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId()
470 + " in remote app. appId = " + eachApp.getId());
473 } catch (Exception e) {
474 logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
480 public void deleteById(final Long id) {
481 fnUserRoleDao.deleteById(id);