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
|
package com.kwoksys.framework.servlets;
import com.kwoksys.biz.ServiceProvider;
import com.kwoksys.biz.admin.AdminService;
import com.kwoksys.biz.admin.dto.AccessUser;
import com.kwoksys.biz.auth.AuthService;
import com.kwoksys.biz.auth.core.Access;
import com.kwoksys.biz.auth.core.AuthUtils;
import com.kwoksys.biz.auth.dto.AccessPage;
import com.kwoksys.biz.system.SystemService;
import com.kwoksys.biz.system.core.Localizer;
import com.kwoksys.biz.system.dto.SystemInfo;
import com.kwoksys.framework.common.RequestContext;
import com.kwoksys.framework.common.ResponseContext;
import com.kwoksys.framework.configs.ConfigManager;
import com.kwoksys.framework.configs.LogConfigManager;
import com.kwoksys.framework.exceptions.DatabaseException;
import com.kwoksys.framework.session.CacheManager;
import com.kwoksys.framework.session.CookieManager;
import com.kwoksys.framework.session.SessionManager;
import org.apache.struts.action.RequestProcessor;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Custom RequestProcessor.
*/
public class RequestProcessorServlet extends RequestProcessor {
private static final Logger logger = Logger.getLogger(RequestProcessorServlet.class.getName());
private SystemInfo systemInfo;
public void process(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
RequestContext requestContext = new RequestContext(request);
ResponseContext responseContext = new ResponseContext(response);
try {
// This line is required for utf-8 encoding to work.
request.setCharacterEncoding(ConfigManager.system.getCharacterEncoding());
// These lines are for making the app not to cache pages.
// Especially important for the AJAX to work correctly.
response.setHeader("Pragma", "no-cache"); // For HTTP/1.0 backward compatibility.
response.setHeader("Cache-Control", "no-cache"); // For HTTP/1.1.
((ServletRequest) response).setCharacterEncoding(ConfigManager.system.getCharacterEncoding());
// Pass pageStartTime to jsp pages.
request.setAttribute(RequestContext.PAGE_START_TIME, System.currentTimeMillis());
if (!validate(requestContext)) {
responseContext.sendServiceUnavailable();
return;
}
HttpSession session = request.getSession();
// Do this once for a session
initSession(session);
String requestPath = request.getRequestURI();
String pageName = request.getServletPath();
AccessPage accessPage = Access.getAccessPage(pageName);
Integer moduleId = accessPage == null ? 0 : accessPage.getModuleId();
request.setAttribute(RequestContext.PAGE_KEY, pageName);
request.setAttribute(RequestContext.MODULE_KEY, moduleId);
request.setAttribute(RequestContext.SYSDATE, systemInfo.getSysdate());
Cookie[] cookies = request.getCookies();
AccessUser user = Access.getCookieUser(cookies);
String sessionToken = CookieManager.getSessionToken(cookies).trim();
// Ready to serve the page, let's log it first.
logger.info(LogConfigManager.PAGE_REQUEST_PREFIX + " " + requestPath + ", user ID: " + user.getId());
AuthService authService = ServiceProvider.getAuthService(requestContext);
boolean isValidSessionToken = authService.isValidUserSession(user.getId(), sessionToken);
// Check if the session is valid
if (!isValidSessionToken) {
if (ConfigManager.auth.isBasicAuth()) {
if (!authService.isValidBasicAuthentication(user)) {
Access.requestBasicAuthCredential(requestContext, responseContext);
return;
} else {
// Initialize user session
authService.initializeUserSession(request, response, user);
}
} else if (user.isLoggedOn()) {
// If the user is already logged on, without a valid session token, empty auth cookies
AuthUtils.resetAuthCookies(response);
}
}
// This sounds un-necessary but during basic authentication, we could get a different id than
// what's stored in cookies.
AdminService adminService = ServiceProvider.getAdminService(requestContext);
user = adminService.getUser(user.getId());
request.setAttribute(RequestContext.USER_KEY, user);
if (Access.isPublicPage(pageName)) {
// No permission checking required for public pages.
} else if (accessPage == null) {
// We don't have such page, show a 404.
responseContext.sendNotFound();
return;
} else if (!Access.hasSpecialPagePermission(user, accessPage)) {
Access.forbidden(response);
return;
} else if (!isValidSessionToken && !ConfigManager.auth.isBasicAuth() && user.isLoggedOn()) {
Access.requestCredential(requestContext, responseContext, "sessionExpired");
return;
// We check whether the user is allowed to see pages that require permission.
} else if (!Access.hasPermission(user, pageName)) {
if (!user.isLoggedOn()) {
// Request username/password with error code loginRequired.
Access.requestCredential(requestContext, responseContext, "loginRequired");
return;
} else {
Access.forbidden(response);
return;
}
}
} catch (Exception e) {
// If there are errors with the request processor, don't go to the requested resource.
logger.log(Level.SEVERE, "Problem processing request filter.", e);
responseContext.sendServerError();
return;
}
try {
super.process(request, response);
} catch (Exception e) {
logger.log(Level.SEVERE, "Problem processing request.", e);
responseContext.sendServerError();
return;
}
}
private boolean validate(RequestContext requestContext) {
// Checks database availability by executing a query, also check to see if the current cache key matches
// cached cache key. This is for cache flushing across multiple servers.
SystemService systemService = ServiceProvider.getSystemService(requestContext);
if (!SystemInitServlet.init) {
logger.warning("System not initialized. " + SystemInitServlet.initError);
return false;
}
try {
systemInfo = systemService.getSystemInfo();
if (!systemInfo.getCacheKey().equals(ConfigManager.system.getCacheKey())) {
// Refresh the cache.
ConfigManager.init();
}
// Run a process to check if there are any caches to remove
new CacheManager(requestContext).checkRemoveCaches(systemInfo.getSysdate().getTime());
} catch (DatabaseException e) {
// Don't log anything
return false;
}
return true;
}
private static void initSession(HttpSession session) {
if (session.getAttribute(SessionManager.SESSION_INIT) == null) {
session.setAttribute(SessionManager.SESSION_INIT, true);
Localizer.setSessionLocale(session, ConfigManager.system.getLocaleString());
}
}
private static void printRequest(HttpServletRequest request) {
System.out.println("\n=== Headers ===");
Enumeration headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String name = (String)headerNames.nextElement();
System.out.println(name + ": " + request.getHeader(name));
}
System.out.println("\n=== Parameters ===");
Enumeration parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String name = (String)parameterNames.nextElement();
System.out.println(name + ": " + request.getParameter(name));
}
}
} |
Partager