2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2017 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.Iterator;
45 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;
52 import javax.servlet.ServletContext;
53 import javax.servlet.http.HttpServletRequest;
54 import javax.servlet.http.HttpSession;
56 import org.apache.commons.codec.DecoderException;
57 import org.apache.commons.codec.binary.Hex;
58 import org.onap.portalapp.portal.domain.EPRole;
59 import org.onap.portalapp.portal.domain.EPUser;
60 import org.onap.portalapp.portal.domain.EPUserApp;
61 import org.onap.portalapp.portal.exceptions.RoleFunctionException;
62 import org.onap.portalapp.portal.service.EPRoleFunctionService;
63 import org.onap.portalsdk.core.domain.RoleFunction;
64 import org.onap.portalsdk.core.exception.SessionExpiredException;
65 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
66 import org.onap.portalsdk.core.menu.MenuBuilder;
67 import org.onap.portalsdk.core.service.DataAccessService;
68 import org.onap.portalsdk.core.util.SystemProperties;
69 import org.onap.portalsdk.core.web.support.AppUtils;
70 import org.springframework.beans.factory.annotation.Autowired;
72 public class EPUserUtils {
74 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPUserUtils.class);
76 private final static Long ACCOUNT_ADMIN_ROLE_ID = 999L;
78 public static final String ALL_ROLE_FUNCTIONS = "allRoleFunctions";
80 // These decode values are based on HexDecoder
81 private static final String decodeValueOfForwardSlash = "2f";
82 private static final String decodeValueOfHyphen = "2d";
83 private static final String decodeValueOfAsterisk = "2a";
85 private static DataAccessService dataAccessService;
88 * Gets the EPUser object from the session.
92 * @return EPUser object that was created upon login
93 * @throws SessionExpiredException
94 * if no session exists.
96 public static EPUser getUserSession(HttpServletRequest request) {
97 HttpSession session = AppUtils.getSession(request);
99 throw new SessionExpiredException();
100 return (EPUser) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
104 * Establishes the user's portal session
110 * @param applicationMenuData
112 * @param businessDirectMenuData
114 * @param loginMethod_ignored
115 * How the user authenticated; ignored
116 * @param ePRoleFunctionService
117 * role function service
118 * @throws DecoderException
120 @SuppressWarnings("rawtypes")
121 public static void setUserSession(HttpServletRequest request, EPUser user, Set applicationMenuData,
122 Set businessDirectMenuData, String loginMethod_ignored, EPRoleFunctionService ePRoleFunctionService) throws RoleFunctionException {
123 HttpSession session = request.getSession(true);
125 // clear the current user session to avoid any conflicts
126 EPUserUtils.clearUserSession(request);
127 session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user);
129 setAllRoleFunctions(ePRoleFunctionService.getRoleFunctions(), session);
131 ePRoleFunctionService.getRoleFunctions(request, user);
133 // truncate the role (and therefore the role function) data to save
134 // memory in the session
135 user.setEPRoles(null);
136 session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_NAME), user.getFullName());
138 ServletContext context = session.getServletContext();
139 int licenseVerificationFlag = 3;
141 licenseVerificationFlag = (Integer) context.getAttribute("licenseVerification");
142 } catch (Exception e) {
143 logger.error(EELFLoggerDelegate.errorLogger, "setUserSession failed to get licenseVerification attribute",
146 session.setAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME), "My Portal");
147 session.setAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME),
148 MenuBuilder.filterMenu(applicationMenuData, request));
149 session.setAttribute(SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME),
150 MenuBuilder.filterMenu(businessDirectMenuData, request));
154 * Creates a set of role function names and stores the set as a session
157 * @param allRoleFunctions
158 * List of role functions.
161 * @throws DecoderException
163 private static void setAllRoleFunctions(List<RoleFunction> allRoleFunctions, HttpSession session) throws RoleFunctionException {
164 if (allRoleFunctions == null)
166 Set<String> roleFnSet = new HashSet<String>();
167 for (RoleFunction roleFn : allRoleFunctions){
168 roleFnSet.add(decodeFunctionCode(roleFn.getCode()));
170 session.setAttribute(ALL_ROLE_FUNCTIONS, roleFnSet);
174 public static String decodeFunctionCode(String str) throws RoleFunctionException{
175 String decodedString = str;
176 List<Pattern> decodingList = new ArrayList<>();
177 decodingList.add(Pattern.compile(decodeValueOfForwardSlash));
178 decodingList.add(Pattern.compile(decodeValueOfHyphen));
179 decodingList.add(Pattern.compile(decodeValueOfAsterisk));
180 for (Pattern xssInputPattern : decodingList) {
182 decodedString = decodedString.replaceAll("%" + xssInputPattern,
183 new String(Hex.decodeHex(xssInputPattern.toString().toCharArray())));
184 } catch (DecoderException e) {
185 logger.error(EELFLoggerDelegate.errorLogger, "Failed to decode the Rolefunction: "+ str,
187 throw new RoleFunctionException("decode failed", e);
191 return decodedString;
195 * Removes all stored attributes from the user's session
199 * @throws SessionExpiredException
200 * if no session exists
202 private static void clearUserSession(HttpServletRequest request) {
203 HttpSession session = AppUtils.getSession(request);
205 throw new SessionExpiredException();
207 // removes all stored attributes from the current user's session
208 session.removeAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
209 session.removeAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME));
210 session.removeAttribute(SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME));
211 session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME));
212 session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME));
216 * Gets role information from the user session, in the cached user object. As a
217 * side effect sets a session variable with the roles.
221 * @return Map of role ID to role object
223 @SuppressWarnings("rawtypes")
224 public static HashMap getRoles(HttpServletRequest request) {
225 HashMap roles = null;
227 HttpSession session = AppUtils.getSession(request);
228 roles = (HashMap) session.getAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME));
230 // if roles are not already cached, let's grab them from the user
233 EPUser user = getUserSession(request);
235 // get all user roles (including the tree of child roles)
236 roles = getAllUserRoles(user);
238 session.setAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME), roles);
245 * Builds a map of role ID to role object.
249 * @return Map of role ID to role object
251 @SuppressWarnings({ "rawtypes", "unchecked" })
252 private static HashMap getAllUserRoles(EPUser user) {
253 HashMap roles = new HashMap();
254 Iterator i = user.getEPRoles().iterator();
256 while (i.hasNext()) {
257 EPRole role = (EPRole) i.next();
259 if (role.getActive()) {
260 roles.put(role.getId(), role);
262 // let's take a recursive trip down the tree to add all child
264 addChildRoles(role, roles);
268 // Additionally; the account admin role is overloaded between onap
269 // portal and partners; lets also include that
270 Iterator<EPUserApp> appRolesIterator = user.getEPUserApps().iterator();
271 while (appRolesIterator.hasNext()) {
272 EPRole role = (EPRole) appRolesIterator.next().getRole();
274 if (role.getActive() && role.getId().equals(ACCOUNT_ADMIN_ROLE_ID)) {
275 roles.put(role.getId(), role);
277 // let's take a recursive trip down the tree to add all child
279 addChildRoles(role, roles);
287 * Adds all child roles of the specified role to the map of roles.
292 * Maps role id to role object
294 @SuppressWarnings({ "rawtypes", "unchecked" })
295 private static void addChildRoles(EPRole role, HashMap roles) {
296 Set childRoles = role.getChildRoles();
298 if (childRoles != null && childRoles.size() > 0) {
299 Iterator j = childRoles.iterator();
300 while (j.hasNext()) {
301 EPRole childRole = (EPRole) j.next();
303 if (childRole.getActive()) {
304 roles.put(childRole.getId(), childRole);
306 addChildRoles(childRole, roles);
313 public static boolean hasRole(EPUser user, String roleKey) {
314 return getAllUserRoles(user).keySet().contains(new Long(roleKey));
317 public static DataAccessService getDataAccessService() {
318 return dataAccessService;
322 public void setDataAccessService(DataAccessService dataAccessService) {
323 EPUserUtils.dataAccessService = dataAccessService;
327 * Gets the user's ID from the user object in the session
331 * @return Integer ID of current user
333 public static int getUserId(HttpServletRequest request) {
334 return getUserIdAsLong(request).intValue();
338 * Gets the user's ID from the user object in the session
342 * @return Long ID of current user
344 public static Long getUserIdAsLong(HttpServletRequest request) {
345 Long userId = new Long(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID));
346 if (request != null) {
347 if (getUserSession(request) != null) {
348 userId = getUserSession(request).getId();
355 * Gets the request ID from the request.
361 public static String getRequestId(HttpServletRequest request) {
362 Enumeration<String> headerNames = request.getHeaderNames();
364 String requestId = "";
366 while (headerNames.hasMoreElements()) {
367 String headerName = (String) headerNames.nextElement();
368 logger.debug(EELFLoggerDelegate.debugLogger,
369 "One header is " + headerName + " : " + request.getHeader(headerName));
370 if (headerName.equalsIgnoreCase(SystemProperties.ECOMP_REQUEST_ID)) {
371 requestId = request.getHeader(headerName);
375 } catch (Exception e) {
376 logger.error(EELFLoggerDelegate.errorLogger, "getRequestId failed", e);
379 return (requestId.isEmpty() ? UUID.randomUUID().toString() : requestId);
383 * Gets the full URL from the request.
389 public static String getFullURL(HttpServletRequest request) {
390 if (request != null) {
391 StringBuffer requestURL = request.getRequestURL();
392 String queryString = request.getQueryString();
394 if (queryString == null) {
395 return requestURL.toString();
397 return requestURL.append('?').append(queryString).toString();
403 public static Boolean matchRoleFunctions(String portalApiPath, Set<? extends String> roleFunctions) {
404 String[] path = portalApiPath.split("/");
405 List<String> roleFunList = new ArrayList<>();
406 if (path.length > 1) {
407 roleFunList = roleFunctions.stream().filter(item -> item.startsWith(path[0])).collect(Collectors.toList());
408 if (roleFunList.size() >= 1) {
409 for (String roleFunction : roleFunList) {
410 String[] roleFunctionArray = roleFunction.split("/");
412 if (roleFunctionArray.length == path.length) {
413 for (int i = 0; i < roleFunctionArray.length; i++) {
415 if (!roleFunctionArray[i].equals("*")) {
416 Pattern p = Pattern.compile(Pattern.quote(path[i]), Pattern.CASE_INSENSITIVE);
417 Matcher m = p.matcher(roleFunctionArray[i]);
429 for (String roleFunction : roleFunctions) {
430 if (roleFunction.equals(("*"))) {
432 } else if (portalApiPath.matches(roleFunction)) {