RbacTest.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. import cn.reghao.bnt.web.WebApplication;
  2. import cn.reghao.bnt.web.admin.controller.LoginController;
  3. import cn.reghao.bnt.web.admin.db.repository.MenuRepository;
  4. import cn.reghao.bnt.web.admin.db.repository.RoleRepository;
  5. import cn.reghao.bnt.web.admin.db.repository.UserRepository;
  6. import cn.reghao.bnt.web.admin.model.constant.MenuType;
  7. import cn.reghao.bnt.web.admin.model.constant.RoleType;
  8. import cn.reghao.bnt.web.admin.model.po.Menu;
  9. import cn.reghao.bnt.web.admin.model.po.Role;
  10. import cn.reghao.bnt.web.admin.model.po.User;
  11. import cn.reghao.bnt.web.admin.service.AccountService;
  12. import cn.reghao.bnt.web.admin.service.AccountSessionService;
  13. import cn.reghao.bnt.web.admin.service.MenuService;
  14. import cn.reghao.bnt.web.config.web.exception.ControllerErrorHandler;
  15. import cn.reghao.jutil.jdk.security.RandomString;
  16. import io.swagger.v3.oas.annotations.Operation;
  17. import lombok.AllArgsConstructor;
  18. import lombok.Getter;
  19. import lombok.extern.slf4j.Slf4j;
  20. import org.junit.jupiter.api.Test;
  21. import org.springframework.beans.factory.annotation.Autowired;
  22. import org.springframework.boot.test.context.SpringBootTest;
  23. import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext;
  24. import org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext;
  25. import org.springframework.context.ApplicationContext;
  26. import org.springframework.data.domain.PageRequest;
  27. import org.springframework.security.crypto.password.PasswordEncoder;
  28. import org.springframework.session.jdbc.JdbcIndexedSessionRepository;
  29. import org.springframework.test.context.ActiveProfiles;
  30. import org.springframework.web.bind.annotation.PostMapping;
  31. import org.springframework.web.bind.annotation.RequestMethod;
  32. import org.springframework.web.bind.annotation.ResponseBody;
  33. import org.springframework.web.context.WebApplicationContext;
  34. import org.springframework.web.method.HandlerMethod;
  35. import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
  36. import org.springframework.web.servlet.mvc.condition.RequestMethodsRequestCondition;
  37. import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
  38. import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
  39. import java.lang.annotation.Annotation;
  40. import java.lang.reflect.Method;
  41. import java.util.*;
  42. import java.util.stream.Collectors;
  43. /**
  44. * @author reghao
  45. * @date 2025-09-30 16:03:44
  46. */
  47. @Slf4j
  48. @ActiveProfiles("dev")
  49. @SpringBootTest(classes = WebApplication.class)
  50. public class RbacTest {
  51. @Autowired
  52. UserRepository userRepository;
  53. @Autowired
  54. private PasswordEncoder passwordEncoder;
  55. public void updatePassword() {
  56. int userId = 1;
  57. User user = userRepository.findById(userId).orElse(null);
  58. if (user == null) {
  59. return;
  60. }
  61. String newPassword = "admin123456";
  62. String newSalt = RandomString.getSalt(64);
  63. String encodedNewPasswd = passwordEncoder.encode(newPassword + newSalt);
  64. user.setEncodedPassword(encodedNewPasswd);
  65. user.setSalt(newSalt);
  66. userRepository.save(user);
  67. }
  68. @Autowired
  69. MenuService menuService;
  70. @Autowired
  71. MenuRepository menuRepository;
  72. @Autowired
  73. ApplicationContext applicationContext;
  74. @Test
  75. public void menuTest() {
  76. List<Menu> menuList = new ArrayList<>();
  77. Map<String, Menu> groupMap = menuRepository.findByDeletedIsFalseAndType(MenuType.DIR.name()).stream()
  78. .collect(Collectors.groupingBy(Menu::getUrl,
  79. Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0))));
  80. Object bean = applicationContext.getBean("requestMappingHandlerMapping");
  81. if (!(bean instanceof RequestMappingHandlerMapping requestMappingHandlerMapping)) {
  82. return;
  83. }
  84. Set<String> allUrls = new HashSet<>();
  85. Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping.getHandlerMethods();
  86. for (Map.Entry<RequestMappingInfo, HandlerMethod> mappingInfoHandlerMethodEntry : map.entrySet()) {
  87. RequestMappingInfo requestMappingInfo = mappingInfoHandlerMethodEntry.getKey();
  88. HandlerMethod handlerMethod = mappingInfoHandlerMethodEntry.getValue();
  89. List<String> requestMethods = requestMappingInfo.getMethodsCondition().getMethods().stream()
  90. .map(RequestMethod::name)
  91. .collect(Collectors.toList());
  92. List<String> urls = new ArrayList<>(requestMappingInfo.getPatternValues());
  93. String requestMethod = "";
  94. if (!requestMethods.isEmpty()) {
  95. requestMethod = requestMethods.get(0).toLowerCase(Locale.ROOT);
  96. }
  97. String url = urls.get(0).substring(1);
  98. String uniqueUrl = String.format("%s %s", requestMethod, url);
  99. if (!allUrls.add(uniqueUrl)) {
  100. log.info("url {} exist", uniqueUrl);
  101. }
  102. Class<?> clazz = handlerMethod.getMethod().getDeclaringClass();
  103. Method method = handlerMethod.getMethod();
  104. String className = clazz.getName();
  105. String methodName = method.getName();
  106. Annotation[] classAnnotations = clazz.getDeclaredAnnotations();
  107. Annotation[] methodAnnotations = method.getDeclaredAnnotations();
  108. if (className.equals(LoginController.class.getName())) {
  109. log.info("skip LoginController");
  110. continue;
  111. } else if (className.equals(ControllerErrorHandler.class.getName())) {
  112. log.info("skip ControllerErrorHandler");
  113. continue;
  114. } else if (url.startsWith("v3") || url.startsWith("swagger")) {
  115. log.info("skip swagger");
  116. continue;
  117. }
  118. String menuName = methodName;
  119. MenuType menuType = MenuType.GET;
  120. boolean visible = true;
  121. for (Annotation annotation : methodAnnotations) {
  122. if (annotation instanceof Operation) {
  123. Operation operation = (Operation) annotation;
  124. menuName = operation.summary();
  125. } else if (annotation instanceof PostMapping) {
  126. menuType = MenuType.POST;
  127. } else if (annotation instanceof ResponseBody) {
  128. visible = false;
  129. }
  130. }
  131. int pid = 0;
  132. Menu menu = menuRepository.findByDeletedIsFalseAndTypeAndUrl(menuType.name(), url);
  133. if (menu == null) {
  134. log.info("{} not exist", url);
  135. for (String parent : groupMap.keySet()) {
  136. if (url.startsWith(parent)) {
  137. pid = groupMap.get(parent).getId();
  138. }
  139. }
  140. Menu menu1 = new Menu(menuType, visible, menuName, url, pid);
  141. menuList.add(menu1);
  142. }
  143. }
  144. //menuRepository.saveAll(menuList);
  145. System.out.println();
  146. List<Menu> allMenus = menuRepository.findAllByDeleted(false).stream()
  147. .filter(menu -> !menu.getType().equals(MenuType.DIR.name()))
  148. .collect(Collectors.toList());
  149. for (Menu menu : allMenus) {
  150. String type = menu.getType();
  151. String url = menu.getUrl();
  152. String key = String.format("%s %s", type, url).toLowerCase();
  153. if (!allUrls.contains(key)) {
  154. log.info("{} not exit in current url set", key);
  155. //menuService.deleteMenu(menu.getId());
  156. }
  157. }
  158. }
  159. @Autowired
  160. RoleRepository roleRepository;
  161. @Test
  162. public void roleTest() {
  163. for (RoleType roleType : RoleType.values()) {
  164. Role role = new Role(roleType);
  165. Role roleEntity = roleRepository.findByName(role.getName());
  166. if (roleEntity == null) {
  167. //roleRepository.save(role);
  168. } else {
  169. log.info("role {} exist", role.getName());
  170. }
  171. }
  172. }
  173. @Test
  174. public void getAllUrlsTest() {
  175. List<Map<String, String>> resList = new ArrayList<>();
  176. Object bean = applicationContext.getBean("requestMappingHandlerMapping");
  177. if (!(bean instanceof RequestMappingHandlerMapping requestMappingHandlerMapping)) {
  178. return;
  179. }
  180. Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping.getHandlerMethods();
  181. for (Map.Entry<RequestMappingInfo, HandlerMethod> mappingInfoHandlerMethodEntry : map.entrySet()) {
  182. Map<String, String> resultMap = new LinkedHashMap<>();
  183. RequestMappingInfo requestMappingInfo = mappingInfoHandlerMethodEntry.getKey();
  184. HandlerMethod handlerMethod = mappingInfoHandlerMethodEntry.getValue();
  185. resultMap.put("className", handlerMethod.getMethod().getDeclaringClass().getName());
  186. Annotation[] declaredAnnotations = handlerMethod.getMethod().getDeclaredAnnotations();
  187. /*Annotation[] parentAnnotations = handlerMethod.getBeanType().getAnnotations();
  188. for (Annotation annotation : parentAnnotations) {
  189. if (annotation instanceof Api) {
  190. Api api = (Api) annotation;
  191. resultMap.put("classDesc", api.value());
  192. } else if (annotation instanceof RequestMapping) {
  193. RequestMapping requestMapping = (RequestMapping) annotation;
  194. if (null != requestMapping.value() && requestMapping.value().length > 0) {
  195. resultMap.put("classURL", requestMapping.value()[0]);
  196. }
  197. }
  198. }*/
  199. resultMap.put("methodName", handlerMethod.getMethod().getName());
  200. /*Annotation[] annotations = handlerMethod.getMethod().getDeclaredAnnotations();
  201. if (annotations != null) {
  202. for (Annotation annotation : annotations) {
  203. if (annotation instanceof ApiOperation) {
  204. ApiOperation methodDesc = (ApiOperation) annotation;
  205. String desc = methodDesc.value();
  206. resultMap.put("methodDesc", desc);
  207. }
  208. }
  209. }*/
  210. PatternsRequestCondition p = requestMappingInfo.getPatternsCondition();
  211. for (String url : p.getPatterns()) {
  212. resultMap.put("methodURL", url);
  213. }
  214. RequestMethodsRequestCondition methodsRequestCondition = requestMappingInfo.getMethodsCondition();
  215. for (RequestMethod requestMethod : methodsRequestCondition.getMethods()) {
  216. resultMap.put("requestType", requestMethod.toString());
  217. }
  218. resList.add(resultMap);
  219. }
  220. List<ReqUrl> list = map.keySet().stream().map(requestMappingInfo -> {
  221. List<String> list1 = new ArrayList<>(requestMappingInfo.getPatternsCondition().getPatterns());
  222. List<RequestMethod> list2 = new ArrayList<>(requestMappingInfo.getMethodsCondition().getMethods());
  223. String url = list1.get(0);
  224. if (url.equals("/error") || url.startsWith("/swagger")) {
  225. return null;
  226. }
  227. String method = list2.get(0).name();
  228. return new ReqUrl(method, url);
  229. }).filter(Objects::nonNull).collect(Collectors.toList());
  230. System.out.println();
  231. }
  232. @AllArgsConstructor
  233. @Getter
  234. static class ReqUrl {
  235. private String method;
  236. private String url;
  237. @Override
  238. public String toString() {
  239. return url;
  240. }
  241. }
  242. @Autowired
  243. JdbcIndexedSessionRepository sessionRepository;
  244. @Autowired
  245. AccountService accountService;
  246. @Autowired
  247. AccountSessionService accountSessionService;
  248. @Test
  249. public void sessionTest() {
  250. accountService.getUserVOByPage(PageRequest.of(0, 100)).forEach(userVO -> {
  251. int userId = userVO.getUserId();
  252. accountSessionService.getUserSession(userId).forEach(userSession -> {
  253. String sessionId = userSession.getSessionId();
  254. sessionRepository.deleteById(sessionId);
  255. });
  256. });
  257. }
  258. }