package com.njcn.shiro.filter;


import com.njcn.enums.LogTypeEnum;
import com.njcn.service.log.UserLogDetailService;
import com.njcn.shiro.session.UserSessionManager;
import com.njcn.shiro.token.TokenManager;
import com.njcn.sso.shiro.session.SessionStatus;
import com.njcn.utils.AppConfig;
import com.njcn.utils.PubUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 判断是否被T，管理员T人的
 */
public class SimpleAuthFilter extends AccessControlFilter {

	private static final Logger logger= LoggerFactory.getLogger(SimpleAuthFilter.class);

	@Autowired
	private UserLogDetailService userLogDetailService;

	@Autowired
	private AppConfig appConfig;

	@Override
	protected boolean isAccessAllowed(ServletRequest request,
                                      ServletResponse response, Object mappedValue) throws IOException {
		HttpServletRequest httpRequest = ((HttpServletRequest)request);

		String url = httpRequest.getRequestURI();
		if(url.contains("/auth/")){
			return Boolean.TRUE;
		}
		Subject subject = getSubject(request, response);
		Session session = subject.getSession();
		SessionStatus sessionStatus = (SessionStatus) session.getAttribute(UserSessionManager.SESSION_STATUS);
		//不为空，且为false，表示该session处于非正常状态，当前用户需要跳转，重新登录
		if (null != sessionStatus && !sessionStatus.isOnlineStatus()) {
			return  Boolean.FALSE;
		}
		return Boolean.TRUE;
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request1,
			ServletResponse response) throws Exception {
		HttpServletRequest request = (HttpServletRequest) request1;
//		userLogDetailService.saveUserLog(TokenManager.getToken().getUserIndex(), TokenManager.getToken().getLoginName(),"会话已过期","失败",appConfig.getSystemFlag(), PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),2);
		//先退出
		Subject subject = getSubject(request, response);
		subject.logout();
		HttpServletResponse httpResponse = ((HttpServletResponse)response);
		//判断是不是Ajax请求
		if (ShiroFilterUtils.isAjax(request) ) {
			httpResponse.sendError(301);
			ShiroFilterUtils.out(httpResponse, "该用户被踢下线");
		}else{
			WebUtils.saveRequest(request);
			//再重定向
			WebUtils.issueRedirect(request, response,  ShiroFilterUtils.KICKED_OUT);
		}
		return false;
	}

}
