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