Domain model change
[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.FnRoleComposite;
62 import org.onap.portal.domain.db.fn.FnUser;
63 import org.onap.portal.domain.db.fn.FnUserRole;
64 import org.onap.portal.domain.dto.transport.Role;
65 import org.onap.portal.exception.RoleFunctionException;
66 import org.onap.portal.service.fn.old.EPRoleFunctionService;
67 import org.onap.portalsdk.core.domain.RoleFunction;
68 import org.onap.portalsdk.core.exception.SessionExpiredException;
69 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
70 import org.onap.portalsdk.core.menu.MenuBuilder;
71 import org.onap.portalsdk.core.service.DataAccessService;
72 import org.onap.portalsdk.core.util.SystemProperties;
73 import org.onap.portalsdk.core.web.support.AppUtils;
74 import org.springframework.beans.factory.annotation.Autowired;
75
76 @NoArgsConstructor
77 public class EPUserUtils {
78
79        public static final String ALL_ROLE_FUNCTIONS = "allRoleFunctions";
80
81        private static final String decodeValueOfForwardSlash = "2f";
82        private static final String decodeValueOfHyphen = "2d";
83        private static final String decodeValueOfAsterisk = "2a";
84        private static final Long ACCOUNT_ADMIN_ROLE_ID = 999L;
85
86        private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPUserUtils.class);
87        private static DataAccessService dataAccessService;
88
89        /**
90         * Gets the EPUser object from the session.
91         *
92         * @param request HttpServletRequest
93         * @return EPUser object that was created upon login
94         * @throws SessionExpiredException if no session exists.
95         */
96        public static FnUser getUserSession(HttpServletRequest request) {
97               HttpSession session = AppUtils.getSession(request);
98               if (session == null) {
99                      throw new SessionExpiredException();
100               }
101               return (FnUser) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
102        }
103
104        /**
105         * Establishes the user's portal session
106         *
107         * @param request HttpServletRequest
108         * @param user EPUser
109         * @param applicationMenuData Menu data
110         * @param businessDirectMenuData Menu data
111         * @param ePRoleFunctionService role function service
112         */
113        @SuppressWarnings("rawtypes")
114        public static void setUserSession(HttpServletRequest request, FnUser user, Set applicationMenuData,
115                Set businessDirectMenuData, EPRoleFunctionService ePRoleFunctionService) throws RoleFunctionException {
116               HttpSession session = request.getSession(true);
117
118               // clear the current user session to avoid any conflicts
119               EPUserUtils.clearUserSession(request);
120               session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user);
121
122               setAllRoleFunctions(ePRoleFunctionService.getRoleFunctions(), session);
123
124               ePRoleFunctionService.getRoleFunctions(request, user);
125
126               // truncate the role (and therefore the role function) data to save
127               // memory in the session
128               user.setFnRoles(null);
129               session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_NAME), user.getFullName());
130
131               ServletContext context = session.getServletContext();
132               try {
133                      context.getAttribute("licenseVerification");
134               } catch (Exception e) {
135                      logger.error(EELFLoggerDelegate.errorLogger,
136                              "setUserSession failed to get licenseVerification attribute",
137                              e);
138               }
139               session.setAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME), "My Portal");
140               session.setAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME),
141                       MenuBuilder.filterMenu(applicationMenuData, request));
142               session.setAttribute(SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME),
143                       MenuBuilder.filterMenu(businessDirectMenuData, request));
144        }
145
146        /**
147         * Creates a set of role function names and stores the set as a session attribute.
148         *
149         * @param allRoleFunctions List of role functions.
150         * @param session HttpSession
151         */
152        private static void setAllRoleFunctions(List<RoleFunction> allRoleFunctions, HttpSession session)
153                throws RoleFunctionException {
154               if (allRoleFunctions == null) {
155                      return;
156               }
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 HttpServletRequest
189         * @throws SessionExpiredException if no session exists
190         */
191        private static void clearUserSession(HttpServletRequest request) {
192               HttpSession session = AppUtils.getSession(request);
193               if (session == null) {
194                      throw new SessionExpiredException();
195               }
196
197               // removes all stored attributes from the current user's session
198               session.removeAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
199               session.removeAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME));
200               session.removeAttribute(
201                       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 side effect sets a session
208         * variable with the roles.
209         *
210         * @param request HttpServletRequest
211         * @return Map of role ID to role object
212         */
213        @SuppressWarnings("rawtypes")
214        public static Map getRoles(HttpServletRequest request) {
215               HashMap roles;
216
217               HttpSession session = AppUtils.getSession(request);
218               roles = (HashMap) session
219                       .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                      FnUser 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 EPUser
239         * @return Map of role ID to role object
240         */
241        @SuppressWarnings({"rawtypes", "unchecked"})
242        private static HashMap getAllUserRoles(FnUser user) {
243               HashMap roles = new HashMap();
244
245               for (FnRole role : user.getFnRoles()) {
246                      if (role.getActiveYn()) {
247                             roles.put(role.getId(), role);
248                             addChildRoles(role, roles);
249                      }
250               }
251
252               // Additionally; the account admin role is overloaded between onap
253               // portal and partners; lets also include that
254               for (FnUserRole epUserApp : user.getUserApps()) {
255                      FnRole role = epUserApp.getRoleId();
256
257                      if (role.getActiveYn() && role.getId().equals(ACCOUNT_ADMIN_ROLE_ID)) {
258                             roles.put(role.getId(), role);
259
260                             // let's take a recursive trip down the tree to add all child
261                             // roles
262                             addChildRoles(role, roles);
263                      }
264               }
265
266               return roles;
267        }
268
269        /**
270         * Adds all child roles of the specified role to the map of roles.
271         *
272         * @param role EPRole
273         * @param roles Maps role id to role object
274         */
275        @SuppressWarnings({"rawtypes", "unchecked"})
276        private static void addChildRoles(FnRole role, HashMap roles) {
277               List<Role> childRoles = role.getChildRoles()
278                   .stream()
279                   .map(FnRoleComposite::getChildRoles)
280                   .collect(Collectors.toList());
281               if (!childRoles.isEmpty()) {
282                      for (Object o : childRoles) {
283                             FnRole childRole = (FnRole) o;
284                             if (childRole.getActiveYn()) {
285                                    roles.put(childRole.getId(), childRole);
286                                    addChildRoles(childRole, roles);
287                             }
288                      }
289               }
290
291        }
292
293        public static boolean hasRole(FnUser user, String roleKey) {
294               return getAllUserRoles(user).keySet().contains(new Long(roleKey));
295        }
296
297        public static DataAccessService getDataAccessService() {
298               return dataAccessService;
299        }
300
301        @Autowired
302        public static void setDataAccessService(DataAccessService dataAccessService) {
303               EPUserUtils.dataAccessService = dataAccessService;
304        }
305
306        /**
307         * Gets the user's ID from the user object in the session
308         *
309         * @param request HttpServletRequest
310         * @return Integer ID of current user
311         */
312        public static int getUserId(HttpServletRequest request) {
313               return getUserIdAsLong(request).intValue();
314        }
315
316        /**
317         * Gets the user's ID from the user object in the session
318         *
319         * @param request HttpServletREquest
320         * @return Long ID of current user
321         */
322        static Long getUserIdAsLong(HttpServletRequest request) {
323               Long userId = new Long(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID));
324               if (request != null && getUserSession(request) != null) {
325                      userId = getUserSession(request).getId();
326               }
327               return userId;
328        }
329
330        /**
331         * Gets the request ID from the request.
332         *
333         * @param request HttpServletRequest
334         * @return Request ID
335         */
336        public static String getRequestId(HttpServletRequest request) {
337               Enumeration<String> headerNames = request.getHeaderNames();
338
339               String requestId = "";
340               try {
341                      while (headerNames.hasMoreElements()) {
342                             String headerName = headerNames.nextElement();
343                             logger.debug(EELFLoggerDelegate.debugLogger,
344                                     "One header is " + headerName + " : " + request.getHeader(headerName));
345                             if (headerName.equalsIgnoreCase(SystemProperties.ECOMP_REQUEST_ID)) {
346                                    requestId = request.getHeader(headerName);
347                                    break;
348                             }
349                      }
350               } catch (Exception e) {
351                      logger.error(EELFLoggerDelegate.errorLogger, "getRequestId failed", e);
352               }
353
354               return (requestId.isEmpty() ? UUID.randomUUID().toString() : requestId);
355        }
356
357        /**
358         * Gets the full URL from the request.
359         *
360         * @param request HttpServletRequest
361         * @return Full URL
362         */
363        static String getFullURL(HttpServletRequest request) {
364               if (request != null) {
365                      StringBuffer requestURL = request.getRequestURL();
366                      String queryString = request.getQueryString();
367
368                      if (queryString == null) {
369                             return requestURL.toString();
370                      } else {
371                             return requestURL.append('?').append(queryString).toString();
372                      }
373               }
374               return "";
375        }
376
377        public static Boolean matchRoleFunctions(String portalApiPath, Set<? extends String> roleFunctions) {
378               String[] path = portalApiPath.split("/");
379               List<String> roleFunList;
380               if (path.length > 1) {
381                      roleFunList = roleFunctions.stream().filter(item -> item.startsWith(path[0]))
382                              .collect(Collectors.toList());
383                      if (roleFunList.size() >= 1) {
384                             for (String roleFunction : roleFunList) {
385                                    String[] roleFunctionArray = roleFunction.split("/");
386                                    boolean b = true;
387                                    if (roleFunctionArray.length == path.length) {
388                                           for (int i = 0; i < roleFunctionArray.length; i++) {
389                                                  if (!roleFunctionArray[i].equals("*")) {
390                                                         Pattern p = Pattern.compile(Pattern.quote(path[i]),
391                                                                 Pattern.CASE_INSENSITIVE);
392                                                         Matcher m = p.matcher(roleFunctionArray[i]);
393                                                         b = m.matches();
394                                                  }
395                                           }
396                                           if (b) {
397                                                  return true;
398                                           }
399                                    }
400                             }
401                      }
402               } else {
403                      for (String roleFunction : roleFunctions) {
404                             if (roleFunction.equals(("*"))) {
405                                    return true;
406                             } else if (portalApiPath.matches(roleFunction)) {
407                                    return true;
408                             }
409                      }
410               }
411               return false;
412        }
413 }