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