[PORTAL-16 PORTAL-18] Widget ms; staging
[portal.git] / ecomp-portal-BE-common / src / main / java / org / openecomp / portalapp / util / EPUserUtils.java
1 /*-
2  * ================================================================================
3  * ECOMP Portal
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ================================================================================
19  */
20 package org.openecomp.portalapp.util;
21
22 import java.util.Enumeration;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.Iterator;
26 import java.util.List;
27 import java.util.Set;
28 import java.util.UUID;
29
30 import javax.servlet.ServletContext;
31 import javax.servlet.http.HttpServletRequest;
32 import javax.servlet.http.HttpSession;
33
34 import org.openecomp.portalapp.portal.domain.EPRole;
35 import org.openecomp.portalapp.portal.domain.EPUser;
36 import org.openecomp.portalapp.portal.domain.EPUserApp;
37 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
38 import org.openecomp.portalsdk.core.domain.RoleFunction;
39 import org.openecomp.portalsdk.core.exception.SessionExpiredException;
40 import org.openecomp.portalsdk.core.lm.FusionLicenseManager;
41 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
42 import org.openecomp.portalsdk.core.menu.MenuBuilder;
43 import org.openecomp.portalsdk.core.service.DataAccessService;
44 import org.openecomp.portalsdk.core.util.SystemProperties;
45 import org.openecomp.portalsdk.core.web.support.AppUtils;
46 import org.springframework.beans.factory.annotation.Autowired;
47
48 public class EPUserUtils {
49
50         private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPUserUtils.class);
51
52         private final static Long ACCOUNT_ADMIN_ROLE_ID = 999L;
53
54         public static final String ALL_ROLE_FUNCTIONS = "allRoleFunctions";
55
56         private static DataAccessService dataAccessService;
57
58         /**
59          * Gets the EPUser object from the session.
60          * 
61          * @param request
62          *            HttpServletRequest
63          * @return EPUser object that was created upon login
64          * @throws SessionExpiredException
65          *             if no session exists.
66          */
67         public static EPUser getUserSession(HttpServletRequest request) {
68                 HttpSession session = AppUtils.getSession(request);
69                 if (session == null)
70                         throw new SessionExpiredException();
71                 return (EPUser) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
72         }
73
74         /**
75          * Establishes the user's portal session
76          * 
77          * @param request
78          *            HttpServletRequest
79          * @param user
80          *            EPUser
81          * @param applicationMenuData
82          *            Menu data
83          * @param businessDirectMenuData
84          *            Menu data
85          * @param loginMethod_ignored
86          *            How the user authenticated; ignored
87          * @param allRoleFunctions
88          *            Set of user's roles
89          */
90         @SuppressWarnings("rawtypes")
91         public static void setUserSession(HttpServletRequest request, EPUser user, Set applicationMenuData,
92                         Set businessDirectMenuData, String loginMethod_ignored, List<RoleFunction> allRoleFunctions) {
93                 HttpSession session = request.getSession(true);
94
95                 // clear the current user session to avoid any conflicts
96                 EPUserUtils.clearUserSession(request);
97                 session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user);
98
99                 getAllRoleFunctions(allRoleFunctions, session);
100
101                 getRoleFunctions(request);
102
103                 // truncate the role (and therefore the role function) data to save
104                 // memory in the session
105                 user.setEPRoles(null);
106                 session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_NAME), user.getFullName());
107
108                 ServletContext context = session.getServletContext();
109                 int licenseVerificationFlag = 3;
110                 try {
111                         licenseVerificationFlag = (Integer) context.getAttribute("licenseVerification");
112                 } catch (Exception e) {
113                         logger.error(EELFLoggerDelegate.errorLogger, "setUserSession failed to get licenseVerification attribute",
114                                         e);
115                 }
116                 switch (licenseVerificationFlag) {
117                 case FusionLicenseManager.DEVELOPER_LICENSE:
118                         session.setAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME),
119                                         "My Portal [Development Version]");
120                         break;
121                 case FusionLicenseManager.EXPIRED_LICENSE:
122                         session.setAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME),
123                                         "My Portal [LICENSE EXPIRED]");
124                         break;
125                 case FusionLicenseManager.VALID_LICENSE:
126                         session.setAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME), "My Portal");
127                         break;
128                 default:
129                         session.setAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME),
130                                         "My Portal [INVALID LICENSE]");
131                         break;
132                 }
133
134                 session.setAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME),
135                                 MenuBuilder.filterMenu(applicationMenuData, request));
136                 session.setAttribute(SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME),
137                                 MenuBuilder.filterMenu(businessDirectMenuData, request));
138         }
139
140         /**
141          * Creates a set of role function names and stores the set as a session
142          * attribute.
143          * 
144          * @param allRoleFunctions
145          *            List of role functions.
146          * @param session
147          *            HttpSession
148          */
149         private static void getAllRoleFunctions(List<RoleFunction> allRoleFunctions, HttpSession session) {
150                 if (allRoleFunctions == null)
151                         return;
152                 Set<String> roleFnSet = new HashSet<String>();
153                 for (RoleFunction roleFn : allRoleFunctions)
154                         roleFnSet.add(roleFn.getCode());
155                 session.setAttribute(ALL_ROLE_FUNCTIONS, roleFnSet);
156         }
157
158         /**
159          * Removes all stored attributes from the user's session
160          * 
161          * @param request
162          *            HttpServletRequest
163          * @throws SessionExpiredException
164          *             if no session exists
165          */
166         private static void clearUserSession(HttpServletRequest request) {
167                 HttpSession session = AppUtils.getSession(request);
168                 if (session == null)
169                         throw new SessionExpiredException();
170
171                 // removes all stored attributes from the current user's session
172                 session.removeAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
173                 session.removeAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME));
174                 session.removeAttribute(SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME));
175                 session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME));
176                 session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME));
177         }
178
179         /**
180          * Builds a set of role functions and sets a session attribute with it.
181          * 
182          * @param request
183          *            HttpServletRequest
184          * @return Set of role functions that was built.
185          */
186         @SuppressWarnings({ "rawtypes", "unchecked" })
187         private static Set getRoleFunctions(HttpServletRequest request) {
188                 HashSet roleFunctions = null;
189
190                 HttpSession session = request.getSession();
191                 roleFunctions = (HashSet) session
192                                 .getAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME));
193
194                 if (roleFunctions == null) {
195                         HashMap roles = getRoles(request);
196                         roleFunctions = new HashSet();
197
198                         Iterator i = roles.keySet().iterator();
199
200                         while (i.hasNext()) {
201                                 Long roleKey = (Long) i.next();
202                                 EPRole role = (EPRole) roles.get(roleKey);
203
204                                 Iterator j = role.getRoleFunctions().iterator();
205
206                                 while (j.hasNext()) {
207                                         RoleFunction function = (RoleFunction) j.next();
208                                         roleFunctions.add(function.getCode());
209                                 }
210                         }
211
212                         session.setAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME),
213                                         roleFunctions);
214                 }
215
216                 return roleFunctions;
217         }
218
219         /**
220          * Gets role information from the user session, in the cached user object.
221          * As a side effect sets a session variable with the roles.
222          * 
223          * @param request
224          *            HttpServletRequest
225          * @return Map of role ID to role object
226          */
227         @SuppressWarnings("rawtypes")
228         private static HashMap getRoles(HttpServletRequest request) {
229                 HashMap roles = null;
230
231                 HttpSession session = AppUtils.getSession(request);
232                 roles = (HashMap) session.getAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME));
233
234                 // if roles are not already cached, let's grab them from the user
235                 // session
236                 if (roles == null) {
237                         EPUser user = getUserSession(request);
238
239                         // get all user roles (including the tree of child roles)
240                         roles = getAllUserRoles(user);
241
242                         session.setAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME), roles);
243                 }
244
245                 return roles;
246         }
247
248         /**
249          * Builds a map of role ID to role object.
250          * 
251          * @param user
252          *            EPUser
253          * @return Map of role ID to role object
254          */
255         @SuppressWarnings({ "rawtypes", "unchecked" })
256         private static HashMap getAllUserRoles(EPUser user) {
257                 HashMap roles = new HashMap();
258                 Iterator i = user.getEPRoles().iterator();
259
260                 while (i.hasNext()) {
261                         EPRole role = (EPRole) i.next();
262
263                         if (role.getActive()) {
264                                 roles.put(role.getId(), role);
265
266                                 // let's take a recursive trip down the tree to add all child
267                                 // roles
268                                 addChildRoles(role, roles);
269                         }
270                 }
271
272                 // Additionally; the account admin role is overloaded between ecomp
273                 // portal and partners; lets also include that
274                 Iterator<EPUserApp> appRolesIterator = user.getEPUserApps().iterator();
275                 while (appRolesIterator.hasNext()) {
276                         EPRole role = (EPRole) appRolesIterator.next().getRole();
277
278                         if (role.getActive() && role.getId().equals(ACCOUNT_ADMIN_ROLE_ID)) {
279                                 roles.put(role.getId(), role);
280
281                                 // let's take a recursive trip down the tree to add all child
282                                 // roles
283                                 addChildRoles(role, roles);
284                         }
285                 }
286
287                 return roles;
288         }
289
290         /**
291          * Adds all child roles of the specified role to the map of roles.
292          * 
293          * @param role
294          *            EPRole
295          * @param roles
296          *            Maps role id to role object
297          */
298         @SuppressWarnings({ "rawtypes", "unchecked" })
299         private static void addChildRoles(EPRole role, HashMap roles) {
300                 Set childRoles = role.getChildRoles();
301
302                 if (childRoles != null && childRoles.size() > 0) {
303                         Iterator j = childRoles.iterator();
304                         while (j.hasNext()) {
305                                 EPRole childRole = (EPRole) j.next();
306
307                                 if (childRole.getActive()) {
308                                         roles.put(childRole.getId(), childRole);
309
310                                         addChildRoles(childRole, roles);
311                                 }
312                         }
313                 }
314
315         }
316
317         public static boolean hasRole(EPUser user, String roleKey) {
318                 return getAllUserRoles(user).keySet().contains(new Long(roleKey));
319         }
320
321         public static DataAccessService getDataAccessService() {
322                 return dataAccessService;
323         }
324
325         @Autowired
326         public void setDataAccessService(DataAccessService dataAccessService) {
327                 EPUserUtils.dataAccessService = dataAccessService;
328         }
329
330         /**
331          * Gets the user's ID from the user object in the session
332          * 
333          * @param request
334          *            HttpServletRequest
335          * @return Integer ID of current user
336          */
337         public static int getUserId(HttpServletRequest request) {
338                 return getUserIdAsLong(request).intValue();
339         }
340
341         /**
342          * Gets the user's ID from the user object in the session
343          * 
344          * @param request
345          *            HttpServletREquest
346          * @return Long ID of current user
347          */
348         public static Long getUserIdAsLong(HttpServletRequest request) {
349                 Long userId = new Long(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID));
350                 if (request != null) {
351                         if (getUserSession(request) != null) {
352                                 userId = getUserSession(request).getId();
353                         }
354                 }
355                 return userId;
356         }
357
358         /**
359          * Gets the request ID from the request.
360          * 
361          * @param request
362          *            HttpServletRequest
363          * @return Request ID
364          */
365         public static String getRequestId(HttpServletRequest request) {
366                 Enumeration<String> headerNames = request.getHeaderNames();
367
368                 String requestId = "";
369                 try {
370                         while (headerNames.hasMoreElements()) {
371                                 String headerName = (String) headerNames.nextElement();
372                                 logger.debug(EELFLoggerDelegate.debugLogger,
373                                                 "One header is " + headerName + " : " + request.getHeader(headerName));
374                                 if (headerName.equalsIgnoreCase(SystemProperties.ECOMP_REQUEST_ID)) {
375                                         requestId = request.getHeader(headerName);
376                                         break;
377                                 }
378                         }
379                 } catch (Exception e) {
380                         logger.error(EELFLoggerDelegate.errorLogger, "HEADER!!!! Exception : " + EcompPortalUtils.getStackTrace(e));
381                 }
382
383                 return (requestId.isEmpty() ? UUID.randomUUID().toString() : requestId);
384         }
385
386         /**
387          * Gets the full URL from the request.
388          * 
389          * @param request
390          *            HttpServletRequest
391          * @return Full URL
392          */
393         public static String getFullURL(HttpServletRequest request) {
394                 if (request != null) {
395                         StringBuffer requestURL = request.getRequestURL();
396                         String queryString = request.getQueryString();
397
398                         if (queryString == null) {
399                                 return requestURL.toString();
400                         } else {
401                                 return requestURL.append('?').append(queryString).toString();
402                         }
403                 }
404                 return "";
405         }
406
407 }