package com.jilongda.manage.security; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.jilongda.manage.authority.mapper.SecResourcesMapper; import com.jilongda.manage.authority.model.SecResources; import com.jilongda.common.security.JwtTokenUtils; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * @author xiaochen * @ClassName RbacAuthorityService * @Description * @date 2020-09-23 11:32 */ @Component @Slf4j public class RbacAuthorityService { private final SysUserDetailsService loadUserDetailsService; private final SecResourcesMapper secResourcesMapper; @Autowired public RbacAuthorityService(SysUserDetailsService loadUserDetailsService, SecResourcesMapper secResourcesMapper) { this.loadUserDetailsService = loadUserDetailsService; this.secResourcesMapper = secResourcesMapper; } /** * 校验权限 * * @param request * @param authentication * @return */ public boolean hasPermission(HttpServletRequest request, Authentication authentication) { String userName = JwtTokenUtils.getUsername(authentication); boolean hasPermission = false; if (StringUtils.isNotBlank(userName)) { SecurityUserDetails sysUserDetails = loadUserDetailsService.loadUserByUsername(userName); //获取资源,前后端分离,所以过滤页面权限,只保留按钮权限 List resources = sysUserDetails.getResources().stream() // 过滤页面权限 1页面 2按钮 .filter(resource -> resource.getCate().intValue() != 1) // 不允许通过的请求地址 .filter(resource -> !resource.getPermit()) // 过滤 URL 为空 .filter(resource -> StringUtils.isNotBlank(resource.getPath())) // 过滤 METHOD 为空,METHOD不可能为空 .collect(Collectors.toList()); List sysResources; List antPathRequestMatchers = new ArrayList<>(); Long uid = sysUserDetails.getId(); // 超管 if (uid.equals(1)) { sysResources = secResourcesMapper.selectList(Wrappers.lambdaQuery(SecResources.class)); } else { // 其他管理员 sysResources = secResourcesMapper.selectResourceByUid(uid); } // 过滤页面权限 1页面 2按钮 List resourcesList = sysResources.stream().filter(resource -> resource.getCate().intValue() != 1) // 过滤 URL 为空 .filter(resource -> StringUtils.isNotBlank(resource.getPath())) // 过滤 METHOD 为空,METHOD不可能为空 .collect(Collectors.toList()); resourcesList.forEach(item -> { antPathRequestMatchers.add(new AntPathRequestMatcher(item.getPath())); }); AntPathRequestMatcher antPathMatcher; for (SecResources btnPerm : resources) { antPathMatcher = new AntPathRequestMatcher(btnPerm.getPath()); if (antPathMatcher.matches(request)) { hasPermission = true; break; } } return hasPermission; } else { return false; } } }