getAppRolesForUser() method up in UserRolesController
[portal.git] / portal-BE / src / main / java / org / onap / portal / service / ExternalAccessRolesService.java
1 /*
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ===================================================================
9  *
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
14  *
15  *             http://www.apache.org/licenses/LICENSE-2.0
16  *
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.
22  *
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
27  *
28  *             https://creativecommons.org/licenses/by/4.0/
29  *
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.
35  *
36  * ============LICENSE_END============================================
37  *
38  *
39  */
40
41 package org.onap.portal.service;
42
43 import java.util.ArrayList;
44 import java.util.HashMap;
45 import java.util.List;
46 import java.util.Map;
47 import java.util.Optional;
48 import java.util.SortedSet;
49 import java.util.TreeSet;
50 import java.util.stream.Collectors;
51 import javax.persistence.EntityManager;
52 import javax.persistence.Tuple;
53 import org.onap.portal.domain.db.ep.EpAppFunction;
54 import org.onap.portal.domain.db.fn.FnApp;
55 import org.onap.portal.domain.db.fn.FnFunction;
56 import org.onap.portal.domain.db.fn.FnRole;
57 import org.onap.portal.domain.db.fn.FnRoleFunction;
58 import org.onap.portal.domain.dto.transport.CentralV2Role;
59 import org.onap.portal.domain.dto.transport.GlobalRoleWithApplicationRoleFunction;
60 import org.onap.portal.domain.dto.transport.Role;
61 import org.onap.portal.exception.RoleFunctionException;
62 import org.onap.portal.logging.logic.EPLogUtil;
63 import org.onap.portal.service.ep.EpAppFunctionService;
64 import org.onap.portal.service.fn.FnAppService;
65 import org.onap.portal.service.fn.FnRoleService;
66 import org.onap.portal.utils.EPCommonSystemProperties;
67 import org.onap.portal.utils.EPUserUtils;
68 import org.onap.portal.utils.EcompPortalUtils;
69 import org.onap.portal.utils.PortalConstants;
70 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
71 import org.onap.portalsdk.core.util.SystemProperties;
72 import org.springframework.beans.factory.annotation.Autowired;
73 import org.springframework.http.HttpEntity;
74 import org.springframework.http.HttpMethod;
75 import org.springframework.http.ResponseEntity;
76 import org.springframework.stereotype.Service;
77 import org.springframework.web.client.RestTemplate;
78
79 @Service
80 public class ExternalAccessRolesService {
81
82   private static final String APP_ROLE_NAME_PARAM = "appRoleName";
83   private static final String GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM = "getRoletoUpdateInExternalAuthSystem";
84   private static final String GET_PORTAL_APP_ROLES_QUERY = "getPortalAppRoles";
85   private static final String GET_ROLE_FUNCTION_QUERY = "getRoleFunction";
86   private static final String FUNCTION_CODE_PARAMS = "functionCode";
87   private static final String AND_FUNCTION_CD_EQUALS = " and function_cd = '";
88   private static final String OWNER = ".owner";
89   private static final String ADMIN = ".admin";
90   private static final String ACCOUNT_ADMINISTRATOR = ".Account_Administrator";
91   private static final String FUNCTION_PIPE = "|";
92   private static final String EXTERNAL_AUTH_PERMS = "perms";
93   private static final String EXTERNAL_AUTH_ROLE_DESCRIPTION = "description";
94   private static final String IS_EMPTY_JSON_STRING = "{}";
95   private static final String CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE = "Connecting to External Auth system";
96   private static final String APP_ID = "appId";
97   private static final String ROLE_NAME = "name";
98   private static final String APP_ID_EQUALS = " app_id = ";
99
100   private static final String GET_GLOBAL_ROLE_WITH_APPLICATION_ROLE_FUNCTIONS = "select"
101       + "  distinct d.roleId as roleId,"
102       + "  d.roleName as roleName,"
103       + "  d.activeYn as active,"
104       + "  d.priority as priority,"
105       + "  c.epAppFunction.functionCd as functionCd,"
106       + "  e.functionName as functionName,"
107       + "  c.epAppFunction.appId as appId,"
108       + "  c.roleAppId as roleAppId"
109       + " from"
110       + "  FnUserRole a,"
111       + "  FnApp b,"
112       + "  EpAppRoleFunction c,"
113       + "  FnRole d,"
114       + "  EpAppFunction e"
115       + " where"
116       + "  b.appId = c.appId.appId"
117       + "  and a.appId = c.roleAppId"
118       + "  and b.enabled = 'Y'"
119       + "  and c.fnRole.roleId = d.roleId"
120       + "  and d.activeYn = 'Y'"
121       + "  and e.functionCd = c.epAppFunction.functionCd"
122       + "  and c.appId.appId = :appId"
123       + "  and e.appId.appId = c.appId.appId";
124
125   private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesService.class);
126   private RestTemplate template = new RestTemplate();
127
128   private final FnRoleService fnRoleService;
129   private final FnAppService fnAppService;
130   private final EntityManager entityManager;
131   private final EpAppFunctionService epAppFunctionService;
132
133   @Autowired
134   public ExternalAccessRolesService(FnRoleService fnRoleService,
135       FnAppService fnAppService, EntityManager entityManager,
136       EpAppFunctionService epAppFunctionService) {
137     this.fnRoleService = fnRoleService;
138     this.fnAppService = fnAppService;
139     this.entityManager = entityManager;
140     this.epAppFunctionService = epAppFunctionService;
141   }
142
143   String getFunctionCodeType(String roleFuncItem) {
144     String type = null;
145     if ((roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))
146         || (!roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))) {
147       type = "menu";
148     } else if (checkIfCodeHasNoPipesAndHasTypeUrl(roleFuncItem) || checkIfCodeHasPipesAndHasTypeUrl(roleFuncItem)
149         || checkIfCodeHasNoPipesAndHasNoTypeUrl(roleFuncItem)) {
150       type = "url";
151     } else if (roleFuncItem.contains(FUNCTION_PIPE)
152         && (!roleFuncItem.contains("menu") || roleFuncItem.contains("url"))) {
153       type = EcompPortalUtils.getFunctionType(roleFuncItem);
154     }
155     return type;
156   }
157
158   private boolean checkIfCodeHasNoPipesAndHasTypeUrl(String roleFuncItem) {
159     return !roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
160   }
161
162   private boolean checkIfCodeHasPipesAndHasTypeUrl(String roleFuncItem) {
163     return roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
164   }
165
166   private boolean checkIfCodeHasNoPipesAndHasNoTypeUrl(String roleFuncItem) {
167     return !roleFuncItem.contains(FUNCTION_PIPE) && !roleFuncItem.contains("url");
168   }
169
170   List<FnRole> getPortalAppRoleInfo(Long roleId) {
171     return fnRoleService.retrieveAppRoleByRoleIdWhereAppIdIsNull(roleId);
172   }
173
174   ResponseEntity<String> getUserRolesFromExtAuthSystem(String name, HttpEntity<String> getUserRolesEntity) {
175     logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles");
176     ResponseEntity<String> getResponse = template
177         .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
178             + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class);
179     if (getResponse.getStatusCode().value() == 200) {
180       logger.debug(EELFLoggerDelegate.debugLogger,
181           "getAllUserRoleFromExtAuthSystem: Finished GET user roles from external system and received user roles {}",
182           getResponse.getBody());
183     } else {
184       logger.error(EELFLoggerDelegate.errorLogger,
185           "getAllUserRoleFromExtAuthSystem: Failed GET user roles from external system and received user roles {}",
186           getResponse.getBody());
187       EPLogUtil.logExternalAuthAccessAlarm(logger, getResponse.getStatusCode());
188     }
189     return getResponse;
190   }
191
192   Map<String, FnRole> getAppRoleNamesWithUnderscoreMap(FnApp app) {
193     final Map<String, FnRole> currentRolesInDB = new HashMap<>();
194     List<FnRole> getCurrentRoleList = null;
195     final Map<String, Long> appParams = new HashMap<>();
196     if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
197       getCurrentRoleList = fnRoleService.retrieveAppRolesWhereAppIdIsNull();
198     } else {
199       appParams.put("appId", app.getId());
200       getCurrentRoleList = fnRoleService.retrieveAppRolesByAppId(app.getId());
201     }
202     for (FnRole role : getCurrentRoleList) {
203       currentRolesInDB.put(role.getRoleName()
204           .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), role);
205     }
206     return currentRolesInDB;
207   }
208
209   List<CentralV2Role> createCentralRoleObject(List<FnApp> app, List<FnRole> roleInfo,
210       List<CentralV2Role> roleList) throws RoleFunctionException {
211     for (FnRole role : roleInfo) {
212       List<EpAppFunction> cenRoleFuncList = epAppFunctionService
213           .getAppRoleFunctionList(role.getId(), app.get(0).getId());
214       SortedSet<FnRoleFunction> roleFunctionSet = new TreeSet<>();
215       for (EpAppFunction roleFunc : cenRoleFuncList) {
216         String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getFunctionCd());
217         functionCode = EPUserUtils.decodeFunctionCode(functionCode);
218         String type = getFunctionCodeType(roleFunc.getFunctionCd());
219         String action = getFunctionCodeAction(roleFunc.getFunctionCd());
220         FnRoleFunction cenRoleFunc = new FnRoleFunction(role, FnFunction.builder().code(functionCode).name(roleFunc.getFunctionName()).type(type).action(action).build());
221       }
222       SortedSet<CentralV2Role> childRoles = new TreeSet<>();
223       SortedSet<CentralV2Role> parentRoles = new TreeSet<>();
224       CentralV2Role cenRole;
225       if (role.getAppRoleId() == null) {
226         cenRole = CentralV2Role.builder().id(role.getId()).created(role.getCreated())
227             .modified(role.getModified()).createdId(role.getCreatedId().getUserId())
228             .modifiedId(role.getModifiedId().getUserId()).rowNum(role.getRowNum()).name(role.getRoleName())
229             .active(role.getActiveYn()).priority(role.getPriority()).roleFunctions(roleFunctionSet)
230             .childRoles(childRoles).parentRoles(parentRoles).build();
231       } else {
232         cenRole = CentralV2Role.builder().id(role.getAppRoleId())
233             .created(role.getCreated()).modified(role.getModified()).createdId(role.getCreatedId().getUserId())
234             .modifiedId(role.getModifiedId().getUserId()).rowNum(role.getRowNum()).name(role.getRoleName())
235             .active(role.getActiveYn()).priority(role.getPriority()).roleFunctions(roleFunctionSet)
236             .childRoles(childRoles).parentRoles(parentRoles).build();
237       }
238       roleList.add(cenRole);
239     }
240     return roleList;
241   }
242
243   String getFunctionCodeAction(String roleFuncItem) {
244     return (!roleFuncItem.contains(FUNCTION_PIPE)) ? "*" : EcompPortalUtils.getFunctionAction(roleFuncItem);
245   }
246
247   List<CentralV2Role> getRolesForApp(String uebkey) throws Exception {
248     logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Entering into getRolesForApp");
249     List<CentralV2Role> roleList = new ArrayList<>();
250     try {
251       List<FnApp> app = fnAppService.getByUebKey(uebkey);
252       List<FnRole> appRolesList = fnRoleService.getAppRoles(app.get(0).getId());
253       roleList = createCentralRoleObject(app, appRolesList, roleList);
254       if (app.get(0).getId() != PortalConstants.PORTAL_APP_ID) {
255         List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
256         List<FnRole> globalRolesList = fnRoleService.getGlobalRolesOfPortal();
257         List<CentralV2Role> portalsGlobalRolesFinlaList = new ArrayList<>();
258         if (!globalRolesList.isEmpty()) {
259           for (FnRole eprole : globalRolesList) {
260             CentralV2Role cenRole = convertRoleToCentralV2Role(eprole);
261             portalsGlobalRolesFinlaList.add(cenRole);
262           }
263           roleList.addAll(globalRoleList);
264           for (CentralV2Role role : portalsGlobalRolesFinlaList) {
265             CentralV2Role result = roleList.stream().filter(x -> role.getId().equals(x.getId())).findAny()
266                 .orElse(null);
267             if (result == null) {
268               roleList.add(role);
269             }
270           }
271         } else {
272           for (FnRole role : globalRolesList) {
273             CentralV2Role cenRole = convertRoleToCentralV2Role(role);
274             roleList.add(cenRole);
275           }
276         }
277       }
278     } catch (Exception e) {
279       logger.error(EELFLoggerDelegate.errorLogger, "getRolesForApp: Failed!", e);
280       throw e;
281     }
282     logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Finished!");
283     return roleList.stream().distinct().collect(Collectors.toList());
284   }
285
286   private CentralV2Role convertRoleToCentralV2Role(FnRole role) {
287     return CentralV2Role.builder().id(role.getId()).created(role.getCreated())
288         .modified(role.getModified()).createdId(role.getCreatedId().getUserId())
289         .modifiedId(role.getModifiedId().getUserId())
290         .rowNum(role.getRowNum()).name(role.getRoleName()).active(role.getActiveYn())
291         .priority(role.getPriority()).roleFunctions(new TreeSet<>()).childRoles(new TreeSet<>())
292         .parentRoles(new TreeSet<>()).build();
293   }
294
295   private List<CentralV2Role> getGlobalRolesOfApplication(Long appId) {
296     List<GlobalRoleWithApplicationRoleFunction> globalRoles = new ArrayList<>();
297     try {
298       List<Tuple> tuples = entityManager.createQuery(GET_GLOBAL_ROLE_WITH_APPLICATION_ROLE_FUNCTIONS, Tuple.class)
299           .setParameter("appId", appId)
300           .getResultList();
301       globalRoles = tuples.stream().map(this::tupleToGlobalRoleWithApplicationRoleFunction).collect(Collectors.toList());
302     } catch (Exception e) {
303       logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
304     }
305     List<CentralV2Role> roleList = new ArrayList<>();
306     if (globalRoles.size() > 0) {
307       roleList = finalListOfCentralRoles(globalRoles);
308     }
309     return roleList;
310   }
311
312   private GlobalRoleWithApplicationRoleFunction tupleToGlobalRoleWithApplicationRoleFunction(Tuple tuple) {
313     return GlobalRoleWithApplicationRoleFunction.builder().roleId((Long) tuple.get("roleId"))
314         .roleName((String) tuple.get("roleName"))
315         .functionCd((String) tuple.get("functionCd")).functionName((String) tuple.get("functionName"))
316         .active((Boolean) tuple.get("active")).priority((Integer) tuple.get("priority"))
317         .appId((Long) tuple.get("appId")).roleAppId((Long) tuple.get("roleAppId")).build();
318   }
319
320   private List<CentralV2Role> finalListOfCentralRoles(List<GlobalRoleWithApplicationRoleFunction> globalRoles) {
321     List<CentralV2Role> rolesfinalList = new ArrayList<>();
322     for (GlobalRoleWithApplicationRoleFunction role : globalRoles) {
323       boolean found = false;
324       for (CentralV2Role cenRole : rolesfinalList) {
325         if (role.getRoleId().equals(cenRole.getId())) {
326           SortedSet<FnRoleFunction> roleFunctions = cenRole.getRoleFunctions();
327           FnRoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
328           roleFunctions.add(cenRoleFun);
329           cenRole.setRoleFunctions(roleFunctions);
330           found = true;
331           break;
332         }
333       }
334       if (!found) {
335         CentralV2Role cenrole = new CentralV2Role();
336         cenrole.setName(role.getRoleName());
337         cenrole.setId(role.getRoleId());
338         cenrole.setActive(role.getActive());
339         cenrole.setPriority(role.getPriority());
340         SortedSet<FnRoleFunction> roleFunctions = new TreeSet<>();
341         FnRoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
342         roleFunctions.add(cenRoleFun);
343         cenrole.setRoleFunctions(roleFunctions);
344         rolesfinalList.add(cenrole);
345       }
346     }
347     return rolesfinalList;
348   }
349
350   private FnRoleFunction createCentralRoleFunctionForGlobalRole(GlobalRoleWithApplicationRoleFunction role) {
351     String instance;
352     String type;
353     String action;
354     FnRoleFunction cenRoleFun = null;
355     if (role.getFunctionCd().contains(FUNCTION_PIPE)) {
356       instance = EcompPortalUtils.getFunctionCode(role.getFunctionCd());
357       type = EcompPortalUtils.getFunctionType(role.getFunctionCd());
358       action = EcompPortalUtils.getFunctionAction(role.getFunctionCd());
359       cenRoleFun = FnRoleFunction.builder().build();
360       FnRole fnRole = FnRole.builder().build();
361       FnFunction fnFunction = FnFunction.builder().functionCd(instance).name(role.getFunctionName()).type(type).action(action).build();
362       cenRoleFun.setRoleId(fnRole);
363       cenRoleFun.setFunctionCd(fnFunction);
364     } else {
365       type = getFunctionCodeType(role.getFunctionCd());
366       action = getFunctionCodeAction(role.getFunctionCd());
367       FnFunction fnFunction = FnFunction.builder().functionCd(role.getFunctionCd()).name(role.getFunctionName()).type(type).action(action).build();
368       cenRoleFun.setRoleId(new FnRole());
369       cenRoleFun.setFunctionCd(fnFunction);
370     }
371     return cenRoleFun;
372   }
373 }