summaryrefslogtreecommitdiffstats
path: root/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/web/support/UserUtils.java
blob: 915f6e55c8d37591aea62ec3f590980bb591bbff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
/*
 * ============LICENSE_START==========================================
 * ONAP Portal SDK
 * ===================================================================
 * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
 * ===================================================================
 *
 * Unless otherwise specified, all software contained herein is licensed
 * under the Apache License, Version 2.0 (the "License");
 * you may not use this software except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *             http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Unless otherwise specified, all documentation contained herein is licensed
 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
 * you may not use this documentation except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *             https://creativecommons.org/licenses/by/4.0/
 *
 * Unless required by applicable law or agreed to in writing, documentation
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * ============LICENSE_END============================================
 *
 * 
 */
package org.onap.portalsdk.core.web.support;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.onap.portalsdk.core.domain.Role;
import org.onap.portalsdk.core.domain.RoleFunction;
import org.onap.portalsdk.core.domain.User;
import org.onap.portalsdk.core.exception.SessionExpiredException;
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
import org.onap.portalsdk.core.menu.MenuBuilder;
import org.onap.portalsdk.core.restful.domain.EcompRole;
import org.onap.portalsdk.core.restful.domain.EcompRoleFunction;
import org.onap.portalsdk.core.restful.domain.EcompUser;
import org.onap.portalsdk.core.util.SystemProperties;

import com.fasterxml.jackson.databind.ObjectMapper;

@SuppressWarnings("rawtypes")
public class UserUtils {

	private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserUtils.class);

	public static final String KEY_USER_ROLES_CACHE = "userRoles";

	public static void setUserSession(HttpServletRequest request, User user, Set applicationMenuData,
			Set businessDirectMenuData, String loginMethod, List<RoleFunction> roleFunctionList) {
		HttpSession session = request.getSession(true);

		UserUtils.clearUserSession(request); // let's clear the current user
												// session to avoid any
												// conflicts during the set

		session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user);
		session.setAttribute(SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_ATTRIBUTE_NAME), loginMethod);

		getRoleFunctions(request);

		session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_NAME), user.getFullName());
		session.setAttribute(SystemProperties.FIRST_NAME, user.getFirstName());
		session.setAttribute(SystemProperties.LAST_NAME, user.getLastName());
		session.setAttribute(SystemProperties.ROLE_FUNCTION_LIST, roleFunctionList);
		
		String displayName = "";
		if (SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME) != null)
			displayName = SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME);
		session.setAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME), displayName);
		session.setAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME),
				MenuBuilder.filterMenu(applicationMenuData, request));
		session.setAttribute(SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME),
				MenuBuilder.filterMenu(businessDirectMenuData, request));
	}

	public static void clearUserSession(HttpServletRequest request) {
		HttpSession session = AppUtils.getSession(request);

		if (session == null) {
			throw new SessionExpiredException();
		}

		// removes all stored attributes from the current user's session
		session.removeAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
		session.removeAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME));
		session.removeAttribute(SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME));
		session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME));
		session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME));
		session.removeAttribute(SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_ATTRIBUTE_NAME));
		session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTION_LIST));

	}

	@SuppressWarnings("unchecked")
	public static Set getRoleFunctions(HttpServletRequest request) {
		HttpSession session = request.getSession();
		HashSet roleFunctions = (HashSet) session
				.getAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME));

		if (roleFunctions == null) {
			Map roles = getRoles(request);
			roleFunctions = new HashSet();

			Iterator i = roles.keySet().iterator();

			while (i.hasNext()) {
				Long roleKey = (Long) i.next();
				Role role = (Role) roles.get(roleKey);

				Iterator j = role.getRoleFunctions().iterator();

				while (j.hasNext()) {
					RoleFunction function = (RoleFunction) j.next();
					roleFunctions.add(function.getCode());
				}
			}
			session.setAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME),
					roleFunctions);
		}
		return roleFunctions;
	}

	public static Map getRoles(HttpServletRequest request) {
		// HttpSession session = request.getSession();
		HttpSession session = AppUtils.getSession(request);
		Map roles = (Map) session.getAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME));

		// if roles are not already cached, let's grab them from the user
		// session
		if (roles == null) {
			User user = getUserSession(request);

			// get all user roles (including the tree of child roles)
			roles = getAllUserRoles(user);

			session.setAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME),
					getAllUserRoles(user));
		}

		return roles;
	}

	public static User getUserSession(HttpServletRequest request) {
		HttpSession session = AppUtils.getSession(request);

		if (session == null) {
			throw new SessionExpiredException();
		}

		return (User) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
	}

	@SuppressWarnings("unchecked")
	public static Map getAllUserRoles(User user) {
		HashMap roles = new HashMap();
		Iterator i = user.getRoles().iterator();

		while (i.hasNext()) {
			Role role = (Role) i.next();

			if (role.getActive()) {
				roles.put(role.getId(), role);

				// let's take a recursive trip down the tree to add all child
				// roles
				addChildRoles(role, roles);
			}
		}

		return roles;
	}

	@SuppressWarnings("unchecked")
	private static void addChildRoles(Role role, Map roles) {
		Set childRoles = role.getChildRoles();
		if (childRoles != null && !childRoles.isEmpty()) {
			Iterator j = childRoles.iterator();
			while (j.hasNext()) {
				Role childRole = (Role) j.next();
				if (childRole.getActive()) {
					roles.put(childRole.getId(), childRole);
					addChildRoles(childRole, roles);
				}
			}
		}

	}

	public static boolean hasRole(HttpServletRequest request, String roleKey) {
		return getRoles(request).keySet().contains(new Long(roleKey));
	}

	public static boolean hasRole(User user, String roleKey) {
		return getAllUserRoles(user).keySet().contains(new Long(roleKey));
	}

	public static boolean isAccessible(HttpServletRequest request, String functionKey) {
		return getRoleFunctions(request).contains(functionKey);
	}

	public static String getLoginMethod(HttpServletRequest request) {
		HttpSession session = AppUtils.getSession(request);

		if (session == null) {
			throw new SessionExpiredException();
		}

		return (String) session
				.getAttribute(SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_ATTRIBUTE_NAME));
	}

	public static int getUserId(HttpServletRequest request) {
		return getUserIdAsLong(request).intValue();
	}

	public static Long getUserIdAsLong(HttpServletRequest request) {
		Long userId = new Long(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID));
		if (request != null  && getUserSession(request) != null) 
				userId = getUserSession(request).getId();

		return userId;
	}

	private static final Object stackTraceLock = new Object();

	/**
	 * Serializes a stack trace of the specified throwable and returns it as a
	 * string.
	 * 
	 * TODO: why is synchronization required?
	 * 
	 * @param t
	 * @return String version of stack trace
	 */
	public static String getStackTrace(Throwable t) {
		synchronized (stackTraceLock) {
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw);
			t.printStackTrace(pw);
			return sw.toString();
		}
	}

	/**
	 * Gets the full URL of the request by joining the request and any query string.
	 * 
	 * @param request
	 * @return Full URL of the request including query parameters
	 */
	public static String getFullURL(HttpServletRequest request) {
		if (request != null) {
			StringBuffer requestURL = request.getRequestURL();
			String queryString = request.getQueryString();

			if (queryString == null) {
				return requestURL.toString();
			} else {
				return requestURL.append('?').append(queryString).toString();
			}
		}
		return "";
	}

	/**
	 * Gets or generates a request ID by searching for header X-ECOMP-RequestID. If
	 * not found, generates a new random UUID.
	 * 
	 * @param request
	 * @return Request ID for the specified request
	 */
	public static String getRequestId(HttpServletRequest request) {
		Enumeration<String> headerNames = request.getHeaderNames();

		String requestId = "";
		try {
			while (headerNames.hasMoreElements()) {
				String headerName = headerNames.nextElement();
				if (logger.isTraceEnabled())
					logger.trace(EELFLoggerDelegate.debugLogger, "getRequestId: header {} = {}", headerName,
							request.getHeader(headerName));
				if (headerName.equalsIgnoreCase(SystemProperties.ECOMP_REQUEST_ID)) {
					requestId = request.getHeader(headerName);
					break;
				}
			}
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.debugLogger, "getRequestId: failed to get headder", e);
		}

		if (requestId.isEmpty())
			requestId = UUID.randomUUID().toString();
		logger.debug(EELFLoggerDelegate.debugLogger, "getRequestId: result is {}", requestId);
		return requestId;
	}

	/**
	 * Converts a Hibernate-mapped User object to a JSON-serializable EcompUser
	 * object.
	 * 
	 * @param user
	 * @return EcompUser with a subset of fields.
	 */
	public static EcompUser convertToEcompUser(User user) {
		ObjectMapper mapper = new ObjectMapper();

		EcompUser userJson = new EcompUser();
		userJson.setEmail(user.getEmail());
		userJson.setFirstName(user.getFirstName());
		userJson.setHrid(user.getHrid());
		userJson.setJobTitle(user.getJobTitle());
		userJson.setLastName(user.getLastName());
		userJson.setLoginId(user.getLoginId());
		userJson.setOrgManagerUserId(user.getOrgManagerUserId());
		userJson.setMiddleInitial(user.getMiddleInitial());
		userJson.setOrgCode(user.getOrgCode());
		userJson.setOrgId(user.getOrgId());
		userJson.setPhone(user.getPhone());
		userJson.setOrgUserId(user.getOrgUserId());
		userJson.setActive(user.getActive());
		Set<EcompRole> ecompRoles = new TreeSet<>();
		Set<Role> roles = user.getRoles();
		Iterator<Role> roleIter = roles.iterator();

		while (roleIter.hasNext()) {
			Object nextValue = roleIter.next();
			Role role = mapper.convertValue(nextValue, Role.class);
			ecompRoles.add(convertToEcompRole(role));
		}
		userJson.setRoles(ecompRoles);
		return userJson;
	}

	/**
	 * Converts a Hibernate-mapped Role object to a JSON-serializable EcompRole
	 * object.
	 * 
	 * @param role
	 * @return EcompRole with a subset of fields: ID and name
	 */
    public static EcompRole convertToEcompRole(Role role) {
		ObjectMapper mapper = new ObjectMapper();

        EcompRole ecompRole = new EcompRole();
        ecompRole.setId(role.getId());
        ecompRole.setName(role.getName());
        Set<EcompRoleFunction> ecompRolefunctions = new TreeSet<>();
        @SuppressWarnings("unchecked")
        Set<RoleFunction> rolefunctions = role.getRoleFunctions();
        Iterator<RoleFunction> roleFnIter = rolefunctions.iterator();
        while (roleFnIter.hasNext()) {
			Object nextValue = roleFnIter.next();
			RoleFunction roleFunction = mapper.convertValue(nextValue, RoleFunction.class);
            ecompRolefunctions.add(convertToEcompRoleFunction(roleFunction));
        }
        ecompRole.setRoleFunctions(ecompRolefunctions);
        return ecompRole;
 }
 
 public static EcompRoleFunction convertToEcompRoleFunction(RoleFunction rolefun)
 {
        EcompRoleFunction ecompRoleFunction = new EcompRoleFunction();
        ecompRoleFunction.setName(rolefun.getName());
        ecompRoleFunction.setCode(rolefun.getCode());
        ecompRoleFunction.setType(rolefun.getType());
        ecompRoleFunction.setAction(rolefun.getAction());
        return ecompRoleFunction;
 }
 


}