-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathSessionResource.java
More file actions
313 lines (282 loc) · 11 KB
/
Copy pathSessionResource.java
File metadata and controls
313 lines (282 loc) · 11 KB
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
/*******************************************************************************
* Copyright 2015 Defense Health Agency (DHA)
*
* If your use of this software does not include any GPLv2 components:
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file 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.
* ----------------------------------------------------------------------------
* If your use of this software includes any GPLv2 components:
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*******************************************************************************/
package prerna.semoss.web.services.local;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.catalina.core.ApplicationContext;
import org.apache.catalina.core.ApplicationContextFacade;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.session.StandardManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.owasp.encoder.Encode;
import jakarta.annotation.security.PermitAll;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.Response;
import prerna.auth.User;
import prerna.om.Insight;
import prerna.om.InsightStore;
import prerna.util.Constants;
import prerna.util.insight.InsightUtility;
import prerna.web.conf.DBLoader;
import prerna.web.services.util.WebUtility;
@Path("/session")
@PermitAll
public class SessionResource {
private static final Logger classLogger = LogManager.getLogger(SessionResource.class);
private static final String CANCEL_INVALIDATION = "cancelInvalidation";
private Object lock = new Object();
/**
* Returns the number of active servers related to a given manager.
*
* @param request
* @return
*/
@GET
@Path("/active")
@Produces("application/json;charset=utf-8")
public Response getActiveSessions(@Context HttpServletRequest request) {
Map<String, Object> ret = new HashMap<>();
HttpSession session = request.getSession(true);
try {
User user = null;
if (session != null) {
user = (User) session.getAttribute(Constants.SESSION_USER);
}
classLogger.info("User is pulling the # of active sessions");
StandardManager manager = getManager(session);
if (manager != null) {
int sessions = manager.getActiveSessions();
if (session.isNew()) {
sessions -= 1;
}
ret.put("activeSessions", sessions);
} else {
ret.put("activeSessions", "Error in getting manager context");
}
} finally {
if (session.isNew()) {
session.invalidate();
}
}
return WebUtility.getResponse(ret, 200);
}
/**
* Getting the manager
*
* @param request
*/
public static StandardManager getManager(HttpSession session) {
ApplicationContextFacade applicationContextFacade = (ApplicationContextFacade) session.getServletContext();
try {
Field applicationContextField = applicationContextFacade.getClass().getDeclaredField("context");
applicationContextField.setAccessible(true);
ApplicationContext appContext = (ApplicationContext) applicationContextField.get(applicationContextFacade);
Field standardContextField = appContext.getClass().getDeclaredField("context");
standardContextField.setAccessible(true);
StandardContext standardContext = (StandardContext) standardContextField.get(appContext);
return (StandardManager) standardContext.getManager();
} catch (IllegalAccessException | IllegalArgumentException | NoSuchFieldException | SecurityException e) {
classLogger.error("Failed to access the StandardManager from the servlet context via reflection", e);
}
return null;
}
/*
* End points for cleanup of the thread to account for closing/opening
*/
@POST
@Path("/cleanSession")
@Produces("application/json;charset=utf-8")
public Response cleanSession(@Context HttpServletRequest request) {
// need to compare when this method was called
// to a potential cancellation
Date execTime = new Date();
HttpSession session = request.getSession(false);
if (session == null) {
classLogger.info("Invalid session for cleaning");
Map<String, String> ret = new HashMap<>();
ret.put("output", "Invalid session");
return WebUtility.getResponse(ret, 400);
}
classLogger.info("Start invalidation of session");
String sessionId = session.getId();
// clear up insight store
InsightStore inStore = InsightStore.getInstance();
Set<String> insightIDs = inStore.getInsightIDsForSession(sessionId);
if (insightIDs != null) {
Set<String> copy = new HashSet<>(insightIDs);
for (String insightId : copy) {
Insight insight = InsightStore.getInstance().get(insightId);
if (insight == null) {
continue;
}
InsightUtility.dropInsight(insight);
}
classLogger.info("Successfully removed insight information from session");
// clear the current session store
insightIDs.removeAll(copy);
}
// wait 10 seconds
try {
Thread.sleep(10_000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
classLogger.error("Interrupted while waiting to invalidate the session during cleanup", e);
}
String output = null;
if (request.isRequestedSessionIdValid()) {
// did the FE at any point cancel this clean?
Date cancelTime = null;
synchronized (lock) {
cancelTime = (Date) session.getAttribute(CANCEL_INVALIDATION);
}
if (cancelTime == null) {
// kill the entire session
classLogger.info("Invalidating session");
session.invalidate();
output = "invalidated";
} else {
boolean isCancelled = execTime.before(cancelTime);
if (isCancelled) {
classLogger.info("Cancelled invalidating session");
output = "cancelled";
} else {
// kill the entire session
classLogger.info("Invalidating session");
session.invalidate();
output = "invalidated";
}
}
} else {
// in case during the time this was called
// the session has been invalidated by some other means
// like a logout
classLogger.info("Session has already been invalidated");
output = "invalidated";
}
Map<String, String> ret = new HashMap<>();
ret.put("output", output);
return WebUtility.getResponse(ret, 200);
}
@POST
@Path("/cancelCleanSession")
@Produces("application/json;charset=utf-8")
public Response cancelCleanSession(@Context HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
Map<String, String> ret = new HashMap<>();
ret.put("output", "Invalid session");
return WebUtility.getResponse(ret, 400);
}
classLogger.info("Cancelling invalidation...");
Date d = new Date();
synchronized (lock) {
session.setAttribute(CANCEL_INVALIDATION, d);
}
Map<String, String> ret = new HashMap<>();
ret.put("output", "cancel");
return WebUtility.getResponse(ret, 200);
}
@GET
@Path("/invalidateSession")
@Produces("application/json;charset=utf-8")
public void invalidateSession(@Context HttpServletRequest request, @Context HttpServletResponse response)
throws IOException {
String redirectUrl = request.getHeader("referer");
response.setStatus(302);
HttpSession session = request.getSession(false);
User thisUser = null;
if (session != null) {
thisUser = (User) session.getAttribute(Constants.SESSION_USER);
}
// log the user logout
classLogger.info("User is being forcibly invalidated");
// redirect to login/logout page
if (DBLoader.useLogoutPage()) {
classLogger.info("Session ended. Redirect to logout page");
String customUrl = DBLoader.getCustomLogoutUrl();
if (customUrl != null && !customUrl.isEmpty()) {
response.setHeader("redirect", customUrl);
response.sendError(302, "Need to redirect to " + customUrl);
} else {
String scheme = WebUtility.inputSQLSanitizer(request.getScheme()); // http
if (!scheme.trim().equalsIgnoreCase("https") && !scheme.trim().equalsIgnoreCase("http")) {
throw new IllegalArgumentException("scheme is invalid, please input proper scheme");
}
String serverName = WebUtility.inputSQLSanitizer(request.getServerName()); // hostname.com
int serverPort = request.getServerPort(); // 8080
String contextPath = WebUtility.inputSQLSanitizer(request.getContextPath()); // /Monolith
redirectUrl = "";
redirectUrl += scheme + "://" + serverName;
if (serverPort != 80 && serverPort != 443) {
redirectUrl += ":" + serverPort;
}
redirectUrl += contextPath + "/logout/";
redirectUrl = WebUtility.cleanHttpResponse(redirectUrl);
response.setHeader("redirect", redirectUrl);
response.sendError(302, "Need to redirect to " + redirectUrl);
}
} else {
classLogger.info("Session ended. Redirect to login page");
redirectUrl = redirectUrl + WebUtility.determineLoginExtension(request);
String encodedRedirectUrl = Encode.forHtml(redirectUrl);
response.setHeader("redirect", encodedRedirectUrl);
response.sendError(302, "Need to redirect to " + encodedRedirectUrl);
}
if (session != null) {
classLogger.info("Invalidating session");
session.invalidate();
}
}
@GET
@Path("/insights")
@Produces("application/json;charset=utf-8")
public Response getInsights(@Context HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
Map<String, String> ret = new HashMap<>();
ret.put("output", "Invalid session");
return WebUtility.getResponse(ret, 400);
}
String sessionId = session.getId();
Set<String> ids = InsightStore.getInstance().getInsightIDsForSession(sessionId);
return WebUtility.getResponse(ids, 200);
}
}