package cn.palmte.work.shiro;

import cn.palmte.work.service.SysPermissionService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * Created by wang.lin@esstx.cn on 2018/5/6.
 */
@Component
public class ShiroPermissionsFilter extends PermissionsAuthorizationFilter {

    @Autowired
    private SysPermissionService sysPermissionService;

    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {

        // 记录日志

        /**获取用户信息，可以根据用户信息查看有没有对应模块的权限*/
        ShiroPrincipal principal = (ShiroPrincipal) SecurityUtils.getSubject().getPrincipal();
        //获得请求路径
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String path = httpServletRequest.getServletPath();
        //true有权限; false没有权限
        boolean isPermitted = true;
        /*if(sysPermissionService==null){
            sysPermissionService= (SysPermissionService) SpringContextUtils.getContext().getBean("sysPermissionService");
        }*/
        List<String> allUrls = sysPermissionService.getAllPermissionList();
        if (principal != null && allUrls.contains(path)) {
            List<String> urls = principal.getUrls();
            if (!urls.contains(path)) {
                isPermitted = false;
            }
        }
        return isPermitted;
    }

    /**
     * shiro认证perms资源失败后回调方法
     *
     * @param servletRequest
     * @param servletResponse
     * @return
     * @throws IOException
     */
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException {
        try {
            servletResponse.setCharacterEncoding("UTF-8");
            servletResponse.setContentType("application/json");
            HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
            httpServletResponse.sendRedirect("../common/401.html");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}