List of usage examples for javax.servlet.http HttpServletRequest removeAttribute
public void removeAttribute(String name);
From source file:org.beangle.security.web.context.HttpSessionContextIntegrationFilter.java
public void doFilterHttp(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { if (request.getAttribute(FILTER_APPLIED) != null) { // ensure that filter is only applied once per request chain.doFilter(request, response); return;/*from w ww . j a v a 2 s .co m*/ } HttpSession httpSession = safeGetSession(request, forceEagerSessionCreation); boolean httpSessionExistedAtStartOfRequest = httpSession != null; SecurityContext contextBeforeChainExecution = readSecurityContextFromSession(httpSession); // Make the HttpSession null, as we don't want to keep a reference to it // lying // around in case chain.doFilter() invalidates it. httpSession = null; if (contextBeforeChainExecution == null) { contextBeforeChainExecution = generateNewContext(); logger.debug("New SecurityContext instance will be associated with SecurityContextHolder"); } else { logger.debug("Obtained a valid SecurityContext from Beangle_SECURITY_CONTEXT to " + "associate with SecurityContextHolder: '{}'", contextBeforeChainExecution); } int contextHashBeforeChainExecution = contextBeforeChainExecution.hashCode(); request.setAttribute(FILTER_APPLIED, Boolean.TRUE); // Create a wrapper that will eagerly update the session with the // security context // if anything in the chain does a sendError() or sendRedirect(). // See SEC-398 OnRedirectUpdateSessionResponseWrapper responseWrapper = new OnRedirectUpdateSessionResponseWrapper( response, request, httpSessionExistedAtStartOfRequest, contextHashBeforeChainExecution); // Proceed with chain try { // This is the only place in this class where // SecurityContextHolder.setContext() is called SecurityContextHolder.setContext(contextBeforeChainExecution); chain.doFilter(request, responseWrapper); } finally { // This is the only place in this class where // SecurityContextHolder.getContext() is called SecurityContext contextAfterChainExecution = SecurityContextHolder.getContext(); // Crucial removal of SecurityContextHolder contents - do this // before anything else. SecurityContextHolder.clearContext(); request.removeAttribute(FILTER_APPLIED); // storeSecurityContextInSession() might already be called by the // response wrapper // if something in the chain called sendError() or sendRedirect(). // This ensures we only call it // once per request. if (!responseWrapper.isSessionUpdateDone()) { storeSecurityContextInSession(contextAfterChainExecution, request, httpSessionExistedAtStartOfRequest, contextHashBeforeChainExecution); } logger.debug("SecurityContextHolder now cleared, as request processing completed"); } }
From source file:org.pentaho.platform.web.http.filters.HttpSessionPentahoSessionIntegrationFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // Do we really need the checks on the types in practice ? if (!(request instanceof HttpServletRequest)) { throw new ServletException("Can only process HttpServletRequest"); }//from w ww . j ava2 s . co m if (!(response instanceof HttpServletResponse)) { throw new ServletException("Can only process HttpServletResponse"); } HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; if (httpRequest.getAttribute(FILTER_APPLIED) != null) { // ensure that filter is only applied once per request chain.doFilter(httpRequest, httpResponse); return; } HttpSession httpSession = safeGetSession(httpRequest, forceEagerSessionCreation); boolean httpSessionExistedAtStartOfRequest = httpSession != null; IPentahoSession pentahoSessionBeforeChainExecution = readPentahoSessionFromHttpSession(httpSession); // Make the HttpSession null, as we don't want to keep a reference to it lying // around in case chain.doFilter() invalidates it. httpSession = null; localeLeftovers(httpRequest); if (pentahoSessionBeforeChainExecution == null) { pentahoSessionBeforeChainExecution = generatePentahoSession(httpRequest); if (logger.isDebugEnabled()) { logger.debug("Found no IPentahoSession in HTTP session; created new IPentahoSession"); } } else { if (logger.isDebugEnabled()) { logger.debug("Obtained a valid IPentahoSession from HTTP session to " + "associate with PentahoSessionHolder: '" + pentahoSessionBeforeChainExecution + "'"); } } httpRequest.setAttribute(FILTER_APPLIED, Boolean.TRUE); // Create a wrapper that will eagerly update the session with the Pentaho session // if anything in the chain does a sendError() or sendRedirect(). OnRedirectUpdateSessionResponseWrapper responseWrapper = new OnRedirectUpdateSessionResponseWrapper( httpResponse, httpRequest, httpSessionExistedAtStartOfRequest); // Proceed with chain try { // This is the only place in this class where PentahoSessionHolder.setSession() is called PentahoSessionHolder.setSession(pentahoSessionBeforeChainExecution); chain.doFilter(httpRequest, responseWrapper); } finally { // This is the only place in this class where PentahoSessionHolder.getSession() is called IPentahoSession pentahoSessionAfterChainExecution = PentahoSessionHolder.getSession(); // Crucial removal of PentahoSessionHolder contents - do this before anything else. PentahoSessionHolder.removeSession(); httpRequest.removeAttribute(FILTER_APPLIED); // storePentahoSessionInHttpSession() might already be called by the response wrapper // if something in the chain called sendError() or sendRedirect(). This ensures we only call it // once per request. if (!responseWrapper.isSessionUpdateDone()) { storePentahoSessionInHttpSession(pentahoSessionAfterChainExecution, httpRequest, httpSessionExistedAtStartOfRequest); } if (logger.isDebugEnabled()) { logger.debug("PentahoSessionHolder now cleared, as request processing completed"); } } }
From source file:org.paxle.gui.impl.servlets.LoginView.java
@Override public Template handleRequest(HttpServletRequest request, HttpServletResponse response, Context context) throws Exception { Template template = null;//from w ww . j a v a 2 s . co m try { // Get the session HttpSession session = request.getSession(true); boolean doRedirect = false; if (request.getParameter("doLogin") != null) { // getting user-name + password String userName = request.getParameter("login.username"); String password = request.getParameter("login.password"); if (password == null) password = ""; // getting the userAdmin service IServiceManager manager = (IServiceManager) context.get(IServiceManager.SERVICE_MANAGER); UserAdmin uAdmin = (UserAdmin) manager.getService(UserAdmin.class.getName()); // auth user final User user = this.guiAuthManager.authenticatedAs(request, userName, password); if (user != null) { // remember login state session.setAttribute("logon.isDone", Boolean.TRUE); // set user-data into the session session.setAttribute(HttpContext.AUTHENTICATION_TYPE, HttpServletRequest.FORM_AUTH); session.setAttribute(HttpContext.AUTHORIZATION, uAdmin.getAuthorization(user)); session.setAttribute(HttpContext.REMOTE_USER, user); // keep user-settings in sync with user-language settings CookieTool cookieTool = (CookieTool) context.get("cookieTool"); if (cookieTool.get("l10n") != null) { @SuppressWarnings("unchecked") Dictionary<String, Object> userProps = user.getProperties(); userProps.put(UserView.USER_LANGUAGE, cookieTool.get("l10n").getValue()); } doRedirect = true; } else { context.put("errorMsg", "Unable to login. Username or password is invalid"); } } else if (request.getParameter("doLogout") != null) { session.removeAttribute("logon.isDone"); session.removeAttribute(HttpContext.AUTHENTICATION_TYPE); session.removeAttribute(HttpContext.AUTHORIZATION); session.removeAttribute(HttpContext.REMOTE_USER); doRedirect = true; } if (doRedirect) { // redirect to target if (session.getAttribute("login.target") != null) { response.sendRedirect((String) session.getAttribute("login.target")); session.removeAttribute("login.target"); } else if (request.getParameter("login.target") != null) { response.sendRedirect((String) request.getParameter("login.target")); request.removeAttribute("login.target"); } else { response.sendRedirect("/"); } } else { template = this.getTemplate("/resources/templates/LoginView.vm"); } } catch (Exception e) { this.logger.error(String.format("Unexpected '%s': %s", e.getClass().getName(), e.getMessage()), e); throw e; } return template; }
From source file:org.acegisecurity.context.HttpSessionContextIntegrationFilter.java
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { Assert.isInstanceOf(HttpServletRequest.class, req, "ServletRequest must be an instance of HttpServletRequest"); Assert.isInstanceOf(HttpServletResponse.class, res, "ServletResponse must be an instance of HttpServletResponse"); HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; if (request.getAttribute(FILTER_APPLIED) != null) { // ensure that filter is only applied once per request chain.doFilter(request, response); return;// w w w . ja v a 2 s . co m } HttpSession httpSession = null; try { httpSession = request.getSession(forceEagerSessionCreation); } catch (IllegalStateException ignored) { } boolean httpSessionExistedAtStartOfRequest = httpSession != null; SecurityContext contextBeforeChainExecution = readSecurityContextFromSession(httpSession); // Make the HttpSession null, as we don't want to keep a reference to it lying // around in case chain.doFilter() invalidates it. httpSession = null; if (contextBeforeChainExecution == null) { contextBeforeChainExecution = generateNewContext(); if (logger.isDebugEnabled()) { logger.debug("New SecurityContext instance will be associated with SecurityContextHolder"); } } else { if (logger.isDebugEnabled()) { logger.debug("Obtained a valid SecurityContext from ACEGI_SECURITY_CONTEXT to " + "associate with SecurityContextHolder: '" + contextBeforeChainExecution + "'"); } } int contextHashBeforeChainExecution = contextBeforeChainExecution.hashCode(); request.setAttribute(FILTER_APPLIED, Boolean.TRUE); // Create a wrapper that will eagerly update the session with the security context // if anything in the chain does a sendError() or sendRedirect(). // See SEC-398 OnRedirectUpdateSessionResponseWrapper responseWrapper = new OnRedirectUpdateSessionResponseWrapper( response, request, httpSessionExistedAtStartOfRequest, contextHashBeforeChainExecution); // Proceed with chain try { // This is the only place in this class where SecurityContextHolder.setContext() is called SecurityContextHolder.setContext(contextBeforeChainExecution); chain.doFilter(request, responseWrapper); } finally { // This is the only place in this class where SecurityContextHolder.getContext() is called SecurityContext contextAfterChainExecution = SecurityContextHolder.getContext(); // Crucial removal of SecurityContextHolder contents - do this before anything else. SecurityContextHolder.clearContext(); request.removeAttribute(FILTER_APPLIED); // storeSecurityContextInSession() might already be called by the response wrapper // if something in the chain called sendError() or sendRedirect(). This ensures we only call it // once per request. if (!responseWrapper.isSessionUpdateDone()) { storeSecurityContextInSession(contextAfterChainExecution, request, httpSessionExistedAtStartOfRequest, contextHashBeforeChainExecution); } if (logger.isDebugEnabled()) { logger.debug("SecurityContextHolder now cleared, as request processing completed"); } } }
From source file:org.apache.servicemix.http.processors.ConsumerProcessor.java
public void process(HttpServletRequest request, HttpServletResponse response) throws Exception { if (log.isDebugEnabled()) { log.debug("Receiving HTTP request: " + request); }/*from w w w . java 2 s . c o m*/ if ("GET".equals(request.getMethod())) { processGetRequest(request, response); return; } if (!started) { response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Endpoint is stopped"); return; } if (!"POST".equals(request.getMethod())) { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, request.getMethod() + " not supported"); return; } // Not giving a specific mutex will synchronize on the contination itself Continuation cont = ContinuationSupport.getContinuation(request, null); MessageExchange exchange; // If the continuation is not a retry if (!cont.isPending()) { try { Context ctx = createContext(request); request.setAttribute(Context.class.getName(), ctx); exchange = soapHelper.onReceive(ctx); exchanges.put(exchange.getExchangeId(), exchange); NormalizedMessage inMessage = exchange.getMessage("in"); Map<String, String> protocolHeaders = new HashMap(); if (getConfiguration().isWantHeadersFromHttpIntoExchange()) { protocolHeaders.putAll(getHeaders(request)); } protocolHeaders.put(AbstractProcessor.HEADER_X_REMOTE_HOST, getClientIp(request)); inMessage.setProperty(JbiConstants.PROTOCOL_HEADERS, protocolHeaders); if (request.getHeader(HEADER_X_CORRELATION_ID) != null) { response.addHeader(HEADER_X_CORRELATION_ID, request.getHeader(HEADER_X_CORRELATION_ID)); } String smxInstanceName = System.getProperty(SMX_INSTANCE_NAME_PROPERTY); if (smxInstanceName != null) { response.addHeader(HEADER_X_POWERED_BY, smxInstanceName); } else { log.warn(SMX_INSTANCE_NAME_PROPERTY + " property was not set in servicemix.xml file"); } locks.put(exchange.getExchangeId(), cont); request.setAttribute(MessageExchange.class.getName(), exchange.getExchangeId()); synchronized (cont) { channel.send(exchange); if (log.isDebugEnabled()) { log.debug("Suspending continuation for exchange: " + exchange.getExchangeId()); } boolean result = cont.suspend(suspentionTime); exchange = exchanges.remove(exchange.getExchangeId()); request.removeAttribute(MessageExchange.class.getName()); if (!result) { locks.remove(exchange.getExchangeId()); throw new Exception("Exchange timed out"); } } } catch (RetryRequest retry) { throw retry; } catch (SoapFault fault) { sendFault(fault, request, response); return; } catch (Exception e) { sendFault(new SoapFault(e), request, response); return; } } else { synchronized (cont) { String id = (String) request.getAttribute(MessageExchange.class.getName()); locks.remove(id); exchange = exchanges.remove(id); request.removeAttribute(MessageExchange.class.getName()); // Check if this is a timeout if (exchange == null) { throw new IllegalStateException("Exchange not found"); } if (log.isDebugEnabled() && request.getHeader(HEADER_X_CORRELATION_ID) != null) { String externalCorrelationId = request.getHeader(HEADER_X_CORRELATION_ID); String exchangeCorrelationId = (String) exchange.getProperty(JbiConstants.CORRELATION_ID); log.debug("Message exchange with correlationId='" + exchangeCorrelationId + "' is correlated with external message exchange with correlationId='" + externalCorrelationId + "'"); } if (!cont.isResumed()) { Exception e = new Exception("Exchange timed out: " + exchange.getExchangeId()); sendFault(new SoapFault(e), request, response); return; } } } if (exchange.getStatus() == ExchangeStatus.ERROR) { if (exchange.getError() != null) { throw new Exception(exchange.getError()); } else { throw new Exception("Unknown Error"); } } else if (exchange.getStatus() == ExchangeStatus.ACTIVE) { try { if (exchange.getFault() != null) { processFault(exchange, request, response); } else { processResponse(exchange, request, response); } } finally { exchange.setStatus(ExchangeStatus.DONE); channel.send(exchange); } } else if (exchange.getStatus() == ExchangeStatus.DONE) { // This happens when there is no response to send back response.setStatus(HttpServletResponse.SC_ACCEPTED); } }
From source file:org.apache.catalina.core.StandardWrapperValve.java
/** * Invoke the servlet we are managing, respecting the rules regarding * servlet lifecycle and SingleThreadModel support. * * @param request Request to be processed * @param response Response to be produced * @param valveContext Valve context used to forward to the next Valve * * @exception IOException if an input/output error occurred * @exception ServletException if a servlet error occurred */// ww w. j av a2 s .c om public final void invoke(Request request, Response response, ValveContext valveContext) throws IOException, ServletException { // Initialize local variables we may need boolean unavailable = false; Throwable throwable = null; // This should be a Request attribute... long t1 = System.currentTimeMillis(); requestCount++; StandardWrapper wrapper = (StandardWrapper) getContainer(); HttpRequest hrequest = (HttpRequest) request; Servlet servlet = null; HttpServletRequest hreq = (HttpServletRequest) request.getRequest(); HttpServletResponse hres = (HttpServletResponse) response.getResponse(); // Check for the application being marked unavailable if (!((Context) wrapper.getParent()).getAvailable()) { hres.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardContext.isUnavailable")); unavailable = true; } // Check for the servlet being marked unavailable if (!unavailable && wrapper.isUnavailable()) { log(sm.getString("standardWrapper.isUnavailable", wrapper.getName())); if (hres == null) { ; // NOTE - Not much we can do generically } else { long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { hres.setDateHeader("Retry-After", available); hres.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { hres.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } } unavailable = true; } // Allocate a servlet instance to process this request try { if (!unavailable) { servlet = wrapper.allocate(); } } catch (UnavailableException e) { long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { hres.setDateHeader("Retry-After", available); hres.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { hres.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } } catch (ServletException e) { log(sm.getString("standardWrapper.allocateException", wrapper.getName()), e); throwable = e; exception(request, response, e); servlet = null; } catch (Throwable e) { log(sm.getString("standardWrapper.allocateException", wrapper.getName()), e); throwable = e; exception(request, response, e); servlet = null; } // Acknowlege the request try { response.sendAcknowledgement(); } catch (IOException e) { hreq.removeAttribute(Globals.JSP_FILE_ATTR); log(sm.getString("standardWrapper.acknowledgeException", wrapper.getName()), e); throwable = e; exception(request, response, e); } catch (Throwable e) { log(sm.getString("standardWrapper.acknowledgeException", wrapper.getName()), e); throwable = e; exception(request, response, e); servlet = null; } MessageBytes requestPathMB = null; if (hreq != null) { requestPathMB = hrequest.getRequestPathMB(); } hreq.setAttribute(ApplicationFilterFactory.DISPATCHER_TYPE_ATTR, ApplicationFilterFactory.REQUEST_INTEGER); hreq.setAttribute(ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR, requestPathMB); // Create the filter chain for this request ApplicationFilterFactory factory = ApplicationFilterFactory.getInstance(); ApplicationFilterChain filterChain = factory.createFilterChain((ServletRequest) request, wrapper, servlet); // Call the filter chain for this request // NOTE: This also calls the servlet's service() method try { String jspFile = wrapper.getJspFile(); if (jspFile != null) hreq.setAttribute(Globals.JSP_FILE_ATTR, jspFile); else hreq.removeAttribute(Globals.JSP_FILE_ATTR); if ((servlet != null) && (filterChain != null)) { filterChain.doFilter(hreq, hres); } hreq.removeAttribute(Globals.JSP_FILE_ATTR); } catch (ClientAbortException e) { hreq.removeAttribute(Globals.JSP_FILE_ATTR); throwable = e; exception(request, response, e); } catch (IOException e) { hreq.removeAttribute(Globals.JSP_FILE_ATTR); log(sm.getString("standardWrapper.serviceException", wrapper.getName()), e); throwable = e; exception(request, response, e); } catch (UnavailableException e) { hreq.removeAttribute(Globals.JSP_FILE_ATTR); log(sm.getString("standardWrapper.serviceException", wrapper.getName()), e); // throwable = e; // exception(request, response, e); wrapper.unavailable(e); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { hres.setDateHeader("Retry-After", available); hres.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { hres.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } // Do not save exception in 'throwable', because we // do not want to do exception(request, response, e) processing } catch (ServletException e) { hreq.removeAttribute(Globals.JSP_FILE_ATTR); Throwable rootCause = e; Throwable rootCauseCheck = null; // Extra aggressive rootCause finding do { try { rootCauseCheck = (Throwable) PropertyUtils.getProperty(rootCause, "rootCause"); if (rootCauseCheck != null) rootCause = rootCauseCheck; } catch (ClassCastException ex) { rootCauseCheck = null; } catch (IllegalAccessException ex) { rootCauseCheck = null; } catch (NoSuchMethodException ex) { rootCauseCheck = null; } catch (java.lang.reflect.InvocationTargetException ex) { rootCauseCheck = null; } } while (rootCauseCheck != null); if (!(rootCause instanceof ClientAbortException)) { log(sm.getString("standardWrapper.serviceException", wrapper.getName()), rootCause); } throwable = e; exception(request, response, e); } catch (Throwable e) { hreq.removeAttribute(Globals.JSP_FILE_ATTR); log(sm.getString("standardWrapper.serviceException", wrapper.getName()), e); throwable = e; exception(request, response, e); } // Release the filter chain (if any) for this request try { if (filterChain != null) filterChain.release(); } catch (Throwable e) { log(sm.getString("standardWrapper.releaseFilters", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } } // Deallocate the allocated servlet instance try { if (servlet != null) { wrapper.deallocate(servlet); } } catch (Throwable e) { log(sm.getString("standardWrapper.deallocateException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } } // If this servlet has been marked permanently unavailable, // unload it and release this instance try { if ((servlet != null) && (wrapper.getAvailable() == Long.MAX_VALUE)) { wrapper.unload(); } } catch (Throwable e) { log(sm.getString("standardWrapper.unloadException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } } long t2 = System.currentTimeMillis(); long time = t2 - t1; processingTime += time; if (time > maxTime) maxTime = time; if (time < minTime) minTime = time; }
From source file:com.jsmartframework.web.manager.BeanHandler.java
private void finalizeAuthBean(Object bean, HttpServletRequest request, HttpServletResponse response) { executePreDestroy(bean);//from w w w .j a v a2s . c o m AuthBean authBean = bean.getClass().getAnnotation(AuthBean.class); try { for (Field field : HELPER.getBeanFields(bean.getClass())) { if (field.getAnnotations().length > 0) { field.setAccessible(true); if (field.isAnnotationPresent(AuthField.class)) { AuthField authField = field.getAnnotation(AuthField.class); Object value = field.get(bean); if (value != null) { // Return encrypted auth fields as cookies to check if customer is still // logged on next request String cookieValue = AuthEncrypter.encrypt(request, authBean.secretKey(), value); Cookie cookie = getAuthenticationCookie(request, authField.value(), cookieValue, -1); response.addCookie(cookie); } else { // Case value is null we force Cookie deletion on client side Cookie cookie = getAuthenticationCookie(request, authField.value(), null, 0); response.addCookie(cookie); } } field.set(bean, null); } } } catch (Exception ex) { LOGGER.log(Level.SEVERE, "Finalize injection on AuthBean [" + bean + "] failed: " + ex.getMessage()); } request.removeAttribute(HELPER.getClassName(authBean, bean.getClass())); }
From source file:uk.ac.cam.cl.dtg.segue.api.managers.UserAccountManager.java
/** * Authenticate Callback will receive the authentication information from the different provider types. (e.g. OAuth * 2.0 (IOAuth2Authenticator) or bespoke) * /*from www. j a va 2s. co m*/ * This method will either register a new user and attach the linkedAccount or locate the existing account of the * user and create a session for that. * * @param request * - http request from the user - should contain url encoded token details. * @param response * to store the session in our own segue cookie. * @param provider * - the provider who has just authenticated the user. * @return Response containing the user object. Alternatively a SegueErrorResponse could be returned. * @throws AuthenticationProviderMappingException * - if we cannot locate an appropriate authenticator. * @throws SegueDatabaseException * - if there is a local database error. * @throws IOException * - Problem reading something * @throws NoUserException * - If the user doesn't exist with the provider. * @throws AuthenticatorSecurityException * - If there is a security probably with the authenticator. * @throws CrossSiteRequestForgeryException * - as per exception description. * @throws CodeExchangeException * - as per exception description. * @throws AuthenticationCodeException * - as per exception description. */ public RegisteredUserDTO authenticateCallback(final HttpServletRequest request, final HttpServletResponse response, final String provider) throws AuthenticationProviderMappingException, AuthenticatorSecurityException, NoUserException, IOException, SegueDatabaseException, AuthenticationCodeException, CodeExchangeException, CrossSiteRequestForgeryException { IAuthenticator authenticator = this.userAuthenticationManager.mapToProvider(provider); // get the auth provider user data. UserFromAuthProvider providerUserDO = this.userAuthenticationManager.getThirdPartyUserInformation(request, provider); // if the UserFromAuthProvider exists then this is a login request so process it. RegisteredUser userFromLinkedAccount = this.userAuthenticationManager.getSegueUserFromLinkedAccount( authenticator.getAuthenticationProvider(), providerUserDO.getProviderUserId()); if (userFromLinkedAccount != null) { return this.logUserIn(request, response, userFromLinkedAccount); } RegisteredUser currentUser = getCurrentRegisteredUserDO(request); // if the user is currently logged in and this is a request for a linked account, then create the new link. if (null != currentUser) { Boolean intentionToLinkRegistered = (Boolean) request.getSession() .getAttribute(LINK_ACCOUNT_PARAM_NAME); if (intentionToLinkRegistered == null || !intentionToLinkRegistered) { throw new SegueDatabaseException("User is already authenticated - " + "expected request to link accounts but none was found."); } List<AuthenticationProvider> usersProviders = this.database .getAuthenticationProvidersByUser(currentUser); if (!usersProviders.contains(authenticator.getAuthenticationProvider())) { // create linked account this.userAuthenticationManager.linkProviderToExistingAccount(currentUser, authenticator.getAuthenticationProvider(), providerUserDO); // clear link accounts intention until next time request.removeAttribute(LINK_ACCOUNT_PARAM_NAME); } return this.convertUserDOToUserDTO(getCurrentRegisteredUserDO(request)); } else { // this must be a registration request RegisteredUser segueUserDO = this .registerUserWithFederatedProvider(authenticator.getAuthenticationProvider(), providerUserDO); RegisteredUserDTO segueUserDTO = this.logUserIn(request, response, segueUserDO); segueUserDTO.setFirstLogin(true); try { ImmutableMap<String, Object> emailTokens = ImmutableMap.of("provider", provider.toLowerCase()); emailManager.sendTemplatedEmailToUser(segueUserDTO, emailManager.getEmailTemplateDTO("email-template-registration-confirmation-federated"), emailTokens, EmailType.SYSTEM); } catch (ContentManagerException e) { log.error("Registration email could not be sent due to content issue: " + e.getMessage()); } return segueUserDTO; } }
From source file:esg.node.filters.AccessLoggingFilter.java
@SuppressWarnings("unchecked") public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (filterConfig == null) return;// w w w . j a v a2 s.c om int id = -1; //Record identifying tuple String userID = null; String email = null; String url = null; String fileID = null; String remoteAddress = null; String userAgent = null; long dateFetched = 0L; long batchUpdateTime = 0L; boolean hasNoBackingFile = false; //(note: serviceName defined in global scope) //firewall off any errors so that nothing stops the show... try { log.debug("accessLogging DAO -> " + accessLoggingDAO); if (accessLoggingDAO != null) { //This filter should only appy to specific requests //in particular requests for data files (*.nc) HttpServletRequest req = (HttpServletRequest) request; url = req.getRequestURL().toString().trim(); System.out.println("Requested URL: [" + url + "]"); //Don't need this anymore... but too much of a pain at the moment to change //Remember to change the filter xml entry file in the installer //filters/esg-access-logging-filter b/filters/esg-access-logging-filter Matcher exemptFilesMatcher = exemptUrlPattern.matcher(url); if (exemptFilesMatcher.matches()) { System.out.println( "I am not logging requested file with this extension..., punting on: [" + url + "]"); chain.doFilter(request, response); return; } Matcher exemptServiceMatcher = exemptServicePattern.matcher(url); if (exemptServiceMatcher.matches()) { System.out.println( "I am not logging this, it is an exempt service..., punting on: [" + url + "]"); chain.doFilter(request, response); return; } Matcher allowedFilesMatcher = urlExtensionPattern.matcher(url); if (!allowedFilesMatcher.matches()) { System.out.println("This is not an url that we are interested in logging: [" + url + "]"); chain.doFilter(request, response); return; } // only proceed if the request has been authorized final Boolean requestIsAuthorized = (Boolean) request.getAttribute(AUTHORIZATION_REQUEST_ATTRIBUTE); log.debug("AUTHORIZATION_REQUEST_ATTRIBUTE=" + requestIsAuthorized); if (requestIsAuthorized == null || requestIsAuthorized == false) { System.out.println( "**UnAuthorized Request, punting on: " + req.getRequestURL().toString().trim()); chain.doFilter(request, response); return; } System.out.println("Executing filter on: " + url); //------------------------------------------------------------------------------------------ //For Token authentication there is a Validation Map present with user and email information //------------------------------------------------------------------------------------------ Map<String, String> validationMap = (Map<String, String>) req.getAttribute("validationMap"); if (validationMap != null) { userID = validationMap.get("user"); email = validationMap.get("email"); //Want to make sure that any snooping filters //behind this one does not have access to this //information (posted by the //authorizationTokenValidationFilter, which should //immediately preceed this one). This is in //effort to limit information exposure the //best we can. req.removeAttribute("validationMap"); } else { log.warn("Validation Map is [" + validationMap + "] - (not a token based request)"); } //------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------ //For TokenLESS authentication the userid information is in a parameter called "esg.openid" //------------------------------------------------------------------------------------------ if (userID == null || userID.isEmpty()) { userID = ((req.getAttribute("esg.openid") == null) ? "<no-id>" : req.getAttribute("esg.openid").toString()); if (userID == null || userID.isEmpty()) { log.warn( "This request is apparently not a \"tokenless\" request either - no openid attribute!!!!!"); } log.warn("AccessLoggingFilter - Tokenless: UserID = [" + userID + "]"); } //------------------------------------------------------------------------------------------ fileID = "0A"; remoteAddress = req.getRemoteAddr(); userAgent = (String) req.getAttribute("userAgent"); dateFetched = System.currentTimeMillis() / 1000; batchUpdateTime = dateFetched; //For the life of my I am not sure why this is there, something from the gridftp metrics collection. -gmb id = accessLoggingDAO.logIngressInfo(userID, email, url, fileID, remoteAddress, userAgent, serviceName, batchUpdateTime, dateFetched); System.out.println("myID: [" + id + "] = accessLoggingDAO.logIngressInfo(userID: [" + userID + "], email, url: [" + url + "], fileID, remoteAddress, userAgent, serviceName, batchUpdateTime, dateFetched)"); } else { log.error("DAO is null :[" + accessLoggingDAO + "]"); HttpServletResponse resp = (HttpServletResponse) response; resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid State Of ESG Access Logging Filter: DAO=[" + accessLoggingDAO + "]"); } } catch (Throwable t) { log.error(t); HttpServletResponse resp = (HttpServletResponse) response; resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Caught unforseen Exception in ESG Access Logging Filter"); } try { ByteCountListener byteCountListener = new ByteCountListener() { int myID = -1; long duration = -1; long startTime = -1; long dataSize = -1; long byteCount = -1; boolean success = false; public void setRecordID(int id) { this.myID = id; } public void setStartTime(long startTime) { this.startTime = startTime; } public void setDataSizeBytes(long dataSize) { this.dataSize = dataSize; } //This callback method should get called by the ByteCountingResponseStream when it is *closed* public void setByteCount(long xferSize) { byteCount = xferSize; System.out.println("**** setByteCount(" + xferSize + ")"); if ((AccessLoggingFilter.this.accessLoggingDAO != null) && (myID > 0)) { if (dataSize == xferSize) { success = true; } duration = System.currentTimeMillis() - startTime; System.out.println("AccessLoggingFilter.this.accessLoggingDAO.logEgressInfo(myID: [" + myID + "], success: [" + success + "], duration: [" + duration + "]ms, dataSize [" + dataSize + "], xferSize: [" + xferSize + "] );"); AccessLoggingFilter.this.accessLoggingDAO.logEgressInfo(myID, success, duration, dataSize, xferSize); } } public long getByteCount() { return byteCount; } }; byteCountListener.setRecordID(id); byteCountListener.setDataSizeBytes(resolveUrlToFile(url).length()); byteCountListener.setStartTime(System.currentTimeMillis()); AccessLoggingResponseWrapper accessLoggingResponseWrapper = new AccessLoggingResponseWrapper( (HttpServletResponse) response, byteCountListener); chain.doFilter(request, accessLoggingResponseWrapper); } catch (Throwable t) { log.error(t); HttpServletResponse resp = (HttpServletResponse) response; resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Caught unforseen Exception in ESG Access Logging Filter (url may not be resolvable to an exisiting file) " + t.getMessage()); } }
From source file:org.apache.struts.webapp.example.SaveSubscriptionAction.java
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // Extract attributes and parameters we will need MessageResources messages = getResources(request); HttpSession session = request.getSession(); SubscriptionForm subform = (SubscriptionForm) form; String action = subform.getAction(); if (action == null) { action = "?"; }// w ww . ja va 2 s . c o m if (log.isDebugEnabled()) { log.debug("SaveSubscriptionAction: Processing " + action + " action"); } // Is there a currently logged on user? User user = (User) session.getAttribute(Constants.USER_KEY); if (user == null) { if (log.isTraceEnabled()) { log.trace(" User is not logged on in session " + session.getId()); } return (mapping.findForward("logon")); } // Was this transaction cancelled? if (isCancelled(request)) { if (log.isTraceEnabled()) { log.trace(" Transaction '" + action + "' was cancelled"); } session.removeAttribute(Constants.SUBSCRIPTION_KEY); return (mapping.findForward("success")); } // Is there a related Subscription object? Subscription subscription = (Subscription) session.getAttribute(Constants.SUBSCRIPTION_KEY); if ("Create".equals(action)) { subscription = user.createSubscription(request.getParameter("host")); } if (subscription == null) { if (log.isTraceEnabled()) { log.trace(" Missing subscription for user '" + user.getUsername() + "'"); } response.sendError(HttpServletResponse.SC_BAD_REQUEST, messages.getMessage("error.noSubscription")); return (null); } // Was this transaction a Delete? if (action.equals("Delete")) { if (log.isTraceEnabled()) { log.trace(" Deleting mail server '" + subscription.getHost() + "' for user '" + user.getUsername() + "'"); } user.removeSubscription(subscription); session.removeAttribute(Constants.SUBSCRIPTION_KEY); try { UserDatabase database = (UserDatabase) servlet.getServletContext() .getAttribute(Constants.DATABASE_KEY); database.save(); } catch (Exception e) { log.error("Database save", e); } return (mapping.findForward("success")); } // All required validations were done by the form itself // Update the persistent subscription information if (log.isTraceEnabled()) { log.trace(" Populating database from form bean"); } try { PropertyUtils.copyProperties(subscription, subform); } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; log.error("Subscription.populate", t); throw new ServletException("Subscription.populate", t); } catch (Throwable t) { log.error("Subscription.populate", t); throw new ServletException("Subscription.populate", t); } try { UserDatabase database = (UserDatabase) servlet.getServletContext().getAttribute(Constants.DATABASE_KEY); database.save(); } catch (Exception e) { log.error("Database save", e); } // Remove the obsolete form bean and current subscription if (mapping.getAttribute() != null) { if ("request".equals(mapping.getScope())) request.removeAttribute(mapping.getAttribute()); else session.removeAttribute(mapping.getAttribute()); } session.removeAttribute(Constants.SUBSCRIPTION_KEY); // Forward control to the specified success URI if (log.isTraceEnabled()) { log.trace(" Forwarding to success page"); } return (mapping.findForward("success")); }