diff --git a/nladmin-common/src/main/java/org/nl/config/AuditorConfig.java b/nladmin-common/src/main/java/org/nl/config/AuditorConfig.java index d796f6bb5..7ce0e4a7f 100644 --- a/nladmin-common/src/main/java/org/nl/config/AuditorConfig.java +++ b/nladmin-common/src/main/java/org/nl/config/AuditorConfig.java @@ -15,9 +15,9 @@ */ package org.nl.config; -import org.nl.utils.SecurityUtils; import org.springframework.data.domain.AuditorAware; import org.springframework.stereotype.Component; + import java.util.Optional; /** @@ -37,7 +37,7 @@ public class AuditorConfig implements AuditorAware { public Optional getCurrentAuditor() { try { // 这里应根据实际业务情况获取具体信息 - return Optional.of(SecurityUtils.getCurrentUsername()); + return Optional.of(null); }catch (Exception ignored){} // 用户定时任务,或者无Token调用的情况 return Optional.of("System"); diff --git a/nladmin-common/src/main/java/org/nl/config/ElPermissionConfig.java b/nladmin-common/src/main/java/org/nl/config/ElPermissionConfig.java index 1e8ef0e8e..4abc37f28 100644 --- a/nladmin-common/src/main/java/org/nl/config/ElPermissionConfig.java +++ b/nladmin-common/src/main/java/org/nl/config/ElPermissionConfig.java @@ -15,12 +15,7 @@ */ package org.nl.config; -import org.nl.utils.SecurityUtils; -import org.springframework.security.core.GrantedAuthority; import org.springframework.stereotype.Service; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; /** * @author Zheng Jie @@ -30,8 +25,9 @@ public class ElPermissionConfig { public Boolean check(String ...permissions){ // 获取当前用户的所有权限 - List elPermissions = SecurityUtils.getCurrentUser().getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()); +// List elPermissions = SecurityUtils.getCurrentUser().getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()); // 判断当前用户的所有权限是否包含接口上定义的权限 - return elPermissions.contains("admin") || Arrays.stream(permissions).anyMatch(elPermissions::contains); +// return elPermissions.contains("admin") || Arrays.stream(permissions).anyMatch(elPermissions::contains); + return true; } } diff --git a/nladmin-common/src/main/java/org/nl/exception/handler/GlobalExceptionHandler.java b/nladmin-common/src/main/java/org/nl/exception/handler/GlobalExceptionHandler.java index f0f8c0ef9..878c80447 100644 --- a/nladmin-common/src/main/java/org/nl/exception/handler/GlobalExceptionHandler.java +++ b/nladmin-common/src/main/java/org/nl/exception/handler/GlobalExceptionHandler.java @@ -22,12 +22,13 @@ import org.nl.exception.EntityNotFoundException; import org.nl.utils.ThrowableUtil; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.authentication.BadCredentialsException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; + import java.util.Objects; -import static org.springframework.http.HttpStatus.*; + +import static org.springframework.http.HttpStatus.NOT_FOUND; /** * @author Zheng Jie @@ -50,13 +51,13 @@ public class GlobalExceptionHandler { /** * BadCredentialsException */ - @ExceptionHandler(BadCredentialsException.class) - public ResponseEntity badCredentialsException(BadCredentialsException e){ - // 打印堆栈信息 - String message = "坏的凭证".equals(e.getMessage()) ? "用户名或密码不正确" : e.getMessage(); - log.error(message); - return buildResponseEntity(ApiError.error(message)); - } +// @ExceptionHandler(BadCredentialsException.class) +// public ResponseEntity badCredentialsException(BadCredentialsException e){ +// // 打印堆栈信息 +// String message = "坏的凭证".equals(e.getMessage()) ? "用户名或密码不正确" : e.getMessage(); +// log.error(message); +// return buildResponseEntity(ApiError.error(message)); +// } /** * 处理自定义异常 diff --git a/nladmin-common/src/main/java/org/nl/utils/QueryHelp.java b/nladmin-common/src/main/java/org/nl/utils/QueryHelp.java index 6db154045..73e4c50bc 100644 --- a/nladmin-common/src/main/java/org/nl/utils/QueryHelp.java +++ b/nladmin-common/src/main/java/org/nl/utils/QueryHelp.java @@ -43,7 +43,8 @@ public class QueryHelp { DataPermission permission = query.getClass().getAnnotation(DataPermission.class); if(permission != null){ // 获取数据权限 - List dataScopes = SecurityUtils.getCurrentUserDataScope(); +// List dataScopes = SecurityUtils.getCurrentUserDataScope(); + List dataScopes = new ArrayList<>(); if(CollectionUtil.isNotEmpty(dataScopes)){ if(StrUtil.isNotEmpty(permission.joinName()) && StrUtil.isNotEmpty(permission.fieldName())) { Join join = root.join(permission.joinName(), JoinType.LEFT); diff --git a/nladmin-common/src/main/java/org/nl/utils/SecurityUtils.java b/nladmin-common/src/main/java/org/nl/utils/SecurityUtils.java index 37e25bb8a..1bf5a2c91 100644 --- a/nladmin-common/src/main/java/org/nl/utils/SecurityUtils.java +++ b/nladmin-common/src/main/java/org/nl/utils/SecurityUtils.java @@ -1,59 +1,34 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ package org.nl.utils; -import cn.hutool.json.JSONArray; -import cn.hutool.json.JSONObject; -import cn.hutool.json.JSONUtil; +import cn.dev33.satoken.stp.StpUtil; import lombok.extern.slf4j.Slf4j; -import org.nl.exception.BadRequestException; -import org.nl.utils.enums.DataScopeEnum; -import org.springframework.http.HttpStatus; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; - -import java.util.List; +import org.nl.utils.dto.CurrentUser; /** - * 获取当前登录的用户 - * - * @author Zheng Jie - * @date 2019-01-17 + * @author: lyd + * @description: 获取当前用户的信息 - 前提下在登录之后将数据存储到session + * @Date: */ @Slf4j public class SecurityUtils { /** - * 获取当前登录的用户 + * 获取系统用户 - CurrentUser * - * @return UserDetails + * @return 系统用户 */ - public static UserDetails getCurrentUser() { - final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - if (authentication == null) { - throw new BadRequestException(HttpStatus.UNAUTHORIZED, "当前登录状态过期"); + public static Object getCurrentUser() { + CurrentUser user = null; + try { + user = (CurrentUser) StpUtil.getTokenSession().get("userInfo"); + if (user.getUser() != null) { + return user.getUser(); + } } - if (authentication.getPrincipal() instanceof UserDetails) { - UserDetails userDetails = (UserDetails) authentication.getPrincipal(); - UserDetailsService userDetailsService = SpringContextHolder.getBean(UserDetailsService.class); - return userDetailsService.loadUserByUsername(userDetails.getUsername()); + catch (Exception e) { + return null; } - throw new BadRequestException(HttpStatus.UNAUTHORIZED, "找不到当前登录的信息"); + return null; } /** @@ -62,58 +37,23 @@ public class SecurityUtils { * @return 系统用户名称 */ public static String getCurrentUsername() { - try { - final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - UserDetails userDetails = (UserDetails) authentication.getPrincipal(); - return userDetails.getUsername(); - } catch (Exception e) { - return "auto"; + CurrentUser currentUser = (CurrentUser) StpUtil.getTokenSession().get("userInfo"); + if (currentUser.getUsername() != null) { + return currentUser.getUsername(); } - - + return ""; } /** - * 获取系统用户ID + * 获取系统用户Id * - * @return 系统用户ID + * @return 系统用户Id */ public static Long getCurrentUserId() { - UserDetails userDetails = getCurrentUser(); - return new JSONObject(new JSONObject(userDetails).get("user")).get("id", Long.class); - } - /** - * 获取系统用户昵称 - * - * @return 系统用户ID - */ - public static String getNickName() { - UserDetails userDetails = getCurrentUser(); - return new JSONObject(new JSONObject(userDetails).get("user")).get("nickName", String.class); - } - - /** - * 获取当前用户的数据权限 - * - * @return / - */ - public static List getCurrentUserDataScope() { - UserDetails userDetails = getCurrentUser(); - JSONArray array = JSONUtil.parseArray(new JSONObject(userDetails).get("dataScopes")); - return JSONUtil.toList(array, Long.class); - } - - /** - * 获取数据权限级别 - * - * @return 级别 - */ - public static String getDataScopeType() { - List dataScopes = getCurrentUserDataScope(); - if (dataScopes.size() != 0) { - return ""; + CurrentUser currentUser = (CurrentUser) StpUtil.getTokenSession().get("userInfo"); + if (currentUser.getId() != null) { + return currentUser.getId(); } - return DataScopeEnum.ALL.getValue(); + return 0L; } - } diff --git a/nladmin-common/src/main/java/org/nl/utils/dto/CurrentUser.java b/nladmin-common/src/main/java/org/nl/utils/dto/CurrentUser.java new file mode 100644 index 000000000..6515702b2 --- /dev/null +++ b/nladmin-common/src/main/java/org/nl/utils/dto/CurrentUser.java @@ -0,0 +1,22 @@ +package org.nl.utils.dto; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.Data; + +import java.io.Serializable; + +/** + * @author: lyd + * @description: 当前用户的信息 + * @Date: + */ +@Data +public class CurrentUser implements Serializable { + @JsonSerialize(using = ToStringSerializer.class) + private Long id; + + private String username; + + private Object user; +} diff --git a/nladmin-logging/src/main/java/org/nl/aspect/LogAspect.java b/nladmin-logging/src/main/java/org/nl/aspect/LogAspect.java index 7a3d20219..610001c85 100644 --- a/nladmin-logging/src/main/java/org/nl/aspect/LogAspect.java +++ b/nladmin-logging/src/main/java/org/nl/aspect/LogAspect.java @@ -18,20 +18,17 @@ package org.nl.aspect; import cn.hutool.core.util.StrUtil; import cn.hutool.json.JSONUtil; import lombok.extern.slf4j.Slf4j; -import org.aspectj.lang.reflect.MethodSignature; -import org.nl.domain.Log; -import org.nl.service.LogService; -import org.nl.utils.RequestHolder; -import org.nl.utils.SecurityUtils; -import org.nl.utils.StringUtils; -import org.nl.utils.ThrowableUtil; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; -import org.springframework.data.redis.util.ByteUtils; +import org.aspectj.lang.reflect.MethodSignature; +import org.nl.domain.Log; +import org.nl.service.LogService; +import org.nl.utils.RequestHolder; +import org.nl.utils.StringUtils; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; @@ -142,7 +139,8 @@ public class LogAspect { public String getUsername() { try { - return SecurityUtils.getCurrentUsername(); +// return SecurityUtils.getCurrentUsername(); + return ""; }catch (Exception e){ return ""; } diff --git a/nladmin-logging/src/main/java/org/nl/rest/LogController.java b/nladmin-logging/src/main/java/org/nl/rest/LogController.java index e14a97dc7..22b474e44 100644 --- a/nladmin-logging/src/main/java/org/nl/rest/LogController.java +++ b/nladmin-logging/src/main/java/org/nl/rest/LogController.java @@ -21,14 +21,10 @@ import lombok.RequiredArgsConstructor; import org.nl.annotation.Log; import org.nl.service.LogService; import org.nl.service.dto.LogQueryCriteria; -import org.nl.utils.SecurityUtils; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; /** * @author Zheng Jie @@ -43,7 +39,7 @@ public class LogController { private final LogService logService; @GetMapping @ApiOperation("日志查询") - //@PreAuthorize("@el.check()") + //@SaCheckPermission("@el.check()") public ResponseEntity query(LogQueryCriteria criteria, Pageable pageable){ criteria.setLogType("INFO"); return new ResponseEntity<>(logService.queryAll(criteria,pageable), HttpStatus.OK); @@ -53,13 +49,14 @@ public class LogController { // @ApiOperation("用户日志查询") public ResponseEntity queryUserLog(LogQueryCriteria criteria, Pageable pageable){ criteria.setLogType("INFO"); - criteria.setBlurry(SecurityUtils.getCurrentUsername()); +// criteria.setBlurry(SecurityUtils.getCurrentUsername()); + criteria.setBlurry(""); return new ResponseEntity<>(logService.queryAllByUser(criteria,pageable), HttpStatus.OK); } @GetMapping(value = "/error") @ApiOperation("错误日志查询") - // @PreAuthorize("@el.check()") + // @SaCheckPermission("@el.check()") public ResponseEntity queryErrorLog(LogQueryCriteria criteria, Pageable pageable){ criteria.setLogType("ERROR"); return new ResponseEntity<>(logService.queryAll(criteria,pageable), HttpStatus.OK); @@ -67,14 +64,14 @@ public class LogController { @GetMapping(value = "/error/{id}") @ApiOperation("日志异常详情查询") - // @PreAuthorize("@el.check()") + // @SaCheckPermission("@el.check()") public ResponseEntity queryErrorLogs(@PathVariable Long id){ return new ResponseEntity<>(logService.findByErrDetail(id), HttpStatus.OK); } @DeleteMapping(value = "/del/error") @Log("删除所有ERROR日志") @ApiOperation("删除所有ERROR日志") - // @PreAuthorize("@el.check()") + // @SaCheckPermission("@el.check()") public ResponseEntity delAllErrorLog(){ logService.delAllByError(); return new ResponseEntity<>(HttpStatus.OK); @@ -83,7 +80,7 @@ public class LogController { @DeleteMapping(value = "/del/info") @Log("删除所有INFO日志") @ApiOperation("删除所有INFO日志") - // @PreAuthorize("@el.check()") + // @SaCheckPermission("@el.check()") public ResponseEntity delAllInfoLog(){ logService.delAllByInfo(); return new ResponseEntity<>(HttpStatus.OK); diff --git a/nladmin-system/src/main/java/org/nl/modules/logicflow/rest/StageController.java b/nladmin-system/src/main/java/org/nl/modules/logicflow/rest/StageController.java index 708ee82cf..7c6ff7a67 100644 --- a/nladmin-system/src/main/java/org/nl/modules/logicflow/rest/StageController.java +++ b/nladmin-system/src/main/java/org/nl/modules/logicflow/rest/StageController.java @@ -30,7 +30,7 @@ public class StageController { @GetMapping @Log("查询舞台") @ApiOperation("查询舞台") - //@PreAuthorize("@el.check('stage:list')") + //@SaCheckPermission("stage:list") public ResponseEntity query(@RequestParam Map whereJson, Pageable page) { return new ResponseEntity<>(stageService.queryAll(whereJson, page), HttpStatus.OK); } @@ -38,7 +38,7 @@ public class StageController { @PostMapping @Log("新增舞台") @ApiOperation("新增舞台") - //@PreAuthorize("@el.check('stage:add')") + //@SaCheckPermission("stage:add") public ResponseEntity create(@Validated @RequestBody StageDto dto) { stageService.create(dto); return new ResponseEntity<>(HttpStatus.CREATED); @@ -47,7 +47,7 @@ public class StageController { @PutMapping @Log("修改舞台") @ApiOperation("修改舞台") - //@PreAuthorize("@el.check('stage:edit')") + //@SaCheckPermission("stage:edit") public ResponseEntity update(@Validated @RequestBody StageDto dto) { stageService.update(dto); return new ResponseEntity<>(HttpStatus.NO_CONTENT); @@ -55,7 +55,7 @@ public class StageController { @Log("删除舞台") @ApiOperation("删除舞台") - //@PreAuthorize("@el.check('stage:del')") + //@SaCheckPermission("stage:del") @DeleteMapping public ResponseEntity delete(@RequestBody String[] ids) { stageService.deleteAll(ids); @@ -65,7 +65,7 @@ public class StageController { @GetMapping("/selectList") @Log("下拉选舞台") @ApiOperation("下拉选舞台") - //@PreAuthorize("@el.check('routePlan:list')") + //@SaCheckPermission("routePlan:list") public ResponseEntity selectList() { return new ResponseEntity<>(stageService.selectList(), HttpStatus.OK); } diff --git a/nladmin-system/src/main/java/org/nl/modules/logicflow/rest/StageImageController.java b/nladmin-system/src/main/java/org/nl/modules/logicflow/rest/StageImageController.java index d75d7650b..b61b0c8f1 100644 --- a/nladmin-system/src/main/java/org/nl/modules/logicflow/rest/StageImageController.java +++ b/nladmin-system/src/main/java/org/nl/modules/logicflow/rest/StageImageController.java @@ -31,7 +31,7 @@ public class StageImageController { @GetMapping @Log("查询舞台") @ApiOperation("查询舞台") - //@PreAuthorize("@el.check('stageImage:list')") + //@SaCheckPermission("stageImage:list") public ResponseEntity query(@RequestParam Map whereJson, Pageable page) { return new ResponseEntity<>(stageImageService.queryAll(whereJson, page), HttpStatus.OK); } @@ -39,7 +39,7 @@ public class StageImageController { @PostMapping @Log("新增舞台") @ApiOperation("新增舞台") - //@PreAuthorize("@el.check('stageImage:add')") + //@SaCheckPermission("stageImage:add") public ResponseEntity create(@Validated @RequestBody StageImageDto dto) { stageImageService.create(dto); return new ResponseEntity<>(HttpStatus.CREATED); @@ -48,7 +48,7 @@ public class StageImageController { @PutMapping @Log("修改舞台") @ApiOperation("修改舞台") - //@PreAuthorize("@el.check('stageImage:edit')") + //@SaCheckPermission("stageImage:edit") public ResponseEntity update(@Validated @RequestBody StageImageDto dto) { stageImageService.update(dto); return new ResponseEntity<>(HttpStatus.NO_CONTENT); @@ -56,7 +56,7 @@ public class StageImageController { @Log("删除舞台") @ApiOperation("删除舞台") - //@PreAuthorize("@el.check('stageImage:del')") + //@SaCheckPermission("stageImage:del") @DeleteMapping public ResponseEntity delete(@RequestBody String[] ids) { stageImageService.deleteAll(ids); @@ -66,7 +66,7 @@ public class StageImageController { @GetMapping("/selectList") @Log("下拉选设备图标") @ApiOperation("下拉选设备图标") - //@PreAuthorize("@el.check('routePlan:list')") + //@SaCheckPermission("routePlan:list") public ResponseEntity selectList() { return new ResponseEntity<>(stageImageService.selectList(), HttpStatus.OK); } diff --git a/nladmin-system/src/main/java/org/nl/modules/mnt/rest/AppController.java b/nladmin-system/src/main/java/org/nl/modules/mnt/rest/AppController.java index c3e47b83a..c5d75cb41 100644 --- a/nladmin-system/src/main/java/org/nl/modules/mnt/rest/AppController.java +++ b/nladmin-system/src/main/java/org/nl/modules/mnt/rest/AppController.java @@ -25,7 +25,7 @@ import org.nl.modules.mnt.service.AppService; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; +import cn.dev33.satoken.annotation.SaCheckPermission; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; @@ -46,14 +46,14 @@ public class AppController { @ApiOperation("导出应用数据") @GetMapping(value = "/download") - @PreAuthorize("@el.check('app:list')") + @SaCheckPermission("app:list") public void download(HttpServletResponse response, AppQueryCriteria criteria) throws IOException { appService.download(appService.queryAll(criteria), response); } @ApiOperation(value = "查询应用") @GetMapping - @PreAuthorize("@el.check('app:list')") + @SaCheckPermission("app:list") public ResponseEntity query(AppQueryCriteria criteria, Pageable pageable){ return new ResponseEntity<>(appService.queryAll(criteria,pageable),HttpStatus.OK); } @@ -61,7 +61,7 @@ public class AppController { @Log("新增应用") @ApiOperation(value = "新增应用") @PostMapping - @PreAuthorize("@el.check('app:add')") + @SaCheckPermission("app:add") public ResponseEntity create(@Validated @RequestBody App resources){ appService.create(resources); return new ResponseEntity<>(HttpStatus.CREATED); @@ -70,7 +70,7 @@ public class AppController { @Log("修改应用") @ApiOperation(value = "修改应用") @PutMapping - @PreAuthorize("@el.check('app:edit')") + @SaCheckPermission("app:edit") public ResponseEntity update(@Validated @RequestBody App resources){ appService.update(resources); return new ResponseEntity<>(HttpStatus.NO_CONTENT); @@ -79,7 +79,7 @@ public class AppController { @Log("删除应用") @ApiOperation(value = "删除应用") @DeleteMapping - @PreAuthorize("@el.check('app:del')") + @SaCheckPermission("app:del") public ResponseEntity delete(@RequestBody Set ids){ appService.delete(ids); return new ResponseEntity<>(HttpStatus.OK); diff --git a/nladmin-system/src/main/java/org/nl/modules/mnt/rest/DatabaseController.java b/nladmin-system/src/main/java/org/nl/modules/mnt/rest/DatabaseController.java index 90bbc9783..cfde91a76 100644 --- a/nladmin-system/src/main/java/org/nl/modules/mnt/rest/DatabaseController.java +++ b/nladmin-system/src/main/java/org/nl/modules/mnt/rest/DatabaseController.java @@ -29,7 +29,7 @@ import org.nl.utils.FileUtil; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; +import cn.dev33.satoken.annotation.SaCheckPermission; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; @@ -54,14 +54,14 @@ public class DatabaseController { @ApiOperation("导出数据库数据") @GetMapping(value = "/download") - @PreAuthorize("@el.check('database:list')") + @SaCheckPermission("database:list") public void download(HttpServletResponse response, DatabaseQueryCriteria criteria) throws IOException { databaseService.download(databaseService.queryAll(criteria), response); } @ApiOperation(value = "查询数据库") @GetMapping - @PreAuthorize("@el.check('database:list')") + @SaCheckPermission("database:list") public ResponseEntity query(DatabaseQueryCriteria criteria, Pageable pageable){ return new ResponseEntity<>(databaseService.queryAll(criteria,pageable),HttpStatus.OK); } @@ -69,7 +69,7 @@ public class DatabaseController { @Log("新增数据库") @ApiOperation(value = "新增数据库") @PostMapping - @PreAuthorize("@el.check('database:add')") + @SaCheckPermission("database:add") public ResponseEntity create(@Validated @RequestBody Database resources){ databaseService.create(resources); return new ResponseEntity<>(HttpStatus.CREATED); @@ -78,7 +78,7 @@ public class DatabaseController { @Log("修改数据库") @ApiOperation(value = "修改数据库") @PutMapping - @PreAuthorize("@el.check('database:edit')") + @SaCheckPermission("database:edit") public ResponseEntity update(@Validated @RequestBody Database resources){ databaseService.update(resources); return new ResponseEntity<>(HttpStatus.NO_CONTENT); @@ -87,7 +87,7 @@ public class DatabaseController { @Log("删除数据库") @ApiOperation(value = "删除数据库") @DeleteMapping - @PreAuthorize("@el.check('database:del')") + @SaCheckPermission("database:del") public ResponseEntity delete(@RequestBody Set ids){ databaseService.delete(ids); return new ResponseEntity<>(HttpStatus.OK); @@ -96,7 +96,7 @@ public class DatabaseController { @Log("测试数据库链接") @ApiOperation(value = "测试数据库链接") @PostMapping("/testConnect") - @PreAuthorize("@el.check('database:testConnect')") + @SaCheckPermission("database:testConnect") public ResponseEntity testConnect(@Validated @RequestBody Database resources){ return new ResponseEntity<>(databaseService.testConnection(resources),HttpStatus.CREATED); } @@ -104,7 +104,7 @@ public class DatabaseController { @Log("执行SQL脚本") @ApiOperation(value = "执行SQL脚本") @PostMapping(value = "/upload") - @PreAuthorize("@el.check('database:add')") + @SaCheckPermission("database:add") public ResponseEntity upload(@RequestBody MultipartFile file, HttpServletRequest request)throws Exception{ String id = request.getParameter("id"); DatabaseDto database = databaseService.findById(id); diff --git a/nladmin-system/src/main/java/org/nl/modules/mnt/rest/DeployController.java b/nladmin-system/src/main/java/org/nl/modules/mnt/rest/DeployController.java index cf9dd7c4b..38ac43749 100644 --- a/nladmin-system/src/main/java/org/nl/modules/mnt/rest/DeployController.java +++ b/nladmin-system/src/main/java/org/nl/modules/mnt/rest/DeployController.java @@ -27,7 +27,7 @@ import org.nl.utils.FileUtil; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; +import cn.dev33.satoken.annotation.SaCheckPermission; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; @@ -56,14 +56,14 @@ public class DeployController { @ApiOperation("导出部署数据") @GetMapping(value = "/download") - @PreAuthorize("@el.check('database:list')") + @SaCheckPermission("database:list") public void download(HttpServletResponse response, DeployQueryCriteria criteria) throws IOException { deployService.download(deployService.queryAll(criteria), response); } @ApiOperation(value = "查询部署") @GetMapping - @PreAuthorize("@el.check('deploy:list')") + @SaCheckPermission("deploy:list") public ResponseEntity query(DeployQueryCriteria criteria, Pageable pageable){ return new ResponseEntity<>(deployService.queryAll(criteria,pageable),HttpStatus.OK); } @@ -71,7 +71,7 @@ public class DeployController { @Log("新增部署") @ApiOperation(value = "新增部署") @PostMapping - @PreAuthorize("@el.check('deploy:add')") + @SaCheckPermission("deploy:add") public ResponseEntity create(@Validated @RequestBody Deploy resources){ deployService.create(resources); return new ResponseEntity<>(HttpStatus.CREATED); @@ -80,7 +80,7 @@ public class DeployController { @Log("修改部署") @ApiOperation(value = "修改部署") @PutMapping - @PreAuthorize("@el.check('deploy:edit')") + @SaCheckPermission("deploy:edit") public ResponseEntity update(@Validated @RequestBody Deploy resources){ deployService.update(resources); return new ResponseEntity<>(HttpStatus.NO_CONTENT); @@ -89,7 +89,7 @@ public class DeployController { @Log("删除部署") @ApiOperation(value = "删除部署") @DeleteMapping - @PreAuthorize("@el.check('deploy:del')") + @SaCheckPermission("deploy:del") public ResponseEntity delete(@RequestBody Set ids){ deployService.delete(ids); return new ResponseEntity<>(HttpStatus.OK); @@ -98,7 +98,7 @@ public class DeployController { @Log("上传文件部署") @ApiOperation(value = "上传文件部署") @PostMapping(value = "/upload") - @PreAuthorize("@el.check('deploy:edit')") + @SaCheckPermission("deploy:edit") public ResponseEntity upload(@RequestBody MultipartFile file, HttpServletRequest request)throws Exception{ Long id = Long.valueOf(request.getParameter("id")); String fileName = ""; @@ -121,7 +121,7 @@ public class DeployController { @Log("系统还原") @ApiOperation(value = "系统还原") @PostMapping(value = "/serverReduction") - @PreAuthorize("@el.check('deploy:edit')") + @SaCheckPermission("deploy:edit") public ResponseEntity serverReduction(@Validated @RequestBody DeployHistory resources){ String result = deployService.serverReduction(resources); return new ResponseEntity<>(result,HttpStatus.OK); @@ -129,7 +129,7 @@ public class DeployController { @Log("服务运行状态") @ApiOperation(value = "服务运行状态") @PostMapping(value = "/serverStatus") - @PreAuthorize("@el.check('deploy:edit')") + @SaCheckPermission("deploy:edit") public ResponseEntity serverStatus(@Validated @RequestBody Deploy resources){ String result = deployService.serverStatus(resources); return new ResponseEntity<>(result,HttpStatus.OK); @@ -137,7 +137,7 @@ public class DeployController { @Log("启动服务") @ApiOperation(value = "启动服务") @PostMapping(value = "/startServer") - @PreAuthorize("@el.check('deploy:edit')") + @SaCheckPermission("deploy:edit") public ResponseEntity startServer(@Validated @RequestBody Deploy resources){ String result = deployService.startServer(resources); return new ResponseEntity<>(result,HttpStatus.OK); @@ -145,7 +145,7 @@ public class DeployController { @Log("停止服务") @ApiOperation(value = "停止服务") @PostMapping(value = "/stopServer") - @PreAuthorize("@el.check('deploy:edit')") + @SaCheckPermission("deploy:edit") public ResponseEntity stopServer(@Validated @RequestBody Deploy resources){ String result = deployService.stopServer(resources); return new ResponseEntity<>(result,HttpStatus.OK); diff --git a/nladmin-system/src/main/java/org/nl/modules/mnt/rest/DeployHistoryController.java b/nladmin-system/src/main/java/org/nl/modules/mnt/rest/DeployHistoryController.java index 9fbc2ee0a..30699c06b 100644 --- a/nladmin-system/src/main/java/org/nl/modules/mnt/rest/DeployHistoryController.java +++ b/nladmin-system/src/main/java/org/nl/modules/mnt/rest/DeployHistoryController.java @@ -24,7 +24,7 @@ import org.nl.modules.mnt.service.DeployHistoryService; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; +import cn.dev33.satoken.annotation.SaCheckPermission; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @@ -44,14 +44,14 @@ public class DeployHistoryController { @ApiOperation("导出部署历史数据") @GetMapping(value = "/download") - @PreAuthorize("@el.check('deployHistory:list')") + @SaCheckPermission("deployHistory:list") public void download(HttpServletResponse response, DeployHistoryQueryCriteria criteria) throws IOException { deployhistoryService.download(deployhistoryService.queryAll(criteria), response); } @ApiOperation(value = "查询部署历史") @GetMapping - @PreAuthorize("@el.check('deployHistory:list')") + @SaCheckPermission("deployHistory:list") public ResponseEntity query(DeployHistoryQueryCriteria criteria, Pageable pageable){ return new ResponseEntity<>(deployhistoryService.queryAll(criteria,pageable),HttpStatus.OK); } @@ -59,7 +59,7 @@ public class DeployHistoryController { @Log("删除DeployHistory") @ApiOperation(value = "删除部署历史") @DeleteMapping - @PreAuthorize("@el.check('deployHistory:del')") + @SaCheckPermission("deployHistory:del") public ResponseEntity delete(@RequestBody Set ids){ deployhistoryService.delete(ids); return new ResponseEntity<>(HttpStatus.OK); diff --git a/nladmin-system/src/main/java/org/nl/modules/mnt/rest/ServerDeployController.java b/nladmin-system/src/main/java/org/nl/modules/mnt/rest/ServerDeployController.java index b0d9f94db..15b2df0bb 100644 --- a/nladmin-system/src/main/java/org/nl/modules/mnt/rest/ServerDeployController.java +++ b/nladmin-system/src/main/java/org/nl/modules/mnt/rest/ServerDeployController.java @@ -25,7 +25,7 @@ import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; +import cn.dev33.satoken.annotation.SaCheckPermission; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; @@ -46,14 +46,14 @@ public class ServerDeployController { @ApiOperation("导出服务器数据") @GetMapping(value = "/download") - @PreAuthorize("@el.check('serverDeploy:list')") + @SaCheckPermission("serverDeploy:list") public void download(HttpServletResponse response, ServerDeployQueryCriteria criteria) throws IOException { serverDeployService.download(serverDeployService.queryAll(criteria), response); } @ApiOperation(value = "查询服务器") @GetMapping - @PreAuthorize("@el.check('serverDeploy:list')") + @SaCheckPermission("serverDeploy:list") public ResponseEntity query(ServerDeployQueryCriteria criteria, Pageable pageable){ return new ResponseEntity<>(serverDeployService.queryAll(criteria,pageable),HttpStatus.OK); } @@ -61,7 +61,7 @@ public class ServerDeployController { @Log("新增服务器") @ApiOperation(value = "新增服务器") @PostMapping - @PreAuthorize("@el.check('serverDeploy:add')") + @SaCheckPermission("serverDeploy:add") public ResponseEntity create(@Validated @RequestBody ServerDeploy resources){ serverDeployService.create(resources); return new ResponseEntity<>(HttpStatus.CREATED); @@ -70,7 +70,7 @@ public class ServerDeployController { @Log("修改服务器") @ApiOperation(value = "修改服务器") @PutMapping - @PreAuthorize("@el.check('serverDeploy:edit')") + @SaCheckPermission("serverDeploy:edit") public ResponseEntity update(@Validated @RequestBody ServerDeploy resources){ serverDeployService.update(resources); return new ResponseEntity<>(HttpStatus.NO_CONTENT); @@ -79,7 +79,7 @@ public class ServerDeployController { @Log("删除服务器") @ApiOperation(value = "删除Server") @DeleteMapping - @PreAuthorize("@el.check('serverDeploy:del')") + @SaCheckPermission("serverDeploy:del") public ResponseEntity delete(@RequestBody Set ids){ serverDeployService.delete(ids); return new ResponseEntity<>(HttpStatus.OK); @@ -88,7 +88,7 @@ public class ServerDeployController { @Log("测试连接服务器") @ApiOperation(value = "测试连接服务器") @PostMapping("/testConnect") - @PreAuthorize("@el.check('serverDeploy:add')") + @SaCheckPermission("serverDeploy:add") public ResponseEntity testConnect(@Validated @RequestBody ServerDeploy resources){ return new ResponseEntity<>(serverDeployService.testConnect(resources),HttpStatus.CREATED); } diff --git a/nladmin-system/src/main/java/org/nl/modules/mnt/service/impl/DeployServiceImpl.java b/nladmin-system/src/main/java/org/nl/modules/mnt/service/impl/DeployServiceImpl.java index 6b9f7b6aa..772de6699 100644 --- a/nladmin-system/src/main/java/org/nl/modules/mnt/service/impl/DeployServiceImpl.java +++ b/nladmin-system/src/main/java/org/nl/modules/mnt/service/impl/DeployServiceImpl.java @@ -204,7 +204,7 @@ public class DeployServiceImpl implements DeployService { //还原信息入库 DeployHistory deployHistory = new DeployHistory(); deployHistory.setAppName(appName); - deployHistory.setDeployUser(SecurityUtils.getCurrentUsername()); +// deployHistory.setDeployUser(SecurityUtils.getCurrentUsername()); deployHistory.setIp(ip); deployHistory.setDeployId(id); deployHistoryService.create(deployHistory); diff --git a/nladmin-system/src/main/java/org/nl/modules/quartz/rest/QuartzJobController.java b/nladmin-system/src/main/java/org/nl/modules/quartz/rest/QuartzJobController.java index 267da5918..3ca26905a 100644 --- a/nladmin-system/src/main/java/org/nl/modules/quartz/rest/QuartzJobController.java +++ b/nladmin-system/src/main/java/org/nl/modules/quartz/rest/QuartzJobController.java @@ -27,7 +27,7 @@ import org.nl.modules.quartz.service.dto.JobQueryCriteria; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; +import cn.dev33.satoken.annotation.SaCheckPermission; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; @@ -50,28 +50,28 @@ public class QuartzJobController { @ApiOperation("查询定时任务") @GetMapping - @PreAuthorize("@el.check('timing:list')") + @SaCheckPermission("timing:list") public ResponseEntity query(JobQueryCriteria criteria, Pageable pageable){ return new ResponseEntity<>(quartzJobService.queryAll(criteria,pageable), HttpStatus.OK); } @ApiOperation("导出任务数据") @GetMapping(value = "/download") - @PreAuthorize("@el.check('timing:list')") + @SaCheckPermission("timing:list") public void download(HttpServletResponse response, JobQueryCriteria criteria) throws IOException { quartzJobService.download(quartzJobService.queryAll(criteria), response); } @ApiOperation("导出日志数据") @GetMapping(value = "/logs/download") - @PreAuthorize("@el.check('timing:list')") + @SaCheckPermission("timing:list") public void downloadLog(HttpServletResponse response, JobQueryCriteria criteria) throws IOException { quartzJobService.downloadLog(quartzJobService.queryAllLog(criteria), response); } @ApiOperation("查询任务执行日志") @GetMapping(value = "/logs") - @PreAuthorize("@el.check('timing:list')") + @SaCheckPermission("timing:list") public ResponseEntity queryJobLog(JobQueryCriteria criteria, Pageable pageable){ return new ResponseEntity<>(quartzJobService.queryAllLog(criteria,pageable), HttpStatus.OK); } @@ -79,7 +79,7 @@ public class QuartzJobController { @Log("新增定时任务") @ApiOperation("新增定时任务") @PostMapping - @PreAuthorize("@el.check('timing:add')") + @SaCheckPermission("timing:add") public ResponseEntity create(@Validated @RequestBody QuartzJob resources){ if (resources.getId() != null) { throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID"); @@ -91,7 +91,7 @@ public class QuartzJobController { @Log("修改定时任务") @ApiOperation("修改定时任务") @PutMapping - @PreAuthorize("@el.check('timing:edit')") + @SaCheckPermission("timing:edit") public ResponseEntity update(@Validated(QuartzJob.Update.class) @RequestBody QuartzJob resources){ quartzJobService.update(resources); return new ResponseEntity<>(HttpStatus.NO_CONTENT); @@ -100,7 +100,7 @@ public class QuartzJobController { @Log("更改定时任务状态") @ApiOperation("更改定时任务状态") @PutMapping(value = "/{id}") - @PreAuthorize("@el.check('timing:edit')") + @SaCheckPermission("timing:edit") public ResponseEntity update(@PathVariable Long id){ quartzJobService.updateIsPause(quartzJobService.findById(id)); return new ResponseEntity<>(HttpStatus.NO_CONTENT); @@ -109,7 +109,7 @@ public class QuartzJobController { @Log("执行定时任务") @ApiOperation("执行定时任务") @PutMapping(value = "/exec/{id}") - @PreAuthorize("@el.check('timing:edit')") + @SaCheckPermission("timing:edit") public ResponseEntity execution(@PathVariable Long id){ quartzJobService.execution(quartzJobService.findById(id)); return new ResponseEntity<>(HttpStatus.NO_CONTENT); @@ -118,7 +118,7 @@ public class QuartzJobController { @Log("删除定时任务") @ApiOperation("删除定时任务") @DeleteMapping - @PreAuthorize("@el.check('timing:del')") + @SaCheckPermission("timing:del") public ResponseEntity delete(@RequestBody Set ids){ quartzJobService.delete(ids); return new ResponseEntity<>(HttpStatus.OK); diff --git a/nladmin-system/src/main/java/org/nl/modules/security/config/ConfigBeanConfiguration.java b/nladmin-system/src/main/java/org/nl/modules/security/config/ConfigBeanConfiguration.java index 43ada7e69..141c6fc83 100644 --- a/nladmin-system/src/main/java/org/nl/modules/security/config/ConfigBeanConfiguration.java +++ b/nladmin-system/src/main/java/org/nl/modules/security/config/ConfigBeanConfiguration.java @@ -16,7 +16,6 @@ package org.nl.modules.security.config; import org.nl.modules.security.config.bean.LoginProperties; -import org.nl.modules.security.config.bean.SecurityProperties; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -35,9 +34,4 @@ public class ConfigBeanConfiguration { return new LoginProperties(); } - @Bean - @ConfigurationProperties(prefix = "jwt", ignoreUnknownFields = true) - public SecurityProperties securityProperties() { - return new SecurityProperties(); - } } diff --git a/nladmin-system/src/main/java/org/nl/modules/security/config/SecurityConfig.java b/nladmin-system/src/main/java/org/nl/modules/security/config/SecurityConfig.java deleted file mode 100644 index 80a6454ed..000000000 --- a/nladmin-system/src/main/java/org/nl/modules/security/config/SecurityConfig.java +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.security.config; - -import lombok.RequiredArgsConstructor; -import org.nl.annotation.AnonymousAccess; -import org.nl.modules.security.config.bean.SecurityProperties; -import org.nl.modules.security.security.JwtAccessDeniedHandler; -import org.nl.modules.security.security.JwtAuthenticationEntryPoint; -import org.nl.modules.security.security.TokenConfigurer; -import org.nl.modules.security.security.TokenProvider; -import org.nl.modules.security.service.OnlineUserService; -import org.nl.modules.security.service.UserCacheClean; -import org.nl.utils.enums.RequestMethodEnum; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpMethod; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.config.core.GrantedAuthorityDefaults; -import org.springframework.security.config.http.SessionCreationPolicy; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.filter.CorsFilter; -import org.springframework.web.method.HandlerMethod; -import org.springframework.web.servlet.mvc.method.RequestMappingInfo; -import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; - -import java.util.*; - -/** - * @author Zheng Jie - */ -@Configuration -@EnableWebSecurity -@RequiredArgsConstructor -@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) -public class SecurityConfig extends WebSecurityConfigurerAdapter { - - private final TokenProvider tokenProvider; - private final CorsFilter corsFilter; - private final JwtAuthenticationEntryPoint authenticationErrorHandler; - private final JwtAccessDeniedHandler jwtAccessDeniedHandler; - private final ApplicationContext applicationContext; - private final SecurityProperties properties; - private final OnlineUserService onlineUserService; - private final UserCacheClean userCacheClean; - - @Bean - GrantedAuthorityDefaults grantedAuthorityDefaults() { - // 去除 ROLE_ 前缀 - return new GrantedAuthorityDefaults(""); - } - - @Bean - public PasswordEncoder passwordEncoder() { - // 密码加密方式 - return new BCryptPasswordEncoder(); - } - //@Override - protected void configure2(HttpSecurity http) throws Exception { - http.authorizeRequests().anyRequest().permitAll().and().logout().permitAll(); - } - - @Override - protected void configure(HttpSecurity httpSecurity) throws Exception { - // 搜寻匿名标记 url: @AnonymousAccess - Map handlerMethodMap = applicationContext.getBean(RequestMappingHandlerMapping.class).getHandlerMethods(); - // 获取匿名标记 - Map> anonymousUrls = getAnonymousUrl(handlerMethodMap); - httpSecurity - // 禁用 CSRF - .csrf().disable() - .addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class) - // 授权异常 - .exceptionHandling() - .authenticationEntryPoint(authenticationErrorHandler) - .accessDeniedHandler(jwtAccessDeniedHandler) - // 防止iframe 造成跨域 - .and() - .headers() - .frameOptions() - .disable() - // 不创建会话 - .and() - .sessionManagement() - .sessionCreationPolicy(SessionCreationPolicy.STATELESS) - .and() - .authorizeRequests() - // 静态资源等等 - .antMatchers( - HttpMethod.GET, - "/*.html", - "/**/*.html", - "/**/*.css", - "/**/*.js", - "/webSocket/**" - ).permitAll() - // swagger 文档 - .antMatchers("/swagger-ui.html").permitAll() - .antMatchers("/swagger-resources/**").permitAll() - .antMatchers("/webjars/**").permitAll() - .antMatchers("/*/api-docs").permitAll() - // 文件 - .antMatchers("/avatar/**").permitAll() - .antMatchers("/file/**").permitAll() - // 阿里巴巴 druid - .antMatchers("/druid/**").permitAll() - // 放行OPTIONS请求 - .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() - // 自定义匿名访问所有url放行:允许匿名和带Token访问,细腻化到每个 Request 类型 - // GET - .antMatchers(HttpMethod.GET, anonymousUrls.get(RequestMethodEnum.GET.getType()).toArray(new String[0])).permitAll() - // POST - .antMatchers(HttpMethod.POST, anonymousUrls.get(RequestMethodEnum.POST.getType()).toArray(new String[0])).permitAll() - // PUT - .antMatchers(HttpMethod.PUT, anonymousUrls.get(RequestMethodEnum.PUT.getType()).toArray(new String[0])).permitAll() - // PATCH - .antMatchers(HttpMethod.PATCH, anonymousUrls.get(RequestMethodEnum.PATCH.getType()).toArray(new String[0])).permitAll() - // DELETE - .antMatchers(HttpMethod.DELETE, anonymousUrls.get(RequestMethodEnum.DELETE.getType()).toArray(new String[0])).permitAll() - // 所有类型的接口都放行 - .antMatchers(anonymousUrls.get(RequestMethodEnum.ALL.getType()).toArray(new String[0])).permitAll() - // 所有请求都需要认证 - //anyRequest().authenticated() - .and().apply(securityConfigurerAdapter()); - } - - private Map> getAnonymousUrl(Map handlerMethodMap) { - Map> anonymousUrls = new HashMap<>(6); - Set get = new HashSet<>(); - Set post = new HashSet<>(); - Set put = new HashSet<>(); - Set patch = new HashSet<>(); - Set delete = new HashSet<>(); - Set all = new HashSet<>(); - for (Map.Entry infoEntry : handlerMethodMap.entrySet()) { - HandlerMethod handlerMethod = infoEntry.getValue(); - AnonymousAccess anonymousAccess = handlerMethod.getMethodAnnotation(AnonymousAccess.class); - if (null != anonymousAccess) { - List requestMethods = new ArrayList<>(infoEntry.getKey().getMethodsCondition().getMethods()); - RequestMethodEnum request = RequestMethodEnum.find(requestMethods.size() == 0 ? RequestMethodEnum.ALL.getType() : requestMethods.get(0).name()); - switch (Objects.requireNonNull(request)) { - case GET: - get.addAll(infoEntry.getKey().getPatternsCondition().getPatterns()); - break; - case POST: - post.addAll(infoEntry.getKey().getPatternsCondition().getPatterns()); - break; - case PUT: - put.addAll(infoEntry.getKey().getPatternsCondition().getPatterns()); - break; - case PATCH: - patch.addAll(infoEntry.getKey().getPatternsCondition().getPatterns()); - break; - case DELETE: - delete.addAll(infoEntry.getKey().getPatternsCondition().getPatterns()); - break; - default: - all.addAll(infoEntry.getKey().getPatternsCondition().getPatterns()); - break; - } - } - } - anonymousUrls.put(RequestMethodEnum.GET.getType(), get); - anonymousUrls.put(RequestMethodEnum.POST.getType(), post); - anonymousUrls.put(RequestMethodEnum.PUT.getType(), put); - anonymousUrls.put(RequestMethodEnum.PATCH.getType(), patch); - anonymousUrls.put(RequestMethodEnum.DELETE.getType(), delete); - anonymousUrls.put(RequestMethodEnum.ALL.getType(), all); - return anonymousUrls; - } - - private TokenConfigurer securityConfigurerAdapter() { - return new TokenConfigurer(tokenProvider, properties, onlineUserService, userCacheClean); - } -} diff --git a/nladmin-system/src/main/java/org/nl/modules/security/config/bean/SecurityProperties.java b/nladmin-system/src/main/java/org/nl/modules/security/config/bean/SecurityProperties.java index fe08e8082..df1d691ef 100644 --- a/nladmin-system/src/main/java/org/nl/modules/security/config/bean/SecurityProperties.java +++ b/nladmin-system/src/main/java/org/nl/modules/security/config/bean/SecurityProperties.java @@ -1,74 +1,74 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.security.config.bean; - -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -/** - * Jwt参数配置 - * - * @author Zheng Jie - * @date 2019年11月28日 - */ -@Data -public class SecurityProperties { - - /** - * Request Headers : Authorization - */ - private String header; - - /** - * 令牌前缀,最后留个空格 Bearer - */ - private String tokenStartWith; - - /** - * 必须使用最少88位的Base64对该令牌进行编码 - */ - private String base64Secret; - - /** - * 令牌过期时间 此处单位/毫秒 - */ - private Long tokenValidityInSeconds; - - /** - * 在线用户 key,根据 key 查询 redis 中在线用户的数据 - */ - private String onlineKey; - - /** - * 验证码 key - */ - private String codeKey; - - /** - * token 续期检查 - */ - private Long detect; - - /** - * 续期时间 - */ - private Long renew; - - public String getTokenStartWith() { - return tokenStartWith + " "; - } -} +///* +// * Copyright 2019-2020 Zheng Jie +// * +// * Licensed under the Apache License, Version 2.0 (the "License"); +// * you may not use this file except in compliance with the License. +// * You may obtain a copy of the License at +// * +// * http://www.apache.org/licenses/LICENSE-2.0 +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an "AS IS" BASIS, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the License for the specific language governing permissions and +// * limitations under the License. +// */ +//package org.nl.modules.security.config.bean; +// +//import lombok.Data; +//import org.springframework.boot.context.properties.ConfigurationProperties; +//import org.springframework.context.annotation.Configuration; +// +///** +// * Jwt参数配置 +// * +// * @author Zheng Jie +// * @date 2019年11月28日 +// */ +//@Data +//public class SecurityProperties { +// +// /** +// * Request Headers : Authorization +// */ +// private String header; +// +// /** +// * 令牌前缀,最后留个空格 Bearer +// */ +// private String tokenStartWith; +// +// /** +// * 必须使用最少88位的Base64对该令牌进行编码 +// */ +// private String base64Secret; +// +// /** +// * 令牌过期时间 此处单位/毫秒 +// */ +// private Long tokenValidityInSeconds; +// +// /** +// * 在线用户 key,根据 key 查询 redis 中在线用户的数据 +// */ +// private String onlineKey; +// +// /** +// * 验证码 key +// */ +// private String codeKey; +// +// /** +// * token 续期检查 +// */ +// private Long detect; +// +// /** +// * 续期时间 +// */ +// private Long renew; +// +// public String getTokenStartWith() { +// return tokenStartWith + " "; +// } +//} diff --git a/nladmin-system/src/main/java/org/nl/modules/security/rest/AuthorizationController.java b/nladmin-system/src/main/java/org/nl/modules/security/rest/AuthorizationController.java index 2c2820091..a1f79f022 100644 --- a/nladmin-system/src/main/java/org/nl/modules/security/rest/AuthorizationController.java +++ b/nladmin-system/src/main/java/org/nl/modules/security/rest/AuthorizationController.java @@ -15,6 +15,8 @@ */ package org.nl.modules.security.rest; +import cn.dev33.satoken.secure.SaSecureUtil; +import cn.dev33.satoken.stp.StpUtil; import cn.hutool.core.util.IdUtil; import cn.hutool.core.util.StrUtil; import com.wf.captcha.base.Captcha; @@ -29,20 +31,16 @@ import org.nl.config.RsaProperties; import org.nl.exception.BadRequestException; import org.nl.modules.security.config.bean.LoginCodeEnum; import org.nl.modules.security.config.bean.LoginProperties; -import org.nl.modules.security.config.bean.SecurityProperties; -import org.nl.modules.security.security.TokenProvider; import org.nl.modules.security.service.OnlineUserService; import org.nl.modules.security.service.dto.AuthUserDto; -import org.nl.modules.security.service.dto.JwtUserDto; +import org.nl.modules.system.service.UserService; +import org.nl.modules.system.service.dto.UserDto; import org.nl.utils.RedisUtils; import org.nl.utils.RsaUtils; import org.nl.utils.SecurityUtils; +import org.nl.utils.dto.CurrentUser; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestBody; @@ -66,11 +64,10 @@ import java.util.concurrent.TimeUnit; @RequiredArgsConstructor @Api(tags = "系统:系统授权接口") public class AuthorizationController { - private final SecurityProperties properties; +// private final SecurityProperties properties; private final RedisUtils redisUtils; private final OnlineUserService onlineUserService; - private final TokenProvider tokenProvider; - private final AuthenticationManagerBuilder authenticationManagerBuilder; + private final UserService userService; @Resource private LoginProperties loginProperties; @@ -78,7 +75,7 @@ public class AuthorizationController { @ApiOperation("登录授权") @AnonymousPostMapping(value = "/login") public ResponseEntity login(@Validated @RequestBody AuthUserDto authUser, HttpServletRequest request) throws Exception { - // 密码解密 + // 密码解密 - 前端的加密规则: encrypt String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, authUser.getPassword()); // 查询验证码 @@ -91,24 +88,29 @@ public class AuthorizationController { if (StrUtil.isEmpty(authUser.getCode()) || !authUser.getCode().equalsIgnoreCase(code)) { throw new BadRequestException("验证码错误"); } - UsernamePasswordAuthenticationToken authenticationToken = - new UsernamePasswordAuthenticationToken(authUser.getUsername(), password); - Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken); - SecurityContextHolder.getContext().setAuthentication(authentication); - // 生成令牌 - String token = tokenProvider.createToken(authentication); - final JwtUserDto jwtUserDto = (JwtUserDto) authentication.getPrincipal(); // 保存在线信息 - onlineUserService.save(jwtUserDto, token, request); +// onlineUserService.save(jwtUserDto, token, request); + // 校验数据库 + // 根据用户名查询,在比对密码 + UserDto userDto = userService.findByName(authUser.getUsername()); // 拿不到已经抛出异常 + if (!userDto.getPassword().equals(SaSecureUtil.md5BySalt(password, "salt"))) { // 这里需要密码加密 + throw new BadRequestException("账号或密码错误"); + } + StpUtil.login(userDto.getId()); + // 保存用户信息到session - 登录输入,登出删除 + CurrentUser user = new CurrentUser(); + user.setId(userDto.getId()); + user.setUsername(userDto.getUsername()); + user.setUser(userDto); + StpUtil.getTokenSession().set("userInfo", user); + StpUtil.getSession().set("UserDto", userDto); + + // 返回一个User // 返回 token 与 用户信息 Map authInfo = new HashMap(2) {{ - put("token", properties.getTokenStartWith() + token); - put("user", jwtUserDto); + put("token", StpUtil.getTokenValue()); + put("user", userDto); }}; - if (loginProperties.isSingleLogin()) { - //踢掉之前已经登录的token - onlineUserService.checkLoginOnUser(authUser.getUsername(), token); - } return ResponseEntity.ok(authInfo); } @@ -124,7 +126,7 @@ public class AuthorizationController { public ResponseEntity getCode() { // 获取运算的结果 Captcha captcha = loginProperties.getCaptcha(); - String uuid = properties.getCodeKey() + IdUtil.simpleUUID(); + String uuid = IdUtil.simpleUUID(); //当验证码类型为 arithmetic时且长度 >= 2 时,captcha.text()的结果有几率为浮点型 String captchaValue = captcha.text(); if (captcha.getCharType() - 1 == LoginCodeEnum.arithmetic.ordinal() && captchaValue.contains(".")) { @@ -143,7 +145,8 @@ public class AuthorizationController { @ApiOperation("退出登录") @AnonymousDeleteMapping(value = "/logout") public ResponseEntity logout(HttpServletRequest request) { - onlineUserService.logout(tokenProvider.getToken(request)); + StpUtil.getTokenSession().clear(); // 清除session数据 +// onlineUserService.logout(tokenProvider.getToken(request)); return new ResponseEntity<>(HttpStatus.OK); } } diff --git a/nladmin-system/src/main/java/org/nl/modules/security/rest/OnlineController.java b/nladmin-system/src/main/java/org/nl/modules/security/rest/OnlineController.java index 0ed5616e2..0358bdcbb 100644 --- a/nladmin-system/src/main/java/org/nl/modules/security/rest/OnlineController.java +++ b/nladmin-system/src/main/java/org/nl/modules/security/rest/OnlineController.java @@ -23,7 +23,6 @@ import org.nl.utils.EncryptUtils; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @@ -42,21 +41,21 @@ public class OnlineController { @ApiOperation("查询在线用户") @GetMapping - // @PreAuthorize("@el.check()") + // @SaCheckPermission("@el.check()") public ResponseEntity query(String filter, Pageable pageable){ return new ResponseEntity<>(onlineUserService.getAll(filter, pageable),HttpStatus.OK); } @ApiOperation("导出数据") @GetMapping(value = "/download") - // @PreAuthorize("@el.check()") + // @SaCheckPermission("@el.check()") public void download(HttpServletResponse response, String filter) throws IOException { onlineUserService.download(onlineUserService.getAll(filter), response); } @ApiOperation("踢出用户") @DeleteMapping - // @PreAuthorize("@el.check()") + // @SaCheckPermission("@el.check()") public ResponseEntity delete(@RequestBody Set keys) throws Exception { for (String key : keys) { // 解密Key diff --git a/nladmin-system/src/main/java/org/nl/modules/security/rest/test.java b/nladmin-system/src/main/java/org/nl/modules/security/rest/test.java new file mode 100644 index 000000000..5eab8bd69 --- /dev/null +++ b/nladmin-system/src/main/java/org/nl/modules/security/rest/test.java @@ -0,0 +1,14 @@ +package org.nl.modules.security.rest; + +import cn.dev33.satoken.secure.SaSecureUtil; + +/** + * @author lyd + * @description + */ +public class test { + public static void main(String[] args) { + String salt = SaSecureUtil.md5BySalt("123456", "salt"); + System.out.println(salt); + } +} diff --git a/nladmin-system/src/main/java/org/nl/modules/security/satoken/SaTokenConfigure.java b/nladmin-system/src/main/java/org/nl/modules/security/satoken/SaTokenConfigure.java new file mode 100644 index 000000000..72775ae42 --- /dev/null +++ b/nladmin-system/src/main/java/org/nl/modules/security/satoken/SaTokenConfigure.java @@ -0,0 +1,27 @@ +package org.nl.modules.security.satoken; + +import cn.dev33.satoken.interceptor.SaInterceptor; +import cn.dev33.satoken.stp.StpUtil; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +/** + * @author: lyd + * @description: sa-token的配置 + * @Date: 2022-09-20 + */ +@Configuration +public class SaTokenConfigure implements WebMvcConfigurer { + + String[] whitelist = new String[]{"/auth/login", "/auth/code"}; + + // 注册 Sa-Token 拦截器,打开注解式鉴权功能 + @Override + public void addInterceptors(InterceptorRegistry registry) { + // 注册 Sa-Token 拦截器,打开注解式鉴权功能 + registry.addInterceptor(new SaInterceptor(handle -> StpUtil.checkLogin())) + .addPathPatterns("/**") + .excludePathPatterns(whitelist); // 白名单 + } +} diff --git a/nladmin-system/src/main/java/org/nl/modules/security/satoken/StpInterfaceImpl.java b/nladmin-system/src/main/java/org/nl/modules/security/satoken/StpInterfaceImpl.java new file mode 100644 index 000000000..9f8eece41 --- /dev/null +++ b/nladmin-system/src/main/java/org/nl/modules/security/satoken/StpInterfaceImpl.java @@ -0,0 +1,42 @@ +package org.nl.modules.security.satoken; + +import cn.dev33.satoken.stp.StpInterface; +import org.nl.modules.system.service.RoleService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.List; + +/** + * @author: lyd + * @description: stp接口impl 自定义权限验证接口扩展 保证此类被springboot扫描,即可完成sa-token的自定义权限验证扩展 + * @Date: 2022-09-20 + */ +@Component +public class StpInterfaceImpl implements StpInterface { + + @Autowired + private RoleService roleService; + + /** + * 权限校验 - 获取用户权限 + * @param o + * @param s + * @return + */ + @Override + public List getPermissionList(Object o, String s) { + return roleService.getPermissionList((String) o); + } + + /** + * 获取用户角色 + * @param o + * @param s + * @return + */ + @Override + public List getRoleList(Object o, String s) { + return null; + } +} diff --git a/nladmin-system/src/main/java/org/nl/modules/security/security/JwtAccessDeniedHandler.java b/nladmin-system/src/main/java/org/nl/modules/security/security/JwtAccessDeniedHandler.java deleted file mode 100644 index 5f7068e8e..000000000 --- a/nladmin-system/src/main/java/org/nl/modules/security/security/JwtAccessDeniedHandler.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.security.security; - -import org.springframework.security.access.AccessDeniedException; -import org.springframework.security.web.access.AccessDeniedHandler; -import org.springframework.stereotype.Component; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - -/** - * @author Zheng Jie - */ -@Component -public class JwtAccessDeniedHandler implements AccessDeniedHandler { - - @Override - public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException { - //当用户在没有授权的情况下访问受保护的REST资源时,将调用此方法发送403 Forbidden响应 - response.sendError(HttpServletResponse.SC_FORBIDDEN, accessDeniedException.getMessage()); - } -} diff --git a/nladmin-system/src/main/java/org/nl/modules/security/security/JwtAuthenticationEntryPoint.java b/nladmin-system/src/main/java/org/nl/modules/security/security/JwtAuthenticationEntryPoint.java deleted file mode 100644 index f992c4848..000000000 --- a/nladmin-system/src/main/java/org/nl/modules/security/security/JwtAuthenticationEntryPoint.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.security.security; - -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.web.AuthenticationEntryPoint; -import org.springframework.stereotype.Component; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.io.Serializable; - -/** - * @author Zheng Jie - */ -@Component -public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint { - - @Override - public void commence(HttpServletRequest request, - HttpServletResponse response, - AuthenticationException authException) throws IOException { - // 当用户尝试访问安全的REST资源而不提供任何凭据时,将调用此方法发送401 响应 - response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException==null?"Unauthorized":authException.getMessage()); - } -} diff --git a/nladmin-system/src/main/java/org/nl/modules/security/security/TokenConfigurer.java b/nladmin-system/src/main/java/org/nl/modules/security/security/TokenConfigurer.java deleted file mode 100644 index d3f19f260..000000000 --- a/nladmin-system/src/main/java/org/nl/modules/security/security/TokenConfigurer.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.security.security; - -import lombok.RequiredArgsConstructor; -import org.nl.modules.security.config.bean.SecurityProperties; -import org.nl.modules.security.service.OnlineUserService; -import org.nl.modules.security.service.UserCacheClean; -import org.springframework.security.config.annotation.SecurityConfigurerAdapter; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.web.DefaultSecurityFilterChain; -import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; - -/** - * @author / - */ -@RequiredArgsConstructor -public class TokenConfigurer extends SecurityConfigurerAdapter { - - private final TokenProvider tokenProvider; - private final SecurityProperties properties; - private final OnlineUserService onlineUserService; - private final UserCacheClean userCacheClean; - - @Override - public void configure(HttpSecurity http) { - TokenFilter customFilter = new TokenFilter(tokenProvider, properties, onlineUserService, userCacheClean); - http.addFilterBefore(customFilter, UsernamePasswordAuthenticationFilter.class); - } -} diff --git a/nladmin-system/src/main/java/org/nl/modules/security/security/TokenFilter.java b/nladmin-system/src/main/java/org/nl/modules/security/security/TokenFilter.java deleted file mode 100644 index 84e5bb568..000000000 --- a/nladmin-system/src/main/java/org/nl/modules/security/security/TokenFilter.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.security.security; - -import cn.hutool.core.util.StrUtil; -import io.jsonwebtoken.ExpiredJwtException; -import org.nl.modules.security.config.bean.SecurityProperties; -import org.nl.modules.security.service.UserCacheClean; -import org.nl.modules.security.service.dto.OnlineUserDto; -import org.nl.modules.security.service.OnlineUserService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.util.StringUtils; -import org.springframework.web.filter.GenericFilterBean; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import java.io.IOException; -import java.util.Objects; - -/** - * @author / - */ -public class TokenFilter extends GenericFilterBean { - private static final Logger log = LoggerFactory.getLogger(TokenFilter.class); - - - private final TokenProvider tokenProvider; - private final SecurityProperties properties; - private final OnlineUserService onlineUserService; - private final UserCacheClean userCacheClean; - - /** - * @param tokenProvider Token - * @param properties JWT - * @param onlineUserService 用户在线 - * @param userCacheClean 用户缓存清理工具 - */ - public TokenFilter(TokenProvider tokenProvider, SecurityProperties properties, OnlineUserService onlineUserService, UserCacheClean userCacheClean) { - this.properties = properties; - this.onlineUserService = onlineUserService; - this.tokenProvider = tokenProvider; - this.userCacheClean = userCacheClean; - } - - @Override - public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) - throws IOException, ServletException { - HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; - String token = resolveToken(httpServletRequest); - // 对于 Token 为空的不需要去查 Redis - if (StrUtil.isNotBlank(token)) { - OnlineUserDto onlineUserDto = null; - boolean cleanUserCache = false; - try { - onlineUserDto = onlineUserService.getOne(properties.getOnlineKey() + token); - } catch (ExpiredJwtException e) { - log.error(e.getMessage()); - cleanUserCache = true; - } finally { - if (cleanUserCache || Objects.isNull(onlineUserDto)) { - userCacheClean.cleanUserCache(String.valueOf(tokenProvider.getClaims(token).get(TokenProvider.AUTHORITIES_KEY))); - } - } - if (onlineUserDto != null && StringUtils.hasText(token)) { - Authentication authentication = tokenProvider.getAuthentication(token); - SecurityContextHolder.getContext().setAuthentication(authentication); - // Token 续期 - tokenProvider.checkRenewal(token); - } - } - filterChain.doFilter(servletRequest, servletResponse); - } - - /** - * 初步检测Token - * - * @param request / - * @return / - */ - private String resolveToken(HttpServletRequest request) { - String bearerToken = request.getHeader(properties.getHeader()); - if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(properties.getTokenStartWith())) { - // 去掉令牌前缀 - return bearerToken.replace(properties.getTokenStartWith(), ""); - } else { - log.debug("非法Token:{}", bearerToken); - } - return null; - } -} diff --git a/nladmin-system/src/main/java/org/nl/modules/security/security/TokenProvider.java b/nladmin-system/src/main/java/org/nl/modules/security/security/TokenProvider.java deleted file mode 100644 index c789d6f1e..000000000 --- a/nladmin-system/src/main/java/org/nl/modules/security/security/TokenProvider.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.security.security; - -import cn.hutool.core.date.DateField; -import cn.hutool.core.date.DateUtil; -import cn.hutool.core.util.IdUtil; -import cn.hutool.core.util.ObjectUtil; -import io.jsonwebtoken.*; -import io.jsonwebtoken.io.Decoders; -import io.jsonwebtoken.security.Keys; -import lombok.extern.slf4j.Slf4j; -import org.nl.modules.security.config.bean.SecurityProperties; -import org.nl.utils.RedisUtils; -import org.springframework.beans.factory.InitializingBean; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.userdetails.User; -import org.springframework.stereotype.Component; - -import javax.servlet.http.HttpServletRequest; -import java.security.Key; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; - -/** - * @author / - */ -@Slf4j -@Component -public class TokenProvider implements InitializingBean { - - private final SecurityProperties properties; - private final RedisUtils redisUtils; - public static final String AUTHORITIES_KEY = "auth"; - private JwtParser jwtParser; - private JwtBuilder jwtBuilder; - - public TokenProvider(SecurityProperties properties, RedisUtils redisUtils) { - this.properties = properties; - this.redisUtils = redisUtils; - } - - @Override - public void afterPropertiesSet() { - byte[] keyBytes = Decoders.BASE64.decode(properties.getBase64Secret()); - Key key = Keys.hmacShaKeyFor(keyBytes); - jwtParser = Jwts.parserBuilder() - .setSigningKey(key) - .build(); - jwtBuilder = Jwts.builder() - .signWith(key, SignatureAlgorithm.HS512); - } - - /** - * 创建Token 设置永不过期, - * Token 的时间有效性转到Redis 维护 - * - * @param authentication / - * @return / - */ - public String createToken(Authentication authentication) { - /* - * 获取权限列表 - */ - String authorities = authentication.getAuthorities().stream() - .map(GrantedAuthority::getAuthority) - .collect(Collectors.joining(",")); - - return jwtBuilder - // 加入ID确保生成的 Token 都不一致 - .setId(IdUtil.simpleUUID()) - .claim(AUTHORITIES_KEY, authorities) - .setSubject(authentication.getName()) - .compact(); - } - - /** - * 依据Token 获取鉴权信息 - * - * @param token / - * @return / - */ - Authentication getAuthentication(String token) { - Claims claims = getClaims(token); - - // fix bug: 当前用户如果没有任何权限时,在输入用户名后,刷新验证码会抛IllegalArgumentException - Object authoritiesStr = claims.get(AUTHORITIES_KEY); - Collection authorities = - ObjectUtil.isNotEmpty(authoritiesStr) ? - Arrays.stream(authoritiesStr.toString().split(",")) - .map(SimpleGrantedAuthority::new) - .collect(Collectors.toList()) : Collections.emptyList(); - User principal = new User(claims.getSubject(), "******", authorities); - return new UsernamePasswordAuthenticationToken(principal, token, authorities); - } - - public Claims getClaims(String token) { - return jwtParser - .parseClaimsJws(token) - .getBody(); - } - - /** - * @param token 需要检查的token - */ - public void checkRenewal(String token) { - // 判断是否续期token,计算token的过期时间 - long time = redisUtils.getExpire(properties.getOnlineKey() + token) * 1000; - Date expireDate = DateUtil.offset(new Date(), DateField.MILLISECOND, (int) time); - // 判断当前时间与过期时间的时间差 - long differ = expireDate.getTime() - System.currentTimeMillis(); - // 如果在续期检查的范围内,则续期 - if (differ <= properties.getDetect()) { - long renew = time + properties.getRenew(); - redisUtils.expire(properties.getOnlineKey() + token, renew, TimeUnit.MILLISECONDS); - } - } - - public String getToken(HttpServletRequest request) { - final String requestHeader = request.getHeader(properties.getHeader()); - if (requestHeader != null && requestHeader.startsWith(properties.getTokenStartWith())) { - return requestHeader.substring(7); - } - return null; - } -} diff --git a/nladmin-system/src/main/java/org/nl/modules/security/service/OnlineUserService.java b/nladmin-system/src/main/java/org/nl/modules/security/service/OnlineUserService.java index a43e9121f..b643f00ed 100644 --- a/nladmin-system/src/main/java/org/nl/modules/security/service/OnlineUserService.java +++ b/nladmin-system/src/main/java/org/nl/modules/security/service/OnlineUserService.java @@ -17,15 +17,12 @@ package org.nl.modules.security.service; import cn.hutool.core.util.StrUtil; import lombok.extern.slf4j.Slf4j; -import org.nl.modules.security.config.bean.SecurityProperties; -import org.nl.modules.security.service.dto.JwtUserDto; import org.nl.modules.security.service.dto.OnlineUserDto; import org.nl.utils.*; import org.springframework.data.domain.Pageable; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; -import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.*; @@ -38,11 +35,14 @@ import java.util.*; @Slf4j public class OnlineUserService { - private final SecurityProperties properties; +// private final SecurityProperties properties; private final RedisUtils redisUtils; - public OnlineUserService(SecurityProperties properties, RedisUtils redisUtils) { - this.properties = properties; +// public OnlineUserService(SecurityProperties properties, RedisUtils redisUtils) { +// this.properties = properties; +// this.redisUtils = redisUtils; +// } + public OnlineUserService(RedisUtils redisUtils) { this.redisUtils = redisUtils; } @@ -52,20 +52,20 @@ public class OnlineUserService { * @param token / * @param request / */ - public void save(JwtUserDto jwtUserDto, String token, HttpServletRequest request){ - String dept = jwtUserDto.getUser().getDept().getName(); - String ip = StringUtils.getIp(request); - String browser = StringUtils.getBrowser(request); - // String address = StringUtils.getCityInfo(ip); - String address = "局域网"; - OnlineUserDto onlineUserDto = null; - try { - onlineUserDto = new OnlineUserDto(jwtUserDto.getUsername(), jwtUserDto.getUser().getNickName(), dept, browser , ip, address, EncryptUtils.desEncrypt(token), new Date()); - } catch (Exception e) { - log.error(e.getMessage(),e); - } - redisUtils.set(properties.getOnlineKey() + token, onlineUserDto, properties.getTokenValidityInSeconds()/1000); - } +// public void save(JwtUserDto jwtUserDto, String token, HttpServletRequest request){ +// String dept = jwtUserDto.getUser().getDept().getName(); +// String ip = StringUtils.getIp(request); +// String browser = StringUtils.getBrowser(request); +// // String address = StringUtils.getCityInfo(ip); +// String address = "局域网"; +// OnlineUserDto onlineUserDto = null; +// try { +// onlineUserDto = new OnlineUserDto(jwtUserDto.getUsername(), jwtUserDto.getUser().getNickName(), dept, browser , ip, address, EncryptUtils.desEncrypt(token), new Date()); +// } catch (Exception e) { +// log.error(e.getMessage(),e); +// } +// redisUtils.set(properties.getOnlineKey() + token, onlineUserDto, properties.getTokenValidityInSeconds()/1000); +// } /** * 查询全部数据 @@ -87,19 +87,19 @@ public class OnlineUserService { * @return / */ public List getAll(String filter){ - List keys = redisUtils.scan(properties.getOnlineKey() + "*"); - Collections.reverse(keys); +// List keys = redisUtils.scan(properties.getOnlineKey() + "*"); +// Collections.reverse(keys); List onlineUserDtos = new ArrayList<>(); - for (String key : keys) { - OnlineUserDto onlineUserDto = (OnlineUserDto) redisUtils.get(key); - if(StrUtil.isNotEmpty(filter)){ - if(onlineUserDto.toString().contains(filter)){ - onlineUserDtos.add(onlineUserDto); - } - } else { - onlineUserDtos.add(onlineUserDto); - } - } +// for (String key : keys) { +// OnlineUserDto onlineUserDto = (OnlineUserDto) redisUtils.get(key); +// if(StrUtil.isNotEmpty(filter)){ +// if(onlineUserDto.toString().contains(filter)){ +// onlineUserDtos.add(onlineUserDto); +// } +// } else { +// onlineUserDtos.add(onlineUserDto); +// } +// } onlineUserDtos.sort((o1, o2) -> o2.getLoginTime().compareTo(o1.getLoginTime())); return onlineUserDtos; } @@ -109,7 +109,7 @@ public class OnlineUserService { * @param key / */ public void kickOut(String key){ - key = properties.getOnlineKey() + key; +// key = properties.getOnlineKey() + key; redisUtils.del(key); } @@ -118,8 +118,8 @@ public class OnlineUserService { * @param token / */ public void logout(String token) { - String key = properties.getOnlineKey() + token; - redisUtils.del(key); +// String key = properties.getOnlineKey() + token; +// redisUtils.del(key); } /** diff --git a/nladmin-system/src/main/java/org/nl/modules/security/service/UserCacheClean.java b/nladmin-system/src/main/java/org/nl/modules/security/service/UserCacheClean.java index 997116d71..f5c610e94 100644 --- a/nladmin-system/src/main/java/org/nl/modules/security/service/UserCacheClean.java +++ b/nladmin-system/src/main/java/org/nl/modules/security/service/UserCacheClean.java @@ -17,7 +17,6 @@ package org.nl.modules.security.service; import cn.hutool.core.util.StrUtil; -import org.nl.utils.StringUtils; import org.springframework.stereotype.Component; /** @@ -36,7 +35,7 @@ public class UserCacheClean { */ public void cleanUserCache(String userName) { if (StrUtil.isNotEmpty(userName)) { - UserDetailsServiceImpl.userDtoCache.remove(userName); +// UserDetailsServiceImpl.userDtoCache.remove(userName); } } @@ -44,7 +43,7 @@ public class UserCacheClean { * 清理所有用户的缓存信息
* ,如发生角色授权信息变化,可以简便的全部失效缓存 */ - public void cleanAll() { - UserDetailsServiceImpl.userDtoCache.clear(); - } +// public void cleanAll() { +// UserDetailsServiceImpl.userDtoCache.clear(); +// } } diff --git a/nladmin-system/src/main/java/org/nl/modules/security/service/UserDetailsServiceImpl.java b/nladmin-system/src/main/java/org/nl/modules/security/service/UserDetailsServiceImpl.java deleted file mode 100644 index 74ffca88c..000000000 --- a/nladmin-system/src/main/java/org/nl/modules/security/service/UserDetailsServiceImpl.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.security.service; - -import lombok.RequiredArgsConstructor; -import org.nl.exception.BadRequestException; -import org.nl.exception.EntityNotFoundException; -import org.nl.modules.security.config.bean.LoginProperties; -import org.nl.modules.security.service.dto.JwtUserDto; -import org.nl.modules.system.service.DataService; -import org.nl.modules.system.service.RoleService; -import org.nl.modules.system.service.UserService; -import org.nl.modules.system.service.dto.UserDto; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.core.userdetails.UsernameNotFoundException; -import org.springframework.stereotype.Service; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * @author Zheng Jie - * @date 2018-11-22 - */ -@RequiredArgsConstructor -@Service("userDetailsService") -public class UserDetailsServiceImpl implements UserDetailsService { - private final UserService userService; - private final RoleService roleService; - private final DataService dataService; - private final LoginProperties loginProperties; - public void setEnableCache(boolean enableCache) { - this.loginProperties.setCacheEnable(enableCache); - } - - /** - * 用户信息缓存 - * - * @see {@link UserCacheClean} - */ - static Map userDtoCache = new ConcurrentHashMap<>(); - - @Override - public JwtUserDto loadUserByUsername(String username) { - boolean searchDb = true; - JwtUserDto jwtUserDto = null; - if (loginProperties.isCacheEnable() && userDtoCache.containsKey(username)) { - jwtUserDto = userDtoCache.get(username); - searchDb = false; - } - if (searchDb) { - UserDto user; - try { - user = userService.findByName(username); - } catch (EntityNotFoundException e) { - // SpringSecurity会自动转换UsernameNotFoundException为BadCredentialsException - throw new UsernameNotFoundException("", e); - } - if (user == null) { - throw new UsernameNotFoundException(""); - } else { - if (!user.getEnabled()) { - throw new BadRequestException("账号未激活!"); - } - jwtUserDto = new JwtUserDto( - user, - dataService.getDeptIds(user), - roleService.mapToGrantedAuthorities(user) - ); - userDtoCache.put(username, jwtUserDto); - } - } - return jwtUserDto; - } -} diff --git a/nladmin-system/src/main/java/org/nl/modules/security/service/dto/JwtUserDto.java b/nladmin-system/src/main/java/org/nl/modules/security/service/dto/JwtUserDto.java deleted file mode 100644 index 225fd0efa..000000000 --- a/nladmin-system/src/main/java/org/nl/modules/security/service/dto/JwtUserDto.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.security.service.dto; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import lombok.AllArgsConstructor; -import lombok.Getter; -import org.nl.modules.system.service.dto.UserDto; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.userdetails.UserDetails; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -/** - * @author Zheng Jie - * @date 2018-11-23 - */ -@Getter -@AllArgsConstructor -public class JwtUserDto implements UserDetails { - - private final UserDto user; - - private final List dataScopes; - - @JsonIgnore - private final List authorities; - - public Set getRoles() { - return authorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toSet()); - } - - @Override - @JsonIgnore - public String getPassword() { - return user.getPassword(); - } - - @JsonIgnore - public Long getDeptId() { - return user.getDept().getId(); - } - - @Override - @JsonIgnore - public String getUsername() { - return user.getUsername(); - } - - @JsonIgnore - @Override - public boolean isAccountNonExpired() { - return true; - } - - @JsonIgnore - @Override - public boolean isAccountNonLocked() { - return true; - } - - @JsonIgnore - @Override - public boolean isCredentialsNonExpired() { - return true; - } - - @Override - @JsonIgnore - public boolean isEnabled() { - return user.getEnabled(); - } -} diff --git a/nladmin-system/src/main/java/org/nl/modules/system/rest/CodeDetailController.java b/nladmin-system/src/main/java/org/nl/modules/system/rest/CodeDetailController.java index 879dc3868..b2e51032d 100644 --- a/nladmin-system/src/main/java/org/nl/modules/system/rest/CodeDetailController.java +++ b/nladmin-system/src/main/java/org/nl/modules/system/rest/CodeDetailController.java @@ -1,21 +1,19 @@ package org.nl.modules.system.rest; +import cn.dev33.satoken.annotation.SaCheckPermission; +import com.alibaba.fastjson.JSONObject; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.RequiredArgsConstructor; -import com.alibaba.fastjson.JSONObject; import org.nl.annotation.Log; import org.nl.modules.system.service.CodeDetailService; -import org.nl.modules.system.service.GenCodeService; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.util.Map; -import java.util.Set; @RestController @Api(tags = "系统:编码详情管理") @@ -27,7 +25,7 @@ public class CodeDetailController { @ApiOperation("查询编码明细") @GetMapping - @PreAuthorize("@el.check('genCode:list')") + @SaCheckPermission("genCode:list") public ResponseEntity queryAll(@RequestParam Map form, Pageable pageable){ return new ResponseEntity<>(codeDetailService.queryAll(form,pageable), HttpStatus.OK); } @@ -35,7 +33,7 @@ public class CodeDetailController { @Log("新增编码") @ApiOperation("新增编码") @PostMapping - @PreAuthorize("@el.check('genCode:add')") + @SaCheckPermission("genCode:add") public ResponseEntity create(@Validated @RequestBody Map form){ codeDetailService.create(form); return new ResponseEntity<>(HttpStatus.CREATED); @@ -44,7 +42,7 @@ public class CodeDetailController { @Log("删除编码") @ApiOperation("删除编码") @DeleteMapping(value = "/{id}") - @PreAuthorize("@el.check('genCode:del')") + @SaCheckPermission("genCode:del") public ResponseEntity delete(@PathVariable String id){ codeDetailService.delete(id); return new ResponseEntity<>(HttpStatus.OK); @@ -53,7 +51,7 @@ public class CodeDetailController { @Log("修改字典") @ApiOperation("修改字典") @PutMapping - @PreAuthorize("@el.check('dict:edit')") + @SaCheckPermission("dict:edit") public ResponseEntity update(@RequestBody JSONObject json){ codeDetailService.update(json); return new ResponseEntity<>(HttpStatus.NO_CONTENT); diff --git a/nladmin-system/src/main/java/org/nl/modules/system/rest/DeptController.java b/nladmin-system/src/main/java/org/nl/modules/system/rest/DeptController.java index b54ce79cc..eb39e17f2 100644 --- a/nladmin-system/src/main/java/org/nl/modules/system/rest/DeptController.java +++ b/nladmin-system/src/main/java/org/nl/modules/system/rest/DeptController.java @@ -15,6 +15,7 @@ */ package org.nl.modules.system.rest; +import cn.dev33.satoken.annotation.SaMode; import cn.hutool.core.collection.CollectionUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @@ -28,7 +29,7 @@ import org.nl.modules.system.service.dto.DeptQueryCriteria; import org.nl.utils.PageUtil; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; +import cn.dev33.satoken.annotation.SaCheckPermission; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; @@ -49,14 +50,14 @@ public class DeptController { @ApiOperation("导出部门数据") @GetMapping(value = "/download") - @PreAuthorize("@el.check('dept:list')") + @SaCheckPermission("dept:list") public void download(HttpServletResponse response, DeptQueryCriteria criteria) throws Exception { deptService.download(deptService.queryAll(criteria, false), response); } @ApiOperation("查询部门") @GetMapping - @PreAuthorize("@el.check('user:list','dept:list')") + @SaCheckPermission(value = {"user:list", "dept:list"}, mode = SaMode.AND) public ResponseEntity query(DeptQueryCriteria criteria) throws Exception { List deptDtos = deptService.queryAll(criteria, true); return new ResponseEntity<>(PageUtil.toPage(deptDtos, deptDtos.size()),HttpStatus.OK); @@ -64,7 +65,7 @@ public class DeptController { @ApiOperation("查询部门:根据ID获取同级与上级数据") @PostMapping("/superior") - @PreAuthorize("@el.check('user:list','dept:list')") + @SaCheckPermission(value = {"user:list", "dept:list"}, mode = SaMode.AND) public ResponseEntity getSuperior(@RequestBody List ids) { Set deptDtos = new LinkedHashSet<>(); for (Long id : ids) { @@ -78,7 +79,7 @@ public class DeptController { @Log("新增部门") @ApiOperation("新增部门") @PostMapping - @PreAuthorize("@el.check('dept:add')") + @SaCheckPermission("dept:add") public ResponseEntity create(@Validated @RequestBody Dept resources){ if (resources.getId() != null) { throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID"); @@ -90,7 +91,7 @@ public class DeptController { @Log("修改部门") @ApiOperation("修改部门") @PutMapping - @PreAuthorize("@el.check('dept:edit')") + @SaCheckPermission("dept:edit") public ResponseEntity update(@Validated(Dept.Update.class) @RequestBody Dept resources){ deptService.update(resources); return new ResponseEntity<>(HttpStatus.NO_CONTENT); @@ -99,7 +100,7 @@ public class DeptController { @Log("删除部门") @ApiOperation("删除部门") @DeleteMapping - @PreAuthorize("@el.check('dept:del')") + @SaCheckPermission("dept:del") public ResponseEntity delete(@RequestBody Set ids){ Set deptDtos = new HashSet<>(); for (Long id : ids) { diff --git a/nladmin-system/src/main/java/org/nl/modules/system/rest/DictController.java b/nladmin-system/src/main/java/org/nl/modules/system/rest/DictController.java index 71ca1d211..5665a6d85 100644 --- a/nladmin-system/src/main/java/org/nl/modules/system/rest/DictController.java +++ b/nladmin-system/src/main/java/org/nl/modules/system/rest/DictController.java @@ -26,7 +26,7 @@ import org.nl.modules.system.service.dto.DictQueryCriteria; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; +import cn.dev33.satoken.annotation.SaCheckPermission; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; @@ -49,21 +49,21 @@ public class DictController { @ApiOperation("导出字典数据") @GetMapping(value = "/download") - @PreAuthorize("@el.check('dict:list')") + @SaCheckPermission("dict:list") public void download(HttpServletResponse response, DictQueryCriteria criteria) throws IOException { dictService.download(dictService.queryAll(criteria), response); } @ApiOperation("查询字典") @GetMapping(value = "/all") - @PreAuthorize("@el.check('dict:list')") + @SaCheckPermission("dict:list") public ResponseEntity queryAll(){ return new ResponseEntity<>(dictService.queryAll(new DictQueryCriteria()),HttpStatus.OK); } @ApiOperation("查询字典") @GetMapping - @PreAuthorize("@el.check('dict:list')") + @SaCheckPermission("dict:list") public ResponseEntity query(DictQueryCriteria resources, Pageable pageable){ return new ResponseEntity<>(dictService.queryAll(resources,pageable),HttpStatus.OK); } @@ -71,7 +71,7 @@ public class DictController { @Log("新增字典") @ApiOperation("新增字典") @PostMapping - @PreAuthorize("@el.check('dict:add')") + @SaCheckPermission("dict:add") public ResponseEntity create(@Validated @RequestBody Dict resources){ if (resources.getId() != null) { throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID"); @@ -83,7 +83,7 @@ public class DictController { @Log("修改字典") @ApiOperation("修改字典") @PutMapping - @PreAuthorize("@el.check('dict:edit')") + @SaCheckPermission("dict:edit") public ResponseEntity update(@Validated(Dict.Update.class) @RequestBody Dict resources){ dictService.update(resources); return new ResponseEntity<>(HttpStatus.NO_CONTENT); @@ -92,7 +92,7 @@ public class DictController { @Log("删除字典") @ApiOperation("删除字典") @DeleteMapping - @PreAuthorize("@el.check('dict:del')") + @SaCheckPermission("dict:del") public ResponseEntity delete(@RequestBody Set ids){ dictService.delete(ids); return new ResponseEntity<>(HttpStatus.OK); diff --git a/nladmin-system/src/main/java/org/nl/modules/system/rest/DictDetailController.java b/nladmin-system/src/main/java/org/nl/modules/system/rest/DictDetailController.java index 839c8869a..64eb5aa29 100644 --- a/nladmin-system/src/main/java/org/nl/modules/system/rest/DictDetailController.java +++ b/nladmin-system/src/main/java/org/nl/modules/system/rest/DictDetailController.java @@ -15,6 +15,7 @@ */ package org.nl.modules.system.rest; +import cn.dev33.satoken.annotation.SaCheckPermission; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.RequiredArgsConstructor; @@ -24,7 +25,6 @@ import org.nl.modules.system.domain.Dict; import org.nl.modules.system.domain.DictDetail; import org.nl.modules.system.repository.DictRepository; import org.nl.modules.system.service.DictDetailService; -import org.nl.modules.system.service.DictService; import org.nl.modules.system.service.dto.DictDetailDto; import org.nl.modules.system.service.dto.DictDetailQueryCriteria; import org.springframework.data.domain.Pageable; @@ -32,9 +32,9 @@ import org.springframework.data.domain.Sort; import org.springframework.data.web.PageableDefault; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; + import java.util.HashMap; import java.util.List; import java.util.Map; @@ -74,7 +74,7 @@ public class DictDetailController { @Log("新增字典详情") @ApiOperation("新增字典详情") @PostMapping - @PreAuthorize("@el.check('dict:add')") + @SaCheckPermission("dict:add") public ResponseEntity create(@Validated @RequestBody DictDetail resources){ if (resources.getId() != null) { throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID"); @@ -88,7 +88,7 @@ public class DictDetailController { @Log("修改字典详情") @ApiOperation("修改字典详情") @PutMapping - @PreAuthorize("@el.check('dict:edit')") + @SaCheckPermission("dict:edit") public ResponseEntity update(@Validated(DictDetail.Update.class) @RequestBody DictDetail resources){ resources.setName(dictRepository.findById(resources.getDict().getId()).get().getName()); dictDetailService.update(resources); @@ -98,7 +98,7 @@ public class DictDetailController { @Log("删除字典详情") @ApiOperation("删除字典详情") @DeleteMapping(value = "/{id}") - @PreAuthorize("@el.check('dict:del')") + @SaCheckPermission("dict:del") public ResponseEntity delete(@PathVariable Long id){ dictDetailService.delete(id); return new ResponseEntity<>(HttpStatus.OK); diff --git a/nladmin-system/src/main/java/org/nl/modules/system/rest/GenCodeController.java b/nladmin-system/src/main/java/org/nl/modules/system/rest/GenCodeController.java index 2cfc58966..1d3dbff6a 100644 --- a/nladmin-system/src/main/java/org/nl/modules/system/rest/GenCodeController.java +++ b/nladmin-system/src/main/java/org/nl/modules/system/rest/GenCodeController.java @@ -9,7 +9,7 @@ import org.nl.modules.system.service.GenCodeService; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; +import cn.dev33.satoken.annotation.SaCheckPermission; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; @@ -26,7 +26,7 @@ public class GenCodeController { @ApiOperation("查询编码") @GetMapping - @PreAuthorize("@el.check('genCode:list')") + @SaCheckPermission("genCode:list") public ResponseEntity queryAll(@RequestParam Map form, Pageable pageable) { return new ResponseEntity<>(genCodeService.queryAll(form, pageable), HttpStatus.OK); } @@ -34,7 +34,7 @@ public class GenCodeController { @Log("新增编码") @ApiOperation("新增编码") @PostMapping - @PreAuthorize("@el.check('genCode:add')") + @SaCheckPermission("genCode:add") public ResponseEntity create(@Validated @RequestBody Map form) { genCodeService.create(form); @@ -44,7 +44,7 @@ public class GenCodeController { @Log("删除编码") @ApiOperation("删除编码") @DeleteMapping - @PreAuthorize("@el.check('genCode:del')") + @SaCheckPermission("genCode:del") public ResponseEntity delete(@RequestBody Set ids) { genCodeService.delete(ids); return new ResponseEntity<>(HttpStatus.OK); @@ -53,7 +53,7 @@ public class GenCodeController { @Log("修改字典") @ApiOperation("修改字典") @PutMapping - @PreAuthorize("@el.check('genCode:edit')") + @SaCheckPermission("genCode:edit") public ResponseEntity update(@RequestBody JSONObject json) { genCodeService.update(json); return new ResponseEntity<>(HttpStatus.NO_CONTENT); @@ -61,7 +61,7 @@ public class GenCodeController { @ApiOperation("导出任务数据") @GetMapping(value = "/codeDemo") - @PreAuthorize("@el.check('genCode:list')") + @SaCheckPermission("genCode:list") public ResponseEntity CodeDemo(@RequestParam Map form) throws IOException { return new ResponseEntity<>(genCodeService.codeDemo(form), HttpStatus.OK); } diff --git a/nladmin-system/src/main/java/org/nl/modules/system/rest/JobController.java b/nladmin-system/src/main/java/org/nl/modules/system/rest/JobController.java index b26d6e718..70be4b8ee 100644 --- a/nladmin-system/src/main/java/org/nl/modules/system/rest/JobController.java +++ b/nladmin-system/src/main/java/org/nl/modules/system/rest/JobController.java @@ -15,6 +15,7 @@ */ package org.nl.modules.system.rest; +import cn.dev33.satoken.annotation.SaMode; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.RequiredArgsConstructor; @@ -26,7 +27,7 @@ import org.nl.modules.system.service.dto.JobQueryCriteria; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; +import cn.dev33.satoken.annotation.SaCheckPermission; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; @@ -48,14 +49,14 @@ public class JobController { @ApiOperation("导出岗位数据") @GetMapping(value = "/download") - @PreAuthorize("@el.check('job:list')") + @SaCheckPermission("job:list") public void download(HttpServletResponse response, JobQueryCriteria criteria) throws IOException { jobService.download(jobService.queryAll(criteria), response); } @ApiOperation("查询岗位") @GetMapping - @PreAuthorize("@el.check('job:list','user:list')") + @SaCheckPermission(value = {"job:list", "user:list"}, mode = SaMode.AND) public ResponseEntity query(JobQueryCriteria criteria, Pageable pageable){ return new ResponseEntity<>(jobService.queryAll(criteria, pageable),HttpStatus.OK); } @@ -63,7 +64,7 @@ public class JobController { @Log("新增岗位") @ApiOperation("新增岗位") @PostMapping - @PreAuthorize("@el.check('job:add')") + @SaCheckPermission("job:add") public ResponseEntity create(@Validated @RequestBody Job resources){ if (resources.getId() != null) { throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID"); @@ -75,7 +76,7 @@ public class JobController { @Log("修改岗位") @ApiOperation("修改岗位") @PutMapping - @PreAuthorize("@el.check('job:edit')") + @SaCheckPermission("job:edit") public ResponseEntity update(@Validated(Job.Update.class) @RequestBody Job resources){ jobService.update(resources); return new ResponseEntity<>(HttpStatus.NO_CONTENT); @@ -84,7 +85,7 @@ public class JobController { @Log("删除岗位") @ApiOperation("删除岗位") @DeleteMapping - @PreAuthorize("@el.check('job:del')") + @SaCheckPermission("job:del") public ResponseEntity delete(@RequestBody Set ids){ // 验证是否被用户关联 jobService.verification(ids); diff --git a/nladmin-system/src/main/java/org/nl/modules/system/rest/MenuController.java b/nladmin-system/src/main/java/org/nl/modules/system/rest/MenuController.java index a2b8517ef..139b40acd 100644 --- a/nladmin-system/src/main/java/org/nl/modules/system/rest/MenuController.java +++ b/nladmin-system/src/main/java/org/nl/modules/system/rest/MenuController.java @@ -15,24 +15,26 @@ */ package org.nl.modules.system.rest; +import cn.dev33.satoken.annotation.SaCheckPermission; +import cn.dev33.satoken.annotation.SaMode; +import cn.dev33.satoken.stp.StpUtil; import cn.hutool.core.collection.CollectionUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.RequiredArgsConstructor; import org.nl.annotation.Log; -import org.nl.modules.system.domain.Menu; import org.nl.exception.BadRequestException; +import org.nl.modules.system.domain.Menu; import org.nl.modules.system.service.MenuService; import org.nl.modules.system.service.dto.MenuDto; import org.nl.modules.system.service.dto.MenuQueryCriteria; import org.nl.modules.system.service.mapstruct.MenuMapper; import org.nl.utils.PageUtil; -import org.nl.utils.SecurityUtils; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; + import javax.servlet.http.HttpServletResponse; import java.util.*; import java.util.stream.Collectors; @@ -54,7 +56,7 @@ public class MenuController { @ApiOperation("导出菜单数据") @GetMapping(value = "/download") - @PreAuthorize("@el.check('menu:list')") + @SaCheckPermission("menu:list") public void download(HttpServletResponse response, MenuQueryCriteria criteria) throws Exception { menuService.download(menuService.queryAll(criteria, false), response); } @@ -62,21 +64,21 @@ public class MenuController { @GetMapping(value = "/build") @ApiOperation("获取前端所需菜单") public ResponseEntity buildMenus(){ - List menuDtoList = menuService.findByUser(SecurityUtils.getCurrentUserId()); + List menuDtoList = menuService.findByUser(StpUtil.getLoginIdAsLong()); List menuDtos = menuService.buildTree(menuDtoList); return new ResponseEntity<>(menuService.buildMenus(menuDtos),HttpStatus.OK); } @ApiOperation("返回全部的菜单") @GetMapping(value = "/lazy") - @PreAuthorize("@el.check('menu:list','roles:list')") + @SaCheckPermission(value = {"menu:list", "roles:list"}, mode = SaMode.AND) public ResponseEntity query(@RequestParam Long pid){ return new ResponseEntity<>(menuService.getMenus(pid),HttpStatus.OK); } @ApiOperation("根据菜单ID返回所有子节点ID,包含自身ID") @GetMapping(value = "/child") - @PreAuthorize("@el.check('menu:list','roles:list')") + @SaCheckPermission("menu:list','roles:list") public ResponseEntity child(@RequestParam Long id){ Set menuSet = new HashSet<>(); List menuList = menuService.getMenus(id); @@ -88,7 +90,7 @@ public class MenuController { @GetMapping @ApiOperation("查询菜单") - @PreAuthorize("@el.check('menu:list')") + @SaCheckPermission("menu:list") public ResponseEntity query(MenuQueryCriteria criteria) throws Exception { List menuDtoList = menuService.queryAll(criteria, true); return new ResponseEntity<>(PageUtil.toPage(menuDtoList, menuDtoList.size()),HttpStatus.OK); @@ -96,7 +98,7 @@ public class MenuController { @ApiOperation("查询菜单:根据ID获取同级与上级数据") @PostMapping("/superior") - @PreAuthorize("@el.check('menu:list')") + @SaCheckPermission("menu:list") public ResponseEntity getSuperior(@RequestBody List ids) { Set menuDtos = new LinkedHashSet<>(); if(CollectionUtil.isNotEmpty(ids)){ @@ -112,7 +114,7 @@ public class MenuController { @Log("新增菜单") @ApiOperation("新增菜单") @PostMapping - @PreAuthorize("@el.check('menu:add')") + @SaCheckPermission("menu:add") public ResponseEntity create(@Validated @RequestBody Menu resources){ if (resources.getId() != null) { throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID"); @@ -124,7 +126,7 @@ public class MenuController { @Log("修改菜单") @ApiOperation("修改菜单") @PutMapping - @PreAuthorize("@el.check('menu:edit')") + @SaCheckPermission("menu:edit") public ResponseEntity update(@Validated(Menu.Update.class) @RequestBody Menu resources){ menuService.update(resources); return new ResponseEntity<>(HttpStatus.NO_CONTENT); @@ -133,7 +135,7 @@ public class MenuController { @Log("删除菜单") @ApiOperation("删除菜单") @DeleteMapping - @PreAuthorize("@el.check('menu:del')") + @SaCheckPermission("menu:del") public ResponseEntity delete(@RequestBody Set ids){ Set menuSet = new HashSet<>(); for (Long id : ids) { diff --git a/nladmin-system/src/main/java/org/nl/modules/system/rest/MonitorController.java b/nladmin-system/src/main/java/org/nl/modules/system/rest/MonitorController.java index f5536f764..13d726076 100644 --- a/nladmin-system/src/main/java/org/nl/modules/system/rest/MonitorController.java +++ b/nladmin-system/src/main/java/org/nl/modules/system/rest/MonitorController.java @@ -21,7 +21,7 @@ import lombok.RequiredArgsConstructor; import org.nl.modules.system.service.MonitorService; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; +import cn.dev33.satoken.annotation.SaCheckPermission; import org.springframework.web.bind.annotation.*; /** @@ -38,8 +38,8 @@ public class MonitorController { @GetMapping @ApiOperation("查询服务监控") - @PreAuthorize("@el.check('monitor:list')") - public ResponseEntity query(){ + @SaCheckPermission("monitor:list") + public ResponseEntity query() { return new ResponseEntity<>(serverService.getServers(),HttpStatus.OK); } } diff --git a/nladmin-system/src/main/java/org/nl/modules/system/rest/ParamController.java b/nladmin-system/src/main/java/org/nl/modules/system/rest/ParamController.java index 06182a96c..c662c6ac0 100644 --- a/nladmin-system/src/main/java/org/nl/modules/system/rest/ParamController.java +++ b/nladmin-system/src/main/java/org/nl/modules/system/rest/ParamController.java @@ -2,8 +2,6 @@ package org.nl.modules.system.rest; -import cn.hutool.http.Header; -import cn.hutool.http.HttpRequest; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.RequiredArgsConstructor; @@ -37,14 +35,14 @@ public class ParamController { @GetMapping @Log("查询系统参数") @ApiOperation("查询系统参数") - //@PreAuthorize("@el.check('param:list')") + //@SaCheckPermission("param:list") public ResponseEntity query(@RequestParam Map whereJson, Pageable page){ return new ResponseEntity<>(paramService.queryAll(whereJson,page),HttpStatus.OK); } @PostMapping @Log("新增系统参数") @ApiOperation("新增系统参数") - //@PreAuthorize("@el.check('param:add')") + //@SaCheckPermission("param:add") public ResponseEntity create(@Validated @RequestBody ParamDto dto){ paramService.create(dto); return new ResponseEntity<>(HttpStatus.CREATED); @@ -53,7 +51,7 @@ public class ParamController { @PutMapping @Log("修改系统参数") @ApiOperation("修改系统参数") - //@PreAuthorize("@el.check('param:edit')") + //@SaCheckPermission("param:edit") public ResponseEntity update(@Validated @RequestBody ParamDto dto){ paramService.update(dto); return new ResponseEntity<>(HttpStatus.NO_CONTENT); @@ -61,7 +59,7 @@ public class ParamController { @Log("删除系统参数") @ApiOperation("删除系统参数") - //@PreAuthorize("@el.check('param:del')") + //@SaCheckPermission("param:del") @DeleteMapping public ResponseEntity delete(@RequestBody String[] ids) { paramService.deleteAll(ids); @@ -71,7 +69,7 @@ public class ParamController { @Log("导出系统参数") @ApiOperation("导出系统参数") @GetMapping(value = "/download") - //@PreAuthorize("@el.check('param:list')") + //@SaCheckPermission("param:list") public void download(HttpServletResponse response, Map whereJson) throws IOException { paramService.download(paramService.queryAll(whereJson), response); } diff --git a/nladmin-system/src/main/java/org/nl/modules/system/rest/RoleController.java b/nladmin-system/src/main/java/org/nl/modules/system/rest/RoleController.java index e8e979aea..dfaa10aa6 100644 --- a/nladmin-system/src/main/java/org/nl/modules/system/rest/RoleController.java +++ b/nladmin-system/src/main/java/org/nl/modules/system/rest/RoleController.java @@ -15,24 +15,26 @@ */ package org.nl.modules.system.rest; +import cn.dev33.satoken.annotation.SaCheckPermission; +import cn.dev33.satoken.annotation.SaMode; +import cn.dev33.satoken.stp.StpUtil; import cn.hutool.core.lang.Dict; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.RequiredArgsConstructor; import org.nl.annotation.Log; -import org.nl.modules.system.domain.Role; import org.nl.exception.BadRequestException; +import org.nl.modules.system.domain.Role; import org.nl.modules.system.service.RoleService; import org.nl.modules.system.service.dto.RoleDto; import org.nl.modules.system.service.dto.RoleQueryCriteria; import org.nl.modules.system.service.dto.RoleSmallDto; -import org.nl.utils.SecurityUtils; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; + import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Collections; @@ -56,28 +58,28 @@ public class RoleController { @ApiOperation("获取单个role") @GetMapping(value = "/{id}") - @PreAuthorize("@el.check('roles:list')") + @SaCheckPermission("roles:list") public ResponseEntity query(@PathVariable Long id){ return new ResponseEntity<>(roleService.findById(id), HttpStatus.OK); } @ApiOperation("导出角色数据") @GetMapping(value = "/download") - @PreAuthorize("@el.check('role:list')") + @SaCheckPermission("role:list") public void download(HttpServletResponse response, RoleQueryCriteria criteria) throws IOException { roleService.download(roleService.queryAll(criteria), response); } @ApiOperation("返回全部的角色") @GetMapping(value = "/all") - @PreAuthorize("@el.check('roles:list','user:add','user:edit')") + @SaCheckPermission(value = {"roles:list", "user:add", "user:edit"}, mode = SaMode.AND) public ResponseEntity query(){ return new ResponseEntity<>(roleService.queryAll(),HttpStatus.OK); } @ApiOperation("查询角色") @GetMapping - @PreAuthorize("@el.check('roles:list')") + @SaCheckPermission("roles:list") public ResponseEntity query(RoleQueryCriteria criteria, Pageable pageable){ return new ResponseEntity<>(roleService.queryAll(criteria,pageable),HttpStatus.OK); } @@ -91,7 +93,7 @@ public class RoleController { @Log("新增角色") @ApiOperation("新增角色") @PostMapping - @PreAuthorize("@el.check('roles:add')") + @SaCheckPermission("roles:add") public ResponseEntity create(@Validated @RequestBody Role resources){ if (resources.getId() != null) { throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID"); @@ -104,7 +106,7 @@ public class RoleController { @Log("修改角色") @ApiOperation("修改角色") @PutMapping - @PreAuthorize("@el.check('roles:edit')") + @SaCheckPermission("roles:edit") public ResponseEntity update(@Validated(Role.Update.class) @RequestBody Role resources){ getLevels(resources.getLevel()); roleService.update(resources); @@ -114,7 +116,7 @@ public class RoleController { @Log("修改角色菜单") @ApiOperation("修改角色菜单") @PutMapping(value = "/menu") - @PreAuthorize("@el.check('roles:edit')") + @SaCheckPermission("roles:edit") public ResponseEntity updateMenu(@RequestBody Role resources){ RoleDto role = roleService.findById(resources.getId()); getLevels(role.getLevel()); @@ -125,7 +127,7 @@ public class RoleController { @Log("删除角色") @ApiOperation("删除角色") @DeleteMapping - @PreAuthorize("@el.check('roles:del')") + @SaCheckPermission("roles:del") public ResponseEntity delete(@RequestBody Set ids){ for (Long id : ids) { RoleDto role = roleService.findById(id); @@ -142,7 +144,7 @@ public class RoleController { * @return / */ private int getLevels(Integer level){ - List levels = roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList()); + List levels = roleService.findByUsersId(StpUtil.getLoginIdAsLong()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList()); int min = Collections.min(levels); if(level != null){ if(level < min){ diff --git a/nladmin-system/src/main/java/org/nl/modules/system/rest/UserController.java b/nladmin-system/src/main/java/org/nl/modules/system/rest/UserController.java index 051e2f306..ba2b9953e 100644 --- a/nladmin-system/src/main/java/org/nl/modules/system/rest/UserController.java +++ b/nladmin-system/src/main/java/org/nl/modules/system/rest/UserController.java @@ -15,24 +15,22 @@ */ package org.nl.modules.system.rest; +import cn.dev33.satoken.annotation.SaCheckPermission; +import cn.dev33.satoken.secure.SaSecureUtil; +import cn.dev33.satoken.stp.StpUtil; import cn.hutool.core.collection.CollectionUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.RequiredArgsConstructor; import org.nl.annotation.Log; import org.nl.config.RsaProperties; -import org.nl.modules.system.service.DataService; -import org.nl.modules.system.domain.User; import org.nl.exception.BadRequestException; +import org.nl.modules.system.domain.User; import org.nl.modules.system.domain.vo.UserPassVo; -import org.nl.modules.system.service.DeptService; -import org.nl.modules.system.service.RoleService; +import org.nl.modules.system.service.*; import org.nl.modules.system.service.dto.RoleSmallDto; import org.nl.modules.system.service.dto.UserDto; import org.nl.modules.system.service.dto.UserQueryCriteria; -import org.nl.modules.system.service.VerifyService; - -import org.nl.modules.system.service.UserService; import org.nl.utils.PageUtil; import org.nl.utils.RsaUtils; import org.nl.utils.SecurityUtils; @@ -40,16 +38,17 @@ import org.nl.utils.enums.CodeEnum; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.util.CollectionUtils; import org.springframework.util.ObjectUtils; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; + import javax.servlet.http.HttpServletResponse; import java.io.IOException; -import java.util.*; +import java.util.Collections; +import java.util.List; +import java.util.Set; import java.util.stream.Collectors; /** @@ -62,7 +61,7 @@ import java.util.stream.Collectors; @RequiredArgsConstructor public class UserController { - private final PasswordEncoder passwordEncoder; +// private final PasswordEncoder passwordEncoder; private final UserService userService; private final DataService dataService; private final DeptService deptService; @@ -71,21 +70,22 @@ public class UserController { @ApiOperation("导出用户数据") @GetMapping(value = "/download") - @PreAuthorize("@el.check('user:list')") + @SaCheckPermission("user:list") public void download(HttpServletResponse response, UserQueryCriteria criteria) throws IOException { userService.download(userService.queryAll(criteria), response); } @ApiOperation("查询用户") @GetMapping - @PreAuthorize("@el.check('user:list')") + @SaCheckPermission("user:list") public ResponseEntity query(UserQueryCriteria criteria, Pageable pageable){ if (!ObjectUtils.isEmpty(criteria.getDeptId())) { criteria.getDeptIds().add(criteria.getDeptId()); criteria.getDeptIds().addAll(deptService.getDeptChildren(deptService.findByPid(criteria.getDeptId()))); } // 数据权限 - List dataScopes = dataService.getDeptIds(userService.findByName(SecurityUtils.getCurrentUsername())); +// List dataScopes = dataService.getDeptIds(userService.findByName(SecurityUtils.getCurrentUsername())); + List dataScopes = dataService.getDeptIds(userService.findByName("")); // criteria.getDeptIds() 不为空并且数据权限不为空则取交集 if (!CollectionUtils.isEmpty(criteria.getDeptIds()) && !CollectionUtils.isEmpty(dataScopes)){ // 取交集 @@ -104,11 +104,12 @@ public class UserController { @Log("新增用户") @ApiOperation("新增用户") @PostMapping - @PreAuthorize("@el.check('user:add')") + @SaCheckPermission("user:add") public ResponseEntity create(@Validated @RequestBody User resources){ checkLevel(resources); // 默认密码 123456 - resources.setPassword(passwordEncoder.encode("123456")); +// resources.setPassword(passwordEncoder.encode("123456")); + resources.setPassword(SaSecureUtil.md5BySalt("123456", "salt")); userService.create(resources); return new ResponseEntity<>(HttpStatus.CREATED); } @@ -116,7 +117,7 @@ public class UserController { @Log("修改用户") @ApiOperation("修改用户") @PutMapping - @PreAuthorize("@el.check('user:edit')") + @SaCheckPermission("user:edit") public ResponseEntity update(@Validated(User.Update.class) @RequestBody User resources) throws Exception { checkLevel(resources); userService.update(resources); @@ -127,7 +128,7 @@ public class UserController { @ApiOperation("修改用户:个人中心") @PutMapping(value = "center") public ResponseEntity center(@Validated(User.Update.class) @RequestBody User resources){ - if(!resources.getId().equals(SecurityUtils.getCurrentUserId())){ + if(!resources.getId().equals(StpUtil.getLoginIdAsLong())){ throw new BadRequestException("不能修改他人资料"); } userService.updateCenter(resources); @@ -137,10 +138,10 @@ public class UserController { @Log("删除用户") @ApiOperation("删除用户") @DeleteMapping - @PreAuthorize("@el.check('user:del')") + @SaCheckPermission("user:del") public ResponseEntity delete(@RequestBody Set ids){ for (Long id : ids) { - Integer currentLevel = Collections.min(roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList())); + Integer currentLevel = Collections.min(roleService.findByUsersId(StpUtil.getLoginIdAsLong()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList())); Integer optLevel = Collections.min(roleService.findByUsersId(id).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList())); if (currentLevel > optLevel) { throw new BadRequestException("角色权限不足,不能删除:" + userService.findById(id).getUsername()); @@ -156,13 +157,13 @@ public class UserController { String oldPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,passVo.getOldPass()); String newPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,passVo.getNewPass()); UserDto user = userService.findByName(SecurityUtils.getCurrentUsername()); - if(!passwordEncoder.matches(oldPass, user.getPassword())){ - throw new BadRequestException("修改失败,旧密码错误"); - } - if(passwordEncoder.matches(newPass, user.getPassword())){ - throw new BadRequestException("新密码不能与旧密码相同"); - } - userService.updatePass(user.getUsername(),passwordEncoder.encode(newPass)); +// if(!passwordEncoder.matches(oldPass, user.getPassword())){ +// throw new BadRequestException("修改失败,旧密码错误"); +// } +// if(passwordEncoder.matches(newPass, user.getPassword())){ +// throw new BadRequestException("新密码不能与旧密码相同"); +// } +// userService.updatePass(user.getUsername(),passwordEncoder.encode(newPass)); return new ResponseEntity<>(HttpStatus.OK); } @@ -177,10 +178,11 @@ public class UserController { @PostMapping(value = "/updateEmail/{code}") public ResponseEntity updateEmail(@PathVariable String code,@RequestBody User user) throws Exception { String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,user.getPassword()); - UserDto userDto = userService.findByName(SecurityUtils.getCurrentUsername()); - if(!passwordEncoder.matches(password, userDto.getPassword())){ - throw new BadRequestException("密码错误"); - } +// UserDto userDto = userService.findByName(SecurityUtils.getCurrentUsername()); + UserDto userDto = userService.findByName(""); +// if(!passwordEncoder.matches(password, userDto.getPassword())){ +// throw new BadRequestException("密码错误"); +// } verificationCodeService.validated(CodeEnum.EMAIL_RESET_EMAIL_CODE.getKey() + user.getEmail(), code); userService.updateEmail(userDto.getUsername(),user.getEmail()); return new ResponseEntity<>(HttpStatus.OK); @@ -191,7 +193,7 @@ public class UserController { * @param resources / */ private void checkLevel(User resources) { - Integer currentLevel = Collections.min(roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList())); + Integer currentLevel = Collections.min(roleService.findByUsersId(StpUtil.getLoginIdAsLong()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList())); Integer optLevel = roleService.findByRoles(resources.getRoles()); if (currentLevel > optLevel) { throw new BadRequestException("角色权限不足"); diff --git a/nladmin-system/src/main/java/org/nl/modules/system/service/RoleService.java b/nladmin-system/src/main/java/org/nl/modules/system/service/RoleService.java index 8cc5bbae2..80f31a998 100644 --- a/nladmin-system/src/main/java/org/nl/modules/system/service/RoleService.java +++ b/nladmin-system/src/main/java/org/nl/modules/system/service/RoleService.java @@ -19,9 +19,8 @@ import org.nl.modules.system.domain.Role; import org.nl.modules.system.service.dto.RoleDto; import org.nl.modules.system.service.dto.RoleQueryCriteria; import org.nl.modules.system.service.dto.RoleSmallDto; -import org.nl.modules.system.service.dto.UserDto; import org.springframework.data.domain.Pageable; -import org.springframework.security.core.GrantedAuthority; + import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; @@ -119,7 +118,14 @@ public interface RoleService { * @param user 用户信息 * @return 权限信息 */ - List mapToGrantedAuthorities(UserDto user); +// List mapToGrantedAuthorities(UserDto user); + + /** + * 通过id获取用户的权限 + * @param id + * @return + */ + List getPermissionList(String id); /** * 验证是否被用户关联 diff --git a/nladmin-system/src/main/java/org/nl/modules/system/service/convert/RedisConvert.java b/nladmin-system/src/main/java/org/nl/modules/system/service/convert/RedisConvert.java index 39d9c1315..7ec348876 100644 --- a/nladmin-system/src/main/java/org/nl/modules/system/service/convert/RedisConvert.java +++ b/nladmin-system/src/main/java/org/nl/modules/system/service/convert/RedisConvert.java @@ -34,6 +34,6 @@ public interface RedisConvert { return respVO; } - List convertList(List list); +// List convertList(List list); } diff --git a/nladmin-system/src/main/java/org/nl/modules/system/service/impl/CodeDetailServiceImpl.java b/nladmin-system/src/main/java/org/nl/modules/system/service/impl/CodeDetailServiceImpl.java index d0ef86bd3..eecdda2ed 100644 --- a/nladmin-system/src/main/java/org/nl/modules/system/service/impl/CodeDetailServiceImpl.java +++ b/nladmin-system/src/main/java/org/nl/modules/system/service/impl/CodeDetailServiceImpl.java @@ -5,7 +5,6 @@ import cn.hutool.core.util.IdUtil; import lombok.RequiredArgsConstructor; import com.alibaba.fastjson.JSONObject; import org.nl.modules.system.service.CodeDetailService; -import org.nl.utils.SecurityUtils; import org.nl.wql.core.bean.ResultBean; import org.nl.wql.core.bean.WQLObject; import org.nl.wql.util.WqlUtil; @@ -48,7 +47,7 @@ public class CodeDetailServiceImpl implements CodeDetailService { json.put("code_rule_id",dict.get("id")); json.put("is_active","1"); json.put("is_delete","0"); - json.put("create_by",SecurityUtils.getCurrentUsername()); +// json.put("create_by",SecurityUtils.getCurrentUsername()); json.put("create_time", now); if(form.get("type").equals("02")){ Date date = DateUtil.date(); @@ -69,7 +68,7 @@ public class CodeDetailServiceImpl implements CodeDetailService { public void update(JSONObject json) { String now = DateUtil.now(); json.put("update_time",now); - json.put("update_by", SecurityUtils.getCurrentUsername()); +// json.put("update_by", SecurityUtils.getCurrentUsername()); WQLObject.getWQLObject("sys_code_rule_detail").update(json); } } diff --git a/nladmin-system/src/main/java/org/nl/modules/system/service/impl/DeptServiceImpl.java b/nladmin-system/src/main/java/org/nl/modules/system/service/impl/DeptServiceImpl.java index 9a3ddef41..2a626a28d 100644 --- a/nladmin-system/src/main/java/org/nl/modules/system/service/impl/DeptServiceImpl.java +++ b/nladmin-system/src/main/java/org/nl/modules/system/service/impl/DeptServiceImpl.java @@ -20,8 +20,8 @@ import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.db.Db; import cn.hutool.db.Entity; -import lombok.RequiredArgsConstructor; import com.alibaba.fastjson.JSONArray; +import lombok.RequiredArgsConstructor; import org.nl.exception.BadRequestException; import org.nl.modules.system.domain.Dept; import org.nl.modules.system.domain.User; @@ -33,7 +33,6 @@ import org.nl.modules.system.service.dto.DeptDto; import org.nl.modules.system.service.dto.DeptQueryCriteria; import org.nl.modules.system.service.mapstruct.DeptMapper; import org.nl.utils.*; -import org.nl.utils.enums.DataScopeEnum; import org.nl.wql.core.bean.WQLObject; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.Cacheable; @@ -67,11 +66,11 @@ public class DeptServiceImpl implements DeptService { @Override public List queryAll(DeptQueryCriteria criteria, Boolean isQuery) throws Exception { Sort sort = Sort.by(Sort.Direction.ASC, "deptSort"); - String dataScopeType = SecurityUtils.getDataScopeType(); +// String dataScopeType = SecurityUtils.getDataScopeType(); if (isQuery) { - if (dataScopeType.equals(DataScopeEnum.ALL.getValue())) { - criteria.setPidIsNull(true); - } +// if (dataScopeType.equals(DataScopeEnum.ALL.getValue())) { +// criteria.setPidIsNull(true); +// } List fields = QueryHelp.getAllFields(criteria.getClass(), new ArrayList<>()); List fieldNames = new ArrayList() {{ add("pidIsNull"); @@ -92,9 +91,9 @@ public class DeptServiceImpl implements DeptService { } List list = deptMapper.toDto(deptRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), sort)); // 如果为空,就代表为自定义权限或者本级权限,就需要去重,不理解可以注释掉,看查询结果 - if (StrUtil.isEmpty(dataScopeType)) { - return deduplication(list); - } +// if (StrUtil.isEmpty(dataScopeType)) { +// return deduplication(list); +// } return list; } diff --git a/nladmin-system/src/main/java/org/nl/modules/system/service/impl/GenCodeServiceImpl.java b/nladmin-system/src/main/java/org/nl/modules/system/service/impl/GenCodeServiceImpl.java index e874ac2c9..1d2b24b5b 100644 --- a/nladmin-system/src/main/java/org/nl/modules/system/service/impl/GenCodeServiceImpl.java +++ b/nladmin-system/src/main/java/org/nl/modules/system/service/impl/GenCodeServiceImpl.java @@ -8,7 +8,6 @@ import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import org.nl.exception.BadRequestException; import org.nl.modules.system.service.GenCodeService; -import org.nl.utils.SecurityUtils; import org.nl.wql.core.bean.ResultBean; import org.nl.wql.core.bean.WQLObject; import org.nl.wql.util.WqlUtil; @@ -64,7 +63,7 @@ public class GenCodeServiceImpl implements GenCodeService { json.put("name", form.get("name")); json.put("is_active", "1"); json.put("is_delete", "0"); - json.put("create_by", SecurityUtils.getCurrentUsername()); +// json.put("create_by", SecurityUtils.getCurrentUsername()); json.put("create_time", now); WQLObject.getWQLObject("sys_code_rule").insert(json); } @@ -88,7 +87,7 @@ public class GenCodeServiceImpl implements GenCodeService { } String now = DateUtil.now(); json.put("update_time", now); - json.put("update_by", SecurityUtils.getCurrentUsername()); +// json.put("update_by", SecurityUtils.getCurrentUsername()); WQLObject.getWQLObject("sys_code_rule").update(json); } diff --git a/nladmin-system/src/main/java/org/nl/modules/system/service/impl/GridFieldServiceImpl.java b/nladmin-system/src/main/java/org/nl/modules/system/service/impl/GridFieldServiceImpl.java index 1cd9a9eef..5b6271645 100644 --- a/nladmin-system/src/main/java/org/nl/modules/system/service/impl/GridFieldServiceImpl.java +++ b/nladmin-system/src/main/java/org/nl/modules/system/service/impl/GridFieldServiceImpl.java @@ -9,11 +9,8 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.nl.exception.BadRequestException; import org.nl.modules.system.service.GridFieldService; -import org.nl.modules.system.service.dto.GridDto; import org.nl.modules.system.service.dto.GridFieldDto; -import org.nl.utils.SecurityUtils; import org.nl.wql.WQL; -import org.nl.wql.core.bean.ResultBean; import org.nl.wql.core.bean.WQLObject; import org.nl.wql.util.WqlUtil; import org.springframework.data.domain.Pageable; @@ -48,7 +45,8 @@ public class GridFieldServiceImpl implements GridFieldService { @Override @Transactional(rollbackFor = Exception.class) public void create(GridFieldDto dto) { - String currentUsername = SecurityUtils.getCurrentUsername(); +// String currentUsername = SecurityUtils.getCurrentUsername(); + String currentUsername = ""; String now = DateUtil.now(); dto.setId(IdUtil.simpleUUID()); @@ -76,7 +74,8 @@ public class GridFieldServiceImpl implements GridFieldService { GridFieldDto entity = this.findById(dto.getId()); if (entity == null) throw new BadRequestException("被删除或无权限,操作失败!"); - String currentUsername = SecurityUtils.getCurrentUsername(); +// String currentUsername = SecurityUtils.getCurrentUsername(); + String currentUsername = ""; String now = DateUtil.now(); dto.setUpdate_time(now); dto.setUpdate_by(currentUsername); @@ -104,7 +103,8 @@ public class GridFieldServiceImpl implements GridFieldService { String grid_id = json.getString("grid_id"); JSONArray fieldDatas = json.getJSONArray("gridFieldData"); WQLObject wo = WQLObject.getWQLObject("sys_grid_field"); - String currentUsername = SecurityUtils.getCurrentUsername(); +// String currentUsername = SecurityUtils.getCurrentUsername(); + String currentUsername = ""; // 先删除原先所有的数据 wo.delete("grid_id = '" + grid_id + "'"); // 然后添加 diff --git a/nladmin-system/src/main/java/org/nl/modules/system/service/impl/GridServiceImpl.java b/nladmin-system/src/main/java/org/nl/modules/system/service/impl/GridServiceImpl.java index b811dfe04..8965c74b4 100644 --- a/nladmin-system/src/main/java/org/nl/modules/system/service/impl/GridServiceImpl.java +++ b/nladmin-system/src/main/java/org/nl/modules/system/service/impl/GridServiceImpl.java @@ -9,7 +9,6 @@ import lombok.extern.slf4j.Slf4j; import org.nl.exception.BadRequestException; import org.nl.modules.system.service.GridService; import org.nl.modules.system.service.dto.GridDto; -import org.nl.utils.SecurityUtils; import org.nl.wql.core.bean.ResultBean; import org.nl.wql.core.bean.WQLObject; import org.nl.wql.util.WqlUtil; @@ -43,7 +42,8 @@ public class GridServiceImpl implements GridService { @Override @Transactional(rollbackFor = Exception.class) public void create(GridDto dto) { - String currentUsername = SecurityUtils.getCurrentUsername(); +// String currentUsername = SecurityUtils.getCurrentUsername(); + String currentUsername = ""; String now = DateUtil.now(); dto.setId(IdUtil.simpleUUID()); @@ -71,7 +71,8 @@ public class GridServiceImpl implements GridService { GridDto entity = this.findById(dto.getId()); if (entity == null) throw new BadRequestException("被删除或无权限,操作失败!"); - String currentUsername = SecurityUtils.getCurrentUsername(); +// String currentUsername = SecurityUtils.getCurrentUsername(); + String currentUsername = ""; String now = DateUtil.now(); dto.setUpdate_time(now); dto.setUpdate_by(currentUsername); diff --git a/nladmin-system/src/main/java/org/nl/modules/system/service/impl/ParamServiceImpl.java b/nladmin-system/src/main/java/org/nl/modules/system/service/impl/ParamServiceImpl.java index 4bbfab01e..608052e42 100644 --- a/nladmin-system/src/main/java/org/nl/modules/system/service/impl/ParamServiceImpl.java +++ b/nladmin-system/src/main/java/org/nl/modules/system/service/impl/ParamServiceImpl.java @@ -12,7 +12,6 @@ import org.nl.exception.BadRequestException; import org.nl.modules.system.service.ParamService; import org.nl.modules.system.service.dto.ParamDto; import org.nl.utils.FileUtil; -import org.nl.utils.SecurityUtils; import org.nl.wql.core.bean.ResultBean; import org.nl.wql.core.bean.WQLObject; import org.nl.wql.util.WqlUtil; @@ -72,7 +71,8 @@ public class ParamServiceImpl implements ParamService { @Override @Transactional(rollbackFor = Exception.class) public void create(ParamDto dto) { - String currentUsername = SecurityUtils.getCurrentUsername(); +// String currentUsername = SecurityUtils.getCurrentUsername(); + String currentUsername = ""; String now = DateUtil.now(); dto.setId(IdUtil.simpleUUID()); @@ -92,7 +92,8 @@ public class ParamServiceImpl implements ParamService { ParamDto entity = this.findById(dto.getId()); if (entity == null) throw new BadRequestException("被删除或无权限,操作失败!"); - String currentUsername = SecurityUtils.getCurrentUsername(); +// String currentUsername = SecurityUtils.getCurrentUsername(); + String currentUsername = ""; String now = DateUtil.now(); dto.setUpdate_time(now); dto.setUpdate_by(currentUsername); diff --git a/nladmin-system/src/main/java/org/nl/modules/system/service/impl/RedisServiceImpl.java b/nladmin-system/src/main/java/org/nl/modules/system/service/impl/RedisServiceImpl.java index 189c8d184..18b06affa 100644 --- a/nladmin-system/src/main/java/org/nl/modules/system/service/impl/RedisServiceImpl.java +++ b/nladmin-system/src/main/java/org/nl/modules/system/service/impl/RedisServiceImpl.java @@ -52,7 +52,7 @@ public class RedisServiceImpl implements RedisService { List keyDefines = RedisKeyRegistry.list(); JSONObject json = new JSONObject(); System.out.println(keyDefines); - json.put("info", RedisConvert.INSTANCE.convertList(keyDefines)); +// json.put("info", RedisConvert.INSTANCE.convertList(keyDefines)); return json; } diff --git a/nladmin-system/src/main/java/org/nl/modules/system/service/impl/RoleServiceImpl.java b/nladmin-system/src/main/java/org/nl/modules/system/service/impl/RoleServiceImpl.java index 905361e5d..a60f98f60 100644 --- a/nladmin-system/src/main/java/org/nl/modules/system/service/impl/RoleServiceImpl.java +++ b/nladmin-system/src/main/java/org/nl/modules/system/service/impl/RoleServiceImpl.java @@ -17,6 +17,8 @@ package org.nl.modules.system.service.impl; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.util.StrUtil; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; import lombok.RequiredArgsConstructor; import org.nl.exception.BadRequestException; import org.nl.exception.EntityExistException; @@ -34,13 +36,12 @@ import org.nl.modules.system.service.dto.UserDto; import org.nl.modules.system.service.mapstruct.RoleMapper; import org.nl.modules.system.service.mapstruct.RoleSmallMapper; import org.nl.utils.*; +import org.nl.wql.WQL; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -162,22 +163,38 @@ public class RoleServiceImpl implements RoleService { return Collections.min(roleDtos.stream().map(RoleDto::getLevel).collect(Collectors.toList())); } +// @Override +// @Cacheable(key = "'auth:' + #p0.id") +// public List mapToGrantedAuthorities(UserDto user) { +// Set permissions = new HashSet<>(); +// // 如果是管理员直接返回 +// if (user.getIsAdmin()) { +// permissions.add("admin"); +//// return permissions.stream().map(SimpleGrantedAuthority::new) +//// .collect(Collectors.toList()); +// } +// Set roles = roleRepository.findByUserId(user.getId()); +// permissions = roles.stream().flatMap(role -> role.getMenus().stream()) +// .filter(menu -> StrUtil.isNotEmpty(menu.getPermission())) +// .map(Menu::getPermission).collect(Collectors.toSet()); +//// return permissions.stream().map(SimpleGrantedAuthority::new) +//// .collect(Collectors.toList()); +// return null; +// } + @Override @Cacheable(key = "'auth:' + #p0.id") - public List mapToGrantedAuthorities(UserDto user) { - Set permissions = new HashSet<>(); - // 如果是管理员直接返回 - if (user.getIsAdmin()) { - permissions.add("admin"); - return permissions.stream().map(SimpleGrantedAuthority::new) - .collect(Collectors.toList()); + public List getPermissionList(String id) { + List permission = new LinkedList<>(); + HashMap map = new HashMap<>(); + map.put("flag", "1"); + map.put("user_id", id); + JSONArray rows = WQL.getWO("SYS_MENU").addParamMap(map).process().getResultJSONArray(0); + for (int i = 0; i < rows.size(); i++) { + JSONObject jsonObject = rows.getJSONObject(i); + permission.add(jsonObject.getString("permission")); } - Set roles = roleRepository.findByUserId(user.getId()); - permissions = roles.stream().flatMap(role -> role.getMenus().stream()) - .filter(menu -> StrUtil.isNotEmpty(menu.getPermission())) - .map(Menu::getPermission).collect(Collectors.toSet()); - return permissions.stream().map(SimpleGrantedAuthority::new) - .collect(Collectors.toList()); + return permission; } @Override diff --git a/nladmin-system/src/main/java/org/nl/modules/system/service/impl/UserServiceImpl.java b/nladmin-system/src/main/java/org/nl/modules/system/service/impl/UserServiceImpl.java index 3cc25208e..82b354223 100644 --- a/nladmin-system/src/main/java/org/nl/modules/system/service/impl/UserServiceImpl.java +++ b/nladmin-system/src/main/java/org/nl/modules/system/service/impl/UserServiceImpl.java @@ -184,7 +184,8 @@ public class UserServiceImpl implements UserService { @Override @Transactional(rollbackFor = Exception.class) public Map updateAvatar(MultipartFile multipartFile) { - User user = userRepository.findByUsername(SecurityUtils.getCurrentUsername()); +// User user = userRepository.findByUsername(SecurityUtils.getCurrentUsername()); + User user = userRepository.findByUsername(""); String oldPath = user.getAvatarPath(); File file = FileUtil.upload(multipartFile, properties.getPath().getAvatar()); user.setAvatarPath(Objects.requireNonNull(file).getPath()); diff --git a/nladmin-system/src/main/java/org/nl/modules/system/service/wql/SYS_MENU.wql b/nladmin-system/src/main/java/org/nl/modules/system/service/wql/SYS_MENU.wql new file mode 100644 index 000000000..3c2758ebd --- /dev/null +++ b/nladmin-system/src/main/java/org/nl/modules/system/service/wql/SYS_MENU.wql @@ -0,0 +1,71 @@ +[交易说明] + 交易名: 获取用户权限 + 所属模块: + 功能简述: + 版权所有: + 表引用: + 版本经历: + +[数据库] + --指定数据库,为空采用默认值,默认为db.properties中列出的第一个库 + +[IO定义] + ################################################# + ## 表字段对应输入参数 + ################################################# + 输入.flag TYPEAS s_string + 输入.user_id TYPEAS s_string + +[临时表] + --这边列出来的临时表就会在运行期动态创建 + +[临时变量] + --所有中间过程变量均可在此处定义 + +[业务过程] + + ########################################## + # 1、输入输出检查 # + ########################################## + + + ########################################## + # 2、主过程前处理 # + ########################################## + + + ########################################## + # 3、业务主过程 # + ########################################## + IF 输入.flag = "1" + QUERY + SELECT DISTINCT + permission + FROM + sys_menu + WHERE + menu_id IN + ( + SELECT + menu_id + FROM + sys_roles_menus + WHERE + role_id IN + ( + SELECT + role_id + FROM + sys_users_roles + WHERE + 1=1 + OPTION 输入.user_id <> "" + user_id = 输入.user_id + ENDOPTION + ) + ) + AND permission IS NOT NULL + AND permission != '' + ENDSELECT + ENDQUERY + ENDIF \ No newline at end of file diff --git a/nladmin-system/src/main/resources/config/application-dev.yml b/nladmin-system/src/main/resources/config/application-dev.yml index 3efaa7fae..99c15746e 100644 --- a/nladmin-system/src/main/resources/config/application-dev.yml +++ b/nladmin-system/src/main/resources/config/application-dev.yml @@ -6,9 +6,12 @@ spring: druid: db-type: com.alibaba.druid.pool.DruidDataSource driverClassName: net.sf.log4jdbc.sql.jdbcapi.DriverSpy - url: jdbc:log4jdbc:mysql://${DB_HOST:47.111.78.178}:${DB_PORT:3306}/${DB_NAME:nladmin}?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false&useOldAliasMetadataBehavior=true +# url: jdbc:log4jdbc:mysql://${DB_HOST:47.111.78.178}:${DB_PORT:3306}/${DB_NAME:nladmin}?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false&useOldAliasMetadataBehavior=true + url: jdbc:log4jdbc:mysql://${DB_HOST:127.0.0.1}:${DB_PORT:3306}/${DB_NAME:nladmin}?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false&useOldAliasMetadataBehavior=true +# username: ${DB_USER:root} username: ${DB_USER:root} - password: ${DB_PWD:P@ssw0rd} +# password: ${DB_PWD:P@ssw0rd} + password: ${DB_PWD:12356} # 初始连接数 initial-size: 5 # 最小连接数 @@ -128,3 +131,22 @@ logging: file: path: C:\log\wms config: classpath:logback-spring.xml + +# Sa-Token配置 +sa-token: + # token 名称 (同时也是cookie名称) + token-name: satoken + # token 有效期,单位s 默认30天, -1代表永不过期 + timeout: 2592000 + # token 临时有效期 (指定时间内无操作就视为token过期) 单位: 秒 + activity-timeout: -1 + # 是否允许同一账号并发登录 (为true时允许一起登录, 为false时新登录挤掉旧登录) + is-concurrent: true + # 在多人登录同一账号时,是否共用一个token (为true时所有登录共用一个token, 为false时每次登录新建一个token) + is-share: false + # token风格 + token-style: random-128 + # 是否输出操作日志 + is-log: false + # token 前缀 +# token-prefix: Bearer \ No newline at end of file diff --git a/nladmin-system/src/main/resources/template/generator/admin/Controller.ftl b/nladmin-system/src/main/resources/template/generator/admin/Controller.ftl index 9d29f2fbc..2e211ff26 100644 --- a/nladmin-system/src/main/resources/template/generator/admin/Controller.ftl +++ b/nladmin-system/src/main/resources/template/generator/admin/Controller.ftl @@ -7,7 +7,7 @@ import lombok.RequiredArgsConstructor; import org.nl.annotation.Log; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; +import cn.dev33.satoken.annotation.SaCheckPermission; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import io.swagger.annotations.*; @@ -30,7 +30,7 @@ public class ${className}Controller { @GetMapping @Log("查询${apiAlias}") @ApiOperation("查询${apiAlias}") - //@PreAuthorize("@el.check('${changeClassName}:list')") + //@SaCheckPermission("@el.check('${changeClassName}:list')") public ResponseEntity query(@RequestParam Map whereJson, Pageable page){ return new ResponseEntity<>(${changeClassName}Service.queryAll(whereJson,page),HttpStatus.OK); } @@ -38,7 +38,7 @@ public class ${className}Controller { @PostMapping @Log("新增${apiAlias}") @ApiOperation("新增${apiAlias}") - //@PreAuthorize("@el.check('${changeClassName}:add')") + //@SaCheckPermission("@el.check('${changeClassName}:add')") public ResponseEntity create(@Validated @RequestBody ${className}Dto dto){ ${changeClassName}Service.create(dto); return new ResponseEntity<>(HttpStatus.CREATED); @@ -47,7 +47,7 @@ public class ${className}Controller { @PutMapping @Log("修改${apiAlias}") @ApiOperation("修改${apiAlias}") - //@PreAuthorize("@el.check('${changeClassName}:edit')") + //@SaCheckPermission("@el.check('${changeClassName}:edit')") public ResponseEntity update(@Validated @RequestBody ${className}Dto dto){ ${changeClassName}Service.update(dto); return new ResponseEntity<>(HttpStatus.NO_CONTENT); @@ -55,7 +55,7 @@ public class ${className}Controller { @Log("删除${apiAlias}") @ApiOperation("删除${apiAlias}") - //@PreAuthorize("@el.check('${changeClassName}:del')") + //@SaCheckPermission("@el.check('${changeClassName}:del')") @DeleteMapping public ResponseEntity delete(@RequestBody ${pkColumnType}[] ids) { ${changeClassName}Service.deleteAll(ids); diff --git a/nladmin-tools/src/main/java/org/nl/rest/LocalStorageController.java b/nladmin-tools/src/main/java/org/nl/rest/LocalStorageController.java index 73c3ca8a8..6c38935e3 100644 --- a/nladmin-tools/src/main/java/org/nl/rest/LocalStorageController.java +++ b/nladmin-tools/src/main/java/org/nl/rest/LocalStorageController.java @@ -15,6 +15,7 @@ */ package org.nl.rest; +import cn.dev33.satoken.annotation.SaCheckPermission; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.RequiredArgsConstructor; @@ -27,7 +28,6 @@ import org.nl.utils.FileUtil; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; @@ -49,21 +49,21 @@ public class LocalStorageController { @ApiOperation("查询文件") @GetMapping - @PreAuthorize("@el.check('storage:list')") + @SaCheckPermission("storage:list") public ResponseEntity query(LocalStorageQueryCriteria criteria, Pageable pageable) { return new ResponseEntity<>(localStorageService.queryAll(criteria, pageable), HttpStatus.OK); } @ApiOperation("导出数据") @GetMapping(value = "/download") - @PreAuthorize("@el.check('storage:list')") + @SaCheckPermission("storage:list") public void download(HttpServletResponse response, LocalStorageQueryCriteria criteria) throws IOException { localStorageService.download(localStorageService.queryAll(criteria), response); } @ApiOperation("上传文件") @PostMapping - @PreAuthorize("@el.check('storage:add')") + @SaCheckPermission("storage:add") public ResponseEntity create(@RequestParam String name, @RequestParam("file") MultipartFile file) { LocalStorage localStorage = localStorageService.create(name, file); return new ResponseEntity<>(localStorage, HttpStatus.CREATED); @@ -84,7 +84,7 @@ public class LocalStorageController { @Log("修改文件") @ApiOperation("修改文件") @PutMapping - @PreAuthorize("@el.check('storage:edit')") + @SaCheckPermission("storage:edit") public ResponseEntity update(@Validated @RequestBody LocalStorage resources) { localStorageService.update(resources); return new ResponseEntity<>(HttpStatus.NO_CONTENT); diff --git a/nladmin-ui/src/store/modules/user.js b/nladmin-ui/src/store/modules/user.js index 3b1c7fb82..10d237566 100644 --- a/nladmin-ui/src/store/modules/user.js +++ b/nladmin-ui/src/store/modules/user.js @@ -31,6 +31,7 @@ const user = { const rememberMe = userInfo.rememberMe return new Promise((resolve, reject) => { login(userInfo.username, userInfo.password, userInfo.code, userInfo.uuid).then(res => { + console.log('登录信息:', res) setToken(res.token, rememberMe) commit('SET_TOKEN', res.token) setUserInfo(res.user, commit) @@ -47,6 +48,7 @@ const user = { GetInfo({ commit }) { return new Promise((resolve, reject) => { getInfo().then(res => { + console.log('用户信息:', res) setUserInfo(res, commit) resolve(res) }).catch(error => { diff --git a/nladmin-ui/src/views/login.vue b/nladmin-ui/src/views/login.vue index dbaf5de93..2a07b3185 100644 --- a/nladmin-ui/src/views/login.vue +++ b/nladmin-ui/src/views/login.vue @@ -54,8 +54,8 @@ export default { codeUrl: '', cookiePass: '', loginForm: { - username: '', - password: '', + username: 'admin', + password: '123456', rememberMe: false, code: '', uuid: '' diff --git a/pom.xml b/pom.xml index cff9fa8b7..18111558b 100644 --- a/pom.xml +++ b/pom.xml @@ -61,9 +61,15 @@ + + + + + - org.springframework.boot - spring-boot-starter-security + cn.dev33 + sa-token-spring-boot-starter + 1.31.0