Ecomp DTO up
[portal.git] / portal-BE / src / main / java / org / onap / portal / utils / EPUserUtils.java
1 /*
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ===================================================================
9  *
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
14  *
15  *             http://www.apache.org/licenses/LICENSE-2.0
16  *
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.
22  *
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
27  *
28  *             https://creativecommons.org/licenses/by/4.0/
29  *
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.
35  *
36  * ============LICENSE_END============================================
37  *
38  *
39  */
40
41 package org.onap.portal.utils;
42
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;
48 import java.util.Map;
49 import java.util.Set;
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.FnUser;
62 import org.onap.portal.domain.db.fn.FnUserRole;
63 import org.onap.portal.exception.RoleFunctionException;
64 import org.onap.portal.service.fn.old.EPRoleFunctionService;
65 import org.onap.portalsdk.core.domain.RoleFunction;
66 import org.onap.portalsdk.core.exception.SessionExpiredException;
67 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
68 import org.onap.portalsdk.core.menu.MenuBuilder;
69 import org.onap.portalsdk.core.service.DataAccessService;
70 import org.onap.portalsdk.core.util.SystemProperties;
71 import org.onap.portalsdk.core.web.support.AppUtils;
72 import org.springframework.beans.factory.annotation.Autowired;
73
74 @NoArgsConstructor
75 public class EPUserUtils {
76
77        public static final String ALL_ROLE_FUNCTIONS = "allRoleFunctions";
78
79        private static final String decodeValueOfForwardSlash = "2f";
80        private static final String decodeValueOfHyphen = "2d";
81        private static final String decodeValueOfAsterisk = "2a";
82        private static final Long ACCOUNT_ADMIN_ROLE_ID = 999L;
83
84        private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPUserUtils.class);
85        private static DataAccessService dataAccessService;
86
87        /**
88         * Gets the EPUser object from the session.
89         *
90         * @param request HttpServletRequest
91         * @return EPUser object that was created upon login
92         * @throws SessionExpiredException if no session exists.
93         */
94        public static FnUser getUserSession(HttpServletRequest request) {
95               HttpSession session = AppUtils.getSession(request);
96               if (session == null) {
97                      throw new SessionExpiredException();
98               }
99               return (FnUser) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
100        }
101
102        /**
103         * Establishes the user's portal session
104         *
105         * @param request HttpServletRequest
106         * @param user EPUser
107         * @param applicationMenuData Menu data
108         * @param businessDirectMenuData Menu data
109         * @param ePRoleFunctionService role function service
110         */
111        @SuppressWarnings("rawtypes")
112        public static void setUserSession(HttpServletRequest request, FnUser user, Set applicationMenuData,
113                Set businessDirectMenuData, EPRoleFunctionService ePRoleFunctionService) throws RoleFunctionException {
114               HttpSession session = request.getSession(true);
115
116               // clear the current user session to avoid any conflicts
117               EPUserUtils.clearUserSession(request);
118               session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user);
119
120               setAllRoleFunctions(ePRoleFunctionService.getRoleFunctions(), session);
121
122               ePRoleFunctionService.getRoleFunctions(request, user);
123
124               // truncate the role (and therefore the role function) data to save
125               // memory in the session
126               user.setFnRoles(null);
127               session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_NAME), user.getFullName());
128
129               ServletContext context = session.getServletContext();
130               try {
131                      context.getAttribute("licenseVerification");
132               } catch (Exception e) {
133                      logger.error(EELFLoggerDelegate.errorLogger,
134                              "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 attribute.
146         *
147         * @param allRoleFunctions List of role functions.
148         * @param session HttpSession
149         */
150        private static void setAllRoleFunctions(List<RoleFunction> allRoleFunctions, HttpSession session)
151                throws RoleFunctionException {
152               if (allRoleFunctions == null) {
153                      return;
154               }
155               Set<String> roleFnSet = new HashSet<>();
156               for (RoleFunction roleFn : allRoleFunctions) {
157                      roleFnSet.add(decodeFunctionCode(roleFn.getCode()));
158               }
159               session.setAttribute(ALL_ROLE_FUNCTIONS, roleFnSet);
160        }
161
162
163        public static String decodeFunctionCode(String str) throws RoleFunctionException {
164               String decodedString = str;
165               List<Pattern> decodingList = new ArrayList<>();
166               decodingList.add(Pattern.compile(decodeValueOfForwardSlash));
167               decodingList.add(Pattern.compile(decodeValueOfHyphen));
168               decodingList.add(Pattern.compile(decodeValueOfAsterisk));
169               for (Pattern xssInputPattern : decodingList) {
170                      try {
171                             decodedString = decodedString.replaceAll("%" + xssInputPattern,
172                                     new String(Hex.decodeHex(xssInputPattern.toString().toCharArray())));
173                      } catch (DecoderException e) {
174                             logger.error(EELFLoggerDelegate.errorLogger, "Failed to decode the Rolefunction: " + str,
175                                     e);
176                             throw new RoleFunctionException("decode failed", e);
177                      }
178               }
179
180               return decodedString;
181        }
182
183        /**
184         * Removes all stored attributes from the user's session
185         *
186         * @param request HttpServletRequest
187         * @throws SessionExpiredException if no session exists
188         */
189        private static void clearUserSession(HttpServletRequest request) {
190               HttpSession session = AppUtils.getSession(request);
191               if (session == null) {
192                      throw new SessionExpiredException();
193               }
194
195               // removes all stored attributes from the current user's session
196               session.removeAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
197               session.removeAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME));
198               session.removeAttribute(
199                       SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME));
200               session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME));
201               session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME));
202        }
203
204        /**
205         * Gets role information from the user session, in the cached user object. As a side effect sets a session
206         * variable with the roles.
207         *
208         * @param request HttpServletRequest
209         * @return Map of role ID to role object
210         */
211        @SuppressWarnings("rawtypes")
212        public static Map getRoles(HttpServletRequest request) {
213               HashMap roles;
214
215               HttpSession session = AppUtils.getSession(request);
216               roles = (HashMap) session
217                       .getAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME));
218
219               // if roles are not already cached, let's grab them from the user
220               // session
221               if (roles == null) {
222                      FnUser user = getUserSession(request);
223
224                      // get all user roles (including the tree of child roles)
225                      roles = getAllUserRoles(user);
226
227                      session.setAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME), roles);
228               }
229
230               return roles;
231        }
232
233        /**
234         * Builds a map of role ID to role object.
235         *
236         * @param user EPUser
237         * @return Map of role ID to role object
238         */
239        @SuppressWarnings({"rawtypes", "unchecked"})
240        private static HashMap getAllUserRoles(FnUser user) {
241               HashMap roles = new HashMap();
242
243               for (FnRole role : user.getFnRoles()) {
244                      if (role.getActiveYn()) {
245                             roles.put(role.getId(), role);
246                             addChildRoles(role, roles);
247                      }
248               }
249
250               // Additionally; the account admin role is overloaded between onap
251               // portal and partners; lets also include that
252               for (FnUserRole epUserApp : user.getFnUserRoles()) {
253                      FnRole role = epUserApp.getRoleId();
254
255                      if (role.getActiveYn() && role.getRoleId().equals(ACCOUNT_ADMIN_ROLE_ID)) {
256                             roles.put(role.getId(), role);
257
258                             // let's take a recursive trip down the tree to add all child
259                             // roles
260                             addChildRoles(role, roles);
261                      }
262               }
263
264               return roles;
265        }
266
267        /**
268         * Adds all child roles of the specified role to the map of roles.
269         *
270         * @param role EPRole
271         * @param roles Maps role id to role object
272         */
273        @SuppressWarnings({"rawtypes", "unchecked"})
274        private static void addChildRoles(FnRole role, HashMap roles) {
275               Set<FnRole> childRoles = role.getFnRoles();
276               if (childRoles != null && !childRoles.isEmpty()) {
277                      for (Object o : childRoles) {
278                             FnRole childRole = (FnRole) o;
279                             if (childRole.getActiveYn()) {
280                                    roles.put(childRole.getId(), childRole);
281                                    addChildRoles(childRole, roles);
282                             }
283                      }
284               }
285
286        }
287
288        public static boolean hasRole(FnUser user, String roleKey) {
289               return getAllUserRoles(user).keySet().contains(new Long(roleKey));
290        }
291
292        public static DataAccessService getDataAccessService() {
293               return dataAccessService;
294        }
295
296        @Autowired
297        public static void setDataAccessService(DataAccessService dataAccessService) {
298               EPUserUtils.dataAccessService = dataAccessService;
299        }
300
301        /**
302         * Gets the user's ID from the user object in the session
303         *
304         * @param request HttpServletRequest
305         * @return Integer ID of current user
306         */
307        public static int getUserId(HttpServletRequest request) {
308               return getUserIdAsLong(request).intValue();
309        }
310
311        /**
312         * Gets the user's ID from the user object in the session
313         *
314         * @param request HttpServletREquest
315         * @return Long ID of current user
316         */
317        static Long getUserIdAsLong(HttpServletRequest request) {
318               Long userId = new Long(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID));
319               if (request != null && getUserSession(request) != null) {
320                      userId = getUserSession(request).getId();
321               }
322               return userId;
323        }
324
325        /**
326         * Gets the request ID from the request.
327         *
328         * @param request HttpServletRequest
329         * @return Request ID
330         */
331        public static String getRequestId(HttpServletRequest request) {
332               Enumeration<String> headerNames = request.getHeaderNames();
333
334               String requestId = "";
335               try {
336                      while (headerNames.hasMoreElements()) {
337                             String headerName = headerNames.nextElement();
338                             logger.debug(EELFLoggerDelegate.debugLogger,
339                                     "One header is " + headerName + " : " + request.getHeader(headerName));
340                             if (headerName.equalsIgnoreCase(SystemProperties.ECOMP_REQUEST_ID)) {
341                                    requestId = request.getHeader(headerName);
342                                    break;
343                             }
344                      }
345               } catch (Exception e) {
346                      logger.error(EELFLoggerDelegate.errorLogger, "getRequestId failed", e);
347               }
348
349               return (requestId.isEmpty() ? UUID.randomUUID().toString() : requestId);
350        }
351
352        /**
353         * Gets the full URL from the request.
354         *
355         * @param request HttpServletRequest
356         * @return Full URL
357         */
358        static String getFullURL(HttpServletRequest request) {
359               if (request != null) {
360                      StringBuffer requestURL = request.getRequestURL();
361                      String queryString = request.getQueryString();
362
363                      if (queryString == null) {
364                             return requestURL.toString();
365                      } else {
366                             return requestURL.append('?').append(queryString).toString();
367                      }
368               }
369               return "";
370        }
371
372        public static Boolean matchRoleFunctions(String portalApiPath, Set<? extends String> roleFunctions) {
373               String[] path = portalApiPath.split("/");
374               List<String> roleFunList;
375               if (path.length > 1) {
376                      roleFunList = roleFunctions.stream().filter(item -> item.startsWith(path[0]))
377                              .collect(Collectors.toList());
378                      if (roleFunList.size() >= 1) {
379                             for (String roleFunction : roleFunList) {
380                                    String[] roleFunctionArray = roleFunction.split("/");
381                                    boolean b = true;
382                                    if (roleFunctionArray.length == path.length) {
383                                           for (int i = 0; i < roleFunctionArray.length; i++) {
384                                                  if (!roleFunctionArray[i].equals("*")) {
385                                                         Pattern p = Pattern.compile(Pattern.quote(path[i]),
386                                                                 Pattern.CASE_INSENSITIVE);
387                                                         Matcher m = p.matcher(roleFunctionArray[i]);
388                                                         b = m.matches();
389                                                  }
390                                           }
391                                           if (b) {
392                                                  return true;
393                                           }
394                                    }
395                             }
396                      }
397               } else {
398                      for (String roleFunction : roleFunctions) {
399                             if (roleFunction.equals(("*"))) {
400                                    return true;
401                             } else if (portalApiPath.matches(roleFunction)) {
402                                    return true;
403                             }
404                      }
405               }
406               return false;
407        }
408 }