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.utils;
43 import java.util.ArrayList;
44 import java.util.Enumeration;
45 import java.util.HashMap;
46 import java.util.HashSet;
47 import java.util.List;
50 import java.util.UUID;
51 import java.util.regex.Matcher;
52 import java.util.regex.Pattern;
53 import java.util.stream.Collectors;
54 import javax.servlet.ServletContext;
55 import javax.servlet.http.HttpServletRequest;
56 import javax.servlet.http.HttpSession;
57 import lombok.NoArgsConstructor;
58 import org.apache.commons.codec.DecoderException;
59 import org.apache.commons.codec.binary.Hex;
60 import org.onap.portal.domain.db.fn.FnRole;
61 import org.onap.portal.domain.db.fn.FnRoleComposite;
62 import org.onap.portal.domain.db.fn.FnUser;
63 import org.onap.portal.domain.db.fn.FnUserRole;
64 import org.onap.portal.exception.RoleFunctionException;
65 import org.onap.portal.service.fn.old.EPRoleFunctionService;
66 import org.onap.portalsdk.core.domain.RoleFunction;
67 import org.onap.portalsdk.core.exception.SessionExpiredException;
68 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
69 import org.onap.portalsdk.core.menu.MenuBuilder;
70 import org.onap.portalsdk.core.service.DataAccessService;
71 import org.onap.portalsdk.core.util.SystemProperties;
72 import org.onap.portalsdk.core.web.support.AppUtils;
73 import org.springframework.beans.factory.annotation.Autowired;
76 public class EPUserUtils {
78 public static final String ALL_ROLE_FUNCTIONS = "allRoleFunctions";
80 private static final String decodeValueOfForwardSlash = "2f";
81 private static final String decodeValueOfHyphen = "2d";
82 private static final String decodeValueOfAsterisk = "2a";
83 private static final Long ACCOUNT_ADMIN_ROLE_ID = 999L;
85 private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPUserUtils.class);
86 private static DataAccessService dataAccessService;
89 * Gets the EPUser object from the session.
91 * @param request HttpServletRequest
92 * @return EPUser object that was created upon login
93 * @throws SessionExpiredException if no session exists.
95 public static FnUser getUserSession(HttpServletRequest request) {
96 HttpSession session = AppUtils.getSession(request);
97 if (session == null) {
98 throw new SessionExpiredException();
100 return (FnUser) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
104 * Establishes the user's portal session
106 * @param request HttpServletRequest
108 * @param applicationMenuData Menu data
109 * @param businessDirectMenuData Menu data
110 * @param ePRoleFunctionService role function service
112 @SuppressWarnings("rawtypes")
113 public static void setUserSession(HttpServletRequest request, FnUser user, Set applicationMenuData,
114 Set businessDirectMenuData, EPRoleFunctionService ePRoleFunctionService) throws RoleFunctionException {
115 HttpSession session = request.getSession(true);
117 // clear the current user session to avoid any conflicts
118 EPUserUtils.clearUserSession(request);
119 session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user);
121 setAllRoleFunctions(ePRoleFunctionService.getRoleFunctions(), session);
123 ePRoleFunctionService.getRoleFunctions(request, user);
125 // truncate the role (and therefore the role function) data to save
126 // memory in the session
127 user.setFnRoles(null);
128 session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_NAME), user.getFullName());
130 ServletContext context = session.getServletContext();
132 context.getAttribute("licenseVerification");
133 } catch (Exception e) {
134 logger.error(EELFLoggerDelegate.errorLogger,
135 "setUserSession failed to get licenseVerification attribute",
138 session.setAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME), "My Portal");
139 session.setAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME),
140 MenuBuilder.filterMenu(applicationMenuData, request));
141 session.setAttribute(SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME),
142 MenuBuilder.filterMenu(businessDirectMenuData, request));
146 * Creates a set of role function names and stores the set as a session attribute.
148 * @param allRoleFunctions List of role functions.
149 * @param session HttpSession
151 private static void setAllRoleFunctions(List<RoleFunction> allRoleFunctions, HttpSession session)
152 throws RoleFunctionException {
153 if (allRoleFunctions == null) {
156 Set<String> roleFnSet = new HashSet<>();
157 for (RoleFunction roleFn : allRoleFunctions) {
158 roleFnSet.add(decodeFunctionCode(roleFn.getCode()));
160 session.setAttribute(ALL_ROLE_FUNCTIONS, roleFnSet);
164 public static String decodeFunctionCode(String str) throws RoleFunctionException {
165 String decodedString = str;
166 List<Pattern> decodingList = new ArrayList<>();
167 decodingList.add(Pattern.compile(decodeValueOfForwardSlash));
168 decodingList.add(Pattern.compile(decodeValueOfHyphen));
169 decodingList.add(Pattern.compile(decodeValueOfAsterisk));
170 for (Pattern xssInputPattern : decodingList) {
172 decodedString = decodedString.replaceAll("%" + xssInputPattern,
173 new String(Hex.decodeHex(xssInputPattern.toString().toCharArray())));
174 } catch (DecoderException e) {
175 logger.error(EELFLoggerDelegate.errorLogger, "Failed to decode the Rolefunction: " + str,
177 throw new RoleFunctionException("decode failed", e);
181 return decodedString;
185 * Removes all stored attributes from the user's session
187 * @param request HttpServletRequest
188 * @throws SessionExpiredException if no session exists
190 private static void clearUserSession(HttpServletRequest request) {
191 HttpSession session = AppUtils.getSession(request);
192 if (session == null) {
193 throw new SessionExpiredException();
196 // removes all stored attributes from the current user's session
197 session.removeAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
198 session.removeAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME));
199 session.removeAttribute(
200 SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME));
201 session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME));
202 session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME));
206 * Gets role information from the user session, in the cached user object. As a side effect sets a session
207 * variable with the roles.
209 * @param request HttpServletRequest
210 * @return Map of role ID to role object
212 @SuppressWarnings("rawtypes")
213 public static Map getRoles(HttpServletRequest request) {
216 HttpSession session = AppUtils.getSession(request);
217 roles = (HashMap) session
218 .getAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME));
220 // if roles are not already cached, let's grab them from the user
223 FnUser user = getUserSession(request);
225 // get all user roles (including the tree of child roles)
226 roles = getAllUserRoles(user);
228 session.setAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME), roles);
235 * Builds a map of role ID to role object.
238 * @return Map of role ID to role object
240 @SuppressWarnings({"rawtypes", "unchecked"})
241 private static HashMap getAllUserRoles(FnUser user) {
242 HashMap roles = new HashMap();
244 for (FnRole role : user.getFnRoles()) {
245 if (role.getActiveYn()) {
246 roles.put(role.getId(), role);
247 addChildRoles(role, roles);
251 // Additionally; the account admin role is overloaded between onap
252 // portal and partners; lets also include that
253 for (FnUserRole epUserApp : user.getUserApps()) {
254 FnRole role = epUserApp.getRoleId();
256 if (role.getActiveYn() && role.getRoleId().equals(ACCOUNT_ADMIN_ROLE_ID)) {
257 roles.put(role.getId(), role);
259 // let's take a recursive trip down the tree to add all child
261 addChildRoles(role, roles);
269 * Adds all child roles of the specified role to the map of roles.
272 * @param roles Maps role id to role object
274 @SuppressWarnings({"rawtypes", "unchecked"})
275 private static void addChildRoles(FnRole role, HashMap roles) {
276 Set<FnRole> childRoles = role.getChildRoles().stream().map(FnRoleComposite::getChildRoles).collect(Collectors.toSet());
277 if (!childRoles.isEmpty()) {
278 for (Object o : childRoles) {
279 FnRole childRole = (FnRole) o;
280 if (childRole.getActiveYn()) {
281 roles.put(childRole.getId(), childRole);
282 addChildRoles(childRole, roles);
289 public static boolean hasRole(FnUser user, String roleKey) {
290 return getAllUserRoles(user).keySet().contains(new Long(roleKey));
293 public static DataAccessService getDataAccessService() {
294 return dataAccessService;
298 public static void setDataAccessService(DataAccessService dataAccessService) {
299 EPUserUtils.dataAccessService = dataAccessService;
303 * Gets the user's ID from the user object in the session
305 * @param request HttpServletRequest
306 * @return Integer ID of current user
308 public static int getUserId(HttpServletRequest request) {
309 return getUserIdAsLong(request).intValue();
313 * Gets the user's ID from the user object in the session
315 * @param request HttpServletREquest
316 * @return Long ID of current user
318 static Long getUserIdAsLong(HttpServletRequest request) {
319 Long userId = new Long(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID));
320 if (request != null && getUserSession(request) != null) {
321 userId = getUserSession(request).getId();
327 * Gets the request ID from the request.
329 * @param request HttpServletRequest
332 public static String getRequestId(HttpServletRequest request) {
333 Enumeration<String> headerNames = request.getHeaderNames();
335 String requestId = "";
337 while (headerNames.hasMoreElements()) {
338 String headerName = headerNames.nextElement();
339 logger.debug(EELFLoggerDelegate.debugLogger,
340 "One header is " + headerName + " : " + request.getHeader(headerName));
341 if (headerName.equalsIgnoreCase(SystemProperties.ECOMP_REQUEST_ID)) {
342 requestId = request.getHeader(headerName);
346 } catch (Exception e) {
347 logger.error(EELFLoggerDelegate.errorLogger, "getRequestId failed", e);
350 return (requestId.isEmpty() ? UUID.randomUUID().toString() : requestId);
354 * Gets the full URL from the request.
356 * @param request HttpServletRequest
359 static String getFullURL(HttpServletRequest request) {
360 if (request != null) {
361 StringBuffer requestURL = request.getRequestURL();
362 String queryString = request.getQueryString();
364 if (queryString == null) {
365 return requestURL.toString();
367 return requestURL.append('?').append(queryString).toString();
373 public static Boolean matchRoleFunctions(String portalApiPath, Set<? extends String> roleFunctions) {
374 String[] path = portalApiPath.split("/");
375 List<String> roleFunList;
376 if (path.length > 1) {
377 roleFunList = roleFunctions.stream().filter(item -> item.startsWith(path[0]))
378 .collect(Collectors.toList());
379 if (roleFunList.size() >= 1) {
380 for (String roleFunction : roleFunList) {
381 String[] roleFunctionArray = roleFunction.split("/");
383 if (roleFunctionArray.length == path.length) {
384 for (int i = 0; i < roleFunctionArray.length; i++) {
385 if (!roleFunctionArray[i].equals("*")) {
386 Pattern p = Pattern.compile(Pattern.quote(path[i]),
387 Pattern.CASE_INSENSITIVE);
388 Matcher m = p.matcher(roleFunctionArray[i]);
399 for (String roleFunction : roleFunctions) {
400 if (roleFunction.equals(("*"))) {
402 } else if (portalApiPath.matches(roleFunction)) {