package org.ccpit.base.security;

import org.apache.commons.collections.CollectionUtils;
import org.ccpit.base.role.Role;
import org.ccpit.base.user.User;
import org.ccpit.base.utils.UrlRolesMapper;
import org.ccpit.base.utils.UserRolesUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Set;

/**
 * 安全权限拦截器  拦截所有后台请求 判断User role url的对应关系
 * Created by Administrator on 2015/9/2.
 */
@Configurable
public class SecurityInterceptor extends HandlerInterceptorAdapter {
    //默认的返回值 没有找到Url对应的角色的时候返回此参数
    private static final boolean DEFAULT_RETURN = true;
    @Autowired
    private UrlRolesMapper urlRolesMapper;
    @Autowired
    private UserRolesUtil userRolesUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        User user = (User) request.getSession().getAttribute("user_in_session");
        if (user == null) {
            return true;
        }

        Set<Role> roles = urlRolesMapper.getRoles(request.getRequestURI());
        if (roles == null || roles.isEmpty()) {
            return DEFAULT_RETURN;
        }

        Set<Role> roleSet = userRolesUtil.getAllRoles(request);
        return CollectionUtils.containsAny(roles, roleSet);
    }
}
