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.subject.Subject;
import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.goafanti.common.bo.Error;
import com.goafanti.common.bo.Result;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.utils.LoggerUtils;

public class PermissionFilter extends AccessControlFilter {

	@Autowired
	private ShiroFilterUtils shiroFilterUtils;

	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
			throws Exception {

		// 先判断带参数的权限判断
		Subject subject = getSubject(request, response);
		HttpServletRequest httpRequest = ((HttpServletRequest) request);
		String uri = httpRequest.getRequestURI();// 获取URI
		String basePath = httpRequest.getContextPath();// 获取basePath
		if (StringUtils.hasText(uri) && StringUtils.hasText(basePath) && uri.startsWith(basePath)) {
			uri = uri.replaceAll("^\\" + basePath + "\\/+", "").replaceAll("\\.html$", "");
		} else {
			uri = uri.replaceAll("^\\/", "").replaceAll("\\.html$", "");
		}
		if (subject.isPermitted(uri) || subject.hasRole(AFTConstants.SUPERADMIN)) {
			return Boolean.TRUE;
		}
		return Boolean.FALSE;
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		Subject subject = getSubject(request, response);
		if (shiroFilterUtils.isAjax((HttpServletRequest) request)) {
			LoggerUtils.debug(getClass(), "当前用户权限不够，并且是Ajax请求！");
			shiroFilterUtils.out((HttpServletResponse) response, new Result().error(new Error("", "403", "当前用户权限不够!")));
		} else if (null == subject.getPrincipal()) {
			saveRequest(request);
			//WebUtils.issueRedirect(request, response, getLoginUrl());
			WebUtils.issueRedirect(request, response, "index");
		} else {
			WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
		}
		return Boolean.FALSE;
	}

}
