package com.goafanti.core.shiro.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.web.filter.AccessControlFilter;
import org.springframework.beans.factory.annotation.Autowired;

import com.goafanti.common.bo.Error;
import com.goafanti.common.bo.Result;
import com.goafanti.common.utils.LoggerUtils;
import com.goafanti.core.shiro.token.TokenManager;

public class LoginFilter extends AccessControlFilter {
	final static Class<LoginFilter>	CLASS	= LoginFilter.class;

	@Autowired
	private ShiroFilterUtils		shiroFilterUtils;

	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
			throws Exception {
		if (TokenManager.isLogin()) {
			return Boolean.TRUE;
		}
		return Boolean.FALSE;
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		// 保存Request和Response 到登录后的链接
		if (!shiroFilterUtils.isAjax((HttpServletRequest) request)) {
			saveRequestAndRedirectToLogin(request, response);
		} else {
			LoggerUtils.debug(getClass(), "当前用户没有登录，并且是Ajax请求！");
			shiroFilterUtils.out((HttpServletResponse) response, new Result().error(new Error("", "403", "当前用户没有登录!")));
		}
		return Boolean.FALSE;
	}

}
