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.domain.dto.transport.Role;
65 import org.onap.portal.exception.RoleFunctionException;
66 import org.onap.portal.service.EPRoleFunctionService;
67 import org.onap.portalsdk.core.domain.RoleFunction;
68 import org.onap.portalsdk.core.exception.SessionExpiredException;
69 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
70 import org.onap.portalsdk.core.menu.MenuBuilder;
71 import org.onap.portalsdk.core.service.DataAccessService;
72 import org.onap.portalsdk.core.util.SystemProperties;
73 import org.onap.portalsdk.core.web.support.AppUtils;
74 import org.springframework.beans.factory.annotation.Autowired;
77 public class EPUserUtils {
79 public static final String ALL_ROLE_FUNCTIONS = "allRoleFunctions";
81 private static final String decodeValueOfForwardSlash = "2f";
82 private static final String decodeValueOfHyphen = "2d";
83 private static final String decodeValueOfAsterisk = "2a";
84 private static final Long ACCOUNT_ADMIN_ROLE_ID = 999L;
86 private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPUserUtils.class);
87 private static DataAccessService dataAccessService;
90 * Gets the EPUser object from the session.
92 * @param request HttpServletRequest
93 * @return EPUser object that was created upon login
94 * @throws SessionExpiredException if no session exists.
96 public static FnUser getUserSession(HttpServletRequest request) {
97 HttpSession session = AppUtils.getSession(request);
98 if (session == null) {
99 throw new SessionExpiredException();
101 return (FnUser) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
105 * Establishes the user's portal session
107 * @param request HttpServletRequest
109 * @param applicationMenuData Menu data
110 * @param businessDirectMenuData Menu data
111 * @param ePRoleFunctionService role function service
113 @SuppressWarnings("rawtypes")
114 public static void setUserSession(HttpServletRequest request, FnUser user, Set applicationMenuData,
115 Set businessDirectMenuData, EPRoleFunctionService ePRoleFunctionService) throws RoleFunctionException {
116 HttpSession session = request.getSession(true);
118 // clear the current user session to avoid any conflicts
119 EPUserUtils.clearUserSession(request);
120 session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user);
122 setAllRoleFunctions(ePRoleFunctionService.getRoleFunctions(), session);
124 ePRoleFunctionService.getRoleFunctions(request, user);
126 // truncate the role (and therefore the role function) data to save
127 // memory in the session
128 user.setFnRoles(null);
129 session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_NAME), user.getFullName());
131 ServletContext context = session.getServletContext();
133 context.getAttribute("licenseVerification");
134 } catch (Exception e) {
135 logger.error(EELFLoggerDelegate.errorLogger,
136 "setUserSession failed to get licenseVerification attribute",
139 session.setAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME), "My Portal");
140 session.setAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME),
141 MenuBuilder.filterMenu(applicationMenuData, request));
142 session.setAttribute(SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME),
143 MenuBuilder.filterMenu(businessDirectMenuData, request));
147 * Creates a set of role function names and stores the set as a session attribute.
149 * @param allRoleFunctions List of role functions.
150 * @param session HttpSession
152 private static void setAllRoleFunctions(List<RoleFunction> allRoleFunctions, HttpSession session)
153 throws RoleFunctionException {
154 if (allRoleFunctions == null) {
157 Set<String> roleFnSet = new HashSet<>();
158 for (RoleFunction roleFn : allRoleFunctions) {
159 roleFnSet.add(decodeFunctionCode(roleFn.getCode()));
161 session.setAttribute(ALL_ROLE_FUNCTIONS, roleFnSet);
165 public static String decodeFunctionCode(String str) throws RoleFunctionException {
166 String decodedString = str;
167 List<Pattern> decodingList = new ArrayList<>();
168 decodingList.add(Pattern.compile(decodeValueOfForwardSlash));
169 decodingList.add(Pattern.compile(decodeValueOfHyphen));
170 decodingList.add(Pattern.compile(decodeValueOfAsterisk));
171 for (Pattern xssInputPattern : decodingList) {
173 decodedString = decodedString.replaceAll("%" + xssInputPattern,
174 new String(Hex.decodeHex(xssInputPattern.toString().toCharArray())));
175 } catch (DecoderException e) {
176 logger.error(EELFLoggerDelegate.errorLogger, "Failed to decode the Rolefunction: " + str,
178 throw new RoleFunctionException("decode failed", e);
182 return decodedString;
186 * Removes all stored attributes from the user's session
188 * @param request HttpServletRequest
189 * @throws SessionExpiredException if no session exists
191 private static void clearUserSession(HttpServletRequest request) {
192 HttpSession session = AppUtils.getSession(request);
193 if (session == null) {
194 throw new SessionExpiredException();
197 // removes all stored attributes from the current user's session
198 session.removeAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
199 session.removeAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME));
200 session.removeAttribute(
201 SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME));
202 session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME));
203 session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME));
207 * Gets role information from the user session, in the cached user object. As a side effect sets a session
208 * variable with the roles.
210 * @param request HttpServletRequest
211 * @return Map of role ID to role object
213 @SuppressWarnings("rawtypes")
214 public static Map getRoles(HttpServletRequest request) {
217 HttpSession session = AppUtils.getSession(request);
218 roles = (HashMap) session
219 .getAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME));
221 // if roles are not already cached, let's grab them from the user
224 FnUser user = getUserSession(request);
226 // get all user roles (including the tree of child roles)
227 roles = getAllUserRoles(user);
229 session.setAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME), roles);
236 * Builds a map of role ID to role object.
239 * @return Map of role ID to role object
241 @SuppressWarnings({"rawtypes", "unchecked"})
242 private static HashMap getAllUserRoles(FnUser user) {
243 HashMap roles = new HashMap();
245 for (FnRole role : user.getFnRoles()) {
246 if (role.getActiveYn()) {
247 roles.put(role.getId(), role);
248 addChildRoles(role, roles);
252 // Additionally; the account admin role is overloaded between onap
253 // portal and partners; lets also include that
254 for (FnUserRole epUserApp : user.getUserApps()) {
255 FnRole role = epUserApp.getRoleId();
257 if (role.getActiveYn() && role.getId().equals(ACCOUNT_ADMIN_ROLE_ID)) {
258 roles.put(role.getId(), role);
260 // let's take a recursive trip down the tree to add all child
262 addChildRoles(role, roles);
270 * Adds all child roles of the specified role to the map of roles.
273 * @param roles Maps role id to role object
275 @SuppressWarnings({"rawtypes", "unchecked"})
276 private static void addChildRoles(FnRole role, HashMap roles) {
277 List<Role> childRoles = role.getChildRoles()
279 .map(FnRoleComposite::getChildRoles)
280 .collect(Collectors.toList());
281 if (!childRoles.isEmpty()) {
282 for (Object o : childRoles) {
283 FnRole childRole = (FnRole) o;
284 if (childRole.getActiveYn()) {
285 roles.put(childRole.getId(), childRole);
286 addChildRoles(childRole, roles);
293 public static boolean hasRole(FnUser user, String roleKey) {
294 return getAllUserRoles(user).keySet().contains(new Long(roleKey));
297 public static DataAccessService getDataAccessService() {
298 return dataAccessService;
302 public static void setDataAccessService(DataAccessService dataAccessService) {
303 EPUserUtils.dataAccessService = dataAccessService;
307 * Gets the user's ID from the user object in the session
309 * @param request HttpServletRequest
310 * @return Integer ID of current user
312 public static int getUserId(HttpServletRequest request) {
313 return getUserIdAsLong(request).intValue();
317 * Gets the user's ID from the user object in the session
319 * @param request HttpServletREquest
320 * @return Long ID of current user
322 static Long getUserIdAsLong(HttpServletRequest request) {
323 Long userId = new Long(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID));
324 if (request != null && getUserSession(request) != null) {
325 userId = getUserSession(request).getId();
331 * Gets the request ID from the request.
333 * @param request HttpServletRequest
336 public static String getRequestId(HttpServletRequest request) {
337 Enumeration<String> headerNames = request.getHeaderNames();
339 String requestId = "";
341 while (headerNames.hasMoreElements()) {
342 String headerName = headerNames.nextElement();
343 logger.debug(EELFLoggerDelegate.debugLogger,
344 "One header is " + headerName + " : " + request.getHeader(headerName));
345 if (headerName.equalsIgnoreCase(SystemProperties.ECOMP_REQUEST_ID)) {
346 requestId = request.getHeader(headerName);
350 } catch (Exception e) {
351 logger.error(EELFLoggerDelegate.errorLogger, "getRequestId failed", e);
354 return (requestId.isEmpty() ? UUID.randomUUID().toString() : requestId);
358 * Gets the full URL from the request.
360 * @param request HttpServletRequest
363 static String getFullURL(HttpServletRequest request) {
364 if (request != null) {
365 StringBuffer requestURL = request.getRequestURL();
366 String queryString = request.getQueryString();
368 if (queryString == null) {
369 return requestURL.toString();
371 return requestURL.append('?').append(queryString).toString();
377 public static Boolean matchRoleFunctions(String portalApiPath, Set<? extends String> roleFunctions) {
378 String[] path = portalApiPath.split("/");
379 List<String> roleFunList;
380 if (path.length > 1) {
381 roleFunList = roleFunctions.stream().filter(item -> item.startsWith(path[0]))
382 .collect(Collectors.toList());
383 if (roleFunList.size() >= 1) {
384 for (String roleFunction : roleFunList) {
385 String[] roleFunctionArray = roleFunction.split("/");
387 if (roleFunctionArray.length == path.length) {
388 for (int i = 0; i < roleFunctionArray.length; i++) {
389 if (!roleFunctionArray[i].equals("*")) {
390 Pattern p = Pattern.compile(Pattern.quote(path[i]),
391 Pattern.CASE_INSENSITIVE);
392 Matcher m = p.matcher(roleFunctionArray[i]);
403 for (String roleFunction : roleFunctions) {
404 if (roleFunction.equals(("*"))) {
406 } else if (portalApiPath.matches(roleFunction)) {