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