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.HashMap;
51 import java.util.LinkedHashSet;
52 import java.util.List;
54 import java.util.Optional;
56 import java.util.SortedSet;
57 import java.util.stream.Collectors;
58 import javax.persistence.EntityManager;
59 import javax.persistence.Tuple;
60 import javax.servlet.http.HttpServletResponse;
61 import org.apache.cxf.transport.http.HTTPException;
62 import org.onap.portal.dao.fn.FnUserRoleDao;
63 import org.onap.portal.domain.db.ep.EpUserRolesRequest;
64 import org.onap.portal.domain.db.ep.EpUserRolesRequestDet;
65 import org.onap.portal.domain.db.fn.FnApp;
66 import org.onap.portal.domain.db.fn.FnRole;
67 import org.onap.portal.domain.db.fn.FnUser;
68 import org.onap.portal.domain.db.fn.FnUserRole;
69 import org.onap.portal.domain.dto.ecomp.EPUserAppCatalogRoles;
70 import org.onap.portal.domain.dto.ecomp.ExternalSystemAccess;
71 import org.onap.portal.domain.dto.transport.AppWithRolesForUser;
72 import org.onap.portal.domain.dto.transport.FieldsValidator;
73 import org.onap.portal.domain.dto.transport.RemoteRole;
74 import org.onap.portal.domain.dto.transport.RemoteUserWithRoles;
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.EpUserRolesRequestDetService;
79 import org.onap.portal.service.ep.EpUserRolesRequestService;
80 import org.onap.portal.utils.EPCommonSystemProperties;
81 import org.onap.portal.utils.PortalConstants;
82 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
83 import org.onap.portalsdk.core.util.SystemProperties;
84 import org.springframework.beans.factory.annotation.Autowired;
85 import org.springframework.stereotype.Service;
86 import org.springframework.transaction.annotation.Transactional;
90 public class FnUserRoleService {
92 private static final String USER_APP_CATALOG_ROLES =
94 + " A.reqId as reqId,\n"
95 + " B.requestedRoleId.roleId as requestedRoleId,\n"
96 + " A.requestStatus as requestStatus,\n"
97 + " A.appId.appId as appId,\n"
104 + " roleId = B.requestedRoleId.roleId\n"
107 + " EpUserRolesRequest A\n"
108 + " left join EpUserRolesRequestDet B on A.reqId = B.reqId.reqId\n"
110 + " A.userId.userId = :userid\n"
111 + " and A.appId IN (\n"
117 + " appName = :appName\n"
119 + " and A.requestStatus = 'P'\n";
121 private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FnUserRoleService.class);
122 private final FnUserRoleDao fnUserRoleDao;
123 private final FnAppService fnAppService;
124 private final FnRoleService fnRoleService;
125 private final FnUserService fnUserService;
126 private final EpUserRolesRequestService epUserRolesRequestService;
127 private final EpUserRolesRequestDetService epUserRolesRequestDetService;
128 private final EntityManager entityManager;
129 private final ApplicationsRestClientService applicationsRestClientService;
132 public FnUserRoleService(FnUserRoleDao fnUserRoleDao, FnAppService fnAppService,
133 FnRoleService fnRoleService,
134 FnUserService fnUserService,
135 EpUserRolesRequestService epUserRolesRequestService,
136 EpUserRolesRequestDetService epUserRolesRequestDetService,
137 EntityManager entityManager,
138 ApplicationsRestClientService applicationsRestClientService) {
139 this.fnUserRoleDao = fnUserRoleDao;
140 this.fnAppService = fnAppService;
141 this.fnRoleService = fnRoleService;
142 this.fnUserService = fnUserService;
143 this.epUserRolesRequestService = epUserRolesRequestService;
144 this.epUserRolesRequestDetService = epUserRolesRequestDetService;
145 this.entityManager = entityManager;
146 this.applicationsRestClientService = applicationsRestClientService;
149 public List<FnUserRole> getAdminUserRoles(final Long userId, final Long roleId, final Long appId) {
150 return fnUserRoleDao.getAdminUserRoles(userId, roleId, appId).orElse(new ArrayList<>());
153 public boolean isSuperAdmin(final String orgUserId, final Long roleId, final Long appId) {
154 List<FnUserRole> roles = getUserRolesForRoleIdAndAppId(roleId, appId).stream()
155 .filter(role -> role.getUserId().getOrgUserId().equals(orgUserId)).collect(Collectors.toList());
156 return !roles.isEmpty();
159 private List<FnUserRole> getUserRolesForRoleIdAndAppId(final Long roleId, final Long appId) {
160 return Optional.of(fnUserRoleDao.getUserRolesForRoleIdAndAppId(roleId, appId)).orElse(new ArrayList<>());
163 public FnUserRole saveOne(final FnUserRole fnUserRole) {
164 return fnUserRoleDao.save(fnUserRole);
167 public ExternalSystemAccess getExternalRequestAccess() {
168 ExternalSystemAccess res = null;
170 res = new ExternalSystemAccess(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE,
171 Boolean.parseBoolean(
172 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE)));
173 } catch (Exception e) {
174 logger.error(EELFLoggerDelegate.errorLogger, "getExternalRequestAccess failed" + e.getMessage());
179 public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(FnUser userid, String appName) {
180 List<Tuple> tuples = entityManager.createQuery(USER_APP_CATALOG_ROLES, Tuple.class)
181 .setParameter("userid", userid.getUserId())
182 .setParameter("appName", appName)
184 return tuples.stream().map(this::tupleToEPUserAppCatalogRoles).collect(Collectors.toList());
187 private EPUserAppCatalogRoles tupleToEPUserAppCatalogRoles(Tuple tuple) {
188 return new EPUserAppCatalogRoles((Long) tuple.get("reqId"), (Long) tuple.get("requestedRoleId"),
189 (String) tuple.get("roleName"), (String) tuple.get("requestStatus"), (Long) tuple.get("appId"));
192 private boolean postUserRolesToMylogins(AppWithRolesForUser userAppRolesData,
193 ApplicationsRestClientService applicationsRestClientService, Long appId, Long userId)
194 throws JsonProcessingException, HTTPException {
195 boolean result = false;
196 ObjectMapper mapper = new ObjectMapper();
197 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
198 String userRolesAsString = mapper.writeValueAsString(userAppRolesData);
199 logger.error(EELFLoggerDelegate.errorLogger,
200 "Should not be reached here, as the endpoint is not defined yet from the Mylogins");
201 applicationsRestClientService.post(AppWithRolesForUser.class, appId, userRolesAsString,
202 String.format("/user/%s/myLoginroles", userId));
206 public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser newAppRolesForUser, FnUser user) {
207 FieldsValidator fieldsValidator = new FieldsValidator();
208 List<FnRole> appRole;
210 logger.error(EELFLoggerDelegate.errorLogger,
211 "Should not be reached here, still the endpoint is yet to be defined");
212 boolean result = postUserRolesToMylogins(newAppRolesForUser, applicationsRestClientService,
213 newAppRolesForUser.getAppId(), user.getId());
214 logger.debug(EELFLoggerDelegate.debugLogger, "putUserAppRolesRequest: result {}", result);
215 FnApp app = fnAppService.getById(newAppRolesForUser.getAppId());
216 EpUserRolesRequest epUserRolesRequest = new EpUserRolesRequest();
217 epUserRolesRequest.setCreatedDate(LocalDateTime.now());
218 epUserRolesRequest.setUpdatedDate(LocalDateTime.now());
219 epUserRolesRequest.setUserId(user);
220 epUserRolesRequest.setAppId(app);
221 epUserRolesRequest.setRequestStatus("P");
222 List<RoleInAppForUser> appRoleIdList = newAppRolesForUser.getAppRoles();
223 Set<EpUserRolesRequestDet> appRoleDetails = new LinkedHashSet<>();
224 epUserRolesRequestService.saveOne(epUserRolesRequest);
225 for (RoleInAppForUser userAppRoles : appRoleIdList) {
226 Boolean isAppliedVal = userAppRoles.getIsApplied();
228 appRole = fnRoleService
229 .retrieveAppRoleByAppRoleIdAndByAppId(newAppRolesForUser.getAppId(),
230 userAppRoles.getRoleId());
231 if (!appRole.isEmpty()) {
232 EpUserRolesRequestDet epAppRoleDetail = new EpUserRolesRequestDet();
233 epAppRoleDetail.setRequestedRoleId(appRole.get(0));
234 epAppRoleDetail.setRequestType("P");
235 epAppRoleDetail.setReqId(epUserRolesRequest);
236 epUserRolesRequestDetService.saveOne(epAppRoleDetail);
240 epUserRolesRequest.setEpRequestIdDetail(appRoleDetails);
241 fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_OK);
243 } catch (Exception e) {
244 logger.error(EELFLoggerDelegate.errorLogger, "putUserAppRolesRequest failed", e);
245 fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
247 return fieldsValidator;
250 public List<FnRole> importRolesFromRemoteApplication(Long appId) throws HTTPException {
251 FnRole[] appRolesFull = applicationsRestClientService.get(FnRole[].class, appId, "/rolesFull");
252 List<FnRole> rolesList = Arrays.asList(appRolesFull);
253 for (FnRole externalAppRole : rolesList) {
255 // Try to find an existing extern role for the app in the local
256 // onap DB. If so, then use its id to update the existing external
257 // application role record.
258 Long externAppId = externalAppRole.getId();
259 FnRole existingAppRole = fnRoleService.getRole(appId, externAppId);
260 if (existingAppRole != null) {
261 logger.debug(EELFLoggerDelegate.debugLogger,
263 "ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.",
264 appId, externAppId));
267 // persistExternalRoleInEcompDb(externalAppRole, appId,
274 public List<UserApplicationRoles> getUsersFromAppEndpoint(Long appId) throws HTTPException {
275 ArrayList<UserApplicationRoles> userApplicationRoles = new ArrayList<>();
277 FnApp app = fnAppService.getById(appId);
278 //If local or centralized application
279 if (PortalConstants.PORTAL_APP_ID.equals(appId) || app.getAuthCentral()) {
280 List<FnUser> userList = fnUserService.getActiveUsers();
281 for (FnUser user : userList) {
282 UserApplicationRoles userWithAppRoles = convertToUserApplicationRoles(appId, user, app);
283 if (userWithAppRoles.getRoles() != null && userWithAppRoles.getRoles().size() > 0) {
284 userApplicationRoles.add(userWithAppRoles);
291 RemoteUserWithRoles[] remoteUsers = null;
292 String remoteUsersString = applicationsRestClientService.getIncomingJsonString(appId, "/users");
294 remoteUsers = doGetUsers(isAppUpgradeVersion(app), remoteUsersString);
296 userApplicationRoles = new ArrayList<>();
297 for (RemoteUserWithRoles remoteUser : remoteUsers) {
298 UserApplicationRoles userWithRemoteAppRoles = convertToUserApplicationRoles(appId,
300 if (userWithRemoteAppRoles.getRoles() != null
301 && userWithRemoteAppRoles.getRoles().size() > 0) {
302 userApplicationRoles.add(userWithRemoteAppRoles);
304 logger.debug(EELFLoggerDelegate.debugLogger,
305 "User " + userWithRemoteAppRoles.getOrgUserId()
306 + " doesn't have any roles assigned to any app.");
311 return userApplicationRoles;
314 private UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) {
315 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
316 userWithRemoteAppRoles.setAppId(appId);
317 userWithRemoteAppRoles.setOrgUserId(remoteUser.getOrgUserId());
318 userWithRemoteAppRoles.setFirstName(remoteUser.getFirstName());
319 userWithRemoteAppRoles.setLastName(remoteUser.getLastName());
320 userWithRemoteAppRoles.setRoles(remoteUser.getRoles());
321 return userWithRemoteAppRoles;
324 private boolean isAppUpgradeVersion(FnApp app) {
328 private RemoteUserWithRoles[] doGetUsers(boolean postOpenSource, String remoteUsersString) {
330 ObjectMapper mapper = new ObjectMapper();
332 return mapper.readValue(remoteUsersString, RemoteUserWithRoles[].class);
333 } catch (IOException e) {
334 logger.error(EELFLoggerDelegate.errorLogger,
335 "doGetUsers : Failed : Unexpected property in incoming JSON",
337 logger.error(EELFLoggerDelegate.errorLogger,
338 "doGetUsers : Incoming JSON that caused it --> " + remoteUsersString);
341 return new RemoteUserWithRoles[0];
344 private UserApplicationRoles convertToUserApplicationRoles(Long appId, FnUser user, FnApp app) {
345 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
346 userWithRemoteAppRoles.setAppId(appId);
347 userWithRemoteAppRoles.setOrgUserId(user.getOrgUserId());
348 userWithRemoteAppRoles.setFirstName(user.getFirstName());
349 userWithRemoteAppRoles.setLastName(user.getLastName());
350 userWithRemoteAppRoles.setRoles(convertToRemoteRoleList(user, app));
351 return userWithRemoteAppRoles;
354 private List<RemoteRole> convertToRemoteRoleList(FnUser user, FnApp app) {
355 List<RemoteRole> roleList = new ArrayList<>();
356 SortedSet<FnRole> roleSet = user.getAppEPRoles(app);
357 for (FnRole role : roleSet) {
358 logger.debug(EELFLoggerDelegate.debugLogger, "In convertToRemoteRoleList() - for user {}, found Name {}", user.getOrgUserId(), role.getRoleName());
359 RemoteRole rRole = new RemoteRole();
360 rRole.setId(role.getId());
361 rRole.setName(role.getRoleName());
365 //Get the active roles of user for that application using query
366 List<FnRole> userEpRoleList = fnRoleService.getUserRoleOnUserIdAndAppId(user.getId(), app.getId());
368 for (FnRole remoteUserRoleList : userEpRoleList) {
370 RemoteRole remoteRoleListId = roleList.stream().filter(x -> remoteUserRoleList.getId().equals(x.getId()))
371 .findAny().orElse(null);
372 if (remoteRoleListId == null) {
373 logger.debug(EELFLoggerDelegate.debugLogger,
374 "Adding the role to the rolelist () - for user {}, found Name {}", user.getOrgUserId(),
376 remoteUserRoleList.getRoleName());
377 RemoteRole role = new RemoteRole();
378 role.setId(remoteUserRoleList.getId());
379 role.setName(remoteUserRoleList.getRoleName());
386 logger.debug(EELFLoggerDelegate.debugLogger, "rolelist size of the USER() - for user {}, found RoleListSize {}", user.getOrgUserId(), roleList.size());