package com.njcn.shiro.filter;

import com.njcn.enums.LogTypeEnum;
import com.njcn.service.log.UserLogDetailService;
import com.njcn.shiro.token.TokenManager;
import com.njcn.utils.AppConfig;
import com.njcn.utils.PubUtils;
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 javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *@author hongawen
 *@date 2018/3/21 19:48
 */
public class RoleFilter extends AccessControlFilter {

	@Autowired
	private UserLogDetailService userLogDetailService;

	@Autowired
	private AppConfig appConfig;

	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
		String[] arra = (String[])mappedValue;
		Subject subject = getSubject(request, response);
		for (String role : arra) {
			if(subject.hasRole(role)){
				return true;
			}
		}
		return false;
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request1,
			ServletResponse response) throws Exception {
		HttpServletResponse httpResponse = ((HttpServletResponse) response);
		HttpServletRequest request = (HttpServletRequest) request1;
		userLogDetailService.saveUserLog(TokenManager.getToken().getUserIndex(), TokenManager.getToken().getLoginName(),"越权访问","失败",appConfig.getSystemFlag(), PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),2);
		if (ShiroFilterUtils.isAjax(request)) {
			httpResponse.sendError(300);
			ShiroFilterUtils.out(httpResponse, "没有访问权限");
		}else{
			if (StringUtils.hasText(ShiroFilterUtils.UNAUTHORIZED)) {
				WebUtils.issueRedirect(request, response, ShiroFilterUtils.UNAUTHORIZED);
			} else {//否则返回401未授权状态码
				WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
			}
		}
		return false;
	}

}
