All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.adaptrex.security.servlet.LogOutServlet Maven / Gradle / Ivy

/*
 * Copyright 2012 Adaptrex, LLC
 *
 * 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.
 */

package com.adaptrex.core.security.servlet;

import java.util.HashMap;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.ObjectMapper;

@WebServlet(name="Adaptrex Logout", urlPatterns={"/ax-logout"})
public class LogOutServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private static ObjectMapper mapper = new ObjectMapper();
	private static Logger log = LoggerFactory.getLogger(LogOutServlet.class);
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) {
		Subject currentUser = SecurityUtils.getSubject();
		if (currentUser.isAuthenticated()) {
			currentUser.logout();
		}
		
		String redirect = request.getContextPath();
		if (redirect.isEmpty()) redirect = "/";
		
		/*
		 * We could get here either via ajax or direct page load... handle
		 * xhr by passing a json response and direct get with a redirect
		 */
		String with = request.getHeader("X-Requested-With");
		if (with != null && with.equals("XMLHttpRequest")) {
			try {
				response.setContentType("application/json");
				HashMap responseMap = new HashMap();
				responseMap.put("redirect", redirect);
				
			    try {
			    	response.getWriter().print(mapper.writeValueAsString(responseMap));
				} catch (Exception e) {
					response.getWriter().print("");
				}
				
			} catch (Exception e) {
				log.warn("Error", e);
				return;
			} 
		}
		
		
		try {
			response.sendRedirect(redirect);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy