package com.lightinit.hsdataplatform.spring;

import com.lightinit.hsdataplatform.common.ShiroFilterUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Mr.Yao on 2017/11/8.
 */
public class CustomRolesAuthorizationFilter extends AuthorizationFilter {
    public CustomRolesAuthorizationFilter() {
    }
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object mappedValue) throws Exception {
        Subject subject = getSubject(servletRequest, servletResponse);
        String[] rolesArray = (String[]) mappedValue;
        if (rolesArray == null || rolesArray.length == 0) {
            //没有角色限制，有权限访问
            return true;
        }
        for (int i = 0; i < rolesArray.length; i++) {
            if (subject.hasRole(rolesArray[i])) {
                //若当前用户是rolesArray中的任何一个，则有权限访问
                return true;
            }
        }
        if(ShiroFilterUtils.isAjax(servletRequest)){
            Map<String,String> resultMap = new HashMap<String, String>();
            resultMap.put("login_status", "300");
            resultMap.put("message", "\u5F53\u524D\u7528\u6237\u6CA1\u6709\u767B\u5F55\uFF01");//当前用户没有登录！
            ShiroFilterUtils.out(servletResponse, resultMap);
        }
        return false;
    }
}
