EPUserUtils class fix
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / util / EPUserUtils.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
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
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
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.
20  *
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
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
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.
33  *
34  * ============LICENSE_END============================================
35  *
36  * 
37  */
38 package org.onap.portalapp.util;
39
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;
45 import java.util.Map;
46 import java.util.Set;
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;
69
70 public class EPUserUtils {
71         public static final String ALL_ROLE_FUNCTIONS = "allRoleFunctions";
72
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;
77
78         private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPUserUtils.class);
79         private static DataAccessService dataAccessService;
80
81         /**
82          * Gets the EPUser object from the session.
83          * 
84          * @param request
85          *            HttpServletRequest
86          * @return EPUser object that was created upon login
87          * @throws SessionExpiredException
88          *             if no session exists.
89          */
90         public static EPUser getUserSession(HttpServletRequest request) {
91                 HttpSession session = AppUtils.getSession(request);
92                 if (session == null)
93                         throw new SessionExpiredException();
94                 return (EPUser) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
95         }
96
97         /**
98          * Establishes the user's portal session
99          * 
100          * @param request
101          *            HttpServletRequest
102          * @param user
103          *            EPUser
104          * @param applicationMenuData
105          *            Menu data
106          * @param businessDirectMenuData
107          *            Menu data
108          * @param ePRoleFunctionService
109          *            role function service
110          * @throws DecoderException 
111          */
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);
116
117                 // clear the current user session to avoid any conflicts
118                 EPUserUtils.clearUserSession(request);
119                 session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user);
120
121                 setAllRoleFunctions(ePRoleFunctionService.getRoleFunctions(), session);
122
123                 ePRoleFunctionService.getRoleFunctions(request, user);
124
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());
129
130                 ServletContext context = session.getServletContext();
131                 try {
132                         context.getAttribute("licenseVerification");
133                 } catch (Exception e) {
134                         logger.error(EELFLoggerDelegate.errorLogger, "setUserSession failed to get licenseVerification attribute",
135                                         e);
136                 }
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));
142         }
143
144         /**
145          * Creates a set of role function names and stores the set as a session
146          * attribute.
147          * 
148          * @param allRoleFunctions
149          *            List of role functions.
150          * @param session
151          *            HttpSession
152          * @throws DecoderException 
153          */
154         private static void setAllRoleFunctions(List<RoleFunction> allRoleFunctions, HttpSession session) throws RoleFunctionException {
155                 if (allRoleFunctions == null)
156                         return;
157                 Set<String> roleFnSet = new HashSet<>();
158                 for (RoleFunction roleFn : allRoleFunctions){
159                         roleFnSet.add(decodeFunctionCode(roleFn.getCode()));
160                 }
161                 session.setAttribute(ALL_ROLE_FUNCTIONS, roleFnSet);
162         }
163
164         
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) {
172                         try {
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,
177                                                 e);
178                                 throw new RoleFunctionException("decode failed", e);            
179                         }
180                 }
181                 
182                 return decodedString;
183         }
184         
185         /**
186          * Removes all stored attributes from the user's session
187          * 
188          * @param request
189          *            HttpServletRequest
190          * @throws SessionExpiredException
191          *             if no session exists
192          */
193         private static void clearUserSession(HttpServletRequest request) {
194                 HttpSession session = AppUtils.getSession(request);
195                 if (session == null)
196                         throw new SessionExpiredException();
197
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));
204         }
205
206         /**
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.
209          * 
210          * @param request
211          *            HttpServletRequest
212          * @return Map of role ID to role object
213          */
214         @SuppressWarnings("rawtypes")
215         public static Map getRoles(HttpServletRequest request) {
216                 HashMap roles;
217
218                 HttpSession session = AppUtils.getSession(request);
219                 roles = (HashMap) session.getAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME));
220
221                 // if roles are not already cached, let's grab them from the user
222                 // session
223                 if (roles == null) {
224                         EPUser user = getUserSession(request);
225
226                         // get all user roles (including the tree of child roles)
227                         roles = getAllUserRoles(user);
228
229                         session.setAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME), roles);
230                 }
231
232                 return roles;
233         }
234
235         /**
236          * Builds a map of role ID to role object.
237          * 
238          * @param user
239          *            EPUser
240          * @return Map of role ID to role object
241          */
242         @SuppressWarnings({ "rawtypes", "unchecked" })
243         private static HashMap getAllUserRoles(EPUser user) {
244                 HashMap roles = new HashMap();
245
246                 for (EPRole role : user.getEPRoles()) {
247                         if (role.getActive()) {
248                                 roles.put(role.getId(), role);
249
250                                 // let's take a recursive trip down the tree to add all child
251                                 // roles
252                                 addChildRoles(role, roles);
253                         }
254                 }
255
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();
260
261                         if (role.getActive() && role.getId().equals(ACCOUNT_ADMIN_ROLE_ID)) {
262                                 roles.put(role.getId(), role);
263
264                                 // let's take a recursive trip down the tree to add all child
265                                 // roles
266                                 addChildRoles(role, roles);
267                         }
268                 }
269
270                 return roles;
271         }
272
273         /**
274          * Adds all child roles of the specified role to the map of roles.
275          * 
276          * @param role
277          *            EPRole
278          * @param roles
279          *            Maps role id to role object
280          */
281         @SuppressWarnings({ "rawtypes", "unchecked" })
282         private static void addChildRoles(EPRole role, HashMap roles) {
283                 Set childRoles = role.getChildRoles();
284
285                 if (childRoles != null && !childRoles.isEmpty()) {
286                         for (Object o : childRoles) {
287                                 EPRole childRole = (EPRole) o;
288
289                                 if (childRole.getActive()) {
290                                         roles.put(childRole.getId(), childRole);
291
292                                         addChildRoles(childRole, roles);
293                                 }
294                         }
295                 }
296
297         }
298
299         public static boolean hasRole(EPUser user, String roleKey) {
300                 return getAllUserRoles(user).keySet().contains(new Long(roleKey));
301         }
302
303         public static DataAccessService getDataAccessService() {
304                 return dataAccessService;
305         }
306
307         @Autowired
308         public static void setDataAccessService(DataAccessService dataAccessService) {
309                 EPUserUtils.dataAccessService = dataAccessService;
310         }
311
312         /**
313          * Gets the user's ID from the user object in the session
314          * 
315          * @param request
316          *            HttpServletRequest
317          * @return Integer ID of current user
318          */
319         public static int getUserId(HttpServletRequest request) {
320                 return getUserIdAsLong(request).intValue();
321         }
322
323         /**
324          * Gets the user's ID from the user object in the session
325          * 
326          * @param request
327          *            HttpServletREquest
328          * @return Long ID of current user
329          */
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();
334                 }
335                 return userId;
336         }
337
338         /**
339          * Gets the request ID from the request.
340          * 
341          * @param request
342          *            HttpServletRequest
343          * @return Request ID
344          */
345         public static String getRequestId(HttpServletRequest request) {
346                 Enumeration<String> headerNames = request.getHeaderNames();
347
348                 String requestId = "";
349                 try {
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);
356                                         break;
357                                 }
358                         }
359                 } catch (Exception e) {
360                         logger.error(EELFLoggerDelegate.errorLogger, "getRequestId failed", e);
361                 }
362
363                 return (requestId.isEmpty() ? UUID.randomUUID().toString() : requestId);
364         }
365
366         /**
367          * Gets the full URL from the request.
368          * 
369          * @param request
370          *            HttpServletRequest
371          * @return Full URL
372          */
373         static String getFullURL(HttpServletRequest request) {
374                 if (request != null) {
375                         StringBuffer requestURL = request.getRequestURL();
376                         String queryString = request.getQueryString();
377
378                         if (queryString == null) {
379                                 return requestURL.toString();
380                         } else {
381                                 return requestURL.append('?').append(queryString).toString();
382                         }
383                 }
384                 return "";
385         }
386
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("/");
395                                         boolean b = true;
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]);
401                                                                         b = m.matches();
402                                                                 }
403                                                         }
404                                                 if (b) return true;
405                                         }
406                                 }
407                         }
408                 } else {
409                         for (String roleFunction : roleFunctions) {
410                                 if (roleFunction.equals(("*"))) {
411                                         return true;
412                                 } else if (portalApiPath.matches(roleFunction)) {
413                                         return true;
414                                 }
415                         }
416                 }
417                 return false;
418         }
419 }