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============================================
36 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
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.Pattern;
50 import javax.servlet.ServletContext;
51 import javax.servlet.http.HttpServletRequest;
52 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 {
72 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPUserUtils.class);
74 private final static Long ACCOUNT_ADMIN_ROLE_ID = 999L;
76 public static final String ALL_ROLE_FUNCTIONS = "allRoleFunctions";
78 // These decode values are based on HexDecoder
79 private static final String decodeValueOfForwardSlash = "2f";
80 private static final String decodeValueOfHyphen = "2d";
81 private static final String decodeValueOfAsterisk = "2a";
83 private static DataAccessService dataAccessService;
86 * Gets the EPUser object from the session.
90 * @return EPUser object that was created upon login
91 * @throws SessionExpiredException
92 * if no session exists.
94 public static EPUser getUserSession(HttpServletRequest request) {
95 HttpSession session = AppUtils.getSession(request);
97 throw new SessionExpiredException();
98 return (EPUser) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
102 * Establishes the user's portal session
108 * @param applicationMenuData
110 * @param businessDirectMenuData
112 * @param loginMethod_ignored
113 * How the user authenticated; ignored
114 * @param ePRoleFunctionService
115 * role function service
116 * @throws DecoderException
118 @SuppressWarnings("rawtypes")
119 public static void setUserSession(HttpServletRequest request, EPUser user, Set applicationMenuData,
120 Set businessDirectMenuData, String loginMethod_ignored, EPRoleFunctionService ePRoleFunctionService) throws RoleFunctionException {
121 HttpSession session = request.getSession(true);
123 // clear the current user session to avoid any conflicts
124 EPUserUtils.clearUserSession(request);
125 session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user);
127 setAllRoleFunctions(ePRoleFunctionService.getRoleFunctions(), session);
129 ePRoleFunctionService.getRoleFunctions(request, user);
131 // truncate the role (and therefore the role function) data to save
132 // memory in the session
133 user.setEPRoles(null);
134 session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_NAME), user.getFullName());
136 ServletContext context = session.getServletContext();
137 int licenseVerificationFlag = 3;
139 licenseVerificationFlag = (Integer) context.getAttribute("licenseVerification");
140 } catch (Exception e) {
141 logger.error(EELFLoggerDelegate.errorLogger, "setUserSession failed to get licenseVerification attribute",
144 session.setAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME), "My Portal");
145 session.setAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME),
146 MenuBuilder.filterMenu(applicationMenuData, request));
147 session.setAttribute(SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME),
148 MenuBuilder.filterMenu(businessDirectMenuData, request));
152 * Creates a set of role function names and stores the set as a session
155 * @param allRoleFunctions
156 * List of role functions.
159 * @throws DecoderException
161 private static void setAllRoleFunctions(List<RoleFunction> allRoleFunctions, HttpSession session) throws RoleFunctionException {
162 if (allRoleFunctions == null)
164 Set<String> roleFnSet = new HashSet<String>();
165 for (RoleFunction roleFn : allRoleFunctions){
166 roleFnSet.add(decodeFunctionCode(roleFn.getCode()));
168 session.setAttribute(ALL_ROLE_FUNCTIONS, roleFnSet);
172 public static String decodeFunctionCode(String str) throws RoleFunctionException{
173 String decodedString = str;
174 List<Pattern> decodingList = new ArrayList<>();
175 decodingList.add(Pattern.compile(decodeValueOfForwardSlash));
176 decodingList.add(Pattern.compile(decodeValueOfHyphen));
177 decodingList.add(Pattern.compile(decodeValueOfAsterisk));
178 for (Pattern xssInputPattern : decodingList) {
180 decodedString = decodedString.replaceAll("%" + xssInputPattern,
181 new String(Hex.decodeHex(xssInputPattern.toString().toCharArray())));
182 } catch (DecoderException e) {
183 logger.error(EELFLoggerDelegate.errorLogger, "Failed to decode the Rolefunction: "+ str,
185 throw new RoleFunctionException("decode failed", e);
189 return decodedString;
193 * Removes all stored attributes from the user's session
197 * @throws SessionExpiredException
198 * if no session exists
200 private static void clearUserSession(HttpServletRequest request) {
201 HttpSession session = AppUtils.getSession(request);
203 throw new SessionExpiredException();
205 // removes all stored attributes from the current user's session
206 session.removeAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
207 session.removeAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME));
208 session.removeAttribute(SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME));
209 session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME));
210 session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME));
214 * Gets role information from the user session, in the cached user object. As a
215 * side effect sets a session variable with the roles.
219 * @return Map of role ID to role object
221 @SuppressWarnings("rawtypes")
222 public static HashMap getRoles(HttpServletRequest request) {
223 HashMap roles = null;
225 HttpSession session = AppUtils.getSession(request);
226 roles = (HashMap) session.getAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME));
228 // if roles are not already cached, let's grab them from the user
231 EPUser user = getUserSession(request);
233 // get all user roles (including the tree of child roles)
234 roles = getAllUserRoles(user);
236 session.setAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME), roles);
243 * Builds a map of role ID to role object.
247 * @return Map of role ID to role object
249 @SuppressWarnings({ "rawtypes", "unchecked" })
250 private static HashMap getAllUserRoles(EPUser user) {
251 HashMap roles = new HashMap();
252 Iterator i = user.getEPRoles().iterator();
254 while (i.hasNext()) {
255 EPRole role = (EPRole) i.next();
257 if (role.getActive()) {
258 roles.put(role.getId(), role);
260 // let's take a recursive trip down the tree to add all child
262 addChildRoles(role, roles);
266 // Additionally; the account admin role is overloaded between ecomp
267 // portal and partners; lets also include that
268 Iterator<EPUserApp> appRolesIterator = user.getEPUserApps().iterator();
269 while (appRolesIterator.hasNext()) {
270 EPRole role = (EPRole) appRolesIterator.next().getRole();
272 if (role.getActive() && role.getId().equals(ACCOUNT_ADMIN_ROLE_ID)) {
273 roles.put(role.getId(), role);
275 // let's take a recursive trip down the tree to add all child
277 addChildRoles(role, roles);
285 * Adds all child roles of the specified role to the map of roles.
290 * Maps role id to role object
292 @SuppressWarnings({ "rawtypes", "unchecked" })
293 private static void addChildRoles(EPRole role, HashMap roles) {
294 Set childRoles = role.getChildRoles();
296 if (childRoles != null && childRoles.size() > 0) {
297 Iterator j = childRoles.iterator();
298 while (j.hasNext()) {
299 EPRole childRole = (EPRole) j.next();
301 if (childRole.getActive()) {
302 roles.put(childRole.getId(), childRole);
304 addChildRoles(childRole, roles);
311 public static boolean hasRole(EPUser user, String roleKey) {
312 return getAllUserRoles(user).keySet().contains(new Long(roleKey));
315 public static DataAccessService getDataAccessService() {
316 return dataAccessService;
320 public void setDataAccessService(DataAccessService dataAccessService) {
321 EPUserUtils.dataAccessService = dataAccessService;
325 * Gets the user's ID from the user object in the session
329 * @return Integer ID of current user
331 public static int getUserId(HttpServletRequest request) {
332 return getUserIdAsLong(request).intValue();
336 * Gets the user's ID from the user object in the session
340 * @return Long ID of current user
342 public static Long getUserIdAsLong(HttpServletRequest request) {
343 Long userId = new Long(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID));
344 if (request != null) {
345 if (getUserSession(request) != null) {
346 userId = getUserSession(request).getId();
353 * Gets the request ID from the request.
359 public static String getRequestId(HttpServletRequest request) {
360 Enumeration<String> headerNames = request.getHeaderNames();
362 String requestId = "";
364 while (headerNames.hasMoreElements()) {
365 String headerName = (String) headerNames.nextElement();
366 logger.debug(EELFLoggerDelegate.debugLogger,
367 "One header is " + headerName + " : " + request.getHeader(headerName));
368 if (headerName.equalsIgnoreCase(SystemProperties.ECOMP_REQUEST_ID)) {
369 requestId = request.getHeader(headerName);
373 } catch (Exception e) {
374 logger.error(EELFLoggerDelegate.errorLogger, "getRequestId failed", e);
377 return (requestId.isEmpty() ? UUID.randomUUID().toString() : requestId);
381 * Gets the full URL from the request.
387 public static String getFullURL(HttpServletRequest request) {
388 if (request != null) {
389 StringBuffer requestURL = request.getRequestURL();
390 String queryString = request.getQueryString();
392 if (queryString == null) {
393 return requestURL.toString();
395 return requestURL.append('?').append(queryString).toString();