2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
8 * Unless otherwise specified, all software contained herein is licensed
9 * under the Apache License, Version 2.0 (the "License");
10 * you may not use this software except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * Unless otherwise specified, all documentation contained herein is licensed
22 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23 * you may not use this documentation except in compliance with the License.
24 * You may obtain a copy of the License at
26 * https://creativecommons.org/licenses/by/4.0/
28 * Unless required by applicable law or agreed to in writing, documentation
29 * distributed under the License is distributed on an "AS IS" BASIS,
30 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31 * See the License for the specific language governing permissions and
32 * limitations under the License.
34 * ============LICENSE_END============================================
38 package org.onap.portalapp.util;
40 import java.util.ArrayList;
41 import java.util.Enumeration;
42 import java.util.HashMap;
43 import java.util.HashSet;
44 import java.util.List;
47 import java.util.UUID;
48 import java.util.regex.Matcher;
49 import java.util.regex.Pattern;
50 import java.util.stream.Collectors;
51 import javax.servlet.ServletContext;
52 import javax.servlet.http.HttpServletRequest;
53 import javax.servlet.http.HttpSession;
54 import org.apache.commons.codec.DecoderException;
55 import org.apache.commons.codec.binary.Hex;
56 import org.onap.portalapp.portal.domain.EPRole;
57 import org.onap.portalapp.portal.domain.EPUser;
58 import org.onap.portalapp.portal.domain.EPUserApp;
59 import org.onap.portalapp.portal.exceptions.RoleFunctionException;
60 import org.onap.portalapp.portal.service.EPRoleFunctionService;
61 import org.onap.portalsdk.core.domain.RoleFunction;
62 import org.onap.portalsdk.core.exception.SessionExpiredException;
63 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
64 import org.onap.portalsdk.core.menu.MenuBuilder;
65 import org.onap.portalsdk.core.service.DataAccessService;
66 import org.onap.portalsdk.core.util.SystemProperties;
67 import org.onap.portalsdk.core.web.support.AppUtils;
68 import org.springframework.beans.factory.annotation.Autowired;
70 public class EPUserUtils {
71 public static final String ALL_ROLE_FUNCTIONS = "allRoleFunctions";
73 private static final String decodeValueOfForwardSlash = "2f";
74 private static final String decodeValueOfHyphen = "2d";
75 private static final String decodeValueOfAsterisk = "2a";
76 private static final Long ACCOUNT_ADMIN_ROLE_ID = 999L;
78 private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPUserUtils.class);
79 private static DataAccessService dataAccessService;
82 * Gets the EPUser object from the session.
86 * @return EPUser object that was created upon login
87 * @throws SessionExpiredException
88 * if no session exists.
90 public static EPUser getUserSession(HttpServletRequest request) {
91 HttpSession session = AppUtils.getSession(request);
93 throw new SessionExpiredException();
94 return (EPUser) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
98 * Establishes the user's portal session
104 * @param applicationMenuData
106 * @param businessDirectMenuData
108 * @param ePRoleFunctionService
109 * role function service
110 * @throws DecoderException
112 @SuppressWarnings("rawtypes")
113 public static void setUserSession(HttpServletRequest request, EPUser 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.setEPRoles(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, "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
148 * @param allRoleFunctions
149 * List of role functions.
152 * @throws DecoderException
154 private static void setAllRoleFunctions(List<RoleFunction> allRoleFunctions, HttpSession session) throws RoleFunctionException {
155 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
190 * @throws SessionExpiredException
191 * if no session exists
193 private static void clearUserSession(HttpServletRequest request) {
194 HttpSession session = AppUtils.getSession(request);
196 throw new SessionExpiredException();
198 // removes all stored attributes from the current user's session
199 session.removeAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
200 session.removeAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME));
201 session.removeAttribute(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
208 * side effect sets a session variable with the roles.
212 * @return Map of role ID to role object
214 @SuppressWarnings("rawtypes")
215 public static Map getRoles(HttpServletRequest request) {
218 HttpSession session = AppUtils.getSession(request);
219 roles = (HashMap) session.getAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME));
221 // if roles are not already cached, let's grab them from the user
224 EPUser 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.
240 * @return Map of role ID to role object
242 @SuppressWarnings({ "rawtypes", "unchecked" })
243 private static HashMap getAllUserRoles(EPUser user) {
244 HashMap roles = new HashMap();
246 for (EPRole role : user.getEPRoles()) {
247 if (role.getActive()) {
248 roles.put(role.getId(), role);
250 // let's take a recursive trip down the tree to add all child
252 addChildRoles(role, roles);
256 // Additionally; the account admin role is overloaded between onap
257 // portal and partners; lets also include that
258 for (EPUserApp epUserApp : user.getEPUserApps()) {
259 EPRole role = epUserApp.getRole();
261 if (role.getActive() && role.getId().equals(ACCOUNT_ADMIN_ROLE_ID)) {
262 roles.put(role.getId(), role);
264 // let's take a recursive trip down the tree to add all child
266 addChildRoles(role, roles);
274 * Adds all child roles of the specified role to the map of roles.
279 * Maps role id to role object
281 @SuppressWarnings({ "rawtypes", "unchecked" })
282 private static void addChildRoles(EPRole role, HashMap roles) {
283 Set childRoles = role.getChildRoles();
285 if (childRoles != null && !childRoles.isEmpty()) {
286 for (Object o : childRoles) {
287 EPRole childRole = (EPRole) o;
289 if (childRole.getActive()) {
290 roles.put(childRole.getId(), childRole);
292 addChildRoles(childRole, roles);
299 public static boolean hasRole(EPUser user, String roleKey) {
300 return getAllUserRoles(user).keySet().contains(new Long(roleKey));
303 public static DataAccessService getDataAccessService() {
304 return dataAccessService;
308 public static void setDataAccessService(DataAccessService dataAccessService) {
309 EPUserUtils.dataAccessService = dataAccessService;
313 * Gets the user's ID from the user object in the session
317 * @return Integer ID of current user
319 public static int getUserId(HttpServletRequest request) {
320 return getUserIdAsLong(request).intValue();
324 * Gets the user's ID from the user object in the session
328 * @return Long ID of current user
330 static Long getUserIdAsLong(HttpServletRequest request) {
331 Long userId = new Long(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID));
332 if (request != null && getUserSession(request) != null) {
333 userId = getUserSession(request).getId();
339 * Gets the request ID from the request.
345 public static String getRequestId(HttpServletRequest request) {
346 Enumeration<String> headerNames = request.getHeaderNames();
348 String requestId = "";
350 while (headerNames.hasMoreElements()) {
351 String headerName = headerNames.nextElement();
352 logger.debug(EELFLoggerDelegate.debugLogger,
353 "One header is " + headerName + " : " + request.getHeader(headerName));
354 if (headerName.equalsIgnoreCase(SystemProperties.ECOMP_REQUEST_ID)) {
355 requestId = request.getHeader(headerName);
359 } catch (Exception e) {
360 logger.error(EELFLoggerDelegate.errorLogger, "getRequestId failed", e);
363 return (requestId.isEmpty() ? UUID.randomUUID().toString() : requestId);
367 * Gets the full URL from the request.
373 static String getFullURL(HttpServletRequest request) {
374 if (request != null) {
375 StringBuffer requestURL = request.getRequestURL();
376 String queryString = request.getQueryString();
378 if (queryString == null) {
379 return requestURL.toString();
381 return requestURL.append('?').append(queryString).toString();
387 public static Boolean matchRoleFunctions(String portalApiPath, Set<? extends String> roleFunctions) {
388 String[] path = portalApiPath.split("/");
389 List<String> roleFunList;
390 if (path.length > 1) {
391 roleFunList = roleFunctions.stream().filter(item -> item.startsWith(path[0])).collect(Collectors.toList());
392 if (roleFunList.size() >= 1) {
393 for (String roleFunction : roleFunList) {
394 String[] roleFunctionArray = roleFunction.split("/");
396 if (roleFunctionArray.length == path.length) {
397 for (int i = 0; i < roleFunctionArray.length; i++) {
398 if (!roleFunctionArray[i].equals("*")) {
399 Pattern p = Pattern.compile(Pattern.quote(path[i]), Pattern.CASE_INSENSITIVE);
400 Matcher m = p.matcher(roleFunctionArray[i]);
409 for (String roleFunction : roleFunctions) {
410 if (roleFunction.equals(("*"))) {
412 } else if (portalApiPath.matches(roleFunction)) {