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