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