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.FnUser;
62 import org.onap.portal.domain.db.fn.FnUserRole;
63 import org.onap.portal.exception.RoleFunctionException;
64 import org.onap.portal.service.fn.old.EPRoleFunctionService;
65 import org.onap.portalsdk.core.domain.RoleFunction;
66 import org.onap.portalsdk.core.exception.SessionExpiredException;
67 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
68 import org.onap.portalsdk.core.menu.MenuBuilder;
69 import org.onap.portalsdk.core.service.DataAccessService;
70 import org.onap.portalsdk.core.util.SystemProperties;
71 import org.onap.portalsdk.core.web.support.AppUtils;
72 import org.springframework.beans.factory.annotation.Autowired;
75 public class EPUserUtils {
77 public static final String ALL_ROLE_FUNCTIONS = "allRoleFunctions";
79 private static final String decodeValueOfForwardSlash = "2f";
80 private static final String decodeValueOfHyphen = "2d";
81 private static final String decodeValueOfAsterisk = "2a";
82 private static final Long ACCOUNT_ADMIN_ROLE_ID = 999L;
84 private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPUserUtils.class);
85 private static DataAccessService dataAccessService;
88 * Gets the EPUser object from the session.
90 * @param request HttpServletRequest
91 * @return EPUser object that was created upon login
92 * @throws SessionExpiredException if no session exists.
94 public static FnUser getUserSession(HttpServletRequest request) {
95 HttpSession session = AppUtils.getSession(request);
96 if (session == null) {
97 throw new SessionExpiredException();
99 return (FnUser) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
103 * Establishes the user's portal session
105 * @param request HttpServletRequest
107 * @param applicationMenuData Menu data
108 * @param businessDirectMenuData Menu data
109 * @param ePRoleFunctionService role function service
111 @SuppressWarnings("rawtypes")
112 public static void setUserSession(HttpServletRequest request, FnUser user, Set applicationMenuData,
113 Set businessDirectMenuData, EPRoleFunctionService ePRoleFunctionService) throws RoleFunctionException {
114 HttpSession session = request.getSession(true);
116 // clear the current user session to avoid any conflicts
117 EPUserUtils.clearUserSession(request);
118 session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user);
120 setAllRoleFunctions(ePRoleFunctionService.getRoleFunctions(), session);
122 ePRoleFunctionService.getRoleFunctions(request, user);
124 // truncate the role (and therefore the role function) data to save
125 // memory in the session
126 user.setFnRoles(null);
127 session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_NAME), user.getFullName());
129 ServletContext context = session.getServletContext();
131 context.getAttribute("licenseVerification");
132 } catch (Exception e) {
133 logger.error(EELFLoggerDelegate.errorLogger,
134 "setUserSession failed to get licenseVerification attribute",
137 session.setAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME), "My Portal");
138 session.setAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME),
139 MenuBuilder.filterMenu(applicationMenuData, request));
140 session.setAttribute(SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME),
141 MenuBuilder.filterMenu(businessDirectMenuData, request));
145 * Creates a set of role function names and stores the set as a session attribute.
147 * @param allRoleFunctions List of role functions.
148 * @param session HttpSession
150 private static void setAllRoleFunctions(List<RoleFunction> allRoleFunctions, HttpSession session)
151 throws RoleFunctionException {
152 if (allRoleFunctions == null) {
155 Set<String> roleFnSet = new HashSet<>();
156 for (RoleFunction roleFn : allRoleFunctions) {
157 roleFnSet.add(decodeFunctionCode(roleFn.getCode()));
159 session.setAttribute(ALL_ROLE_FUNCTIONS, roleFnSet);
163 public static String decodeFunctionCode(String str) throws RoleFunctionException {
164 String decodedString = str;
165 List<Pattern> decodingList = new ArrayList<>();
166 decodingList.add(Pattern.compile(decodeValueOfForwardSlash));
167 decodingList.add(Pattern.compile(decodeValueOfHyphen));
168 decodingList.add(Pattern.compile(decodeValueOfAsterisk));
169 for (Pattern xssInputPattern : decodingList) {
171 decodedString = decodedString.replaceAll("%" + xssInputPattern,
172 new String(Hex.decodeHex(xssInputPattern.toString().toCharArray())));
173 } catch (DecoderException e) {
174 logger.error(EELFLoggerDelegate.errorLogger, "Failed to decode the Rolefunction: " + str,
176 throw new RoleFunctionException("decode failed", e);
180 return decodedString;
184 * Removes all stored attributes from the user's session
186 * @param request HttpServletRequest
187 * @throws SessionExpiredException if no session exists
189 private static void clearUserSession(HttpServletRequest request) {
190 HttpSession session = AppUtils.getSession(request);
191 if (session == null) {
192 throw new SessionExpiredException();
195 // removes all stored attributes from the current user's session
196 session.removeAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
197 session.removeAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME));
198 session.removeAttribute(
199 SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME));
200 session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME));
201 session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME));
205 * Gets role information from the user session, in the cached user object. As a side effect sets a session
206 * variable with the roles.
208 * @param request HttpServletRequest
209 * @return Map of role ID to role object
211 @SuppressWarnings("rawtypes")
212 public static Map getRoles(HttpServletRequest request) {
215 HttpSession session = AppUtils.getSession(request);
216 roles = (HashMap) session
217 .getAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME));
219 // if roles are not already cached, let's grab them from the user
222 FnUser user = getUserSession(request);
224 // get all user roles (including the tree of child roles)
225 roles = getAllUserRoles(user);
227 session.setAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME), roles);
234 * Builds a map of role ID to role object.
237 * @return Map of role ID to role object
239 @SuppressWarnings({"rawtypes", "unchecked"})
240 private static HashMap getAllUserRoles(FnUser user) {
241 HashMap roles = new HashMap();
243 for (FnRole role : user.getFnRoles()) {
244 if (role.getActiveYn()) {
245 roles.put(role.getId(), role);
246 addChildRoles(role, roles);
250 // Additionally; the account admin role is overloaded between onap
251 // portal and partners; lets also include that
252 for (FnUserRole epUserApp : user.getFnUserRoles()) {
253 FnRole role = epUserApp.getRoleId();
255 if (role.getActiveYn() && role.getRoleId().equals(ACCOUNT_ADMIN_ROLE_ID)) {
256 roles.put(role.getId(), role);
258 // let's take a recursive trip down the tree to add all child
260 addChildRoles(role, roles);
268 * Adds all child roles of the specified role to the map of roles.
271 * @param roles Maps role id to role object
273 @SuppressWarnings({"rawtypes", "unchecked"})
274 private static void addChildRoles(FnRole role, HashMap roles) {
275 Set<FnRole> childRoles = role.getFnRoles();
276 if (childRoles != null && !childRoles.isEmpty()) {
277 for (Object o : childRoles) {
278 FnRole childRole = (FnRole) o;
279 if (childRole.getActiveYn()) {
280 roles.put(childRole.getId(), childRole);
281 addChildRoles(childRole, roles);
288 public static boolean hasRole(FnUser user, String roleKey) {
289 return getAllUserRoles(user).keySet().contains(new Long(roleKey));
292 public static DataAccessService getDataAccessService() {
293 return dataAccessService;
297 public static void setDataAccessService(DataAccessService dataAccessService) {
298 EPUserUtils.dataAccessService = dataAccessService;
302 * Gets the user's ID from the user object in the session
304 * @param request HttpServletRequest
305 * @return Integer ID of current user
307 public static int getUserId(HttpServletRequest request) {
308 return getUserIdAsLong(request).intValue();
312 * Gets the user's ID from the user object in the session
314 * @param request HttpServletREquest
315 * @return Long ID of current user
317 static Long getUserIdAsLong(HttpServletRequest request) {
318 Long userId = new Long(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID));
319 if (request != null && getUserSession(request) != null) {
320 userId = getUserSession(request).getId();
326 * Gets the request ID from the request.
328 * @param request HttpServletRequest
331 public static String getRequestId(HttpServletRequest request) {
332 Enumeration<String> headerNames = request.getHeaderNames();
334 String requestId = "";
336 while (headerNames.hasMoreElements()) {
337 String headerName = headerNames.nextElement();
338 logger.debug(EELFLoggerDelegate.debugLogger,
339 "One header is " + headerName + " : " + request.getHeader(headerName));
340 if (headerName.equalsIgnoreCase(SystemProperties.ECOMP_REQUEST_ID)) {
341 requestId = request.getHeader(headerName);
345 } catch (Exception e) {
346 logger.error(EELFLoggerDelegate.errorLogger, "getRequestId failed", e);
349 return (requestId.isEmpty() ? UUID.randomUUID().toString() : requestId);
353 * Gets the full URL from the request.
355 * @param request HttpServletRequest
358 static String getFullURL(HttpServletRequest request) {
359 if (request != null) {
360 StringBuffer requestURL = request.getRequestURL();
361 String queryString = request.getQueryString();
363 if (queryString == null) {
364 return requestURL.toString();
366 return requestURL.append('?').append(queryString).toString();
372 public static Boolean matchRoleFunctions(String portalApiPath, Set<? extends String> roleFunctions) {
373 String[] path = portalApiPath.split("/");
374 List<String> roleFunList;
375 if (path.length > 1) {
376 roleFunList = roleFunctions.stream().filter(item -> item.startsWith(path[0]))
377 .collect(Collectors.toList());
378 if (roleFunList.size() >= 1) {
379 for (String roleFunction : roleFunList) {
380 String[] roleFunctionArray = roleFunction.split("/");
382 if (roleFunctionArray.length == path.length) {
383 for (int i = 0; i < roleFunctionArray.length; i++) {
384 if (!roleFunctionArray[i].equals("*")) {
385 Pattern p = Pattern.compile(Pattern.quote(path[i]),
386 Pattern.CASE_INSENSITIVE);
387 Matcher m = p.matcher(roleFunctionArray[i]);
398 for (String roleFunction : roleFunctions) {
399 if (roleFunction.equals(("*"))) {
401 } else if (portalApiPath.matches(roleFunction)) {