🎨 引入spring-java-format插件,代码格式管理

This commit is contained in:
b2baccline
2020-06-25 00:19:21 +08:00
parent 2b01fb6f5b
commit 89add5d79a
329 changed files with 6464 additions and 6260 deletions

View File

@@ -15,4 +15,5 @@ import org.springframework.context.annotation.Configuration;
@ServletComponentScan("com.hccake.ballcat.admin.oauth.filter") @ServletComponentScan("com.hccake.ballcat.admin.oauth.filter")
@Configuration @Configuration
public class UpmsAutoConfiguration { public class UpmsAutoConfiguration {
} }

View File

@@ -1,18 +1,18 @@
package com.hccake.ballcat.admin.constants; package com.hccake.ballcat.admin.constants;
/** /**
* @author Hccake * @author Hccake
*/ */
public final class SecurityConst { public final class SecurityConst {
private SecurityConst() {
private SecurityConst(){} }
/** /**
* 刷新 * 刷新
*/ */
public static final String REFRESH_TOKEN = "refresh_token"; public static final String REFRESH_TOKEN = "refresh_token";
/** /**
* 角色前缀 * 角色前缀
*/ */

View File

@@ -10,25 +10,28 @@ import lombok.Getter;
*/ */
public final class SysPermissionConst { public final class SysPermissionConst {
private SysPermissionConst(){} private SysPermissionConst() {
}
@Getter @Getter
@AllArgsConstructor @AllArgsConstructor
public enum Type{ public enum Type {
/**
* 目录
*/
DIRECTORY(0),
/**
* 菜单
*/
MENU(1),
/**
* 按钮/权限
*/
BUTTON(2);
private final int value; /**
} * 目录
*/
DIRECTORY(0),
/**
* 菜单
*/
MENU(1),
/**
* 按钮/权限
*/
BUTTON(2);
private final int value;
}
} }

View File

@@ -10,41 +10,44 @@ import lombok.Getter;
*/ */
public final class SysUserConst { public final class SysUserConst {
private SysUserConst() { private SysUserConst() {
} }
@Getter @Getter
@AllArgsConstructor @AllArgsConstructor
public enum Status { public enum Status {
/**
* 正常
*/
NORMAL(1),
/**
* 锁定的
*/
LOCKED(0);
private final Integer value; /**
} * 正常
*/
NORMAL(1),
/**
* 锁定的
*/
LOCKED(0);
/** private final Integer value;
* 用户类型1系统用户2平台用户
*/
@Getter
@AllArgsConstructor
public enum Type {
/** }
* 系统用户
*/
SYSTEM(1),
/**
* 平台用户
*/
CUSTOMER(2);
private final Integer value; /**
} * 用户类型1系统用户2平台用户
*/
@Getter
@AllArgsConstructor
public enum Type {
/**
* 系统用户
*/
SYSTEM(1),
/**
* 平台用户
*/
CUSTOMER(2);
private final Integer value;
}
} }

View File

@@ -7,10 +7,9 @@ package com.hccake.ballcat.admin.constants;
*/ */
public final class UrlMappingConst { public final class UrlMappingConst {
private UrlMappingConst() {} private UrlMappingConst() {
}
public static final String OAUTH_LOGIN = "/oauth/token";
public static final String OAUTH_LOGIN = "/oauth/token";
} }

View File

@@ -15,7 +15,6 @@ import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
/** /**
* 访问日志 * 访问日志
* *
@@ -24,37 +23,35 @@ import org.springframework.web.bind.annotation.RestController;
*/ */
@RestController @RestController
@RequiredArgsConstructor @RequiredArgsConstructor
@RequestMapping("/log/adminaccesslog" ) @RequestMapping("/log/adminaccesslog")
@Api(value = "adminaccesslog", tags = "访问日志管理") @Api(value = "adminaccesslog", tags = "访问日志管理")
public class AdminAccessLogController { public class AdminAccessLogController {
private final AdminAccessLogService adminAccessLogService;
/** private final AdminAccessLogService adminAccessLogService;
* 分页查询
* @param page 分页对象
* @param adminAccessLog 访问日志
* @return
*/
@ApiOperation(value = "分页查询", notes = "分页查询")
@GetMapping("/page" )
@PreAuthorize("@per.hasPermission('log:adminaccesslog:read')")
public R<IPage<AdminAccessLog>> getAccessLogApiPage(
Page<AdminAccessLog> page, AdminAccessLog adminAccessLog) {
return R.ok(adminAccessLogService.page(page, Wrappers.query(adminAccessLog)));
}
/**
* 分页查询
* @param page 分页对象
* @param adminAccessLog 访问日志
* @return
*/
@ApiOperation(value = "分页查询", notes = "分页查询")
@GetMapping("/page")
@PreAuthorize("@per.hasPermission('log:adminaccesslog:read')")
public R<IPage<AdminAccessLog>> getAccessLogApiPage(Page<AdminAccessLog> page, AdminAccessLog adminAccessLog) {
return R.ok(adminAccessLogService.page(page, Wrappers.query(adminAccessLog)));
}
/** /**
* 通过id查询访问日志 * 通过id查询访问日志
* @param id id * @param id id
* @return R * @return R
*/ */
@ApiOperation(value = "通过id查询后台访问日志", notes = "通过id查询后台访问日志") @ApiOperation(value = "通过id查询后台访问日志", notes = "通过id查询后台访问日志")
@GetMapping("/{id}") @GetMapping("/{id}")
@PreAuthorize("@per.hasPermission('log:adminaccesslog:read')") @PreAuthorize("@per.hasPermission('log:adminaccesslog:read')")
public R<AdminAccessLog> getById(@PathVariable("id" ) Long id) { public R<AdminAccessLog> getById(@PathVariable("id") Long id) {
return R.ok(adminAccessLogService.getById(id)); return R.ok(adminAccessLogService.getById(id));
} }
} }

View File

@@ -15,7 +15,6 @@ import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
/** /**
* 操作日志 * 操作日志
* *
@@ -27,35 +26,33 @@ import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/log/adminoperationlog") @RequestMapping("/log/adminoperationlog")
@Api(value = "adminoperationlog", tags = "操作日志管理") @Api(value = "adminoperationlog", tags = "操作日志管理")
public class AdminOperationLogController { public class AdminOperationLogController {
private final OperationLogAdminService operationLogAdminService;
/** private final OperationLogAdminService operationLogAdminService;
* 分页查询
*
* @param page 分页对象
* @param adminOperationLog 操作日志
* @return
*/
@ApiOperation(value = "分页查询", notes = "分页查询")
@GetMapping("/page")
@PreAuthorize("@per.hasPermission('log:adminoperationlog:read')")
public R<IPage<AdminOperationLog>> getOperationLogAdminPage(
Page<AdminOperationLog> page, AdminOperationLog adminOperationLog) {
return R.ok(operationLogAdminService.page(page, Wrappers.query(adminOperationLog)));
}
/**
* 分页查询
* @param page 分页对象
* @param adminOperationLog 操作日志
* @return
*/
@ApiOperation(value = "分页查询", notes = "分页查询")
@GetMapping("/page")
@PreAuthorize("@per.hasPermission('log:adminoperationlog:read')")
public R<IPage<AdminOperationLog>> getOperationLogAdminPage(Page<AdminOperationLog> page,
AdminOperationLog adminOperationLog) {
return R.ok(operationLogAdminService.page(page, Wrappers.query(adminOperationLog)));
}
/** /**
* 通过id查询操作日志 * 通过id查询操作日志
* * @param id id
* @param id id * @return R
* @return R */
*/ @ApiOperation(value = "通过id查询", notes = "通过id查询")
@ApiOperation(value = "通过id查询", notes = "通过id查询") @GetMapping("/{id}")
@GetMapping("/{id}") @PreAuthorize("@per.hasPermission('log:adminoperationlog:read')")
@PreAuthorize("@per.hasPermission('log:adminoperationlog:read')") public R<AdminOperationLog> getById(@PathVariable("id") Long id) {
public R<AdminOperationLog> getById(@PathVariable("id") Long id) { return R.ok(operationLogAdminService.getById(id));
return R.ok(operationLogAdminService.getById(id)); }
}
} }

View File

@@ -31,61 +31,51 @@ import java.util.Optional;
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
public class AdminAccessLogHandler implements AccessLogHandler<AdminAccessLog> { public class AdminAccessLogHandler implements AccessLogHandler<AdminAccessLog> {
private final AccessLogAdminSaveThread accessLogAdminSaveThread;
/** private final AccessLogAdminSaveThread accessLogAdminSaveThread;
* 生产一个日志
*
* @return accessLog
* @param request 请求信息
* @param response 响应信息
* @param time 执行时长
* @param myThrowable 异常信息
*/
@Override
public AdminAccessLog prodLog(HttpServletRequest request, HttpServletResponse response, Long time, Throwable myThrowable) {
AdminAccessLog adminAccessLog = new AdminAccessLog() /**
.setTraceId(MDC.get(LogConstant.TRACE_ID)) * 生产一个日志
.setCreateTime(LocalDateTime.now()) * @return accessLog
.setTime(time) * @param request 请求信息
.setIp(IPUtil.getIpAddr(request)) * @param response 响应信息
.setMethod(request.getMethod()) * @param time 执行时长
.setUserAgent(request.getHeader("user-agent")) * @param myThrowable 异常信息
.setUri(URLUtil.getPath(request.getRequestURI())) */
.setMatchingPattern(String.valueOf(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE))) @Override
.setErrorMsg(Optional.ofNullable(myThrowable).map(Throwable::getMessage).orElse(null)) public AdminAccessLog prodLog(HttpServletRequest request, HttpServletResponse response, Long time,
.setHttpStatus(response.getStatus()) Throwable myThrowable) {
.setReqParams(JSONUtil.toJsonStr(request.getParameterMap()));
// 非文件上传请求记录body AdminAccessLog adminAccessLog = new AdminAccessLog().setTraceId(MDC.get(LogConstant.TRACE_ID))
if (!LogUtils.isMultipartContent(request)){ .setCreateTime(LocalDateTime.now()).setTime(time).setIp(IPUtil.getIpAddr(request))
adminAccessLog.setReqBody(LogUtils.getRequestBody(request)); .setMethod(request.getMethod()).setUserAgent(request.getHeader("user-agent"))
} .setUri(URLUtil.getPath(request.getRequestURI()))
.setMatchingPattern(
String.valueOf(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE)))
.setErrorMsg(Optional.ofNullable(myThrowable).map(Throwable::getMessage).orElse(null))
.setHttpStatus(response.getStatus()).setReqParams(JSONUtil.toJsonStr(request.getParameterMap()));
// 如果登陆用户 则记录用户名和用户id // 非文件上传请求记录body
Optional.ofNullable(SecurityUtils.getSysUserDetails()) if (!LogUtils.isMultipartContent(request)) {
.map(SysUserDetails::getSysUser) adminAccessLog.setReqBody(LogUtils.getRequestBody(request));
.ifPresent(x -> { }
adminAccessLog.setUserId(x.getUserId());
adminAccessLog.setUsername(x.getUsername());
});
return adminAccessLog;
}
/**
* 记录日志
*
* @param accessLog 访问日志
*/
@Override
public void saveLog(AdminAccessLog accessLog) {
accessLogAdminSaveThread.putObject(accessLog);
}
// 如果登陆用户 则记录用户名和用户id
Optional.ofNullable(SecurityUtils.getSysUserDetails()).map(SysUserDetails::getSysUser).ifPresent(x -> {
adminAccessLog.setUserId(x.getUserId());
adminAccessLog.setUsername(x.getUsername());
});
return adminAccessLog;
}
/**
* 记录日志
* @param accessLog 访问日志
*/
@Override
public void saveLog(AdminAccessLog accessLog) {
accessLogAdminSaveThread.putObject(accessLog);
}
} }

View File

@@ -10,14 +10,14 @@ import org.springframework.stereotype.Component;
*/ */
@Component @Component
public class AdminExceptionHandler implements GlobalExceptionHandler { public class AdminExceptionHandler implements GlobalExceptionHandler {
/**
* 在此处理错误信息 /**
* 进行落库入ES 发送报警通知等信息 * 在此处理错误信息 进行落库入ES 发送报警通知等信息
* * @param throwable
* @param throwable */
*/ @Override
@Override public void handle(Throwable throwable) {
public void handle(Throwable throwable) { System.out.println("后台错误日志处理:" + throwable.getMessage());
System.out.println("后台错误日志处理:" + throwable.getMessage()); }
}
} }

View File

@@ -16,15 +16,17 @@ import org.springframework.stereotype.Component;
@Component @Component
@RequiredArgsConstructor @RequiredArgsConstructor
public class AdminOperationLogHandler implements OperationLogHandler { public class AdminOperationLogHandler implements OperationLogHandler {
private final OperationLogAdminService operationLogAdminService;
/** private final OperationLogAdminService operationLogAdminService;
* 保存操作日志
* @param operationLogDTO 操作日志DTO /**
*/ * 保存操作日志
@Override * @param operationLogDTO 操作日志DTO
public void saveLog(OperationLogDTO operationLogDTO) { */
AdminOperationLog adminOperationLog = OperationLogConverter.INSTANCE.dtoToPo(operationLogDTO); @Override
operationLogAdminService.save(adminOperationLog); public void saveLog(OperationLogDTO operationLogDTO) {
} AdminOperationLog adminOperationLog = OperationLogConverter.INSTANCE.dtoToPo(operationLogDTO);
operationLogAdminService.save(adminOperationLog);
}
} }

View File

@@ -23,82 +23,98 @@ import java.time.LocalDateTime;
@Accessors(chain = true) @Accessors(chain = true)
@ApiModel(value = "后台访问日志") @ApiModel(value = "后台访问日志")
public class AdminAccessLog extends Model<AdminAccessLog> { public class AdminAccessLog extends Model<AdminAccessLog> {
private static final long serialVersionUID = 1L;
/** private static final long serialVersionUID = 1L;
* 编号
*/ /**
@TableId * 编号
@ApiModelProperty(value = "编号") */
private Long id; @TableId
/** @ApiModelProperty(value = "编号")
* 追踪ID private Long id;
*/
@ApiModelProperty(value="追踪ID") /**
private String traceId; * 追踪ID
/** */
* 用户ID @ApiModelProperty(value = "追踪ID")
*/ private String traceId;
@ApiModelProperty(value = "用户ID")
private Integer userId; /**
/** * 用户ID
* 用户名 */
*/ @ApiModelProperty(value = "用户ID")
@ApiModelProperty(value = "用户名") private Integer userId;
private String username;
/** /**
* 访问IP地址 * 用户名
*/ */
@ApiModelProperty(value = "访问IP地址") @ApiModelProperty(value = "用户名")
private String ip; private String username;
/**
* 用户代理 /**
*/ * 访问IP地址
@ApiModelProperty(value = "用户代理") */
private String userAgent; @ApiModelProperty(value = "访问IP地址")
/** private String ip;
* 请求URI
*/ /**
@ApiModelProperty(value = "请求URI") * 用户代理
private String uri; */
/** @ApiModelProperty(value = "用户代理")
* 请求映射地址 private String userAgent;
*/
@ApiModelProperty(value = "请求映射地址") /**
private String matchingPattern; * 请求URI
/** */
* 操作方式 @ApiModelProperty(value = "请求URI")
*/ private String uri;
@ApiModelProperty(value = "操作方式")
private String method; /**
/** * 请求映射地址
* 请求参数 */
*/ @ApiModelProperty(value = "请求映射地址")
@ApiModelProperty(value = "请求参数") private String matchingPattern;
private String reqParams;
/** /**
* 请求body * 操作方式
*/ */
@ApiModelProperty(value = "请求body") @ApiModelProperty(value = "操作方式")
private String reqBody; private String method;
/**
* 响应状态码 /**
*/ * 请求参数
@ApiModelProperty(value = "响应状态码") */
private Integer httpStatus; @ApiModelProperty(value = "请求参数")
/** private String reqParams;
* 错误消息
*/ /**
@ApiModelProperty(value = "错误消息") * 请求body
private String errorMsg; */
/** @ApiModelProperty(value = "请求body")
* 执行时长 private String reqBody;
*/
@ApiModelProperty(value = "执行时长") /**
private Long time; * 响应状态码
/** */
* 创建时间 @ApiModelProperty(value = "响应状态码")
*/ private Integer httpStatus;
@ApiModelProperty(value = "创建时间")
private LocalDateTime createTime; /**
* 错误消息
*/
@ApiModelProperty(value = "错误消息")
private String errorMsg;
/**
* 执行时长
*/
@ApiModelProperty(value = "执行时长")
private Long time;
/**
* 创建时间
*/
@ApiModelProperty(value = "创建时间")
private LocalDateTime createTime;
} }

View File

@@ -21,72 +21,86 @@ import java.time.LocalDateTime;
@EqualsAndHashCode(callSuper = true) @EqualsAndHashCode(callSuper = true)
@ApiModel(value = "操作日志") @ApiModel(value = "操作日志")
public class AdminOperationLog extends Model<AdminOperationLog> { public class AdminOperationLog extends Model<AdminOperationLog> {
private static final long serialVersionUID = 1L;
/** private static final long serialVersionUID = 1L;
* 编号
*/ /**
@TableId * 编号
@ApiModelProperty(value="编号") */
private Long id; @TableId
/** @ApiModelProperty(value = "编号")
* 追踪ID private Long id;
*/
@ApiModelProperty(value="追踪ID") /**
private String traceId; * 追踪ID
/** */
* 日志消息 @ApiModelProperty(value = "追踪ID")
*/ private String traceId;
@ApiModelProperty(value="日志消息")
private String msg; /**
/** * 日志消息
* 访问IP地址 */
*/ @ApiModelProperty(value = "日志消息")
@ApiModelProperty(value="访问IP地址") private String msg;
private String ip;
/** /**
* 用户代理 * 访问IP地址
*/ */
@ApiModelProperty(value="用户代理") @ApiModelProperty(value = "访问IP地址")
private String userAgent; private String ip;
/**
* 请求URI /**
*/ * 用户代理
@ApiModelProperty(value="请求URI") */
private String uri; @ApiModelProperty(value = "用户代理")
/** private String userAgent;
* 请求方法
*/ /**
@ApiModelProperty(value="请求方法") * 请求URI
private String method; */
/** @ApiModelProperty(value = "请求URI")
* 操作提交的数据 private String uri;
*/
@ApiModelProperty(value="操作提交的数据") /**
private String params; * 请求方法
/** */
* 操作状态 @ApiModelProperty(value = "请求方法")
*/ private String method;
@ApiModelProperty(value="操作状态")
private Integer status; /**
/** * 操作提交的数据
* 操作类型 */
*/ @ApiModelProperty(value = "操作提交的数据")
@ApiModelProperty(value="操作类型") private String params;
private Integer type;
/** /**
* 执行时长 * 操作状态
*/ */
@ApiModelProperty(value="执行时长") @ApiModelProperty(value = "操作状态")
private Long time; private Integer status;
/**
* 创建者 /**
*/ * 操作类型
@ApiModelProperty(value="创建者") */
private String operator; @ApiModelProperty(value = "操作类型")
/** private Integer type;
* 创建时间
*/ /**
@ApiModelProperty(value="创建时间") * 执行时长
private LocalDateTime createTime; */
@ApiModelProperty(value = "执行时长")
private Long time;
/**
* 创建者
*/
@ApiModelProperty(value = "创建者")
private String operator;
/**
* 创建时间
*/
@ApiModelProperty(value = "创建时间")
private LocalDateTime createTime;
} }

View File

@@ -15,5 +15,7 @@ import org.springframework.stereotype.Service;
*/ */
@Slf4j @Slf4j
@Service @Service
public class AdminAccessLogServiceImpl extends ServiceImpl<AdminAccessLogMapper, AdminAccessLog> implements AdminAccessLogService { public class AdminAccessLogServiceImpl extends ServiceImpl<AdminAccessLogMapper, AdminAccessLog>
implements AdminAccessLogService {
} }

View File

@@ -13,6 +13,7 @@ import org.springframework.stereotype.Service;
* @date 2019-10-15 20:42:32 * @date 2019-10-15 20:42:32
*/ */
@Service @Service
public class OperationLogAdminServiceImpl extends ServiceImpl<AdminOperationLogMapper, AdminOperationLog> implements OperationLogAdminService { public class OperationLogAdminServiceImpl extends ServiceImpl<AdminOperationLogMapper, AdminOperationLog>
implements OperationLogAdminService {
} }

View File

@@ -18,34 +18,34 @@ import java.util.List;
@Component @Component
@RequiredArgsConstructor @RequiredArgsConstructor
public class AccessLogAdminSaveThread extends AbstractQueueThread<AdminAccessLog> { public class AccessLogAdminSaveThread extends AbstractQueueThread<AdminAccessLog> {
private final AdminAccessLogService adminAccessLogService;
/** private final AdminAccessLogService adminAccessLogService;
* 线程启动时的日志打印
*/
@Override
public void startLog() {
log.info("后台访问日志存储线程已启动===");
}
/** /**
* 错误日志打印 * 线程启动时的日志打印
* */
* @param e @Override
* @param list public void startLog() {
*/ log.info("后台访问日志存储线程已启动===");
@Override }
public void errorLog(Throwable e, List<AdminAccessLog> list) {
log.error("后台访问日志记录异常, [msg]:{}, [data]:{}", e.getMessage(), list); /**
} * 错误日志打印
* @param e
* @param list
*/
@Override
public void errorLog(Throwable e, List<AdminAccessLog> list) {
log.error("后台访问日志记录异常, [msg]:{}, [data]:{}", e.getMessage(), list);
}
/**
* 数据保存
* @param list
*/
@Override
public void save(List<AdminAccessLog> list) throws Exception {
adminAccessLogService.saveBatch(list);
}
/**
* 数据保存
*
* @param list
*/
@Override
public void save(List<AdminAccessLog> list) throws Exception {
adminAccessLogService.saveBatch(list);
}
} }

View File

@@ -17,7 +17,6 @@ import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
/** /**
* @author Hccake * @author Hccake
*/ */
@@ -26,12 +25,13 @@ import org.springframework.web.bind.annotation.RestController;
@Api(value = "oauth", tags = "用户认证模块") @Api(value = "oauth", tags = "用户认证模块")
@RequiredArgsConstructor @RequiredArgsConstructor
public class AuthController { public class AuthController {
private final TokenStore tokenStore; private final TokenStore tokenStore;
private final ApplicationEventPublisher publisher; private final ApplicationEventPublisher publisher;
/** /**
* 退出token * 退出token
*
* @param authHeader Authorization * @param authHeader Authorization
*/ */
@DeleteMapping("/logout") @DeleteMapping("/logout")
@@ -62,5 +62,4 @@ public class AuthController {
return R.ok(); return R.ok();
} }
} }

View File

@@ -15,7 +15,6 @@ import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
/** /**
* 系统配置表 * 系统配置表
* *
@@ -27,76 +26,71 @@ import org.springframework.web.bind.annotation.*;
@RequestMapping("sys/config") @RequestMapping("sys/config")
@Api(value = "sys/config", tags = "系统配置") @Api(value = "sys/config", tags = "系统配置")
public class SysConfigController { public class SysConfigController {
private final SysConfigService sysConfigService;
/** private final SysConfigService sysConfigService;
* 分页查询
*
* @param page 分页对象
* @param sysConfig 系统配置表
* @return
*/
@ApiOperation(value = "分页查询", notes = "分页查询")
@GetMapping("/page")
@PreAuthorize("@per.hasPermission('sys:config:read')")
public R<IPage<SysConfig>> getSysConfigPage(
Page<SysConfig> page, SysConfig sysConfig) {
return R.ok(sysConfigService.page(page, Wrappers.query(sysConfig)));
}
/** /**
* 通过id查询系统配置表 * 分页查询
* * @param page 分页对象
* @param id id * @param sysConfig 系统配置表
* @return R * @return
*/ */
@ApiOperation(value = "通过id查询", notes = "通过id查询") @ApiOperation(value = "分页查询", notes = "分页查询")
@GetMapping("/{id}") @GetMapping("/page")
@PreAuthorize("@per.hasPermission('sys:config:read')") @PreAuthorize("@per.hasPermission('sys:config:read')")
public R<SysConfig> getById(@PathVariable("id") Integer id) { public R<IPage<SysConfig>> getSysConfigPage(Page<SysConfig> page, SysConfig sysConfig) {
return R.ok(sysConfigService.getById(id)); return R.ok(sysConfigService.page(page, Wrappers.query(sysConfig)));
} }
/** /**
* 新增系统配置表 * 通过id查询系统配置表
* * @param id id
* @param sysConfig 系统配置表 * @return R
* @return R */
*/ @ApiOperation(value = "通过id查询", notes = "通过id查询")
@ApiOperation(value = "新增系统配置表", notes = "新增系统配置表") @GetMapping("/{id}")
@CreateOperationLogging(msg = "新增系统配置表") @PreAuthorize("@per.hasPermission('sys:config:read')")
@PostMapping public R<SysConfig> getById(@PathVariable("id") Integer id) {
@PreAuthorize("@per.hasPermission('sys:config:add')") return R.ok(sysConfigService.getById(id));
public R save(@RequestBody SysConfig sysConfig) { }
return R.ok(sysConfigService.save(sysConfig));
}
/** /**
* 修改系统配置表 * 新增系统配置表
* * @param sysConfig 系统配置表
* @param sysConfig 系统配置表 * @return R
* @return R */
*/ @ApiOperation(value = "新增系统配置表", notes = "新增系统配置表")
@ApiOperation(value = "修改系统配置表", notes = "修改系统配置表") @CreateOperationLogging(msg = "新增系统配置表")
@UpdateOperationLogging(msg = "修改系统配置表") @PostMapping
@PutMapping @PreAuthorize("@per.hasPermission('sys:config:add')")
@PreAuthorize("@per.hasPermission('sys:config:edit')") public R save(@RequestBody SysConfig sysConfig) {
public R updateById(@RequestBody SysConfig sysConfig) { return R.ok(sysConfigService.save(sysConfig));
return R.ok(sysConfigService.updateById(sysConfig)); }
}
/** /**
* 通过id删除系统配置表 * 修改系统配置表
* * @param sysConfig 系统配置表
* @param id id * @return R
* @return R */
*/ @ApiOperation(value = "修改系统配置表", notes = "修改系统配置表")
@ApiOperation(value = "通过id删除系统配置表", notes = "通过id删除系统配置表") @UpdateOperationLogging(msg = "修改系统配置表")
@DeleteOperationLogging(msg = "通过id删除系统配置表") @PutMapping
@DeleteMapping("/{id}") @PreAuthorize("@per.hasPermission('sys:config:edit')")
@PreAuthorize("@per.hasPermission('sys:config:del')") public R updateById(@RequestBody SysConfig sysConfig) {
public R removeById(@PathVariable Integer id) { return R.ok(sysConfigService.updateById(sysConfig));
return R.ok(sysConfigService.removeById(id)); }
}
/**
* 通过id删除系统配置表
* @param id id
* @return R
*/
@ApiOperation(value = "通过id删除系统配置表", notes = "通过id删除系统配置表")
@DeleteOperationLogging(msg = "通过id删除系统配置表")
@DeleteMapping("/{id}")
@PreAuthorize("@per.hasPermission('sys:config:del')")
public R removeById(@PathVariable Integer id) {
return R.ok(sysConfigService.removeById(id));
}
} }

View File

@@ -21,7 +21,6 @@ import org.springframework.web.bind.annotation.*;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
/** /**
* 字典表 * 字典表
* *
@@ -33,155 +32,136 @@ import java.util.Map;
@RequestMapping("/sys/dict") @RequestMapping("/sys/dict")
@Api(value = "/sys/dict", tags = "字典表管理") @Api(value = "/sys/dict", tags = "字典表管理")
public class SysDictController { public class SysDictController {
private final SysDictManager sysDictManager;
private final SysDictManager sysDictManager;
/** /**
* 通过字典标识查找对应字典项 * 通过字典标识查找对应字典项
* * @param dictCode 字典标识
* @param dictCode 字典标识 * @return 同类型字典
* @return 同类型字典 */
*/ @GetMapping("/data-hash/{dictCode}")
@GetMapping("/data-hash/{dictCode}") public R<DictDataAndHashVO> getDictDataAndHash(@PathVariable String dictCode) {
public R<DictDataAndHashVO> getDictDataAndHash(@PathVariable String dictCode) { return R.ok(sysDictManager.queryDictDataAndHashVO(dictCode));
return R.ok(sysDictManager.queryDictDataAndHashVO(dictCode)); }
}
/**
* 通过字典标识查找对应字典项
* @param dictHashCode 字典标识
* @return 同类型字典
*/
@PostMapping("/invalid-hash")
public R<List<String>> invalidDictHash(@RequestBody Map<String, String> dictHashCode) {
return R.ok(sysDictManager.invalidDictHash(dictHashCode));
}
/** /**
* 通过字典标识查找对应字典项 * 分页查询
* * @param page 分页对象
* @param dictHashCode 字典标识 * @param sysDictQO 字典
* @return 同类型字典 * @return R
*/ */
@PostMapping("/invalid-hash") @ApiOperation(value = "分页查询", notes = "分页查询")
public R<List<String>> invalidDictHash(@RequestBody Map<String, String> dictHashCode) { @GetMapping("/page")
return R.ok(sysDictManager.invalidDictHash(dictHashCode)); @PreAuthorize("@per.hasPermission('sys:dict:read')")
} public R<IPage<SysDict>> getSysDictPage(Page<SysDict> page, SysDictQO sysDictQO) {
return R.ok(sysDictManager.dictPage(page, sysDictQO));
}
/**
* 新增字典表
* @param sysDict 字典表
* @return R
*/
@ApiOperation(value = "新增字典表", notes = "新增字典表")
@CreateOperationLogging(msg = "新增字典表")
@PostMapping
@PreAuthorize("@per.hasPermission('sys:dict:add')")
public R save(@RequestBody SysDict sysDict) {
return sysDictManager.dictSave(sysDict) ? R.ok() : R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "新增字典表失败");
}
/**
* 修改字典表
* @param sysDict 字典表
* @return R
*/
@ApiOperation(value = "修改字典表", notes = "修改字典表")
@UpdateOperationLogging(msg = "修改字典表")
@PutMapping
@PreAuthorize("@per.hasPermission('sys:dict:edit')")
public R updateById(@RequestBody SysDict sysDict) {
return sysDictManager.updateDictById(sysDict) ? R.ok()
: R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "修改字典表失败");
}
/**
* 通过id删除字典表
* @param id id
* @return R
*/
@ApiOperation(value = "通过id删除字典表", notes = "通过id删除字典表")
@DeleteOperationLogging(msg = "通过id删除字典表")
@DeleteMapping("/{id}")
@PreAuthorize("@per.hasPermission('sys:dict:del')")
public R removeById(@PathVariable Integer id) {
return sysDictManager.removeDictById(id) ? R.ok()
: R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "通过id删除字典表失败");
}
/** /**
* 分页查询 * 分页查询
* * @param page 分页对象
* @param page 分页对象 * @param dictCode 字典标识
* @param sysDictQO 字典表 * @return R
* @return R */
*/ @ApiOperation(value = "分页查询", notes = "分页查询")
@ApiOperation(value = "分页查询", notes = "分页查询") @GetMapping("/item/page")
@GetMapping("/page") @PreAuthorize("@per.hasPermission('sys:dict:read')")
@PreAuthorize("@per.hasPermission('sys:dict:read')") public R<IPage<SysDictItem>> getSysDictItemPage(Page<SysDictItem> page, @RequestParam("dictCode") String dictCode) {
public R<IPage<SysDict>> getSysDictPage( return R.ok(sysDictManager.dictItemPage(page, dictCode));
Page<SysDict> page, SysDictQO sysDictQO) { }
return R.ok(sysDictManager.dictPage(page, sysDictQO));
}
/**
* 新增字典项
* @param sysDictItem 字典项
* @return R
*/
@ApiOperation(value = "新增字典项", notes = "新增字典项")
@CreateOperationLogging(msg = "新增字典项")
@PostMapping("item")
@PreAuthorize("@per.hasPermission('sys:dict:add')")
public R saveItem(@RequestBody SysDictItem sysDictItem) {
return sysDictManager.saveDictItem(sysDictItem) ? R.ok()
: R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "新增字典项失败");
}
/** /**
* 新增字典 * 修改字典
* * @param sysDictItem 字典项
* @param sysDict 字典表 * @return R
* @return R */
*/ @ApiOperation(value = "修改字典项", notes = "修改字典项")
@ApiOperation(value = "新增字典表", notes = "新增字典") @UpdateOperationLogging(msg = "修改字典")
@CreateOperationLogging(msg = "新增字典表") @PutMapping("item")
@PostMapping @PreAuthorize("@per.hasPermission('sys:dict:edit')")
@PreAuthorize("@per.hasPermission('sys:dict:add')") public R updateItemById(@RequestBody SysDictItem sysDictItem) {
public R save(@RequestBody SysDict sysDict) { return sysDictManager.updateDictItemById(sysDictItem) ? R.ok()
return sysDictManager.dictSave(sysDict) ? : R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "修改字典项失败");
R.ok() : R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "新增字典表失败"); }
}
/** /**
* 修改字典 * 通过id删除字典
* * @param id id
* @param sysDict 字典表 * @return R
* @return R */
*/ @ApiOperation(value = "通过id删除字典项", notes = "通过id删除字典项")
@ApiOperation(value = "修改字典表", notes = "修改字典") @DeleteOperationLogging(msg = "通过id删除字典")
@UpdateOperationLogging(msg = "修改字典表") @DeleteMapping("/item/{id}")
@PutMapping @PreAuthorize("@per.hasPermission('sys:dict:del')")
@PreAuthorize("@per.hasPermission('sys:dict:edit')") public R removeItemById(@PathVariable Integer id) {
public R updateById(@RequestBody SysDict sysDict) { return sysDictManager.removeDictItemById(id) ? R.ok()
return sysDictManager.updateDictById(sysDict) ? : R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "通过id删除字典项失败");
R.ok() : R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "修改字典表失败"); }
}
/**
* 通过id删除字典表
*
* @param id id
* @return R
*/
@ApiOperation(value = "通过id删除字典表", notes = "通过id删除字典表")
@DeleteOperationLogging(msg = "通过id删除字典表")
@DeleteMapping("/{id}")
@PreAuthorize("@per.hasPermission('sys:dict:del')")
public R removeById(@PathVariable Integer id) {
return sysDictManager.removeDictById(id) ?
R.ok() : R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "通过id删除字典表失败");
}
/**
* 分页查询
*
* @param page 分页对象
* @param dictCode 字典标识
* @return R
*/
@ApiOperation(value = "分页查询", notes = "分页查询")
@GetMapping("/item/page")
@PreAuthorize("@per.hasPermission('sys:dict:read')")
public R<IPage<SysDictItem>> getSysDictItemPage(
Page<SysDictItem> page, @RequestParam("dictCode")String dictCode) {
return R.ok(sysDictManager.dictItemPage(page, dictCode));
}
/**
* 新增字典项
*
* @param sysDictItem 字典项
* @return R
*/
@ApiOperation(value = "新增字典项", notes = "新增字典项")
@CreateOperationLogging(msg = "新增字典项")
@PostMapping("item")
@PreAuthorize("@per.hasPermission('sys:dict:add')")
public R saveItem(@RequestBody SysDictItem sysDictItem) {
return sysDictManager.saveDictItem(sysDictItem) ?
R.ok() : R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "新增字典项失败");
}
/**
* 修改字典项
*
* @param sysDictItem 字典项
* @return R
*/
@ApiOperation(value = "修改字典项", notes = "修改字典项")
@UpdateOperationLogging(msg = "修改字典项")
@PutMapping("item")
@PreAuthorize("@per.hasPermission('sys:dict:edit')")
public R updateItemById(@RequestBody SysDictItem sysDictItem) {
return sysDictManager.updateDictItemById(sysDictItem) ?
R.ok() : R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "修改字典项失败");
}
/**
* 通过id删除字典项
*
* @param id id
* @return R
*/
@ApiOperation(value = "通过id删除字典项", notes = "通过id删除字典项")
@DeleteOperationLogging(msg = "通过id删除字典项")
@DeleteMapping("/item/{id}")
@PreAuthorize("@per.hasPermission('sys:dict:del')")
public R removeItemById(@PathVariable Integer id) {
return sysDictManager.removeDictItemById(id) ?
R.ok() : R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "通过id删除字典项失败");
}
} }

View File

@@ -29,101 +29,92 @@ import java.util.stream.Collectors;
* @date 2019/09/17 * @date 2019/09/17
*/ */
@RestController @RestController
@RequestMapping("/syspermission" ) @RequestMapping("/syspermission")
@Api(value = "syspermission", tags = "权限管理模块" ) @Api(value = "syspermission", tags = "权限管理模块")
@RequiredArgsConstructor @RequiredArgsConstructor
public class SysPermissionController { public class SysPermissionController {
private final SysPermissionService sysPermissionService;
/** private final SysPermissionService sysPermissionService;
* 返回当前用户的路由集合
*
* @return 当前用户的路由
*/
@ApiOperation(value = "动态路由", notes = "动态路由" )
@GetMapping("/router")
public R<List<Router>> getUserPermission() {
//获取角色ID /**
SysUserDetails sysUserDetails = SecurityUtils.getSysUserDetails(); * 返回当前用户的路由集合
List<Integer> roleIds = sysUserDetails.getRoleIds(); * @return 当前用户的路由
if (CollectionUtil.isEmpty(roleIds)) { */
return R.ok(new ArrayList<>()); @ApiOperation(value = "动态路由", notes = "动态路由")
} @GetMapping("/router")
public R<List<Router>> getUserPermission() {
// 获取符合条件的权限 // 获取角色ID
Set<PermissionVO> all = new HashSet<>(); SysUserDetails sysUserDetails = SecurityUtils.getSysUserDetails();
roleIds.forEach(roleId -> all.addAll(sysPermissionService.findPermissionVOByRoleId(roleId))); List<Integer> roleIds = sysUserDetails.getRoleIds();
if (CollectionUtil.isEmpty(roleIds)) {
return R.ok(new ArrayList<>());
}
// 筛选出菜单 // 获取符合条件的权限
List<Router> routerList = all.stream() Set<PermissionVO> all = new HashSet<>();
.filter(menuVo -> SysPermissionConst.Type.MENU.getValue() == menuVo.getType() || SysPermissionConst.Type.DIRECTORY.getValue() == menuVo.getType()) roleIds.forEach(roleId -> all.addAll(sysPermissionService.findPermissionVOByRoleId(roleId)));
.sorted(Comparator.comparingInt(PermissionVO::getSort))
.map(SysPermissionConverter.INSTANCE::toRouter)
.collect(Collectors.toList());
return R.ok(routerList); // 筛选出菜单
} List<Router> routerList = all.stream()
.filter(menuVo -> SysPermissionConst.Type.MENU.getValue() == menuVo.getType()
|| SysPermissionConst.Type.DIRECTORY.getValue() == menuVo.getType())
.sorted(Comparator.comparingInt(PermissionVO::getSort)).map(SysPermissionConverter.INSTANCE::toRouter)
.collect(Collectors.toList());
return R.ok(routerList);
}
/** /**
* 所有的权限集合 * 所有的权限集合
* * @return
* @return */
*/ @GetMapping(value = "/list")
@GetMapping(value = "/list" ) @PreAuthorize("@per.hasPermission('sys:syspermission:read')")
@PreAuthorize("@per.hasPermission('sys:syspermission:read')") public R<List<SysPermission>> getTree() {
public R<List<SysPermission>> getTree() { List<SysPermission> list = sysPermissionService
List<SysPermission> list = sysPermissionService .list(Wrappers.<SysPermission>lambdaQuery().orderByAsc(SysPermission::getSort));
.list(Wrappers.<SysPermission>lambdaQuery() return R.ok(list);
.orderByAsc(SysPermission::getSort)); }
return R.ok(list);
}
/**
* 通过ID查询权限的详细信息
* @param id 权限ID
* @return 权限详细信息
*/
@GetMapping("/{id}")
@PreAuthorize("@per.hasPermission('sys:syspermission:read')")
public R getById(@PathVariable Integer id) {
return R.ok(sysPermissionService.getById(id));
}
/** @ApiOperation(value = "新增权限", notes = "新增权限")
* 通过ID查询权限的详细信息 @CreateOperationLogging(msg = "新增权限")
* @PostMapping
* @param id 权限ID @PreAuthorize("@per.hasPermission('sys:syspermission:add')")
* @return 权限详细信息 public R save(@Valid @RequestBody SysPermission sysMenu) {
*/ return R.ok(sysPermissionService.save(sysMenu));
@GetMapping("/{id}" ) }
@PreAuthorize("@per.hasPermission('sys:syspermission:read')")
public R getById(@PathVariable Integer id) {
return R.ok(sysPermissionService.getById(id));
}
/**
* 更新权限
* @param sysPermission
* @return R
*/
@ApiOperation(value = "修改权限", notes = "修改权限")
@UpdateOperationLogging(msg = "修改权限")
@PutMapping
@PreAuthorize("@per.hasPermission('sys:syspermission:edit')")
public R update(@Valid @RequestBody SysPermission sysPermission) {
return R.ok(sysPermissionService.updatePermissionById(sysPermission));
}
@ApiOperation(value = "新增权限", notes = "新增权限" ) @ApiOperation(value = "通过id删除权限", notes = "通过id删除权限")
@CreateOperationLogging(msg = "新增权限" ) @DeleteOperationLogging(msg = "通过id删除权限")
@PostMapping @DeleteMapping("/{id}")
@PreAuthorize("@per.hasPermission('sys:syspermission:add')") @PreAuthorize("@per.hasPermission('sys:syspermission:del')")
public R save(@Valid @RequestBody SysPermission sysMenu) { public R removeById(@PathVariable Integer id) {
return R.ok(sysPermissionService.save(sysMenu)); return R.ok(sysPermissionService.removePermissionById(id));
} }
/**
* 更新权限
*
* @param sysPermission
* @return R
*/
@ApiOperation(value = "修改权限", notes = "修改权限" )
@UpdateOperationLogging(msg = "修改权限" )
@PutMapping
@PreAuthorize("@per.hasPermission('sys:syspermission:edit')" )
public R update(@Valid @RequestBody SysPermission sysPermission) {
return R.ok(sysPermissionService.updatePermissionById(sysPermission));
}
@ApiOperation(value = "通过id删除权限", notes = "通过id删除权限" )
@DeleteOperationLogging(msg = "通过id删除权限" )
@DeleteMapping("/{id}" )
@PreAuthorize("@per.hasPermission('sys:syspermission:del')" )
public R removeById(@PathVariable Integer id) {
return R.ok(sysPermissionService.removePermissionById(id));
}
} }

View File

@@ -32,125 +32,115 @@ import java.util.stream.Collectors;
@Api(value = "sysrole", tags = "角色管理模块") @Api(value = "sysrole", tags = "角色管理模块")
@RequiredArgsConstructor @RequiredArgsConstructor
public class SysRoleController { public class SysRoleController {
private final SysRoleService sysRoleService;
private final SysRolePermissionService sysRolePermissionService;
private final SysPermissionService sysPermissionService;
/** private final SysRoleService sysRoleService;
* 分页查询角色信息
*
* @param page 分页对象
* @return 分页对象
*/
@GetMapping("/page")
@PreAuthorize("@per.hasPermission('sys:sysrole:read')")
public R<IPage<SysRole>> getRolePage(Page<SysRole> page, SysRoleQO sysRoleQO) {
return R.ok(sysRoleService.page(page, sysRoleQO));
}
/** private final SysRolePermissionService sysRolePermissionService;
* 通过ID查询角色信息
*
* @param id ID
* @return 角色信息
*/
@GetMapping("/{id}")
@PreAuthorize("@per.hasPermission('sys:sysrole:read')")
public R getById(@PathVariable Integer id) {
return R.ok(sysRoleService.getById(id));
}
/** private final SysPermissionService sysPermissionService;
* 新增系统角色表
*
* @param sysRole 系统角色表
* @return R
*/
@ApiOperation(value = "新增系统角色", notes = "新增系统角色")
@CreateOperationLogging(msg = "新增系统角色")
@PostMapping
@PreAuthorize("@per.hasPermission('sys:sysrole:add')")
public R save(@Valid @RequestBody SysRole sysRole) {
return R.ok(sysRoleService.save(sysRole));
}
/** /**
* 修改角色 * 分页查询角色信息
* * @param page 分页对象
* @param role 角色信息 * @return 分页对象
* @return success/false */
*/ @GetMapping("/page")
@ApiOperation(value = "修改系统角色", notes = "修改系统角色") @PreAuthorize("@per.hasPermission('sys:sysrole:read')")
@UpdateOperationLogging(msg = "修改系统角色") public R<IPage<SysRole>> getRolePage(Page<SysRole> page, SysRoleQO sysRoleQO) {
@PutMapping return R.ok(sysRoleService.page(page, sysRoleQO));
@PreAuthorize("@per.hasPermission('sys:sysrole:edit')") }
public R update(@Valid @RequestBody SysRole role) {
return R.ok(sysRoleService.updateById(role));
}
/** /**
* 删除角色 * 通过ID查询角色信息
* * @param id ID
* @param id * @return 角色信息
* @return */
*/ @GetMapping("/{id}")
@DeleteMapping("/{id}") @PreAuthorize("@per.hasPermission('sys:sysrole:read')")
@ApiOperation(value = "通过id删除系统角色", notes = "通过id删除系统角色") public R getById(@PathVariable Integer id) {
@DeleteOperationLogging(msg = "通过id删除系统角色") return R.ok(sysRoleService.getById(id));
@PreAuthorize("@per.hasPermission('sys:sysrole:del')") }
public R removeById(@PathVariable Integer id) {
return R.ok(sysRoleService.removeRoleById(id));
}
/** /**
* 获取角色 * 新增系统角色表
* * @param sysRole 系统角色表
* @return 角色列表 * @return R
*/ */
@GetMapping("/list") @ApiOperation(value = "新增系统角色", notes = "新增系统角色")
public R listRoles() { @CreateOperationLogging(msg = "新增系统角色")
return R.ok(sysRoleService.list(Wrappers.emptyWrapper())); @PostMapping
} @PreAuthorize("@per.hasPermission('sys:sysrole:add')")
public R save(@Valid @RequestBody SysRole sysRole) {
return R.ok(sysRoleService.save(sysRole));
}
/**
* 修改角色
* @param role 角色信息
* @return success/false
*/
@ApiOperation(value = "修改系统角色", notes = "修改系统角色")
@UpdateOperationLogging(msg = "修改系统角色")
@PutMapping
@PreAuthorize("@per.hasPermission('sys:sysrole:edit')")
public R update(@Valid @RequestBody SysRole role) {
return R.ok(sysRoleService.updateById(role));
}
/** /**
* 更新角色权限 * 删除角色
* * @param id
* @param roleId 角色ID * @return
* @param permissionIds 权限ID数组 */
* @return success、false @DeleteMapping("/{id}")
*/ @ApiOperation(value = "通过id删除系统角色", notes = "通过id删除系统角色")
@PutMapping("/permission/ids/{roleId}") @DeleteOperationLogging(msg = "通过id删除系统角色")
@ApiOperation(value = "更新角色权限", notes = "更新角色权限") @PreAuthorize("@per.hasPermission('sys:sysrole:del')")
@UpdateOperationLogging(msg = "更新角色权限") public R removeById(@PathVariable Integer id) {
@PreAuthorize("@per.hasPermission('sys:sysrole:grant')") return R.ok(sysRoleService.removeRoleById(id));
public R savePermissionIds(@PathVariable Integer roleId, @RequestBody Integer[] permissionIds) { }
return R.ok(sysRolePermissionService.saveRolePermissions(roleId, permissionIds));
}
/**
* 获取角色列表
* @return 角色列表
*/
@GetMapping("/list")
public R listRoles() {
return R.ok(sysRoleService.list(Wrappers.emptyWrapper()));
}
/** /**
* 返回角色的菜单集合 * 更新角色权限
* * @param roleId 角色ID
* @param roleId 角色ID * @param permissionIds 权限ID数组
* @return 属性集合 * @return success、false
*/ */
@GetMapping("/permission/ids/{roleId}") @PutMapping("/permission/ids/{roleId}")
public R getPermissionIds(@PathVariable Integer roleId) { @ApiOperation(value = "更新角色权限", notes = "更新角色权限")
return R.ok(sysPermissionService.findPermissionVOByRoleId(roleId) @UpdateOperationLogging(msg = "更新角色权限")
.stream() @PreAuthorize("@per.hasPermission('sys:sysrole:grant')")
.map(PermissionVO::getId) public R savePermissionIds(@PathVariable Integer roleId, @RequestBody Integer[] permissionIds) {
.collect(Collectors.toList())); return R.ok(sysRolePermissionService.saveRolePermissions(roleId, permissionIds));
} }
/**
* 返回角色的菜单集合
* @param roleId 角色ID
* @return 属性集合
*/
@GetMapping("/permission/ids/{roleId}")
public R getPermissionIds(@PathVariable Integer roleId) {
return R.ok(sysPermissionService.findPermissionVOByRoleId(roleId).stream().map(PermissionVO::getId)
.collect(Collectors.toList()));
}
/**
* 获取角色列表
* @return 角色列表
*/
@GetMapping("/select")
public R<List<SelectData>> getSelectData() {
return R.ok(sysRoleService.getSelectData());
}
/**
* 获取角色列表
*
* @return 角色列表
*/
@GetMapping("/select")
public R<List<SelectData>> getSelectData() {
return R.ok(sysRoleService.getSelectData());
}
} }

View File

@@ -45,197 +45,180 @@ import java.util.List;
@Api(value = "sysuser", tags = "用户管理模块") @Api(value = "sysuser", tags = "用户管理模块")
@RequiredArgsConstructor @RequiredArgsConstructor
public class SysUserController { public class SysUserController {
private final SysUserService sysUserService;
private final SysUserRoleService sysUserRoleService;
/** private final SysUserService sysUserService;
* 分页查询用户
*
* @param page 参数集
* @return 用户集合
*/
@GetMapping("/page")
@PreAuthorize("@per.hasPermission('sys:sysuser:read')")
public R<IPage<SysUser>> getUserPage(
Page<SysUser> page, SysUserQO qo) {
return R.ok(sysUserService.page(page, qo));
}
/** private final SysUserRoleService sysUserRoleService;
* 获取用户Select
*
* @return 用户SelectData
*/
@GetMapping("/select")
@PreAuthorize("@per.hasPermission('sys:sysuser:read')")
public R<List<SelectData>> getSelectData() {
return R.ok(sysUserService.getSelectData(null));
}
/**
* 分页查询用户
* @param page 参数集
* @return 用户集合
*/
@GetMapping("/page")
@PreAuthorize("@per.hasPermission('sys:sysuser:read')")
public R<IPage<SysUser>> getUserPage(Page<SysUser> page, SysUserQO qo) {
return R.ok(sysUserService.page(page, qo));
}
/** /**
* 获取用户Select * 获取用户Select
* * @return 用户SelectData
* @return 用户SelectData */
*/ @GetMapping("/select")
@GetMapping("/select/{userType}") @PreAuthorize("@per.hasPermission('sys:sysuser:read')")
@PreAuthorize("@per.hasPermission('sys:sysuser:read')") public R<List<SelectData>> getSelectData() {
public R<List<SelectData>> getSysSelectData(@PathVariable Integer userType) { return R.ok(sysUserService.getSelectData(null));
return R.ok(sysUserService.getSelectData(userType)); }
}
/** /**
* 新增用户 * 获取用户Select
* * @return 用户SelectData
* @param sysUserDto userInfo */
* @return success/false @GetMapping("/select/{userType}")
*/ @PreAuthorize("@per.hasPermission('sys:sysuser:read')")
@PostMapping public R<List<SelectData>> getSysSelectData(@PathVariable Integer userType) {
@ApiOperation(value = "新增系统用户", notes = "新增系统用户") return R.ok(sysUserService.getSelectData(userType));
@CreateOperationLogging(msg = "新增系统用户") }
@PreAuthorize("@per.hasPermission('sys:sysuser:add')")
public R addSysUser(@Valid @RequestBody SysUserDTO sysUserDto) {
SysUser user = sysUserService.getByUsername(sysUserDto.getUsername()); /**
if (user != null) { * 新增用户
return R.failed(BaseResultCode.LOGIC_CHECK_ERROR, "用户名已存在"); * @param sysUserDto userInfo
} * @return success/false
return sysUserService.addSysUser(sysUserDto) ? */
R.ok() : R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "新增系统用户失败"); @PostMapping
} @ApiOperation(value = "新增系统用户", notes = "新增系统用户")
@CreateOperationLogging(msg = "新增系统用户")
@PreAuthorize("@per.hasPermission('sys:sysuser:add')")
public R addSysUser(@Valid @RequestBody SysUserDTO sysUserDto) {
SysUser user = sysUserService.getByUsername(sysUserDto.getUsername());
if (user != null) {
return R.failed(BaseResultCode.LOGIC_CHECK_ERROR, "用户名已存在");
}
return sysUserService.addSysUser(sysUserDto) ? R.ok()
: R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "新增系统用户失败");
}
/** /**
* 修改用户个人信息 * 修改用户个人信息
* * @param sysUserDto userInfo
* @param sysUserDto userInfo * @return success/false
* @return success/false */
*/ @PutMapping
@PutMapping @ApiOperation(value = "修改系统用户", notes = "修改系统用户")
@ApiOperation(value = "修改系统用户", notes = "修改系统用户") @UpdateOperationLogging(msg = "修改系统用户")
@UpdateOperationLogging(msg = "修改系统用户") @PreAuthorize("@per.hasPermission('sys:sysuser:edit')")
@PreAuthorize("@per.hasPermission('sys:sysuser:edit')") public R updateUserInfo(@Valid @RequestBody SysUserDTO sysUserDto) {
public R updateUserInfo(@Valid @RequestBody SysUserDTO sysUserDto) { return sysUserService.updateSysUser(sysUserDto) ? R.ok()
return sysUserService.updateSysUser(sysUserDto) ? : R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "修改系统用户失败");
R.ok() : R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "修改系统用户失败"); }
}
/**
* 删除用户信息
* @param userId
* @return
*/
@DeleteMapping("/{userId}")
@ApiOperation(value = "通过id删除系统用户", notes = "通过id删除系统用户")
@DeleteOperationLogging(msg = "通过id删除系统用户")
@PreAuthorize("@per.hasPermission('sys:sysuser:del')")
public R deleteByUserId(@PathVariable Integer userId) {
return sysUserService.deleteByUserId(userId) ? R.ok()
: R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "删除系统用户失败");
}
/** /**
* 删除用户信息 * 获取用户 所拥有的角色ID
* * @param userId userId
* @param userId */
* @return @GetMapping("/scope/{userId}")
*/ @PreAuthorize("@per.hasPermission('sys:sysuser:grant')")
@DeleteMapping("/{userId}") public R<SysUserScope> getUserRoleIds(@PathVariable Integer userId) {
@ApiOperation(value = "通过id删除系统用户", notes = "通过id删除系统用户")
@DeleteOperationLogging(msg = "通过id删除系统用户")
@PreAuthorize("@per.hasPermission('sys:sysuser:del')")
public R deleteByUserId(@PathVariable Integer userId) {
return sysUserService.deleteByUserId(userId) ?
R.ok() : R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "删除系统用户失败");
}
List<SysRole> roleList = sysUserRoleService.getRoles(userId);
/** List<Integer> roleIds = new ArrayList<>();
* 获取用户 所拥有的角色ID if (CollectionUtil.isNotEmpty(roleList)) {
* for (SysRole role : roleList) {
* @param userId userId roleIds.add(role.getId());
*/ }
@GetMapping("/scope/{userId}") }
@PreAuthorize("@per.hasPermission('sys:sysuser:grant')")
public R<SysUserScope> getUserRoleIds(@PathVariable Integer userId) {
List<SysRole> roleList = sysUserRoleService.getRoles(userId); SysUserScope sysUserScope = new SysUserScope();
sysUserScope.setRoleIds(roleIds);
List<Integer> roleIds = new ArrayList<>(); return R.ok(sysUserScope);
if (CollectionUtil.isNotEmpty(roleList)) { }
for (SysRole role : roleList) {
roleIds.add(role.getId());
}
}
SysUserScope sysUserScope = new SysUserScope(); /**
sysUserScope.setRoleIds(roleIds); * 修改用户权限信息 比如角色 数据权限等
* @param sysUserScope sysUserScope
* @return success/false
*/
@PutMapping("/scope/{userId}")
@ApiOperation(value = "系统用户授权", notes = "系统用户授权")
@UpdateOperationLogging(msg = "系统用户授权")
@PreAuthorize("@per.hasPermission('sys:sysuser:grant')")
public R updateUserScope(@PathVariable Integer userId, @RequestBody SysUserScope sysUserScope) {
return sysUserService.updateUserScope(userId, sysUserScope) ? R.ok()
: R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "系统用户授权失败");
}
return R.ok(sysUserScope); /**
} * 修改用户密码
* @param userId
* @param pass
* @param confirm
* @return
*/
@PutMapping("/pass/{userId}")
@ApiOperation(value = "修改系统用户密码", notes = "修改系统用户密码")
@UpdateOperationLogging(msg = "修改系统用户密码")
@PreAuthorize("@per.hasPermission('sys:sysuser:pass')")
public R updateUserPass(@PathVariable Integer userId, String pass, String confirm) {
if (StrUtil.isBlank(pass) || StrUtil.isBlank(confirm) || !pass.equals(confirm)) {
return R.failed(SystemResultCode.BAD_REQUEST, "错误的密码!");
}
return sysUserService.updateUserPass(userId, pass) ? R.ok()
: R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "修改用户密码失败!");
}
/** /**
* 修改用户权限信息 * 批量修改用户状态
* 比如角色 * @param userIds
* 数据权限等 * @return
* */
* @param sysUserScope sysUserScope @PutMapping("/status")
* @return success/false @ApiOperation(value = "批量修改用户状态", notes = "批量修改用户状态")
*/ @UpdateOperationLogging(msg = "批量修改用户状态")
@PutMapping("/scope/{userId}") @PreAuthorize("@per.hasPermission('sys:sysuser:edit')")
@ApiOperation(value = "系统用户授权", notes = "系统用户授权") public R updateUserStatus(@NotEmpty(message = "用户ID不能为空") @RequestBody List<Integer> userIds,
@UpdateOperationLogging(msg = "系统用户授权") @NotNull(message = "用户状态不能为空") @RequestParam Integer status) {
@PreAuthorize("@per.hasPermission('sys:sysuser:grant')")
public R updateUserScope(@PathVariable Integer userId, @RequestBody SysUserScope sysUserScope) {
return sysUserService.updateUserScope(userId, sysUserScope) ?
R.ok() : R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "系统用户授权失败");
}
if (!SysUserConst.Status.NORMAL.getValue().equals(status)
&& !SysUserConst.Status.LOCKED.getValue().equals(status)) {
throw new ValidationException("不支持的用户状态!");
}
return sysUserService.updateUserStatus(userIds, status) ? R.ok()
: R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "批量修改用户状态!");
}
/** @ApiOperation(value = "修改系统用户头像", notes = "修改系统用户头像")
* 修改用户密码 @UpdateOperationLogging(msg = "修改系统用户头像")
* @PreAuthorize("@per.hasPermission('sys:sysuser:edit')")
* @param userId @PostMapping("/avatar")
* @param pass public R<String> updateAvatar(@RequestParam("file") MultipartFile file, @RequestParam("userId") Integer userId) {
* @param confirm String objectName;
* @return try {
*/ objectName = sysUserService.updateAvatar(file, userId);
@PutMapping("/pass/{userId}") }
@ApiOperation(value = "修改系统用户密码", notes = "修改系统用户密码") catch (IOException e) {
@UpdateOperationLogging(msg = "修改系统用户密码") log.error("修改系统用户头像异常", e);
@PreAuthorize("@per.hasPermission('sys:sysuser:pass')") return R.failed(BaseResultCode.FILE_UPLOAD_ERROR);
public R updateUserPass(@PathVariable Integer userId, String pass, String confirm) { }
if (StrUtil.isBlank(pass) || StrUtil.isBlank(confirm) || !pass.equals(confirm)) { return R.ok(objectName);
return R.failed(SystemResultCode.BAD_REQUEST, "错误的密码!"); }
}
return sysUserService.updateUserPass(userId, pass) ?
R.ok() : R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "修改用户密码失败!");
}
/**
* 批量修改用户状态
*
* @param userIds
* @return
*/
@PutMapping("/status")
@ApiOperation(value = "批量修改用户状态", notes = "批量修改用户状态")
@UpdateOperationLogging(msg = "批量修改用户状态")
@PreAuthorize("@per.hasPermission('sys:sysuser:edit')")
public R updateUserStatus(@NotEmpty(message = "用户ID不能为空") @RequestBody List<Integer> userIds,
@NotNull(message = "用户状态不能为空") @RequestParam Integer status) {
if (!SysUserConst.Status.NORMAL.getValue().equals(status) && !SysUserConst.Status.LOCKED.getValue().equals(status)) {
throw new ValidationException("不支持的用户状态!");
}
return sysUserService.updateUserStatus(userIds, status) ?
R.ok() : R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "批量修改用户状态!");
}
@ApiOperation(value = "修改系统用户头像", notes = "修改系统用户头像")
@UpdateOperationLogging(msg = "修改系统用户头像")
@PreAuthorize("@per.hasPermission('sys:sysuser:edit')")
@PostMapping("/avatar")
public R<String> updateAvatar(@RequestParam("file") MultipartFile file, @RequestParam("userId") Integer userId) {
String objectName;
try {
objectName = sysUserService.updateAvatar(file, userId);
} catch (IOException e) {
log.error("修改系统用户头像异常", e);
return R.failed(BaseResultCode.FILE_UPLOAD_ERROR);
}
return R.ok(objectName);
}
} }

View File

@@ -33,183 +33,161 @@ import java.util.stream.Collectors;
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
public class SysDictManager { public class SysDictManager {
private final SysDictService sysDictService;
private final SysDictItemService sysDictItemService;
private final SysDictService sysDictService;
/** private final SysDictItemService sysDictItemService;
* 字典表分页
*
* @param page 分页参数
* @param sysDictQO 查询参数
* @return 字典表分页数据
*/
public IPage<SysDict> dictPage(Page<SysDict> page, SysDictQO sysDictQO) {
return sysDictService.page(page, sysDictQO);
}
/** /**
* 保存字典 * 字典表分页
* * @param page 分页参数
* @param sysDict 字典对象 * @param sysDictQO 查询参数
* @return 执行是否成功 * @return 字典表分页数据
*/ */
public boolean dictSave(SysDict sysDict) { public IPage<SysDict> dictPage(Page<SysDict> page, SysDictQO sysDictQO) {
sysDict.setHashCode(IdUtil.fastSimpleUUID()); return sysDictService.page(page, sysDictQO);
sysDict.setDeleted(GlobalConstants.NOT_DELETED_FLAG); }
return sysDictService.save(sysDict);
}
/** /**
* 更新字典 * 保存字典
* * @param sysDict 字典对象
* @param sysDict 字典对象 * @return 执行是否成功
* @return 执行是否成功 */
*/ public boolean dictSave(SysDict sysDict) {
public boolean updateDictById(SysDict sysDict) { sysDict.setHashCode(IdUtil.fastSimpleUUID());
// 查询现有数据 sysDict.setDeleted(GlobalConstants.NOT_DELETED_FLAG);
SysDict dict = sysDictService.getById(sysDict.getId()); return sysDictService.save(sysDict);
if (BooleanEnum.TRUE.getValue() != dict.getEditable()) { }
throw new BusinessException(
BaseResultCode.LOGIC_CHECK_ERROR.getCode(), "该字典项目不能修改"
);
}
sysDict.setHashCode(IdUtil.fastSimpleUUID());
return sysDictService.updateById(sysDict);
}
/** /**
* 删除字典 * 更新字典
* * @param sysDict 字典对象
* @param id 字典id * @return 执行是否成功
* @return 执行是否成功 */
*/ public boolean updateDictById(SysDict sysDict) {
@Transactional(rollbackFor = Exception.class) // 查询现有数据
public boolean removeDictById(Integer id) { SysDict dict = sysDictService.getById(sysDict.getId());
// 查询现有数据 if (BooleanEnum.TRUE.getValue() != dict.getEditable()) {
SysDict dict = sysDictService.getById(id); throw new BusinessException(BaseResultCode.LOGIC_CHECK_ERROR.getCode(), "该字典项目不能修改");
if (BooleanEnum.TRUE.getValue() != dict.getEditable()) { }
throw new BusinessException( sysDict.setHashCode(IdUtil.fastSimpleUUID());
BaseResultCode.LOGIC_CHECK_ERROR.getCode(), "该字典项目不能删除" return sysDictService.updateById(sysDict);
); }
}
// 需级联删除对应的字典项
if (sysDictService.removeById(id)) {
sysDictItemService.remove(Wrappers.<SysDictItem>lambdaUpdate()
.eq(SysDictItem::getDictCode, dict.getCode())
);
return true;
}
return false;
}
/** /**
* 字典项分页 * 删除字典
* * @param id 字典id
* @param page 分页属性 * @return 执行是否成功
* @param dictCode 字典标识 */
* @return 字典项分页数据 @Transactional(rollbackFor = Exception.class)
*/ public boolean removeDictById(Integer id) {
public IPage<SysDictItem> dictItemPage(Page<SysDictItem> page, String dictCode) { // 查询现有数据
return sysDictItemService.page(page, dictCode); SysDict dict = sysDictService.getById(id);
} if (BooleanEnum.TRUE.getValue() != dict.getEditable()) {
throw new BusinessException(BaseResultCode.LOGIC_CHECK_ERROR.getCode(), "该字典项目不能删除");
}
// 需级联删除对应的字典项
if (sysDictService.removeById(id)) {
sysDictItemService
.remove(Wrappers.<SysDictItem>lambdaUpdate().eq(SysDictItem::getDictCode, dict.getCode()));
return true;
}
return false;
}
/** /**
* 新增字典项 * 字典项分页
* * @param page 分页属性
* @param sysDictItem 字典 * @param dictCode 字典标识
* @return 执行是否成功 * @return 字典项分页数据
*/ */
public boolean saveDictItem(SysDictItem sysDictItem) { public IPage<SysDictItem> dictItemPage(Page<SysDictItem> page, String dictCode) {
// 更新字典项Hash值 return sysDictItemService.page(page, dictCode);
if (!sysDictService.updateHashCode(sysDictItem.getDictCode())) { }
return false;
}
sysDictItem.setDeleted(GlobalConstants.NOT_DELETED_FLAG);
return sysDictItemService.save(sysDictItem);
}
/**
* 新增字典项
* @param sysDictItem 字典项
* @return 执行是否成功
*/
public boolean saveDictItem(SysDictItem sysDictItem) {
// 更新字典项Hash值
if (!sysDictService.updateHashCode(sysDictItem.getDictCode())) {
return false;
}
sysDictItem.setDeleted(GlobalConstants.NOT_DELETED_FLAG);
return sysDictItemService.save(sysDictItem);
}
/** /**
* 更新字典项 * 更新字典项
* * @param sysDictItem 字典项
* @param sysDictItem 字典项 * @return 执行是否成功
* @return 执行是否成功 */
*/ public boolean updateDictItemById(SysDictItem sysDictItem) {
public boolean updateDictItemById(SysDictItem sysDictItem) { // 根据ID查询字典
// 根据ID查询字典 SysDict dict = sysDictService.getByCode(sysDictItem.getDictCode());
SysDict dict = sysDictService.getByCode(sysDictItem.getDictCode()); // 校验是否可编辑
// 校验是否可编辑 if (BooleanEnum.TRUE.getValue() != dict.getEditable()) {
if (BooleanEnum.TRUE.getValue() != dict.getEditable()) { throw new BusinessException(BaseResultCode.LOGIC_CHECK_ERROR.getCode(), "该字典项目不能修改");
throw new BusinessException( }
BaseResultCode.LOGIC_CHECK_ERROR.getCode(), "该字典项目不能修改" // 更新字典项Hash值
); if (!sysDictService.updateHashCode(sysDictItem.getDictCode())) {
} return false;
// 更新字典项Hash值 }
if (!sysDictService.updateHashCode(sysDictItem.getDictCode())) { return sysDictItemService.updateById(sysDictItem);
return false;
}
return sysDictItemService.updateById(sysDictItem);
} }
/**
* 删除字典项
* @param id 字典项
* @return 执行是否成功
*/
public boolean removeDictItemById(Integer id) {
// 根据ID查询字典
SysDictItem dictItem = sysDictItemService.getById(id);
SysDict dict = sysDictService.getByCode(dictItem.getDictCode());
// 校验是否系统内置
if (BooleanEnum.TRUE.getValue() != dict.getEditable()) {
throw new BusinessException(BaseResultCode.LOGIC_CHECK_ERROR.getCode(), "该字典项目不能删除");
}
return sysDictItemService.removeById(id);
}
/** /**
* 删除字典项 * 查询字典数据
* * @param dictCode
* @param id 字典项 * @return
* @return 执行是否成功 */
*/ public DictDataAndHashVO queryDictDataAndHashVO(String dictCode) {
public boolean removeDictItemById(Integer id) { // 查询对应hash值以及字典项数据
// 根据ID查询字典 SysDict sysDict = sysDictService.getByCode(dictCode);
SysDictItem dictItem = sysDictItemService.getById(id); if (sysDict == null) {
SysDict dict = sysDictService.getByCode(dictItem.getDictCode()); return null;
// 校验是否系统内置 }
if (BooleanEnum.TRUE.getValue() != dict.getEditable()) { List<SysDictItem> dictItems = sysDictItemService.getByDictCode(dictCode);
throw new BusinessException( // 排序并转换为VO
BaseResultCode.LOGIC_CHECK_ERROR.getCode(), "该字典项目不能删除" List<DictItemVO> dictList = dictItems.stream().sorted(Comparator.comparingInt(SysDictItem::getSort))
); .map(SysDictConverter.INSTANCE::itemPoToVo).collect(Collectors.toList());
}
return sysDictItemService.removeById(id);
}
/** // 组装DataVO
* 查询字典数据 DictDataAndHashVO dictDataAndHashVO = new DictDataAndHashVO();
* dictDataAndHashVO.setHashCode(sysDict.getHashCode());
* @param dictCode dictDataAndHashVO.setDictList(dictList);
* @return return dictDataAndHashVO;
*/ }
public DictDataAndHashVO queryDictDataAndHashVO(String dictCode) {
// 查询对应hash值以及字典项数据
SysDict sysDict = sysDictService.getByCode(dictCode);
if (sysDict == null) {
return null;
}
List<SysDictItem> dictItems = sysDictItemService.getByDictCode(dictCode);
// 排序并转换为VO
List<DictItemVO> dictList = dictItems.stream()
.sorted(Comparator.comparingInt(SysDictItem::getSort))
.map(SysDictConverter.INSTANCE::itemPoToVo)
.collect(Collectors.toList());
// 组装DataVO /**
DictDataAndHashVO dictDataAndHashVO = new DictDataAndHashVO(); * 返回失效的Hash
dictDataAndHashVO.setHashCode(sysDict.getHashCode()); * @param dictHashCode 校验的hashCodeMap
dictDataAndHashVO.setDictList(dictList); * @return
return dictDataAndHashVO; */
} public List<String> invalidDictHash(Map<String, String> dictHashCode) {
List<SysDict> byCode = sysDictService.getByCode(dictHashCode.keySet().toArray(new String[] {}));
// 过滤相等Hash值的字典项并返回需要修改的字典项的Code
return byCode.stream().filter(x -> !dictHashCode.get(x.getCode()).equals(x.getHashCode())).map(SysDict::getCode)
.collect(Collectors.toList());
}
/**
* 返回失效的Hash
*
* @param dictHashCode 校验的hashCodeMap
* @return
*/
public List<String> invalidDictHash(Map<String, String> dictHashCode) {
List<SysDict> byCode = sysDictService.getByCode(dictHashCode.keySet().toArray(new String[]{}));
// 过滤相等Hash值的字典项并返回需要修改的字典项的Code
return byCode.stream()
.filter(x -> !dictHashCode.get(x.getCode()).equals(x.getHashCode()))
.map(SysDict::getCode).collect(Collectors.toList());
}
} }

View File

@@ -15,11 +15,11 @@ import java.util.List;
*/ */
public interface SysDictItemMapper extends BaseMapper<SysDictItem> { public interface SysDictItemMapper extends BaseMapper<SysDictItem> {
/** /**
* 根据字典标识查询对应字典选择项 * 根据字典标识查询对应字典选择项
* * @param dictCode 字典标识
* @param dictCode 字典标识 * @return 对应字典项的SelectData
* @return 对应字典项的SelectData */
*/ List<SelectData> querySelectDataByDictCode(@Param("dictCode") String dictCode);
List<SelectData> querySelectDataByDictCode(@Param("dictCode") String dictCode);
} }

View File

@@ -8,13 +8,13 @@ import java.util.List;
/** /**
* 菜单权限表 Mapper 接口 * 菜单权限表 Mapper 接口
*
* @author * @author
*/ */
public interface SysPermissionMapper extends BaseMapper<SysPermission> { public interface SysPermissionMapper extends BaseMapper<SysPermission> {
/** /**
* 通过角色ID查询权限 * 通过角色ID查询权限
*
* @param roleId 角色ID * @param roleId 角色ID
* @return * @return
*/ */
@@ -22,9 +22,9 @@ public interface SysPermissionMapper extends BaseMapper<SysPermission> {
/** /**
* 通过角色ID查询权限 * 通过角色ID查询权限
*
* @param roleIds Ids * @param roleIds Ids
* @return * @return
*/ */
List<String> listPermissionsByRoleIds(String roleIds); List<String> listPermissionsByRoleIds(String roleIds);
} }

View File

@@ -20,7 +20,6 @@ public interface SysRoleMapper extends BaseMapper<SysRole> {
* 获取角色下拉框数据 * 获取角色下拉框数据
* @return * @return
*/ */
List<SelectData> getSelectData(); List<SelectData> getSelectData();
} }

View File

@@ -1,6 +1,5 @@
package com.hccake.ballcat.admin.modules.sys.mapper; package com.hccake.ballcat.admin.modules.sys.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.hccake.ballcat.admin.modules.sys.model.entity.SysRolePermission; import com.hccake.ballcat.admin.modules.sys.model.entity.SysRolePermission;

View File

@@ -9,25 +9,22 @@ import java.util.List;
/** /**
* 系统用户表 * 系统用户表
*
* @author Hccake * @author Hccake
*/ */
public interface SysUserMapper extends BaseMapper<SysUser> { public interface SysUserMapper extends BaseMapper<SysUser> {
/** /**
* 根据RoleCode 查询对应用户 * 根据RoleCode 查询对应用户
* @param roleCode * @param roleCode
* @return * @return
*/ */
List<SysUser> selectUsersByRoleCode(String roleCode); List<SysUser> selectUsersByRoleCode(String roleCode);
/**
* 返回用户的select数据
* name=> username
* value => userId
*
* @return List<SelectData>
*/
List<SelectData> getSelectData(@Param("type") Integer type);
/**
* 返回用户的select数据 name=> username value => userId
* @return List<SelectData>
*/
List<SelectData> getSelectData(@Param("type") Integer type);
} }

View File

@@ -17,10 +17,8 @@ import java.util.List;
*/ */
public interface SysUserRoleMapper extends BaseMapper<SysUserRole> { public interface SysUserRoleMapper extends BaseMapper<SysUserRole> {
/** /**
* 通过用户ID查询角色s * 通过用户ID查询角色s
*
* @param userId * @param userId
* @return * @return
*/ */
@@ -39,5 +37,6 @@ public interface SysUserRoleMapper extends BaseMapper<SysUserRole> {
* @param roleIds * @param roleIds
* @return * @return
*/ */
Boolean insertUserRoles(@Param("userId") Integer userId, @Param("roleIds") List<Integer> roleIds); Boolean insertUserRoles(@Param("userId") Integer userId, @Param("roleIds") List<Integer> roleIds);
} }

View File

@@ -13,13 +13,13 @@ import org.mapstruct.factory.Mappers;
@Mapper @Mapper
public interface OperationLogConverter { public interface OperationLogConverter {
OperationLogConverter INSTANCE = Mappers.getMapper(OperationLogConverter.class); OperationLogConverter INSTANCE = Mappers.getMapper(OperationLogConverter.class);
/** /**
* 转换OperationLog 为 OperationLogAdmin * 转换OperationLog 为 OperationLogAdmin
* @param operationLogDTO 操作日志DTO * @param operationLogDTO 操作日志DTO
* @return AdminOperationLog * @return AdminOperationLog
*/ */
AdminOperationLog dtoToPo(OperationLogDTO operationLogDTO); AdminOperationLog dtoToPo(OperationLogDTO operationLogDTO);
} }

View File

@@ -12,13 +12,14 @@ import org.mapstruct.factory.Mappers;
*/ */
@Mapper @Mapper
public interface SysDictConverter { public interface SysDictConverter {
SysDictConverter INSTANCE = Mappers.getMapper(SysDictConverter.class);
/** SysDictConverter INSTANCE = Mappers.getMapper(SysDictConverter.class);
* 字典项实体转VO
* @param sysDictItem /**
* @return * 字典项实体转VO
*/ * @param sysDictItem
DictItemVO itemPoToVo(SysDictItem sysDictItem); * @return
*/
DictItemVO itemPoToVo(SysDictItem sysDictItem);
} }

View File

@@ -13,12 +13,13 @@ import org.mapstruct.factory.Mappers;
@Mapper @Mapper
public interface SysPermissionConverter { public interface SysPermissionConverter {
SysPermissionConverter INSTANCE = Mappers.getMapper(SysPermissionConverter.class); SysPermissionConverter INSTANCE = Mappers.getMapper(SysPermissionConverter.class);
/**
* 转换permissionVO为Router
* @param permissionVO
* @return
*/
Router toRouter(PermissionVO permissionVO);
/**
* 转换permissionVO为Router
* @param permissionVO
* @return
*/
Router toRouter(PermissionVO permissionVO);
} }

View File

@@ -13,24 +13,24 @@ import org.mapstruct.factory.Mappers;
@Mapper @Mapper
public interface SysUserConverter { public interface SysUserConverter {
SysUserConverter INSTANCE = Mappers.getMapper(SysUserConverter.class); SysUserConverter INSTANCE = Mappers.getMapper(SysUserConverter.class);
/** /**
* 转换DTO 为 PO * 转换DTO 为 PO
* @param sysUserDTO * @param sysUserDTO
* @return * @return
*/ */
// @Mapping(target = "password", expression = "java( encodePassword(sysUserDTO) )") // @Mapping(target = "password", expression = "java( encodePassword(sysUserDTO) )")
SysUser dtoToPo(SysUserDTO sysUserDTO); SysUser dtoToPo(SysUserDTO sysUserDTO);
/**
* 将前端传输密码进行加解密
* @param sysUserDTO
* @return
*/
/*
* default String encodePassword(SysUserDTO sysUserDTO){ String pass =
* sysUserDTO.getPass(); return "encode"+pass; }
*/
/**
* 将前端传输密码进行加解密
* @param sysUserDTO
* @return
*/
/* default String encodePassword(SysUserDTO sysUserDTO){
String pass = sysUserDTO.getPass();
return "encode"+pass;
}*/
} }

View File

@@ -11,50 +11,59 @@ import lombok.Data;
*/ */
@Data @Data
public class SysUserDTO { public class SysUserDTO {
/**
* 主键id /**
*/ * 主键id
@ApiModelProperty(value="主键id") */
private Integer userId; @ApiModelProperty(value = "主键id")
/** private Integer userId;
* 前端传入密码
*/ /**
@ApiModelProperty(value="前端传入密码") * 前端传入密码
private String pass; */
/** @ApiModelProperty(value = "前端传入密码")
* 登录账号 private String pass;
*/
@ApiModelProperty(value="登录账号") /**
private String username; * 登录账号
/** */
* 昵称 @ApiModelProperty(value = "登录账号")
*/ private String username;
@ApiModelProperty(value="昵称")
private String nickname; /**
/** * 昵称
* 头像 */
*/ @ApiModelProperty(value = "昵称")
@ApiModelProperty(value="头像") private String nickname;
private String avatar;
/** /**
* 性别(0-默认未知,1-男,2-女) * 头像
*/ */
@ApiModelProperty(value="性别(0-默认未知,1-男,2-女)") @ApiModelProperty(value = "头像")
private Integer sex; private String avatar;
/**
* 电子邮件 /**
*/ * 性别(0-默认未知,1-男,2-女)
@ApiModelProperty(value="电子邮件") */
private String email; @ApiModelProperty(value = "性别(0-默认未知,1-男,2-女)")
/** private Integer sex;
* 电话
*/ /**
@ApiModelProperty(value="电话") * 电子邮件
private String phone; */
/** @ApiModelProperty(value = "电子邮件")
* 状态(1-正常,2-冻结) private String email;
*/
@ApiModelProperty(value="状态(1-正常,2-冻结)") /**
private Integer status; * 电话
*/
@ApiModelProperty(value = "电话")
private String phone;
/**
* 状态(1-正常,2-冻结)
*/
@ApiModelProperty(value = "状态(1-正常,2-冻结)")
private Integer status;
} }

View File

@@ -16,5 +16,6 @@ import java.util.List;
@Data @Data
public class SysUserScope { public class SysUserScope {
private List<Integer> roleIds; private List<Integer> roleIds;
} }

View File

@@ -21,53 +21,62 @@ import java.time.LocalDateTime;
@ApiModel(value = "基础配置") @ApiModel(value = "基础配置")
public class SysConfig extends Model<SysConfig> { public class SysConfig extends Model<SysConfig> {
/** /**
* 主键 * 主键
*/ */
@TableId @TableId
@ApiModelProperty(value="主键ID") @ApiModelProperty(value = "主键ID")
private Integer id; private Integer id;
/**
* 配置名称 /**
*/ * 配置名称
@ApiModelProperty(value="配置名称") */
private String name; @ApiModelProperty(value = "配置名称")
/** private String name;
* 配置在缓存中的key名
*/ /**
@ApiModelProperty(value="配置在缓存中的key名") * 配置在缓存中的key名
private String confKey; */
/** @ApiModelProperty(value = "配置在缓存中的key名")
* 配置值 private String confKey;
*/
@ApiModelProperty(value="配置值") /**
private String confValue; * 配置值
/** */
* 分类 @ApiModelProperty(value = "配置值")
*/ private String confValue;
@ApiModelProperty(value="分类")
private String category; /**
/** * 分类
* 描述 */
*/ @ApiModelProperty(value = "分类")
@ApiModelProperty(value="描述") private String category;
private String description;
/**
* 描述
*/
@ApiModelProperty(value = "描述")
private String description;
/** /**
* 逻辑删除标识,已删除:0未删除删除时间戳 * 逻辑删除标识,已删除:0未删除删除时间戳
*/ */
@TableLogic @TableLogic
@ApiModelProperty(value="逻辑删除标识,已删除:0未删除删除时间戳") @ApiModelProperty(value = "逻辑删除标识,已删除:0未删除删除时间戳")
private Long deleted; private Long deleted;
/**
* 创建时间 /**
*/ * 创建时间
@ApiModelProperty(value="创建时间") */
@TableField(fill = FieldFill.INSERT) @ApiModelProperty(value = "创建时间")
private LocalDateTime createTime; @TableField(fill = FieldFill.INSERT)
/** private LocalDateTime createTime;
* 修改时间
*/ /**
@ApiModelProperty(value="修改时间") * 修改时间
@TableField(fill = FieldFill.INSERT_UPDATE) */
private LocalDateTime updateTime; @ApiModelProperty(value = "修改时间")
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
} }

View File

@@ -20,55 +20,65 @@ import java.time.LocalDateTime;
@EqualsAndHashCode(callSuper = true) @EqualsAndHashCode(callSuper = true)
@ApiModel(value = "字典表") @ApiModel(value = "字典表")
public class SysDict extends Model<SysDict> { public class SysDict extends Model<SysDict> {
private static final long serialVersionUID = 1L;
/** private static final long serialVersionUID = 1L;
* 编号
*/ /**
@TableId * 编号
@ApiModelProperty(value = "编号") */
private Integer id; @TableId
/** @ApiModelProperty(value = "编号")
* 标识 private Integer id;
*/
@ApiModelProperty(value = "标识") /**
private String code; * 标识
/** */
* 名称 @ApiModelProperty(value = "标识")
*/ private String code;
@ApiModelProperty(value = "名称")
private String title; /**
/** * 名称
* Hash值 */
*/ @ApiModelProperty(value = "名称")
@ApiModelProperty(value = "Hash值") private String title;
private String hashCode;
/** /**
* 备注 * Hash值
*/ */
@ApiModelProperty(value = "备注") @ApiModelProperty(value = "Hash值")
private String remarks; private String hashCode;
/**
* 可编辑的 /**
*/ * 备注
@ApiModelProperty(value = "1是 0") */
private Integer editable; @ApiModelProperty(value = "备注")
private String remarks;
/**
* 可编辑的
*/
@ApiModelProperty(value = "1是 0")
private Integer editable;
/** /**
* 逻辑删除标识,已删除:0未删除删除时间戳 * 逻辑删除标识,已删除:0未删除删除时间戳
*/ */
@TableLogic @TableLogic
@ApiModelProperty(value="逻辑删除标识,已删除:0未删除删除时间戳") @ApiModelProperty(value = "逻辑删除标识,已删除:0未删除删除时间戳")
private Long deleted; private Long deleted;
/**
* 创建时间 /**
*/ * 创建时间
@TableField(fill = FieldFill.INSERT) */
@ApiModelProperty(value = "创建时间") @TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime; @ApiModelProperty(value = "创建时间")
/** private LocalDateTime createTime;
* 更新时间
*/ /**
@TableField(fill = FieldFill.INSERT_UPDATE) * 更新时间
@ApiModelProperty(value = "更新时间") */
private LocalDateTime updateTime; @TableField(fill = FieldFill.INSERT_UPDATE)
@ApiModelProperty(value = "更新时间")
private LocalDateTime updateTime;
} }

View File

@@ -20,55 +20,65 @@ import java.time.LocalDateTime;
@EqualsAndHashCode(callSuper = true) @EqualsAndHashCode(callSuper = true)
@ApiModel(value = "字典项") @ApiModel(value = "字典项")
public class SysDictItem extends Model<SysDictItem> { public class SysDictItem extends Model<SysDictItem> {
private static final long serialVersionUID = 1L;
/** private static final long serialVersionUID = 1L;
* ID
*/ /**
@TableId * ID
@ApiModelProperty(value = "ID") */
private Integer id; @TableId
/** @ApiModelProperty(value = "ID")
* 字典标识 private Integer id;
*/
@ApiModelProperty(value = "字典标识") /**
private String dictCode; * 字典标识
/** */
* 数据值 @ApiModelProperty(value = "字典标识")
*/ private String dictCode;
@ApiModelProperty(value = "数据值")
private String value; /**
/** * 数据值
* 文本值 */
*/ @ApiModelProperty(value = "数据值")
@ApiModelProperty(value = "文本值") private String value;
private String name;
/** /**
* 排序(升序) * 文本值
*/ */
@ApiModelProperty(value = "排序(升序)") @ApiModelProperty(value = "文本值")
private Integer sort; private String name;
/**
* 备注 /**
*/ * 排序(升序)
@ApiModelProperty(value = "备注") */
private String remarks; @ApiModelProperty(value = "排序(升序)")
private Integer sort;
/**
* 备注
*/
@ApiModelProperty(value = "备注")
private String remarks;
/** /**
* 逻辑删除标识,已删除:0未删除删除时间戳 * 逻辑删除标识,已删除:0未删除删除时间戳
*/ */
@TableLogic @TableLogic
@ApiModelProperty(value="逻辑删除标识,已删除:0未删除删除时间戳") @ApiModelProperty(value = "逻辑删除标识,已删除:0未删除删除时间戳")
private Long deleted; private Long deleted;
/**
* 创建时间 /**
*/ * 创建时间
@TableField(fill = FieldFill.INSERT) */
@ApiModelProperty(value = "创建时间") @TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime; @ApiModelProperty(value = "创建时间")
/** private LocalDateTime createTime;
* 更新时间
*/ /**
@TableField(fill = FieldFill.INSERT_UPDATE) * 更新时间
@ApiModelProperty(value = "更新时间") */
private LocalDateTime updateTime; @TableField(fill = FieldFill.INSERT_UPDATE)
@ApiModelProperty(value = "更新时间")
private LocalDateTime updateTime;
} }

View File

@@ -24,89 +24,106 @@ import java.time.LocalDateTime;
public class SysPermission extends Model<SysPermission> { public class SysPermission extends Model<SysPermission> {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** /**
* 菜单ID * 菜单ID
*/ */
@TableId @TableId
@ApiModelProperty(value="菜单ID") @ApiModelProperty(value = "菜单ID")
private Integer id; private Integer id;
/** /**
* 菜单标题 * 菜单标题
*/ */
@ApiModelProperty(value="菜单标题") @ApiModelProperty(value = "菜单标题")
private String title; private String title;
/** /**
* 菜单权限标识 * 菜单权限标识
*/ */
@ApiModelProperty(value="菜单权限标识") @ApiModelProperty(value = "菜单权限标识")
private String code; private String code;
/** /**
* 路由URL * 路由URL
*/ */
@ApiModelProperty(value="路由URL") @ApiModelProperty(value = "路由URL")
private String path; private String path;
/** /**
* 路由名称 * 路由名称
*/ */
@ApiModelProperty(value="路由名称") @ApiModelProperty(value = "路由名称")
private String routerName; private String routerName;
/** /**
* component地址 * component地址
*/ */
@ApiModelProperty(value="component地址") @ApiModelProperty(value = "component地址")
private String component; private String component;
/** /**
* 重定向地址 * 重定向地址
*/ */
@ApiModelProperty(value="重定向地址") @ApiModelProperty(value = "重定向地址")
private String redirect; private String redirect;
/** /**
* 链接跳转目标 * 链接跳转目标
*/ */
@ApiModelProperty(value="链接跳转目标") @ApiModelProperty(value = "链接跳转目标")
private String target; private String target;
/** /**
* 父菜单ID * 父菜单ID
*/ */
@ApiModelProperty(value="父菜单ID") @ApiModelProperty(value = "父菜单ID")
private Integer parentId; private Integer parentId;
/** /**
* 图标 * 图标
*/ */
@ApiModelProperty(value="图标") @ApiModelProperty(value = "图标")
private String icon; private String icon;
/** /**
* 排序值 * 排序值
*/ */
@ApiModelProperty(value="排序值") @ApiModelProperty(value = "排序值")
private Integer sort; private Integer sort;
/** /**
* 0-开启1- 关闭 * 0-开启1- 关闭
*/ */
@ApiModelProperty(value="0-开启1- 关闭") @ApiModelProperty(value = "0-开启1- 关闭")
private Integer keepAlive; private Integer keepAlive;
/** /**
* 是否隐藏路由: 0否,1是 * 是否隐藏路由: 0否,1是
*/ */
@ApiModelProperty(value="是否隐藏路由: 0否,1是") @ApiModelProperty(value = "是否隐藏路由: 0否,1是")
private Integer hidden; private Integer hidden;
/** /**
* 菜单类型 0菜单 1按钮 * 菜单类型 0菜单 1按钮
*/ */
@ApiModelProperty(value="菜单类型 0菜单 1按钮") @ApiModelProperty(value = "菜单类型 0菜单 1按钮")
private Integer type; private Integer type;
/** /**
* 逻辑删除标识,已删除:0未删除删除时间戳 * 逻辑删除标识,已删除:0未删除删除时间戳
*/ */
@TableLogic @TableLogic
@ApiModelProperty(value="逻辑删除标识,已删除:0未删除删除时间戳") @ApiModelProperty(value = "逻辑删除标识,已删除:0未删除删除时间戳")
private Long deleted; private Long deleted;
/** /**
* 创建时间 * 创建时间
*/ */
@ApiModelProperty(value = "创建时间") @ApiModelProperty(value = "创建时间")
@TableField(fill = FieldFill.INSERT) @TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime; private LocalDateTime createTime;
/** /**
* 更新时间 * 更新时间
*/ */
@@ -114,8 +131,4 @@ public class SysPermission extends Model<SysPermission> {
@TableField(fill = FieldFill.INSERT_UPDATE) @TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime; private LocalDateTime updateTime;
} }

View File

@@ -40,18 +40,21 @@ public class SysRole extends Model<SysRole> {
@ApiModelProperty(value = "角色备注") @ApiModelProperty(value = "角色备注")
private String note; private String note;
/** /**
* 逻辑删除标识,已删除:0未删除删除时间戳 * 逻辑删除标识,已删除:0未删除删除时间戳
*/ */
@TableLogic @TableLogic
@ApiModelProperty(value="逻辑删除标识,已删除:0未删除删除时间戳") @ApiModelProperty(value = "逻辑删除标识,已删除:0未删除删除时间戳")
private Long deleted; private Long deleted;
/** /**
* 创建时间 * 创建时间
*/ */
@ApiModelProperty(value = "创建时间") @ApiModelProperty(value = "创建时间")
@TableField(fill = FieldFill.INSERT) @TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime; private LocalDateTime createTime;
/** /**
* 修改时间 * 修改时间
*/ */
@@ -59,5 +62,4 @@ public class SysRole extends Model<SysRole> {
@TableField(fill = FieldFill.INSERT_UPDATE) @TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime; private LocalDateTime updateTime;
} }

View File

@@ -22,14 +22,17 @@ import lombok.EqualsAndHashCode;
public class SysRolePermission extends Model<SysRolePermission> { public class SysRolePermission extends Model<SysRolePermission> {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** /**
* 角色ID * 角色ID
*/ */
@ApiModelProperty(value = "角色id") @ApiModelProperty(value = "角色id")
private Integer roleId; private Integer roleId;
/** /**
* 权限ID * 权限ID
*/ */
@ApiModelProperty(value = "菜单id") @ApiModelProperty(value = "菜单id")
private Integer permissionId; private Integer permissionId;
} }

View File

@@ -20,82 +20,92 @@ import java.time.LocalDateTime;
@EqualsAndHashCode(callSuper = true) @EqualsAndHashCode(callSuper = true)
@ApiModel(value = "系统用户表") @ApiModel(value = "系统用户表")
public class SysUser extends Model<SysUser> { public class SysUser extends Model<SysUser> {
private static final long serialVersionUID = 1L;
/** private static final long serialVersionUID = 1L;
* 主键id
*/
@TableId
@ApiModelProperty(value="主键id")
private Integer userId;
/**
* 登录账号
*/
@ApiModelProperty(value="登录账号")
private String username;
/**
* 昵称
*/
@ApiModelProperty(value="昵称")
private String nickname;
/**
* 密码
*/
@ApiModelProperty(value="密码")
private String password;
/**
* md5密码盐
*/
@ApiModelProperty(value="md5密码盐")
private String salt;
/**
* 头像
*/
@ApiModelProperty(value="头像")
private String avatar;
/**
* 性别(0-默认未知,1-男,2-女)
*/
@ApiModelProperty(value="性别(0-默认未知,1-男,2-女)")
private Integer sex;
/**
* 电子邮件
*/
@ApiModelProperty(value="电子邮件")
private String email;
/**
* 电话
*/
@ApiModelProperty(value="电话")
private String phone;
/**
* 状态(1-正常,0-冻结)
*/
@ApiModelProperty(value="状态(1-正常, 0-冻结)")
private Integer status;
@ApiModelProperty(value="1:系统用户, 2客户用户") /**
private Integer type; * 主键id
*/
@TableId
@ApiModelProperty(value = "主键id")
private Integer userId;
/** /**
* 逻辑删除标识,已删除:0未删除删除时间戳 * 登录账号
*/ */
@TableLogic @ApiModelProperty(value = "登录账号")
@ApiModelProperty(value="逻辑删除标识,已删除:0未删除删除时间戳") private String username;
private Long deleted;
/**
* 创建时间
*/
@ApiModelProperty(value="创建时间")
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 更新时间
*/
@ApiModelProperty(value="更新时间")
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
/**
* 昵称
*/
@ApiModelProperty(value = "昵称")
private String nickname;
/**
* 密码
*/
@ApiModelProperty(value = "密码")
private String password;
/**
* md5密码盐
*/
@ApiModelProperty(value = "md5密码盐")
private String salt;
/**
* 头像
*/
@ApiModelProperty(value = "头像")
private String avatar;
/**
* 性别(0-默认未知,1-男,2-女)
*/
@ApiModelProperty(value = "性别(0-默认未知,1-男,2-女)")
private Integer sex;
/**
* 电子邮件
*/
@ApiModelProperty(value = "电子邮件")
private String email;
/**
* 电话
*/
@ApiModelProperty(value = "电话")
private String phone;
/**
* 状态(1-正常,0-冻结)
*/
@ApiModelProperty(value = "状态(1-正常, 0-冻结)")
private Integer status;
@ApiModelProperty(value = "1:系统用户, 2客户用户")
private Integer type;
/**
* 逻辑删除标识,已删除:0未删除删除时间戳
*/
@TableLogic
@ApiModelProperty(value = "逻辑删除标识,已删除:0未删除删除时间戳")
private Long deleted;
/**
* 创建时间
*/
@ApiModelProperty(value = "创建时间")
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 更新时间
*/
@ApiModelProperty(value = "更新时间")
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
} }

View File

@@ -22,11 +22,13 @@ import lombok.EqualsAndHashCode;
public class SysUserRole extends Model<SysUserRole> { public class SysUserRole extends Model<SysUserRole> {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** /**
* 用户ID * 用户ID
*/ */
@ApiModelProperty(value = "用户id") @ApiModelProperty(value = "用户id")
private Integer userId; private Integer userId;
/** /**
* 角色ID * 角色ID
*/ */

View File

@@ -20,12 +20,14 @@ import java.time.LocalDateTime;
*/ */
@Data @Data
@ApiModel(value = "字典项查询对象") @ApiModel(value = "字典项查询对象")
public class DictItemQO { public class DictItemQO {
private static final long serialVersionUID = 1L;
/** private static final long serialVersionUID = 1L;
* ID
*/ /**
@ApiModelProperty(value="ID") * ID
private Integer id; */
} @ApiModelProperty(value = "ID")
private Integer id;
}

View File

@@ -4,7 +4,6 @@ import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import lombok.Data; import lombok.Data;
/** /**
* 字典表 查询对象 * 字典表 查询对象
* *
@@ -14,11 +13,13 @@ import lombok.Data;
@Data @Data
@ApiModel(value = "字典表查询对象") @ApiModel(value = "字典表查询对象")
public class DictQO { public class DictQO {
private static final long serialVersionUID = 1L;
/** private static final long serialVersionUID = 1L;
* 编号
*/ /**
@ApiModelProperty(value = "编号") * 编号
private Integer id; */
@ApiModelProperty(value = "编号")
private Integer id;
} }

View File

@@ -15,12 +15,14 @@ import java.time.LocalDateTime;
*/ */
@Data @Data
@ApiModel(value = "字典表查询对象") @ApiModel(value = "字典表查询对象")
public class SysDictQO { public class SysDictQO {
private static final long serialVersionUID = 1L;
/** private static final long serialVersionUID = 1L;
* 编号
*/ /**
@ApiModelProperty(value="编号") * 编号
private Integer id; */
} @ApiModelProperty(value = "编号")
private Integer id;
}

View File

@@ -8,11 +8,13 @@ import javax.validation.constraints.NotBlank;
/** /**
* 角色查询对象 * 角色查询对象
*
* @author Hccake * @author Hccake
*/ */
@Data @Data
@ApiModel(value = "角色查询对象") @ApiModel(value = "角色查询对象")
public class SysRoleQO { public class SysRoleQO {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "角色名称") @ApiModelProperty(value = "角色名称")
@@ -26,4 +28,5 @@ public class SysRoleQO {
@ApiModelProperty(value = "结束时间") @ApiModelProperty(value = "结束时间")
private String endTime; private String endTime;
} }

View File

@@ -13,44 +13,49 @@ import lombok.Data;
@ApiModel("系统用户查询对象") @ApiModel("系统用户查询对象")
public class SysUserQO { public class SysUserQO {
/** /**
* 登录账号 * 登录账号
*/ */
@ApiModelProperty(value="登录账号") @ApiModelProperty(value = "登录账号")
private String username; private String username;
/**
* 昵称
*/
@ApiModelProperty(value="昵称")
private String nickname;
/**
* 性别(0-默认未知,1-男,2-女)
*/
@ApiModelProperty(value="性别(0-默认未知,1-男,2-女)")
private Integer sex;
/**
* 电子邮件
*/
@ApiModelProperty(value="电子邮件")
private String email;
/**
* 电话
*/
@ApiModelProperty(value="电话")
private String phone;
/**
* 状态(1-正常,2-冻结)
*/
@ApiModelProperty(value="状态(1-正常,2-冻结)")
private Integer status;
@ApiModelProperty(value="开始时间") /**
private String startTime; * 昵称
*/
@ApiModelProperty(value = "昵称")
private String nickname;
@ApiModelProperty(value="结束时间") /**
private String endTime; * 性别(0-默认未知,1-男,2-女)
*/
@ApiModelProperty(value = "性别(0-默认未知,1-男,2-女)")
private Integer sex;
@ApiModelProperty(value="用户类型:1:系统用户, 2客户用户") /**
private Integer type; * 电子邮件
*/
@ApiModelProperty(value = "电子邮件")
private String email;
/**
* 电话
*/
@ApiModelProperty(value = "电话")
private String phone;
/**
* 状态(1-正常,2-冻结)
*/
@ApiModelProperty(value = "状态(1-正常,2-冻结)")
private Integer status;
@ApiModelProperty(value = "开始时间")
private String startTime;
@ApiModelProperty(value = "结束时间")
private String endTime;
@ApiModelProperty(value = "用户类型:1:系统用户, 2客户用户")
private Integer type;
} }

View File

@@ -14,15 +14,17 @@ import java.util.List;
@Data @Data
@ApiModel(value = "字典数据VO") @ApiModel(value = "字典数据VO")
public class DictDataAndHashVO { public class DictDataAndHashVO {
/**
* 字典Hash值
*/
@ApiModelProperty(value="字典Hash值")
private String hashCode;
/** /**
* 字典项列表 * 字典Hash值
*/ */
@ApiModelProperty(value="字典数据") @ApiModelProperty(value = "字典Hash值")
private List<DictItemVO> dictList; private String hashCode;
/**
* 字典项列表
*/
@ApiModelProperty(value = "字典数据")
private List<DictItemVO> dictList;
} }

View File

@@ -12,16 +12,20 @@ import lombok.Data;
*/ */
@Data @Data
@ApiModel(value = "字典项VO") @ApiModel(value = "字典项VO")
public class DictItemVO { public class DictItemVO {
private static final long serialVersionUID = 1L;
/** private static final long serialVersionUID = 1L;
* 数据值
*/ /**
@ApiModelProperty(value = "数据值") * 数据值
private String value; */
/** @ApiModelProperty(value = "数据值")
* 标签 private String value;
*/
@ApiModelProperty(value = "文本值") /**
private String name; * 标签
*/
@ApiModelProperty(value = "文本值")
private String name;
} }

View File

@@ -15,107 +15,119 @@ import java.time.LocalDateTime;
@ApiModel(value = "权限VO") @ApiModel(value = "权限VO")
public class PermissionVO { public class PermissionVO {
/** /**
* 菜单ID * 菜单ID
*/ */
@ApiModelProperty(value="菜单ID") @ApiModelProperty(value = "菜单ID")
private Integer id; private Integer id;
/**
* 菜单标题
*/
@ApiModelProperty(value="菜单标题")
private String title;
/**
* 菜单权限标识
*/
@ApiModelProperty(value="菜单权限标识")
private String code;
/**
* 路由URL
*/
@ApiModelProperty(value="路由URL")
private String path;
/**
* 路由名称
*/
@ApiModelProperty(value="路由名称")
private String routerName;
/**
* component地址
*/
@ApiModelProperty(value="component地址")
private String component;
/**
* 重定向地址
*/
@ApiModelProperty(value="重定向地址")
private String redirect;
/**
* 链接跳转目标
*/
@ApiModelProperty(value="链接跳转目标")
private String target;
/**
* 父菜单ID
*/
@ApiModelProperty(value="父菜单ID")
private Integer parentId;
/**
* 图标
*/
@ApiModelProperty(value="图标")
private String icon;
/**
* 排序值
*/
@ApiModelProperty(value="排序值")
private Integer sort;
/**
* 0-开启1- 关闭
*/
@ApiModelProperty(value="0-开启1- 关闭")
private Integer keepAlive;
/**
* 是否隐藏路由: 0否,1是
*/
@ApiModelProperty(value="是否隐藏路由: 0否,1是")
private Integer hidden;
/**
* 菜单类型 0菜单 1按钮
*/
@ApiModelProperty(value="菜单类型 0菜单 1按钮")
private Integer type;
/**
* 创建时间
*/
@ApiModelProperty(value = "创建时间")
private LocalDateTime createTime;
/**
* 更新时间
*/
@ApiModelProperty(value = "更新时间")
private LocalDateTime updateTime;
/**
* 菜单标题
*/
@ApiModelProperty(value = "菜单标题")
private String title;
/**
* 菜单权限标识
*/
@ApiModelProperty(value = "菜单权限标识")
private String code;
/**
* 路由URL
*/
@ApiModelProperty(value = "路由URL")
private String path;
@Override /**
public int hashCode() { * 路由名称
return id.hashCode(); */
} @ApiModelProperty(value = "路由名称")
private String routerName;
/** /**
* permissionId 相同则相同 * component地址
* @param obj */
* @return @ApiModelProperty(value = "component地址")
*/ private String component;
@Override
public boolean equals(Object obj) { /**
if (obj instanceof PermissionVO) { * 重定向地址
Integer permissionId = ((PermissionVO) obj).getId(); */
return id.equals(permissionId); @ApiModelProperty(value = "重定向地址")
} private String redirect;
return super.equals(obj);
} /**
* 链接跳转目标
*/
@ApiModelProperty(value = "链接跳转目标")
private String target;
/**
* 父菜单ID
*/
@ApiModelProperty(value = "父菜单ID")
private Integer parentId;
/**
* 图标
*/
@ApiModelProperty(value = "图标")
private String icon;
/**
* 排序值
*/
@ApiModelProperty(value = "排序值")
private Integer sort;
/**
* 0-开启1- 关闭
*/
@ApiModelProperty(value = "0-开启1- 关闭")
private Integer keepAlive;
/**
* 是否隐藏路由: 0否,1是
*/
@ApiModelProperty(value = "是否隐藏路由: 0否,1是")
private Integer hidden;
/**
* 菜单类型 0菜单 1按钮
*/
@ApiModelProperty(value = "菜单类型 0菜单 1按钮")
private Integer type;
/**
* 创建时间
*/
@ApiModelProperty(value = "创建时间")
private LocalDateTime createTime;
/**
* 更新时间
*/
@ApiModelProperty(value = "更新时间")
private LocalDateTime updateTime;
@Override
public int hashCode() {
return id.hashCode();
}
/**
* permissionId 相同则相同
* @param obj
* @return
*/
@Override
public boolean equals(Object obj) {
if (obj instanceof PermissionVO) {
Integer permissionId = ((PermissionVO) obj).getId();
return id.equals(permissionId);
}
return super.equals(obj);
}
} }

View File

@@ -29,8 +29,9 @@ public class Router {
*/ */
@ApiModelProperty(value = "图标") @ApiModelProperty(value = "图标")
private String icon; private String icon;
/** /**
* 菜单名称 * 菜单名称
*/ */
@ApiModelProperty(value = "标题") @ApiModelProperty(value = "标题")
private String title; private String title;
@@ -46,21 +47,25 @@ public class Router {
*/ */
@ApiModelProperty(value = "前端路由标识路径") @ApiModelProperty(value = "前端路由标识路径")
private String path; private String path;
/** /**
* 菜单权限标识 * 菜单权限标识
*/ */
@ApiModelProperty(value = "前端路由组件") @ApiModelProperty(value = "前端路由组件")
private String component; private String component;
/** /**
* 重定向地址 * 重定向地址
*/ */
@ApiModelProperty(value="重定向地址") @ApiModelProperty(value = "重定向地址")
private String redirect; private String redirect;
/** /**
* 链接跳转目标 * 链接跳转目标
*/ */
@ApiModelProperty(value="链接跳转目标") @ApiModelProperty(value = "链接跳转目标")
private String target; private String target;
/** /**
* 路由缓冲 * 路由缓冲
*/ */
@@ -70,9 +75,7 @@ public class Router {
/** /**
* 是否隐藏路由: 0否,1是 * 是否隐藏路由: 0否,1是
*/ */
@ApiModelProperty(value="是否隐藏路由: 0否,1是") @ApiModelProperty(value = "是否隐藏路由: 0否,1是")
private Integer hidden; private Integer hidden;
} }

View File

@@ -14,24 +14,29 @@ import java.util.List;
@Data @Data
@ApiModel(value = "用户信息") @ApiModel(value = "用户信息")
public class UserInfo implements Serializable { public class UserInfo implements Serializable {
/** /**
* 用户基本信息 * 用户基本信息
*/ */
@ApiModelProperty(value = "用户基本信息") @ApiModelProperty(value = "用户基本信息")
private SysUser sysUser; private SysUser sysUser;
/** /**
* 权限标识集合 * 权限标识集合
*/ */
@ApiModelProperty(value = "权限标识集合") @ApiModelProperty(value = "权限标识集合")
private List<String> permissions; private List<String> permissions;
/** /**
* 角色集合 * 角色集合
*/ */
@ApiModelProperty(value = "角色标识集合") @ApiModelProperty(value = "角色标识集合")
private List<String> roles; private List<String> roles;
/** /**
* 角色ID集合 * 角色ID集合
*/ */
@ApiModelProperty(value = "角色Id集合") @ApiModelProperty(value = "角色Id集合")
private List<Integer> roleIds; private List<Integer> roleIds;
} }

View File

@@ -12,20 +12,20 @@ import java.io.InputStream;
*/ */
public interface FileService { public interface FileService {
/** /**
* 文件上传 * 文件上传
* @param file 文件对象 * @param file 文件对象
* @param objectName 文件对象名 * @param objectName 文件对象名
* @throws IOException IO异常 * @throws IOException IO异常
*/ */
void uploadFile(MultipartFile file, String objectName) throws IOException; void uploadFile(MultipartFile file, String objectName) throws IOException;
/**
* 文件上传
* @param inputStream 文件流
* @param objectName 文件对象名
*
*/
void uploadFile(InputStream inputStream, String objectName);
/**
* 文件上传
* @param inputStream 文件流
* @param objectName 文件对象名
*
*/
void uploadFile(InputStream inputStream, String objectName);
} }

View File

@@ -11,10 +11,11 @@ import com.baomidou.mybatisplus.extension.service.IService;
*/ */
public interface SysConfigService extends IService<SysConfig> { public interface SysConfigService extends IService<SysConfig> {
/** /**
* 根据配置key获取对应value * 根据配置key获取对应value
* @param confKey * @param confKey
* @return confValue * @return confValue
*/ */
String getConfValueByKey(String confKey); String getConfValueByKey(String confKey);
} }

View File

@@ -14,19 +14,19 @@ import java.util.List;
*/ */
public interface SysDictItemService extends IService<SysDictItem> { public interface SysDictItemService extends IService<SysDictItem> {
/** /**
* 根据QueryObeject查询分页数据 * 根据QueryObeject查询分页数据
* @param page 分页参数 * @param page 分页参数
* @param dictCode 查询参数对象 * @param dictCode 查询参数对象
* @return 分页数据 * @return 分页数据
*/ */
IPage<SysDictItem> page(IPage<SysDictItem> page, String dictCode); IPage<SysDictItem> page(IPage<SysDictItem> page, String dictCode);
/**
* 根据Code查询对应字典项数据
* @param dictCode
* @return
*/
List<SysDictItem> getByDictCode(String dictCode);
/**
* 根据Code查询对应字典项数据
* @param dictCode
* @return
*/
List<SysDictItem> getByDictCode(String dictCode);
} }

View File

@@ -15,34 +15,33 @@ import java.util.List;
*/ */
public interface SysDictService extends IService<SysDict> { public interface SysDictService extends IService<SysDict> {
/** /**
* 根据QueryObeject查询分页数据 * 根据QueryObeject查询分页数据
* @param page 分页参数 * @param page 分页参数
* @param qo 查询参数对象 * @param qo 查询参数对象
* @return 分页数据 * @return 分页数据
*/ */
IPage<SysDict> page(IPage<SysDict> page, SysDictQO qo); IPage<SysDict> page(IPage<SysDict> page, SysDictQO qo);
/** /**
* 根据字典标识查询 * 根据字典标识查询
* @param dictCode 字典标识 * @param dictCode 字典标识
* @return 字典数据 * @return 字典数据
*/ */
SysDict getByCode(String dictCode); SysDict getByCode(String dictCode);
/**
* 根据字典标识查询
* @param dictCode 字典标识
* @return 字典数据
*/
List<SysDict> getByCode(String[] dictCode);
/** /**
* 根据字典标识查询 * 更新字典HashCode
* @param dictCode 字典标识 * @param dictCode
* @return 字典数据 * @return
*/ */
List<SysDict> getByCode(String[] dictCode); boolean updateHashCode(String dictCode);
/**
* 更新字典HashCode
* @param dictCode
* @return
*/
boolean updateHashCode(String dictCode);
} }

View File

@@ -15,9 +15,9 @@ import java.util.List;
* @since 2017-10-29 * @since 2017-10-29
*/ */
public interface SysPermissionService extends IService<SysPermission> { public interface SysPermissionService extends IService<SysPermission> {
/** /**
* 通过角色编号查询URL 权限 * 通过角色编号查询URL 权限
*
* @param roleId 角色ID * @param roleId 角色ID
* @return 菜单列表 * @return 菜单列表
*/ */
@@ -25,7 +25,6 @@ public interface SysPermissionService extends IService<SysPermission> {
/** /**
* 级联删除菜单 * 级联删除菜单
*
* @param id 菜单ID * @param id 菜单ID
* @return 成功、失败 * @return 成功、失败
*/ */
@@ -33,9 +32,9 @@ public interface SysPermissionService extends IService<SysPermission> {
/** /**
* 更新菜单信息 * 更新菜单信息
*
* @param sysPermission 菜单信息 * @param sysPermission 菜单信息
* @return 成功、失败 * @return 成功、失败
*/ */
Boolean updatePermissionById(SysPermission sysPermission); Boolean updatePermissionById(SysPermission sysPermission);
} }

View File

@@ -1,6 +1,5 @@
package com.hccake.ballcat.admin.modules.sys.service; package com.hccake.ballcat.admin.modules.sys.service;
import com.baomidou.mybatisplus.extension.service.IService; import com.baomidou.mybatisplus.extension.service.IService;
import com.hccake.ballcat.admin.modules.sys.model.entity.SysRolePermission; import com.hccake.ballcat.admin.modules.sys.model.entity.SysRolePermission;
@@ -16,10 +15,10 @@ public interface SysRolePermissionService extends IService<SysRolePermission> {
/** /**
* 更新角色菜单 * 更新角色菜单
* * @param roleId 角色
* @param roleId 角色
* @param permissionIds 权限ID数组 * @param permissionIds 权限ID数组
* @return * @return
*/ */
Boolean saveRolePermissions(Integer roleId, Integer[] permissionIds); Boolean saveRolePermissions(Integer roleId, Integer[] permissionIds);
} }

View File

@@ -28,7 +28,6 @@ public interface SysRoleService extends IService<SysRole> {
/** /**
* 通过角色ID删除角色 * 通过角色ID删除角色
*
* @param id * @param id
* @return * @return
*/ */
@@ -38,6 +37,6 @@ public interface SysRoleService extends IService<SysRole> {
* 角色的选择数据 * 角色的选择数据
* @return * @return
*/ */
List<SelectData> getSelectData(); List<SelectData> getSelectData();
} }

View File

@@ -1,6 +1,5 @@
package com.hccake.ballcat.admin.modules.sys.service; package com.hccake.ballcat.admin.modules.sys.service;
import com.baomidou.mybatisplus.extension.service.IService; import com.baomidou.mybatisplus.extension.service.IService;
import com.hccake.ballcat.admin.modules.sys.model.entity.SysRole; import com.hccake.ballcat.admin.modules.sys.model.entity.SysRole;
import com.hccake.ballcat.admin.modules.sys.model.entity.SysUserRole; import com.hccake.ballcat.admin.modules.sys.model.entity.SysUserRole;
@@ -29,7 +28,6 @@ public interface SysUserRoleService extends IService<SysUserRole> {
*/ */
Boolean insertUserRoles(Integer userId, List<Integer> roleIds); Boolean insertUserRoles(Integer userId, List<Integer> roleIds);
/** /**
* 更新用户关联关系 * 更新用户关联关系
* @param userId * @param userId
@@ -40,9 +38,9 @@ public interface SysUserRoleService extends IService<SysUserRole> {
/** /**
* 通过用户ID查询角色列表 * 通过用户ID查询角色列表
*
* @param userId * @param userId
* @return List<SysRole> * @return List<SysRole>
*/ */
List<SysRole> getRoles(Integer userId); List<SysRole> getRoles(Integer userId);
} }

View File

@@ -21,102 +21,94 @@ import java.util.List;
*/ */
public interface SysUserService extends IService<SysUser> { public interface SysUserService extends IService<SysUser> {
/** /**
* 查询系统用户列表 * 查询系统用户列表
* @param page 分页对象 * @param page 分页对象
* @param qo 查询参数 * @param qo 查询参数
* @return * @return
*/ */
IPage<SysUser> page(IPage<SysUser> page, SysUserQO qo); IPage<SysUser> page(IPage<SysUser> page, SysUserQO qo);
/**
* 根据用户名查询用户
* @param username
* @return
*/
SysUser getByUsername(String username);
/** /**
* 根据用户名查询用户 * 获取用户详情信息
* @param username * @param user
* @return * @return
*/ */
SysUser getByUsername(String username); UserInfo findUserInfo(SysUser user);
/** /**
* 获取用户详情信息 * 新增系统用户
* @param user * @param sysUserDto
* @return * @return
*/ */
UserInfo findUserInfo(SysUser user); boolean addSysUser(SysUserDTO sysUserDto);
/**
* 更新系统用户信息
* @param sysUserDTO
* @return
*/
boolean updateSysUser(SysUserDTO sysUserDTO);
/** /**
* 新增系统用户 * 更新用户权限信息
* @param sysUserDto * @param userId
* @return * @param sysUserScope
*/ * @return
boolean addSysUser(SysUserDTO sysUserDto); */
boolean updateUserScope(Integer userId, SysUserScope sysUserScope);
/**
* 根据userId删除 用户
* @param userId
* @return
*/
boolean deleteByUserId(Integer userId);
/** /**
* 更新系统用户信息 * 修改用户密码
* @param sysUserDTO * @param userId
* @return * @param pass
*/ * @return
boolean updateSysUser(SysUserDTO sysUserDTO); */
boolean updateUserPass(Integer userId, String pass);
/**
* 批量修改用户状态
* @param userIds
* @param status
* @return
*/
boolean updateUserStatus(List<Integer> userIds, Integer status);
/** /**
* 更新用户权限信息 * 修改系统用户头像
* * @param file 头像文件
* @param userId * @param userId 用户ID
* @param sysUserScope * @return 文件相对路径
* @return * @throws IOException
*/ */
boolean updateUserScope(Integer userId, SysUserScope sysUserScope); String updateAvatar(MultipartFile file, Integer userId) throws IOException;
/**
* 根据角色查询用户
* @return
* @param roleCode
*/
List<SysUser> selectUsersByRoleCode(String roleCode);
/** /**
* 根据userId删除 用户 * 返回用户的select数据
* @param userId * @param type 为空时返回所有客户为1返回系统客户 name=> username value => userId
* @return * @return List<SelectData>
*/ */
boolean deleteByUserId(Integer userId); List<SelectData> getSelectData(Integer type);
/**
* 修改用户密码
* @param userId
* @param pass
* @return
*/
boolean updateUserPass(Integer userId, String pass);
/**
* 批量修改用户状态
* @param userIds
* @param status
* @return
*/
boolean updateUserStatus(List<Integer> userIds, Integer status);
/**
* 修改系统用户头像
* @param file 头像文件
* @param userId 用户ID
* @return 文件相对路径
* @throws IOException
*/
String updateAvatar(MultipartFile file, Integer userId) throws IOException;
/**
* 根据角色查询用户
* @return
* @param roleCode
*/
List<SysUser> selectUsersByRoleCode(String roleCode);
/**
* 返回用户的select数据
* @param type 为空时返回所有客户为1返回系统客户
* name=> username
* value => userId
* @return List<SelectData>
*/
List<SelectData> getSelectData(Integer type);
} }

View File

@@ -17,29 +17,29 @@ import java.io.InputStream;
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
public class FileServiceImpl implements FileService { public class FileServiceImpl implements FileService {
private final FileStorageClient fileStorageClient;
/** private final FileStorageClient fileStorageClient;
* 文件上传
* /**
* @param file 待上传文件 * 文件上传
* @param objectName 文件对象名 * @param file 待上传文件
* * @param objectName 文件对象名
*/ *
@Override */
public void uploadFile(MultipartFile file, String objectName) throws IOException { @Override
fileStorageClient.putObject(objectName, file.getInputStream()); public void uploadFile(MultipartFile file, String objectName) throws IOException {
} fileStorageClient.putObject(objectName, file.getInputStream());
}
/**
* 文件上传
* @param inputStream 文件流
* @param objectName 文件对象名
*
*/
@Override
public void uploadFile(InputStream inputStream, String objectName) {
fileStorageClient.putObject(objectName, inputStream);
}
/**
* 文件上传
*
* @param inputStream 文件流
* @param objectName 文件对象名
*
*/
@Override
public void uploadFile(InputStream inputStream, String objectName) {
fileStorageClient.putObject(objectName, inputStream);
}
} }

View File

@@ -16,15 +16,16 @@ import org.springframework.stereotype.Service;
@Service @Service
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig> implements SysConfigService { public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig> implements SysConfigService {
/** /**
* 根据配置key获取对应value * 根据配置key获取对应value
* * @param confKey 缓存对应key
* @param confKey 缓存对应key * @return confValue
* @return confValue */
*/ @Override
@Override public String getConfValueByKey(String confKey) {
public String getConfValueByKey(String confKey) { SysConfig sysConfig = baseMapper
SysConfig sysConfig = baseMapper.selectOne(Wrappers.<SysConfig>lambdaQuery().eq(SysConfig::getConfKey, confKey)); .selectOne(Wrappers.<SysConfig>lambdaQuery().eq(SysConfig::getConfKey, confKey));
return sysConfig == null ? "": sysConfig.getConfValue(); return sysConfig == null ? "" : sysConfig.getConfValue();
} }
} }

View File

@@ -20,30 +20,27 @@ import java.util.List;
@Service @Service
public class SysDictItemServiceImpl extends ServiceImpl<SysDictItemMapper, SysDictItem> implements SysDictItemService { public class SysDictItemServiceImpl extends ServiceImpl<SysDictItemMapper, SysDictItem> implements SysDictItemService {
/** /**
* 根据QueryObeject查询分页数据 * 根据QueryObeject查询分页数据
* @param page 分页参数 * @param page 分页参数
* @param dictCode 查询参数对象 * @param dictCode 查询参数对象
* @return 分页数据 * @return 分页数据
*/ */
@Override @Override
public IPage<SysDictItem> page(IPage<SysDictItem> page, String dictCode) { public IPage<SysDictItem> page(IPage<SysDictItem> page, String dictCode) {
LambdaQueryWrapper<SysDictItem> wrapper = Wrappers.<SysDictItem>lambdaQuery() LambdaQueryWrapper<SysDictItem> wrapper = Wrappers.<SysDictItem>lambdaQuery().eq(SysDictItem::getDictCode,
.eq(SysDictItem::getDictCode, dictCode); dictCode);
return baseMapper.selectPage(page, wrapper); return baseMapper.selectPage(page, wrapper);
} }
/**
/** * 根据Code查询对应字典项数据
* 根据Code查询对应字典项数据 * @param dictCode
* * @return
* @param dictCode */
* @return @Override
*/ public List<SysDictItem> getByDictCode(String dictCode) {
@Override return baseMapper.selectList(Wrappers.<SysDictItem>lambdaQuery().eq(SysDictItem::getDictCode, dictCode));
public List<SysDictItem> getByDictCode(String dictCode) { }
return baseMapper.selectList(Wrappers.<SysDictItem>lambdaQuery()
.eq(SysDictItem::getDictCode, dictCode));
}
} }

View File

@@ -25,61 +25,52 @@ import java.util.List;
@Service @Service
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> implements SysDictService { public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> implements SysDictService {
/** /**
* 根据QueryObeject查询分页数据 * 根据QueryObeject查询分页数据
* * @param page 分页参数
* @param page 分页参数 * @param qo 查询参数对象
* @param qo 查询参数对象 * @return 分页数据
* @return 分页数据 */
*/ @Override
@Override public IPage<SysDict> page(IPage<SysDict> page, SysDictQO qo) {
public IPage<SysDict> page(IPage<SysDict> page, SysDictQO qo) { LambdaQueryWrapper<SysDict> wrapper = Wrappers.<SysDict>lambdaQuery().eq(ObjectUtil.isNotNull(qo.getId()),
LambdaQueryWrapper<SysDict> wrapper = Wrappers.<SysDict>lambdaQuery() SysDict::getId, qo.getId());
.eq(ObjectUtil.isNotNull(qo.getId()), SysDict::getId, qo.getId()); return baseMapper.selectPage(page, wrapper);
return baseMapper.selectPage(page, wrapper); }
}
/** /**
* 根据字典标识查询 * 根据字典标识查询
* * @param dictCode 字典标识
* @param dictCode 字典标识 * @return 字典数据
* @return 字典数据 */
*/ @Override
@Override public SysDict getByCode(String dictCode) {
public SysDict getByCode(String dictCode) { return baseMapper.selectOne(Wrappers.<SysDict>lambdaQuery().eq(SysDict::getCode, dictCode));
return baseMapper.selectOne( }
Wrappers.<SysDict>lambdaQuery().eq(SysDict::getCode, dictCode)
);
}
/** /**
* 根据字典标识查询 * 根据字典标识查询
* * @param dictCode 字典标识
* @param dictCode 字典标识 * @return 字典数据
* @return 字典数据 */
*/ @Override
@Override public List<SysDict> getByCode(String[] dictCode) {
public List<SysDict> getByCode(String[] dictCode) { if (dictCode == null || dictCode.length == 0) {
if (dictCode == null || dictCode.length == 0) { return new ArrayList<>();
return new ArrayList<>(); }
} return baseMapper.selectList(Wrappers.<SysDict>lambdaQuery().in(SysDict::getCode, dictCode));
return baseMapper.selectList( }
Wrappers.<SysDict>lambdaQuery().in(SysDict::getCode, dictCode)
);
}
/** /**
* 更新字典HashCode * 更新字典HashCode
* * @param dictCode
* @param dictCode * @return
* @return */
*/ @Override
@Override public boolean updateHashCode(String dictCode) {
public boolean updateHashCode(String dictCode) { int flag = baseMapper.update(null, Wrappers.<SysDict>lambdaUpdate()
int flag = baseMapper.update(null, Wrappers.<SysDict>lambdaUpdate() .set(SysDict::getHashCode, IdUtil.fastSimpleUUID()).eq(SysDict::getCode, dictCode));
.set(SysDict::getHashCode, IdUtil.fastSimpleUUID()) return SqlHelper.retBool(flag);
.eq(SysDict::getCode, dictCode)); }
return SqlHelper.retBool(flag);
}
} }

View File

@@ -27,7 +27,9 @@ import java.util.List;
*/ */
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission> implements SysPermissionService { public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission>
implements SysPermissionService {
private final SysRolePermissionMapper sysRolePermissionMapper; private final SysRolePermissionMapper sysRolePermissionMapper;
@Override @Override
@@ -39,17 +41,16 @@ public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, S
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public boolean removePermissionById(Integer id) { public boolean removePermissionById(Integer id) {
// 查询父节点为当前节点的节点 // 查询父节点为当前节点的节点
List<SysPermission> permissionList = this.list(Wrappers.<SysPermission>query() List<SysPermission> permissionList = this
.lambda().eq(SysPermission::getParentId, id)); .list(Wrappers.<SysPermission>query().lambda().eq(SysPermission::getParentId, id));
if (CollUtil.isNotEmpty(permissionList)) { if (CollUtil.isNotEmpty(permissionList)) {
throw new BusinessException(BaseResultCode.LOGIC_CHECK_ERROR.getCode(), "菜单含有下级不能删除"); throw new BusinessException(BaseResultCode.LOGIC_CHECK_ERROR.getCode(), "菜单含有下级不能删除");
} }
sysRolePermissionMapper sysRolePermissionMapper
.delete(Wrappers.<SysRolePermission>query() .delete(Wrappers.<SysRolePermission>query().lambda().eq(SysRolePermission::getPermissionId, id));
.lambda().eq(SysRolePermission::getPermissionId, id));
//删除当前菜单及其子菜单 // 删除当前菜单及其子菜单
return this.removeById(id); return this.removeById(id);
} }
@@ -57,4 +58,5 @@ public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, S
public Boolean updatePermissionById(SysPermission sysPermission) { public Boolean updatePermissionById(SysPermission sysPermission) {
return this.updateById(sysPermission); return this.updateById(sysPermission);
} }
} }

View File

@@ -1,5 +1,4 @@
package com.hccake.ballcat.admin.modules.sys.service.impl; package com.hccake.ballcat.admin.modules.sys.service.impl;
import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.core.toolkit.Wrappers;
@@ -22,31 +21,30 @@ import java.util.stream.Collectors;
* @author * @author
*/ */
@Service @Service
public class SysRolePermissionServiceImpl extends ServiceImpl<SysRolePermissionMapper, SysRolePermission> implements SysRolePermissionService { public class SysRolePermissionServiceImpl extends ServiceImpl<SysRolePermissionMapper, SysRolePermission>
implements SysRolePermissionService {
/** /**
* @param roleId 角色 * @param roleId 角色
* @param permissionIds 权限ID集合 * @param permissionIds 权限ID集合
* @return * @return
*/ */
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public Boolean saveRolePermissions(Integer roleId, Integer[] permissionIds) { public Boolean saveRolePermissions(Integer roleId, Integer[] permissionIds) {
this.remove(Wrappers.<SysRolePermission>query().lambda() this.remove(Wrappers.<SysRolePermission>query().lambda().eq(SysRolePermission::getRoleId, roleId));
.eq(SysRolePermission::getRoleId, roleId));
if (permissionIds == null || permissionIds.length == 0) { if (permissionIds == null || permissionIds.length == 0) {
return Boolean.TRUE; return Boolean.TRUE;
} }
List<SysRolePermission> rolePermissionList = Arrays List<SysRolePermission> rolePermissionList = Arrays.stream(permissionIds).map(permissionId -> {
.stream(permissionIds) SysRolePermission rolePermission = new SysRolePermission();
.map(permissionId -> { rolePermission.setRoleId(roleId);
SysRolePermission rolePermission = new SysRolePermission(); rolePermission.setPermissionId(permissionId);
rolePermission.setRoleId(roleId); return rolePermission;
rolePermission.setPermissionId(permissionId); }).collect(Collectors.toList());
return rolePermission;
}).collect(Collectors.toList());
return this.saveBatch(rolePermissionList); return this.saveBatch(rolePermissionList);
} }
} }

View File

@@ -29,47 +29,45 @@ import java.util.List;
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService { public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
private final SysRolePermissionMapper sysRolePermissionMapper;
/** private final SysRolePermissionMapper sysRolePermissionMapper;
* 查询系统角色列表
*
* @param page 分页对象
* @param qo 查询参数
* @return 分页对象
*/
@Override
public IPage<SysRole> page(IPage<SysRole> page, SysRoleQO qo) {
LambdaQueryWrapper<SysRole> wrapper = Wrappers.<SysRole>lambdaQuery()
.like(StrUtil.isNotBlank(qo.getName()), SysRole::getName, qo.getName())
.like(StrUtil.isNotBlank(qo.getCode()), SysRole::getCode, qo.getCode())
.between(StrUtil.isNotBlank(qo.getStartTime()) && StrUtil.isNotBlank(qo.getEndTime()),
SysRole::getCreateTime, qo.getStartTime(), qo.getEndTime());
return baseMapper.selectPage(page, wrapper);
}
/** /**
* 通过角色ID删除角色,并清空角色菜单缓存 * 查询系统角色列表
* * @param page 分页对象
* @param id * @param qo 查询参数
* @return * @return 分页对象
*/ */
@Override @Override
@Transactional(rollbackFor = Exception.class) public IPage<SysRole> page(IPage<SysRole> page, SysRoleQO qo) {
public Boolean removeRoleById(Integer id) { LambdaQueryWrapper<SysRole> wrapper = Wrappers.<SysRole>lambdaQuery()
sysRolePermissionMapper.delete(Wrappers .like(StrUtil.isNotBlank(qo.getName()), SysRole::getName, qo.getName())
.<SysRolePermission>update().lambda() .like(StrUtil.isNotBlank(qo.getCode()), SysRole::getCode, qo.getCode())
.eq(SysRolePermission::getRoleId, id)); .between(StrUtil.isNotBlank(qo.getStartTime()) && StrUtil.isNotBlank(qo.getEndTime()),
return this.removeById(id); SysRole::getCreateTime, qo.getStartTime(), qo.getEndTime());
} return baseMapper.selectPage(page, wrapper);
}
/**
* 通过角色ID删除角色,并清空角色菜单缓存
* @param id
* @return
*/
@Override
@Transactional(rollbackFor = Exception.class)
public Boolean removeRoleById(Integer id) {
sysRolePermissionMapper
.delete(Wrappers.<SysRolePermission>update().lambda().eq(SysRolePermission::getRoleId, id));
return this.removeById(id);
}
/**
* 角色的选择数据
* @return
*/
@Override
public List<SelectData> getSelectData() {
return baseMapper.getSelectData();
}
/**
* 角色的选择数据
*
* @return
*/
@Override
public List<SelectData> getSelectData() {
return baseMapper.getSelectData();
}
} }

View File

@@ -13,6 +13,7 @@ import java.util.List;
/** /**
* 用户角色关联关系表 * 用户角色关联关系表
*
* @author Hccake * @author Hccake
*/ */
@Service @Service
@@ -30,7 +31,6 @@ public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUs
/** /**
* 插入用户角色关联关系 * 插入用户角色关联关系
*
* @param userId * @param userId
* @param roleIds * @param roleIds
* @return * @return
@@ -42,7 +42,6 @@ public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUs
/** /**
* 更新用户关联关系 * 更新用户关联关系
*
* @param userId * @param userId
* @param roleIds * @param roleIds
*/ */
@@ -51,16 +50,14 @@ public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUs
public boolean updateUserRoles(Integer userId, List<Integer> roleIds) { public boolean updateUserRoles(Integer userId, List<Integer> roleIds) {
// 先清空,后插入 // 先清空,后插入
baseMapper.deleteByUserId(userId); baseMapper.deleteByUserId(userId);
if(CollectionUtil.isNotEmpty(roleIds)){ if (CollectionUtil.isNotEmpty(roleIds)) {
baseMapper.insertUserRoles(userId, roleIds); baseMapper.insertUserRoles(userId, roleIds);
} }
return true; return true;
} }
/** /**
* 通过用户ID 获取用户所有角色ID * 通过用户ID 获取用户所有角色ID
*
* @param userId * @param userId
* @return * @return
*/ */

View File

@@ -51,218 +51,195 @@ import java.util.stream.Collectors;
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService { public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
private final FileService fileService;
private final SysPermissionService sysPermissionService;
private final SysUserRoleService sysUserRoleService;
private final FileService fileService;
@Value("${password.secret-key}") private final SysPermissionService sysPermissionService;
private String secretKey;
private final SysUserRoleService sysUserRoleService;
@Override @Value("${password.secret-key}")
public IPage<SysUser> page(IPage<SysUser> page, SysUserQO qo) { private String secretKey;
LambdaQueryWrapper<SysUser> wrapper = Wrappers.<SysUser>lambdaQuery() @Override
.like(ObjectUtil.isNotNull(qo.getUsername()), SysUser::getUsername, qo.getUsername()) public IPage<SysUser> page(IPage<SysUser> page, SysUserQO qo) {
.like(ObjectUtil.isNotNull(qo.getEmail()), SysUser::getEmail, qo.getEmail())
.like(ObjectUtil.isNotNull(qo.getPhone()), SysUser::getPhone, qo.getPhone())
.like(ObjectUtil.isNotNull(qo.getNickname()), SysUser::getNickname, qo.getNickname())
.eq(ObjectUtil.isNotNull(qo.getStatus()), SysUser::getStatus, qo.getStatus())
.eq(ObjectUtil.isNotNull(qo.getSex()), SysUser::getSex, qo.getSex())
.eq(ObjectUtil.isNotNull(qo.getType()), SysUser::getType, qo.getType());
if (StringUtils.isNotBlank(qo.getStartTime()) && StringUtils.isNotBlank(qo.getEndTime())) {
wrapper.between(SysUser::getCreateTime, qo.getStartTime(), qo.getEndTime());
}
return baseMapper.selectPage(page, wrapper); LambdaQueryWrapper<SysUser> wrapper = Wrappers.<SysUser>lambdaQuery()
} .like(ObjectUtil.isNotNull(qo.getUsername()), SysUser::getUsername, qo.getUsername())
.like(ObjectUtil.isNotNull(qo.getEmail()), SysUser::getEmail, qo.getEmail())
.like(ObjectUtil.isNotNull(qo.getPhone()), SysUser::getPhone, qo.getPhone())
.like(ObjectUtil.isNotNull(qo.getNickname()), SysUser::getNickname, qo.getNickname())
.eq(ObjectUtil.isNotNull(qo.getStatus()), SysUser::getStatus, qo.getStatus())
.eq(ObjectUtil.isNotNull(qo.getSex()), SysUser::getSex, qo.getSex())
.eq(ObjectUtil.isNotNull(qo.getType()), SysUser::getType, qo.getType());
if (StringUtils.isNotBlank(qo.getStartTime()) && StringUtils.isNotBlank(qo.getEndTime())) {
wrapper.between(SysUser::getCreateTime, qo.getStartTime(), qo.getEndTime());
}
return baseMapper.selectPage(page, wrapper);
}
/** /**
* 根据用户名查询用户 * 根据用户名查询用户
* * @param username
* @param username * @return
* @return */
*/ @Override
@Override public SysUser getByUsername(String username) {
public SysUser getByUsername(String username) { return baseMapper.selectOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, username));
return baseMapper.selectOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, username)); }
}
/**
* 通过查用户的全部信息
* @param sysUser 用户
* @return
*/
@Override
public UserInfo findUserInfo(SysUser sysUser) {
UserInfo userInfo = new UserInfo();
userInfo.setSysUser(sysUser);
// 设置角色列表 ID
List<SysRole> roleList = sysUserRoleService.getRoles(sysUser.getUserId());
/** List<Integer> roleIds = new ArrayList<>();
* 通过查用户的全部信息 List<String> roles = new ArrayList<>();
* for (SysRole role : roleList) {
* @param sysUser 用户 roleIds.add(role.getId());
* @return roles.add(role.getCode());
*/ }
@Override
public UserInfo findUserInfo(SysUser sysUser) {
UserInfo userInfo = new UserInfo();
userInfo.setSysUser(sysUser);
// 设置角色列表 ID
List<SysRole> roleList = sysUserRoleService.getRoles(sysUser.getUserId());
List<Integer> roleIds = new ArrayList<>(); userInfo.setRoles(roles);
List<String> roles = new ArrayList<>(); userInfo.setRoleIds(roleIds);
for (SysRole role : roleList) {
roleIds.add(role.getId());
roles.add(role.getCode());
}
userInfo.setRoles(roles); // 设置权限列表permission
userInfo.setRoleIds(roleIds); Set<String> permissions = new HashSet<>();
roleIds.forEach(roleId -> {
List<String> permissionList = sysPermissionService.findPermissionVOByRoleId(roleId).stream()
.filter(sysPermission -> StrUtil.isNotEmpty(sysPermission.getCode())).map(PermissionVO::getCode)
.collect(Collectors.toList());
permissions.addAll(permissionList);
});
userInfo.setPermissions(new ArrayList<>(permissions));
return userInfo;
}
// 设置权限列表permission /**
Set<String> permissions = new HashSet<>(); * 新增系统用户
roleIds.forEach(roleId -> { * @param sysUserDto
List<String> permissionList = sysPermissionService.findPermissionVOByRoleId(roleId) * @return
.stream() */
.filter(sysPermission -> StrUtil.isNotEmpty(sysPermission.getCode())) @Override
.map(PermissionVO::getCode) public boolean addSysUser(SysUserDTO sysUserDto) {
.collect(Collectors.toList()); SysUser sysUser = SysUserConverter.INSTANCE.dtoToPo(sysUserDto);
permissions.addAll(permissionList); sysUser.setStatus(SysUserConst.Status.NORMAL.getValue());
}); sysUser.setType(SysUserConst.Type.SYSTEM.getValue());
userInfo.setPermissions(new ArrayList<>(permissions)); sysUser.setDeleted(GlobalConstants.NOT_DELETED_FLAG);
return userInfo;
}
String password = PasswordUtil.decodeAesAndEncodeBCrypt(sysUserDto.getPass(), secretKey);
sysUser.setPassword(password);
/** return SqlHelper.retBool(baseMapper.insert(sysUser));
* 新增系统用户 }
*
* @param sysUserDto
* @return
*/
@Override
public boolean addSysUser(SysUserDTO sysUserDto) {
SysUser sysUser = SysUserConverter.INSTANCE.dtoToPo(sysUserDto);
sysUser.setStatus(SysUserConst.Status.NORMAL.getValue());
sysUser.setType(SysUserConst.Type.SYSTEM.getValue());
sysUser.setDeleted(GlobalConstants.NOT_DELETED_FLAG);
String password = PasswordUtil.decodeAesAndEncodeBCrypt(sysUserDto.getPass(), secretKey); /**
sysUser.setPassword(password); * 更新系统用户信息
* @param sysUserDTO
* @return
*/
@Override
public boolean updateSysUser(SysUserDTO sysUserDTO) {
SysUser entity = SysUserConverter.INSTANCE.dtoToPo(sysUserDTO);
return SqlHelper.retBool(baseMapper.updateById(entity));
}
return SqlHelper.retBool(baseMapper.insert(sysUser)); /**
} * 更新用户权限信息
* @param userId
* @param sysUserScope
* @return
*/
@Override
@Transactional(rollbackFor = Exception.class)
public boolean updateUserScope(Integer userId, SysUserScope sysUserScope) {
// 更新用户角色关联关系
// TODO 在这里实现 自己业务 模块的权限控制
return sysUserRoleService.updateUserRoles(userId, sysUserScope.getRoleIds());
/** }
* 更新系统用户信息
*
* @param sysUserDTO
* @return
*/
@Override
public boolean updateSysUser(SysUserDTO sysUserDTO) {
SysUser entity = SysUserConverter.INSTANCE.dtoToPo(sysUserDTO);
return SqlHelper.retBool(baseMapper.updateById(entity));
}
/** /**
* 更新用户权限信息 * 根据userId删除 用户
* * @param userId
* * @return
* @param userId */
* @param sysUserScope @Override
* @return public boolean deleteByUserId(Integer userId) {
*/ // TODO 缓存控制
@Override return SqlHelper.retBool(baseMapper.deleteById(userId));
@Transactional(rollbackFor = Exception.class) }
public boolean updateUserScope(Integer userId, SysUserScope sysUserScope) {
// 更新用户角色关联关系
// TODO 在这里实现 自己业务 模块的权限控制
return sysUserRoleService.updateUserRoles(userId, sysUserScope.getRoleIds());
} /**
* 修改用户密码
* @param userId
* @param pass
* @return
*/
@Override
public boolean updateUserPass(Integer userId, String pass) {
/** String password = PasswordUtil.decodeAesAndEncodeBCrypt(pass, secretKey);
* 根据userId删除 用户
*
* @param userId
* @return
*/
@Override
public boolean deleteByUserId(Integer userId) {
// TODO 缓存控制
return SqlHelper.retBool(baseMapper.deleteById(userId));
}
/** int res = baseMapper.update(null,
* 修改用户密码 Wrappers.<SysUser>lambdaUpdate().eq(SysUser::getUserId, userId).set(SysUser::getPassword, password));
*
* @param userId
* @param pass
* @return
*/
@Override
public boolean updateUserPass(Integer userId, String pass) {
String password = PasswordUtil.decodeAesAndEncodeBCrypt(pass, secretKey); return SqlHelper.retBool(res);
}
int res = baseMapper.update(null, Wrappers.<SysUser>lambdaUpdate() /**
.eq(SysUser::getUserId, userId) * 批量修改用户状态
.set(SysUser::getPassword, password) * @param userIds
); * @return
*/
@Override
public boolean updateUserStatus(List<Integer> userIds, Integer status) {
return this.update(
Wrappers.<SysUser>lambdaUpdate().set(SysUser::getStatus, status).in(SysUser::getUserId, userIds));
}
return SqlHelper.retBool(res); @Override
} @Transactional(rollbackFor = Exception.class)
public String updateAvatar(MultipartFile file, Integer userId) throws IOException {
// 获取系统用户头像的文件名
String objectName = "sysuser/" + userId + "/avatar/" + LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE)
+ StrUtil.SLASH + IdUtil.fastSimpleUUID() + StrUtil.DOT + FileUtil.extName(file.getOriginalFilename());
fileService.uploadFile(file, objectName);
/** SysUser sysUser = new SysUser();
* 批量修改用户状态 sysUser.setUserId(userId);
* sysUser.setAvatar(objectName);
* @param userIds baseMapper.updateById(sysUser);
* @return
*/
@Override
public boolean updateUserStatus(List<Integer> userIds, Integer status) {
return this.update(Wrappers.<SysUser>lambdaUpdate()
.set(SysUser::getStatus, status)
.in(SysUser::getUserId, userIds)
);
}
@Override return objectName;
@Transactional(rollbackFor = Exception.class) }
public String updateAvatar(MultipartFile file, Integer userId) throws IOException {
// 获取系统用户头像的文件名
String objectName = "sysuser/" + userId + "/avatar/"
+ LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE) + StrUtil.SLASH
+ IdUtil.fastSimpleUUID() + StrUtil.DOT + FileUtil.extName(file.getOriginalFilename());
fileService.uploadFile(file, objectName);
SysUser sysUser = new SysUser(); /**
sysUser.setUserId(userId); * 根据角色查询用户
sysUser.setAvatar(objectName); * @return
baseMapper.updateById(sysUser); * @param roleCode
*/
@Override
public List<SysUser> selectUsersByRoleCode(String roleCode) {
return baseMapper.selectUsersByRoleCode(roleCode);
}
return objectName; /**
} * 返回用户的select数据 name=> username value => userId
* @return List<SelectData>
/** */
* 根据角色查询用户 @Override
* public List<SelectData> getSelectData(Integer type) {
* @return
* @param roleCode
*/
@Override
public List<SysUser> selectUsersByRoleCode(String roleCode) {
return baseMapper.selectUsersByRoleCode(roleCode);
}
/**
* 返回用户的select数据
* name=> username
* value => userId
*
* @return List<SelectData>
*/
@Override
public List<SelectData> getSelectData(Integer type) {
return baseMapper.getSelectData(type);
}
return baseMapper.getSelectData(type);
}
} }

View File

@@ -20,16 +20,18 @@ import java.io.IOException;
* @date 2019/9/25 22:04 * @date 2019/9/25 22:04
*/ */
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint { public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Autowired
private ObjectMapper objectMapper;
@Override @Autowired
public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException { private ObjectMapper objectMapper;
@Override
public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
AuthenticationException e) throws IOException, ServletException {
httpServletResponse.setHeader("Content-Type", MediaType.APPLICATION_JSON.toString());
httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
httpServletResponse.getWriter()
.write(objectMapper.writeValueAsString(R.failed(SystemResultCode.UNAUTHORIZED, e.getMessage())));
}
httpServletResponse.setHeader("Content-Type", MediaType.APPLICATION_JSON.toString());
httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
httpServletResponse.getWriter().write(
objectMapper.writeValueAsString(R.failed(SystemResultCode.UNAUTHORIZED, e.getMessage()))
);
}
} }

View File

@@ -20,7 +20,6 @@ public class CustomPermissionEvaluator {
/** /**
* 判断接口是否有xxx:xxx权限 * 判断接口是否有xxx:xxx权限
*
* @param permission 权限 * @param permission 权限
* @return {boolean} * @return {boolean}
*/ */
@@ -33,9 +32,8 @@ public class CustomPermissionEvaluator {
return false; return false;
} }
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
return authorities.stream() return authorities.stream().map(GrantedAuthority::getAuthority).filter(StringUtils::hasText)
.map(GrantedAuthority::getAuthority) .anyMatch(x -> PatternMatchUtils.simpleMatch(permission, x));
.filter(StringUtils::hasText)
.anyMatch(x -> PatternMatchUtils.simpleMatch(permission, x));
} }
} }

View File

@@ -11,30 +11,30 @@ import java.util.Map;
/** /**
* @author Hccake * @author Hccake
* @version 1.0 * @version 1.0
* @date 2019/9/27 21:42 * @date 2019/9/27 21:42 自定义 Token 增强器
* 自定义 Token 增强器
*/ */
public class CustomTokenEnhancer implements TokenEnhancer { public class CustomTokenEnhancer implements TokenEnhancer {
/** /**
* 处理 token 增强 * 处理 token 增强
* @param accessToken * @param accessToken
* @param authentication * @param authentication
* @return * @return
*/ */
@Override @Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
final Map<String, Object> additionalInfo = new HashMap<>(8); final Map<String, Object> additionalInfo = new HashMap<>(8);
Object principal = authentication.getUserAuthentication().getPrincipal(); Object principal = authentication.getUserAuthentication().getPrincipal();
SysUserDetails sysUserDetails = (SysUserDetails) principal; SysUserDetails sysUserDetails = (SysUserDetails) principal;
additionalInfo.put("info", sysUserDetails.getSysUser()); additionalInfo.put("info", sysUserDetails.getSysUser());
additionalInfo.put("roles", sysUserDetails.getRoles()); additionalInfo.put("roles", sysUserDetails.getRoles());
additionalInfo.put("permissions", sysUserDetails.getPermissions()); additionalInfo.put("permissions", sysUserDetails.getPermissions());
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo); ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
return accessToken;
}
return accessToken;
}
} }

View File

@@ -16,24 +16,27 @@ import java.util.List;
*/ */
public class SysUserDetails implements UserDetails { public class SysUserDetails implements UserDetails {
private final SysUser sysUser; private final SysUser sysUser;
private final Collection<? extends GrantedAuthority> authorities; private final Collection<? extends GrantedAuthority> authorities;
/** /**
* 权限标识集合 * 权限标识集合
*/ */
private final List<String> permissions; private final List<String> permissions;
/**
* 角色集合
*/
private final List<String> roles;
/**
* 角色ID集合
*/
private final List<Integer> roleIds;
public SysUserDetails(SysUser sysUser, List<String> roles, List<Integer> roleIds, List<String> permissions, Collection<? extends GrantedAuthority> authorities) { /**
* 角色集合
*/
private final List<String> roles;
/**
* 角色ID集合
*/
private final List<Integer> roleIds;
public SysUserDetails(SysUser sysUser, List<String> roles, List<Integer> roleIds, List<String> permissions,
Collection<? extends GrantedAuthority> authorities) {
this.sysUser = sysUser; this.sysUser = sysUser;
this.authorities = authorities; this.authorities = authorities;
this.roles = roles; this.roles = roles;
@@ -41,54 +44,55 @@ public class SysUserDetails implements UserDetails {
this.permissions = permissions; this.permissions = permissions;
} }
@Override @Override
public Collection<? extends GrantedAuthority> getAuthorities() { public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities; return authorities;
} }
@Override @Override
public String getPassword() { public String getPassword() {
return sysUser.getPassword(); return sysUser.getPassword();
} }
@Override @Override
public String getUsername() { public String getUsername() {
return sysUser.getUsername(); return sysUser.getUsername();
} }
@Override @Override
public boolean isAccountNonExpired() { public boolean isAccountNonExpired() {
return true; return true;
} }
@Override @Override
public boolean isAccountNonLocked() { public boolean isAccountNonLocked() {
return GlobalConstants.NOT_DELETED_FLAG.equals(sysUser.getDeleted()); return GlobalConstants.NOT_DELETED_FLAG.equals(sysUser.getDeleted());
} }
@Override @Override
public boolean isCredentialsNonExpired() { public boolean isCredentialsNonExpired() {
return true; return true;
} }
@Override @Override
public boolean isEnabled() { public boolean isEnabled() {
return SysUserConst.Status.NORMAL.getValue().equals(sysUser.getStatus()); return SysUserConst.Status.NORMAL.getValue().equals(sysUser.getStatus());
} }
public SysUser getSysUser() { public SysUser getSysUser() {
return sysUser; return sysUser;
} }
public List<String> getPermissions() { public List<String> getPermissions() {
return permissions; return permissions;
} }
public List<String> getRoles() { public List<String> getRoles() {
return roles; return roles;
} }
public List<Integer> getRoleIds() {
return roleIds;
}
public List<Integer> getRoleIds() {
return roleIds;
}
} }

View File

@@ -27,44 +27,45 @@ import java.util.Set;
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
public class SysUserDetailsServiceImpl implements UserDetailsService { public class SysUserDetailsServiceImpl implements UserDetailsService {
private final SysUserService sysUserService;
@Override private final SysUserService sysUserService;
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
SysUser sysUser = sysUserService.getByUsername(username);
if(sysUser == null){
log.error("登陆:用户名错误,用户名:{}", username);
throw new UsernameNotFoundException("username error!");
}
UserInfo userInfo = sysUserService.findUserInfo(sysUser);
return getUserDetailsByUserInfo(userInfo);
}
/** @Override
* 根据UserInfo 获取 UserDetails public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
* @param userInfo SysUser sysUser = sysUserService.getByUsername(username);
* @return if (sysUser == null) {
*/ log.error("登陆:用户名错误,用户名:{}", username);
private UserDetails getUserDetailsByUserInfo(UserInfo userInfo) { throw new UsernameNotFoundException("username error!");
}
UserInfo userInfo = sysUserService.findUserInfo(sysUser);
return getUserDetailsByUserInfo(userInfo);
}
SysUser user = userInfo.getSysUser(); /**
List<String> roles = userInfo.getRoles(); * 根据UserInfo 获取 UserDetails
List<Integer> roleIds = userInfo.getRoleIds(); * @param userInfo
List<String> permissions = userInfo.getPermissions(); * @return
*/
private UserDetails getUserDetailsByUserInfo(UserInfo userInfo) {
Set<String> dbAuthsSet = new HashSet<>(); SysUser user = userInfo.getSysUser();
if (CollectionUtil.isNotEmpty(roles)) { List<String> roles = userInfo.getRoles();
// 获取角色 List<Integer> roleIds = userInfo.getRoleIds();
dbAuthsSet.addAll(roles); List<String> permissions = userInfo.getPermissions();
// 获取资源
dbAuthsSet.addAll(permissions);
} Set<String> dbAuthsSet = new HashSet<>();
Collection<? extends GrantedAuthority> authorities if (CollectionUtil.isNotEmpty(roles)) {
= AuthorityUtils.createAuthorityList(dbAuthsSet.toArray(new String[0])); // 获取角色
dbAuthsSet.addAll(roles);
// 获取资源
dbAuthsSet.addAll(permissions);
return new SysUserDetails(user, roles, roleIds, permissions, authorities); }
Collection<? extends GrantedAuthority> authorities = AuthorityUtils
.createAuthorityList(dbAuthsSet.toArray(new String[0]));
} return new SysUserDetails(user, roles, roleIds, permissions, authorities);
}
} }

View File

@@ -31,97 +31,92 @@ import java.util.List;
/** /**
* @author Hccake * @author Hccake
* @version 1.0 * @version 1.0
* @date 2019/9/27 16:14 * @date 2019/9/27 16:14 OAuth2 授权服务器配置
* OAuth2 授权服务器配置
*/ */
@Configuration @Configuration
@EnableAuthorizationServer @EnableAuthorizationServer
@RequiredArgsConstructor @RequiredArgsConstructor
public class CustomAuthorizationServerConfigurer implements AuthorizationServerConfigurer { public class CustomAuthorizationServerConfigurer implements AuthorizationServerConfigurer {
private final DataSource dataSource;
private final SysUserDetailsServiceImpl sysUserDetailsService;
private final AuthenticationManager authenticationManager;
private final RedisConnectionFactory redisConnectionFactory;
private final AuthenticationEntryPoint authenticationEntryPoint;
private final CustomWebResponseExceptionTranslator customWebResponseExceptionTranslator;
/** private final DataSource dataSource;
* 定义资源权限控制的配置
*
* @param security
* @throws Exception
*/
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security
.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()")
.authenticationEntryPoint(authenticationEntryPoint)
.allowFormAuthenticationForClients();
}
/** private final SysUserDetailsServiceImpl sysUserDetailsService;
* 客户端的信息服务类配置
*
* @param clients
* @throws Exception
*/
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// 启用 jdbc 方式获取客户端配置信息
clients.jdbc(dataSource);
}
/** private final AuthenticationManager authenticationManager;
* 授权服务的访问路径相关配置
*
* @param endpoints
* @throws Exception
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore())
.userDetailsService(sysUserDetailsService)
.authenticationManager(authenticationManager)
// 自定义token
.tokenEnhancer(tokenEnhancer())
// 强制刷新token时重新生成refreshToken
.reuseRefreshTokens(false)
// 自定义的认证时异常转换
.exceptionTranslator(customWebResponseExceptionTranslator)
// 自定义tokenGranter
.tokenGranter(tokenGranter(endpoints));
}
private final RedisConnectionFactory redisConnectionFactory;
/** private final AuthenticationEntryPoint authenticationEntryPoint;
* 定义token的存储方式
* @return
*/
@Bean
public TokenStore tokenStore() {
RedisTokenStore tokenStore = new RedisTokenStore(redisConnectionFactory);
tokenStore.setPrefix(CachePropertiesHolder.keyPrefix() + SecurityConst.OAUTH_PREFIX);
return tokenStore;
}
private final CustomWebResponseExceptionTranslator customWebResponseExceptionTranslator;
/** /**
* token 增强,追加一些自定义信息 * 定义资源权限控制的配置
* @return TokenEnhancer Token增强处理器 * @param security
*/ * @throws Exception
@Bean */
public TokenEnhancer tokenEnhancer() { @Override
return new CustomTokenEnhancer(); public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
} security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()")
.authenticationEntryPoint(authenticationEntryPoint).allowFormAuthenticationForClients();
}
/**
* 客户端的信息服务类配置
* @param clients
* @throws Exception
*/
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// 启用 jdbc 方式获取客户端配置信息
clients.jdbc(dataSource);
}
private TokenGranter tokenGranter(final AuthorizationServerEndpointsConfigurer endpoints) { /**
// 获取默认的granter集合 * 授权服务的访问路径相关配置
List<TokenGranter> granters = new ArrayList<>(Collections.singletonList(endpoints.getTokenGranter())); * @param endpoints
granters.add(new MobileTokenGranter(authenticationManager,endpoints.getTokenServices(), endpoints.getClientDetailsService(), endpoints.getOAuth2RequestFactory())); * @throws Exception
return new CompositeTokenGranter(granters); */
} @Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore()).userDetailsService(sysUserDetailsService)
.authenticationManager(authenticationManager)
// 自定义token
.tokenEnhancer(tokenEnhancer())
// 强制刷新token时重新生成refreshToken
.reuseRefreshTokens(false)
// 自定义的认证时异常转换
.exceptionTranslator(customWebResponseExceptionTranslator)
// 自定义tokenGranter
.tokenGranter(tokenGranter(endpoints));
}
/**
* 定义token的存储方式
* @return
*/
@Bean
public TokenStore tokenStore() {
RedisTokenStore tokenStore = new RedisTokenStore(redisConnectionFactory);
tokenStore.setPrefix(CachePropertiesHolder.keyPrefix() + SecurityConst.OAUTH_PREFIX);
return tokenStore;
}
/**
* token 增强,追加一些自定义信息
* @return TokenEnhancer Token增强处理器
*/
@Bean
public TokenEnhancer tokenEnhancer() {
return new CustomTokenEnhancer();
}
private TokenGranter tokenGranter(final AuthorizationServerEndpointsConfigurer endpoints) {
// 获取默认的granter集合
List<TokenGranter> granters = new ArrayList<>(Collections.singletonList(endpoints.getTokenGranter()));
granters.add(new MobileTokenGranter(authenticationManager, endpoints.getTokenServices(),
endpoints.getClientDetailsService(), endpoints.getOAuth2RequestFactory()));
return new CompositeTokenGranter(granters);
}
} }

View File

@@ -14,53 +14,48 @@ import org.springframework.security.web.AuthenticationEntryPoint;
/** /**
* @author Hccake * @author Hccake
* @version 1.0 * @version 1.0
* @date 2019/9/27 17:28 * @date 2019/9/27 17:28 资源服务器配置
* 资源服务器配置
*/ */
@Configuration @Configuration
@EnableResourceServer @EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true) @EnableGlobalMethodSecurity(prePostEnabled = true)
@RequiredArgsConstructor @RequiredArgsConstructor
public class CustomResourceServerConfigurer extends ResourceServerConfigurerAdapter { public class CustomResourceServerConfigurer extends ResourceServerConfigurerAdapter {
private final AuthenticationEntryPoint authenticationEntryPoint;
private final PermitAllUrlProperties permitAllUrlProperties;
private final AuthenticationEntryPoint authenticationEntryPoint;
/** private final PermitAllUrlProperties permitAllUrlProperties;
* Add resource-server specific properties (like a resource id). The defaults should work for many applications, but
* you might want to change at least the resource id.
*
* @param resources configurer for the resource server
* @throws Exception if there is a problem
*/
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
// 配置自定义异常处理
resources
.authenticationEntryPoint(authenticationEntryPoint);
}
/** /**
* 通过重载,配置如何通过拦截器保护请求 * Add resource-server specific properties (like a resource id). The defaults should
* @param http * work for many applications, but you might want to change at least the resource id.
* @throws Exception * @param resources configurer for the resource server
*/ * @throws Exception if there is a problem
@Override */
public void configure(HttpSecurity http) throws Exception { @Override
http public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
// 拦截 url 配置 // 配置自定义异常处理
.authorizeRequests() resources.authenticationEntryPoint(authenticationEntryPoint);
.antMatchers(ArrayUtil.toArray(permitAllUrlProperties.getIgnoreUrls(), String.class)) }
.permitAll()
.anyRequest().authenticated()
/**
* 通过重载,配置如何通过拦截器保护请求
* @param http
* @throws Exception
*/
@Override
public void configure(HttpSecurity http) throws Exception {
http
// 拦截 url 配置
.authorizeRequests()
.antMatchers(ArrayUtil.toArray(permitAllUrlProperties.getIgnoreUrls(), String.class)).permitAll()
.anyRequest().authenticated()
// 使用token鉴权时 关闭 session 缓存 // 使用token鉴权时 关闭 session 缓存
.and() .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
// 关闭 csrf 跨站攻击防护
.and().csrf().disable();
}
// 关闭 csrf 跨站攻击防护
.and()
.csrf().disable();
}
} }

View File

@@ -12,14 +12,15 @@ import java.util.List;
/** /**
* @author Hccake * @author Hccake
* @version 1.0 * @version 1.0
* @date 2020/2/18 10:55 * @date 2020/2/18 10:55 资源服务器忽略鉴权的url地址
* 资源服务器忽略鉴权的url地址
*/ */
@Slf4j @Slf4j
@Configuration @Configuration
@ConfigurationProperties(prefix = "security.oauth2") @ConfigurationProperties(prefix = "security.oauth2")
public class PermitAllUrlProperties { public class PermitAllUrlProperties {
@Getter
@Setter @Getter
private List<String> ignoreUrls = new ArrayList<>(); @Setter
private List<String> ignoreUrls = new ArrayList<>();
} }

View File

@@ -22,40 +22,39 @@ import org.springframework.security.web.AuthenticationEntryPoint;
@Configuration @Configuration
@RequiredArgsConstructor @RequiredArgsConstructor
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
private final UserDetailsService userDetailsService;
/** private final UserDetailsService userDetailsService;
* 密码解析器
* @return
*/
@Bean
protected PasswordEncoder passwordEncoder() {
return PasswordUtil.ENCODER;
}
/**
* 密码解析器
* @return
*/
@Bean
protected PasswordEncoder passwordEncoder() {
return PasswordUtil.ENCODER;
}
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
MobileAuthenticationProvider mobileAuthenticationProvider = new MobileAuthenticationProvider(); MobileAuthenticationProvider mobileAuthenticationProvider = new MobileAuthenticationProvider();
mobileAuthenticationProvider.setUserDetailsService(userDetailsService); mobileAuthenticationProvider.setUserDetailsService(userDetailsService);
http.authenticationProvider(mobileAuthenticationProvider); http.authenticationProvider(mobileAuthenticationProvider);
} }
/** /**
* 解决无法注入 authenticationManagerBean 的问题 * 解决无法注入 authenticationManagerBean 的问题
* * @return
* @return * @throws Exception
* @throws Exception */
*/ @Override
@Override @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
@Bean(name = BeanIds.AUTHENTICATION_MANAGER) public AuthenticationManager authenticationManagerBean() throws Exception {
public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean();
return super.authenticationManagerBean(); }
}
@Bean
public AuthenticationEntryPoint authenticationEntryPoint() {
return new CustomAuthenticationEntryPoint();
}
@Bean
public AuthenticationEntryPoint authenticationEntryPoint(){
return new CustomAuthenticationEntryPoint();
}
} }

View File

@@ -6,17 +6,17 @@ import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
/** /**
* @author Hccake * @author Hccake
* @version 1.0 * @version 1.0
* @date 2019/9/29 10:31 * @date 2019/9/29 10:31 自定义的异常处理
* 自定义的异常处理
*/ */
@JsonSerialize(using = CustomOAuth2ExceptionSerializer.class) @JsonSerialize(using = CustomOAuth2ExceptionSerializer.class)
public class CustomOAuth2Exception extends OAuth2Exception { public class CustomOAuth2Exception extends OAuth2Exception {
public CustomOAuth2Exception(String msg, Throwable t) { public CustomOAuth2Exception(String msg, Throwable t) {
super(msg, t); super(msg, t);
} }
public CustomOAuth2Exception(String msg) {
super(msg);
}
public CustomOAuth2Exception(String msg) {
super(msg);
}
} }

View File

@@ -15,12 +15,14 @@ import java.io.IOException;
*/ */
public class CustomOAuth2ExceptionSerializer extends StdSerializer<CustomOAuth2Exception> { public class CustomOAuth2ExceptionSerializer extends StdSerializer<CustomOAuth2Exception> {
public CustomOAuth2ExceptionSerializer() { public CustomOAuth2ExceptionSerializer() {
super(CustomOAuth2Exception.class); super(CustomOAuth2Exception.class);
} }
@Override
public void serialize(CustomOAuth2Exception e, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
throws IOException {
jsonGenerator.writeObject(R.failed(SystemResultCode.UNAUTHORIZED, e.getMessage()));
}
@Override
public void serialize(CustomOAuth2Exception e, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeObject(R.failed(SystemResultCode.UNAUTHORIZED, e.getMessage()));
}
} }

View File

@@ -20,140 +20,136 @@ import java.io.IOException;
/** /**
* @author Hccake * @author Hccake
* @version 1.0 * @version 1.0
* @date 2019/9/29 10:43 * @date 2019/9/29 10:43 覆盖默认的DefaultWebResponseExceptionTranslator的方法
* 覆盖默认的DefaultWebResponseExceptionTranslator的方法
*/ */
@Component @Component
public class CustomWebResponseExceptionTranslator implements WebResponseExceptionTranslator<OAuth2Exception> { public class CustomWebResponseExceptionTranslator implements WebResponseExceptionTranslator<OAuth2Exception> {
private ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer(); private ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer();
@Override
public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
// Try to extract a SpringSecurityException from the stacktrace
Throwable[] causeChain = throwableAnalyzer.determineCauseChain(e);
Exception ase = (OAuth2Exception) throwableAnalyzer.getFirstThrowableOfType(OAuth2Exception.class, causeChain);
@Override if (ase != null) {
public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception { return handleOAuth2Exception((OAuth2Exception) ase);
// Try to extract a SpringSecurityException from the stacktrace }
Throwable[] causeChain = throwableAnalyzer.determineCauseChain(e);
Exception ase = (OAuth2Exception) throwableAnalyzer.getFirstThrowableOfType(OAuth2Exception.class, causeChain);
if (ase != null) { ase = (AuthenticationException) throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class,
return handleOAuth2Exception((OAuth2Exception) ase); causeChain);
} if (ase != null) {
return handleOAuth2Exception(
new CustomWebResponseExceptionTranslator.UnauthorizedException(e.getMessage(), e));
}
ase = (AuthenticationException) throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class, ase = (AccessDeniedException) throwableAnalyzer.getFirstThrowableOfType(AccessDeniedException.class,
causeChain); causeChain);
if (ase != null) { if (ase != null) {
return handleOAuth2Exception(new CustomWebResponseExceptionTranslator.UnauthorizedException(e.getMessage(), e)); return handleOAuth2Exception(
} new CustomWebResponseExceptionTranslator.ForbiddenException(ase.getMessage(), ase));
}
ase = (AccessDeniedException) throwableAnalyzer ase = (HttpRequestMethodNotSupportedException) throwableAnalyzer
.getFirstThrowableOfType(AccessDeniedException.class, causeChain); .getFirstThrowableOfType(HttpRequestMethodNotSupportedException.class, causeChain);
if (ase != null) { if (ase != null) {
return handleOAuth2Exception(new CustomWebResponseExceptionTranslator.ForbiddenException(ase.getMessage(), ase)); return handleOAuth2Exception(new MethodNotAllowed(ase.getMessage(), ase));
} }
ase = (HttpRequestMethodNotSupportedException) throwableAnalyzer.getFirstThrowableOfType( return handleOAuth2Exception(new ServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), e));
HttpRequestMethodNotSupportedException.class, causeChain); }
if (ase != null) {
return handleOAuth2Exception(new MethodNotAllowed(ase.getMessage(), ase));
}
return handleOAuth2Exception(new ServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), e)); private ResponseEntity<OAuth2Exception> handleOAuth2Exception(OAuth2Exception e) throws IOException {
}
private ResponseEntity<OAuth2Exception> handleOAuth2Exception(OAuth2Exception e) throws IOException { int status = e.getHttpErrorCode();
HttpHeaders headers = new HttpHeaders();
headers.set("Cache-Control", "no-store");
headers.set("Pragma", "no-cache");
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
if (status == HttpStatus.UNAUTHORIZED.value() || (e instanceof InsufficientScopeException)) {
headers.set("WWW-Authenticate", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, e.getSummary()));
}
int status = e.getHttpErrorCode(); // 使用自定义的异常类进行包装
HttpHeaders headers = new HttpHeaders(); return new ResponseEntity<>(new CustomOAuth2Exception(e.getMessage(), e), headers, HttpStatus.valueOf(status));
headers.set("Cache-Control", "no-store");
headers.set("Pragma", "no-cache");
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
if (status == HttpStatus.UNAUTHORIZED.value() || (e instanceof InsufficientScopeException)) {
headers.set("WWW-Authenticate", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, e.getSummary()));
}
// 使用自定义的异常类进行包装 }
return new ResponseEntity<>( new CustomOAuth2Exception(e.getMessage(),e), headers,
HttpStatus.valueOf(status));
} @SuppressWarnings("serial")
private static class ForbiddenException extends CustomOAuth2Exception {
public ForbiddenException(String msg, Throwable t) {
super(msg, t);
}
@SuppressWarnings("serial") @Override
private static class ForbiddenException extends CustomOAuth2Exception { public String getOAuth2ErrorCode() {
return "access_denied";
}
public ForbiddenException(String msg, Throwable t) { @Override
super(msg, t); public int getHttpErrorCode() {
} return 403;
}
@Override }
public String getOAuth2ErrorCode() {
return "access_denied";
}
@Override @SuppressWarnings("serial")
public int getHttpErrorCode() { private static class ServerErrorException extends CustomOAuth2Exception {
return 403;
}
} public ServerErrorException(String msg, Throwable t) {
super(msg, t);
}
@SuppressWarnings("serial") @Override
private static class ServerErrorException extends CustomOAuth2Exception { public String getOAuth2ErrorCode() {
return "server_error";
}
public ServerErrorException(String msg, Throwable t) { @Override
super(msg, t); public int getHttpErrorCode() {
} return 500;
}
@Override }
public String getOAuth2ErrorCode() {
return "server_error";
}
@Override @SuppressWarnings("serial")
public int getHttpErrorCode() { private static class UnauthorizedException extends CustomOAuth2Exception {
return 500;
}
} public UnauthorizedException(String msg, Throwable t) {
super(msg, t);
}
@SuppressWarnings("serial") @Override
private static class UnauthorizedException extends CustomOAuth2Exception { public String getOAuth2ErrorCode() {
return "unauthorized";
}
public UnauthorizedException(String msg, Throwable t) { @Override
super(msg, t); public int getHttpErrorCode() {
} return 401;
}
@Override }
public String getOAuth2ErrorCode() {
return "unauthorized";
}
@Override @SuppressWarnings("serial")
public int getHttpErrorCode() { private static class MethodNotAllowed extends CustomOAuth2Exception {
return 401;
}
} public MethodNotAllowed(String msg, Throwable t) {
super(msg, t);
}
@SuppressWarnings("serial") @Override
private static class MethodNotAllowed extends CustomOAuth2Exception { public String getOAuth2ErrorCode() {
return "method_not_allowed";
public MethodNotAllowed(String msg, Throwable t) { }
super(msg, t);
}
@Override
public String getOAuth2ErrorCode() {
return "method_not_allowed";
}
@Override
public int getHttpErrorCode() {
return 405;
}
}
@Override
public int getHttpErrorCode() {
return 405;
}
}
} }

View File

@@ -30,69 +30,67 @@ import java.util.Optional;
/** /**
* @author Hccake * @author Hccake
* @version 1.0 * @version 1.0
* @date 2019/9/28 16:57 * @date 2019/9/28 16:57 前端传递过来的加密密码,需要在登陆之前先解密
* 前端传递过来的加密密码,需要在登陆之前先解密
*/ */
@Slf4j @Slf4j
@Order(0) @Order(0)
@WebFilter(urlPatterns = {UrlMappingConst.OAUTH_LOGIN}) @WebFilter(urlPatterns = { UrlMappingConst.OAUTH_LOGIN })
@RequiredArgsConstructor @RequiredArgsConstructor
public class LoginPasswordDecoderFilter extends OncePerRequestFilter { public class LoginPasswordDecoderFilter extends OncePerRequestFilter {
private final ObjectMapper objectMapper;
@Value("${password.secret-key}") private final ObjectMapper objectMapper;
private String secretKey;
private static final String PASSWORD = "password"; @Value("${password.secret-key}")
private String secretKey;
private static final String GRANT_TYPE = "grant_type"; private static final String PASSWORD = "password";
private static final String TEST_CLIENT = "test"; private static final String GRANT_TYPE = "grant_type";
private static final String TEST_CLIENT = "test";
/** /**
* Same contract as for {@code doFilter}, but guaranteed to be * Same contract as for {@code doFilter}, but guaranteed to be just invoked once per
* just invoked once per request within a single request thread. * request within a single request thread. See {@link #shouldNotFilterAsyncDispatch()}
* See {@link #shouldNotFilterAsyncDispatch()} for details. * for details.
* <p>Provides HttpServletRequest and HttpServletResponse arguments instead of the * <p>
* default ServletRequest and ServletResponse ones. * Provides HttpServletRequest and HttpServletResponse arguments instead of the
* * default ServletRequest and ServletResponse ones.
* @param request * @param request
* @param response * @param response
* @param filterChain * @param filterChain
*/ */
@Override @Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
// 测试客户端 跳过密码解密swagger 或 postman测试时使用 // 测试客户端 跳过密码解密swagger 或 postman测试时使用
Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
User user = (User) Optional.ofNullable(authentication) User user = (User) Optional.ofNullable(authentication).map(Authentication::getPrincipal).orElse(null);
.map(Authentication::getPrincipal).orElse(null); if (user != null && TEST_CLIENT.equals(user.getUsername())) {
if (user != null && TEST_CLIENT.equals(user.getUsername())) { filterChain.doFilter(request, response);
filterChain.doFilter(request, response); return;
return; }
}
// 解密前台加密后的密码 // 解密前台加密后的密码
Map<String, String[]> parameterMap = new HashMap<>(request.getParameterMap()); Map<String, String[]> parameterMap = new HashMap<>(request.getParameterMap());
try{ try {
if(request.getParameter(GRANT_TYPE).equals(PASSWORD)){ if (request.getParameter(GRANT_TYPE).equals(PASSWORD)) {
String password = PasswordUtil.decodeAES(request.getParameter(PASSWORD), secretKey); String password = PasswordUtil.decodeAES(request.getParameter(PASSWORD), secretKey);
parameterMap.put(PASSWORD, new String[]{password}); parameterMap.put(PASSWORD, new String[] { password });
} }
}catch (Exception e){ }
response.setHeader("Content-Type", MediaType.APPLICATION_JSON.toString()); catch (Exception e) {
response.setStatus(HttpStatus.UNAUTHORIZED.value()); response.setHeader("Content-Type", MediaType.APPLICATION_JSON.toString());
response.getWriter().write( response.setStatus(HttpStatus.UNAUTHORIZED.value());
objectMapper.writeValueAsString(R.failed(SystemResultCode.UNAUTHORIZED, e.getMessage())) response.getWriter()
); .write(objectMapper.writeValueAsString(R.failed(SystemResultCode.UNAUTHORIZED, e.getMessage())));
return; return;
} }
// SpringSecurity 默认从ParameterMap中获取密码参数 // SpringSecurity 默认从ParameterMap中获取密码参数
// 由于原生的request中对parameter加锁了无法修改所以使用包装类 // 由于原生的request中对parameter加锁了无法修改所以使用包装类
filterChain.doFilter( new ModifyParamMapRequestWrapper(request, parameterMap), response); filterChain.doFilter(new ModifyParamMapRequestWrapper(request, parameterMap), response);
} }
} }

View File

@@ -32,12 +32,11 @@ import java.util.HashMap;
@RequiredArgsConstructor @RequiredArgsConstructor
@Component @Component
public class LoginEventListener { public class LoginEventListener {
private final OperationLogHandler operationLogHandler; private final OperationLogHandler operationLogHandler;
/** /**
* 登陆成功时间监听 * 登陆成功时间监听 记录用户登录日志
* 记录用户登录日志
*
* @param event 登陆成功 event * @param event 登陆成功 event
*/ */
@EventListener(AuthenticationSuccessEvent.class) @EventListener(AuthenticationSuccessEvent.class)
@@ -52,68 +51,51 @@ public class LoginEventListener {
// https://github.com/spring-projects-experimental/spring-authorization-server // https://github.com/spring-projects-experimental/spring-authorization-server
if ("password".equals(((HashMap) details).get("grant_type"))) { if ("password".equals(((HashMap) details).get("grant_type"))) {
// 记录登陆日志 // 记录登陆日志
OperationLogDTO operationLogDTO = prodOperationLogDTO(source) OperationLogDTO operationLogDTO = prodOperationLogDTO(source).setType(OperationTypeEnum.LOGIN.getValue())
.setType(OperationTypeEnum.LOGIN.getValue())
.setMsg("Login Success"); .setMsg("Login Success");
operationLogHandler.saveLog(operationLogDTO); operationLogHandler.saveLog(operationLogDTO);
} }
} }
/** /**
* On logout success event. * On logout success event.
*
* @param event the event * @param event the event
*/ */
@EventListener(AbstractAuthenticationFailureEvent.class) @EventListener(AbstractAuthenticationFailureEvent.class)
public void onAuthenticationFailureEvent(AbstractAuthenticationFailureEvent event) { public void onAuthenticationFailureEvent(AbstractAuthenticationFailureEvent event) {
AbstractAuthenticationToken source = (AbstractAuthenticationToken) event.getSource(); AbstractAuthenticationToken source = (AbstractAuthenticationToken) event.getSource();
// 记录登出日志 // 记录登出日志
OperationLogDTO operationLogDTO = prodOperationLogDTO(source) OperationLogDTO operationLogDTO = prodOperationLogDTO(source).setType(OperationTypeEnum.LOGIN.getValue())
.setType(OperationTypeEnum.LOGIN.getValue()) .setMsg("Login Error" + event.getException().getMessage()).setStatus(LogStatusEnum.FAIL.getValue());
.setMsg("Login Error" + event.getException().getMessage())
.setStatus(LogStatusEnum.FAIL.getValue());
operationLogHandler.saveLog(operationLogDTO); operationLogHandler.saveLog(operationLogDTO);
} }
/** /**
* On logout success event. * On logout success event.
*
* @param event the event * @param event the event
*/ */
@EventListener(LogoutSuccessEvent.class) @EventListener(LogoutSuccessEvent.class)
public void onLogoutSuccessEvent(LogoutSuccessEvent event) { public void onLogoutSuccessEvent(LogoutSuccessEvent event) {
AbstractAuthenticationToken source = (AbstractAuthenticationToken) event.getSource(); AbstractAuthenticationToken source = (AbstractAuthenticationToken) event.getSource();
// 记录登出日志 // 记录登出日志
OperationLogDTO operationLogDTO = prodOperationLogDTO(source) OperationLogDTO operationLogDTO = prodOperationLogDTO(source).setType(OperationTypeEnum.LOGOUT.getValue())
.setType(OperationTypeEnum.LOGOUT.getValue())
.setMsg("Logout Success"); .setMsg("Logout Success");
operationLogHandler.saveLog(operationLogDTO); operationLogHandler.saveLog(operationLogDTO);
} }
/** /**
* 根据token和请求信息产生一个操作日志 * 根据token和请求信息产生一个操作日志
*
* @param source AbstractAuthenticationToken 当前token * @param source AbstractAuthenticationToken 当前token
* @return OperationLogDTO 操作日志DTO * @return OperationLogDTO 操作日志DTO
*/ */
private OperationLogDTO prodOperationLogDTO(AbstractAuthenticationToken source) { private OperationLogDTO prodOperationLogDTO(AbstractAuthenticationToken source) {
// 获取 Request // 获取 Request
HttpServletRequest request = LogUtils.getHttpServletRequest(); HttpServletRequest request = LogUtils.getHttpServletRequest();
return new OperationLogDTO() return new OperationLogDTO().setCreateTime(LocalDateTime.now()).setIp(IPUtil.getIpAddr(request))
.setCreateTime(LocalDateTime.now()) .setMethod(request.getMethod()).setStatus(LogStatusEnum.SUCCESS.getValue())
.setIp(IPUtil.getIpAddr(request)) .setUserAgent(request.getHeader("user-agent")).setUri(URLUtil.getPath(request.getRequestURI()))
.setMethod(request.getMethod()) .setTraceId(MDC.get(LogConstant.TRACE_ID)).setParams(JSONUtil.toJsonStr(request.getParameterMap()))
.setStatus(LogStatusEnum.SUCCESS.getValue()) .setTime(0L).setOperator(source.getName());
.setUserAgent(request.getHeader("user-agent"))
.setUri(URLUtil.getPath(request.getRequestURI()))
.setTraceId(MDC.get(LogConstant.TRACE_ID))
.setParams(JSONUtil.toJsonStr(request.getParameterMap()))
.setTime(0L)
.setOperator(source.getName());
} }
} }

View File

@@ -14,12 +14,11 @@ import org.springframework.security.core.userdetails.UserDetailsService;
/** /**
* @author lengleng * @author lengleng
* @date 2018/8/5 * @date 2018/8/5 手机登录校验逻辑 验证码登录、社交登录
* 手机登录校验逻辑
* 验证码登录、社交登录
*/ */
@Slf4j @Slf4j
public class MobileAuthenticationProvider implements AuthenticationProvider { public class MobileAuthenticationProvider implements AuthenticationProvider {
private MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor(); private MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
@Getter @Getter
@@ -36,15 +35,15 @@ public class MobileAuthenticationProvider implements AuthenticationProvider {
if (userDetails == null) { if (userDetails == null) {
log.debug("Authentication failed: no credentials provided"); log.debug("Authentication failed: no credentials provided");
throw new BadCredentialsException(messages.getMessage( throw new BadCredentialsException(messages
"AbstractUserDetailsAuthenticationProvider.noopBindAccount", .getMessage("AbstractUserDetailsAuthenticationProvider.noopBindAccount", "Noop Bind Account"));
"Noop Bind Account"));
} }
// 检查账号状态 // 检查账号状态
//detailsChecker.check(userDetails); // detailsChecker.check(userDetails);
MobileAuthenticationToken authenticationToken = new MobileAuthenticationToken(userDetails, userDetails.getAuthorities()); MobileAuthenticationToken authenticationToken = new MobileAuthenticationToken(userDetails,
userDetails.getAuthorities());
authenticationToken.setDetails(mobileAuthenticationToken.getDetails()); authenticationToken.setDetails(mobileAuthenticationToken.getDetails());
return authenticationToken; return authenticationToken;
} }
@@ -53,4 +52,5 @@ public class MobileAuthenticationProvider implements AuthenticationProvider {
public boolean supports(Class<?> authentication) { public boolean supports(Class<?> authentication) {
return MobileAuthenticationToken.class.isAssignableFrom(authentication); return MobileAuthenticationToken.class.isAssignableFrom(authentication);
} }
} }

View File

@@ -9,8 +9,7 @@ import java.util.Collection;
/** /**
* @author lengleng * @author lengleng
* @date 2018/1/9 * @date 2018/1/9 手机号登录令牌
* 手机号登录令牌
*/ */
public class MobileAuthenticationToken extends AbstractAuthenticationToken { public class MobileAuthenticationToken extends AbstractAuthenticationToken {
@@ -24,8 +23,7 @@ public class MobileAuthenticationToken extends AbstractAuthenticationToken {
setAuthenticated(false); setAuthenticated(false);
} }
public MobileAuthenticationToken(Object principal, public MobileAuthenticationToken(Object principal, Collection<? extends GrantedAuthority> authorities) {
Collection<? extends GrantedAuthority> authorities) {
super(authorities); super(authorities);
this.principal = principal; this.principal = principal;
super.setAuthenticated(true); super.setAuthenticated(true);
@@ -56,5 +54,5 @@ public class MobileAuthenticationToken extends AbstractAuthenticationToken {
public void eraseCredentials() { public void eraseCredentials() {
super.eraseCredentials(); super.eraseCredentials();
} }
}
}

View File

@@ -17,64 +17,61 @@ import java.util.Map;
*/ */
public class MobileTokenGranter extends AbstractTokenGranter { public class MobileTokenGranter extends AbstractTokenGranter {
private static final String GRANT_TYPE = "mobile"; private static final String GRANT_TYPE = "mobile";
private final AuthenticationManager authenticationManager; private final AuthenticationManager authenticationManager;
public MobileTokenGranter( public MobileTokenGranter(AuthenticationManager authenticationManager,
AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService,
AuthorizationServerTokenServices tokenServices, OAuth2RequestFactory requestFactory) {
ClientDetailsService clientDetailsService, this(authenticationManager, tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
OAuth2RequestFactory requestFactory) {
this(authenticationManager, tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
} }
protected MobileTokenGranter( protected MobileTokenGranter(AuthenticationManager authenticationManager,
AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService,
AuthorizationServerTokenServices tokenServices, OAuth2RequestFactory requestFactory, String grantType) {
ClientDetailsService clientDetailsService, super(tokenServices, clientDetailsService, requestFactory, grantType);
OAuth2RequestFactory requestFactory, this.authenticationManager = authenticationManager;
String grantType) { }
super(tokenServices, clientDetailsService, requestFactory, grantType);
this.authenticationManager = authenticationManager;
}
@Override @Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) { protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters()); Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
String mobile = parameters.get("mobile"); String mobile = parameters.get("mobile");
if (mobile == null) { if (mobile == null) {
mobile = ""; mobile = "";
} }
mobile = mobile.trim(); mobile = mobile.trim();
MobileAuthenticationToken mobileAuthenticationToken = new MobileAuthenticationToken(mobile); MobileAuthenticationToken mobileAuthenticationToken = new MobileAuthenticationToken(mobile);
Authentication authentication = null; Authentication authentication = null;
try { try {
authentication = this.authenticationManager.authenticate(mobileAuthenticationToken); authentication = this.authenticationManager.authenticate(mobileAuthenticationToken);
logger.debug("Authentication success: " + authentication); logger.debug("Authentication success: " + authentication);
SecurityContextHolder.getContext().setAuthentication(authentication); SecurityContextHolder.getContext().setAuthentication(authentication);
} catch (Exception failed) { }
SecurityContextHolder.clearContext(); catch (Exception failed) {
logger.debug("Authentication request failed: " + failed); SecurityContextHolder.clearContext();
logger.debug("Authentication request failed: " + failed);
//eventPublisher.publishAuthenticationFailure(new BadCredentialsException(failed.getMessage(), failed), // eventPublisher.publishAuthenticationFailure(new
// new PreAuthenticatedAuthenticationToken("access-token", "N/A")); // BadCredentialsException(failed.getMessage(), failed),
// new PreAuthenticatedAuthenticationToken("access-token", "N/A"));
// try { // try {
// authenticationEntryPoint.commence(request, response, // authenticationEntryPoint.commence(request, response,
// new UsernameNotFoundException(failed.getMessage(), failed)); // new UsernameNotFoundException(failed.getMessage(), failed));
// } catch (Exception e) { // } catch (Exception e) {
// logger.error("authenticationEntryPoint handle error:{}", failed); // logger.error("authenticationEntryPoint handle error:{}", failed);
// } // }
} }
OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest); OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
return new OAuth2Authentication(storedOAuth2Request, authentication); return new OAuth2Authentication(storedOAuth2Request, authentication);
} }
} }

View File

@@ -14,44 +14,41 @@ import org.springframework.security.core.context.SecurityContextHolder;
@UtilityClass @UtilityClass
public class SecurityUtils { public class SecurityUtils {
/** /**
* 获取Authentication * 获取Authentication
*/ */
public Authentication getAuthentication() { public Authentication getAuthentication() {
return SecurityContextHolder.getContext().getAuthentication(); return SecurityContextHolder.getContext().getAuthentication();
} }
/** /**
* 获取系统用户Details * 获取系统用户Details
* * @param authentication
* @param authentication * @return SysUser
* @return SysUser * <p>
* <p> */
*/ public SysUserDetails getSysUserDetails(Authentication authentication) {
public SysUserDetails getSysUserDetails(Authentication authentication) { Object principal = authentication.getPrincipal();
Object principal = authentication.getPrincipal(); if (principal instanceof SysUserDetails) {
if (principal instanceof SysUserDetails) { return (SysUserDetails) principal;
return (SysUserDetails) principal; }
} return null;
return null; }
}
/** /**
* 获取用户详情 * 获取用户详情
*/ */
public SysUserDetails getSysUserDetails() { public SysUserDetails getSysUserDetails() {
Authentication authentication = getAuthentication(); Authentication authentication = getAuthentication();
return getSysUserDetails(authentication); return getSysUserDetails(authentication);
} }
/**
* 获取系统用户
*/
public SysUser getSysUser() {
SysUserDetails sysUserDetails = getSysUserDetails();
return sysUserDetails == null ? null : sysUserDetails.getSysUser() ;
}
/**
* 获取系统用户
*/
public SysUser getSysUser() {
SysUserDetails sysUserDetails = getSysUserDetails();
return sysUserDetails == null ? null : sysUserDetails.getSysUser();
}
} }

View File

@@ -13,7 +13,8 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication @SpringBootApplication
public class GeneratorApplication { public class GeneratorApplication {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(GeneratorApplication.class); SpringApplication.run(GeneratorApplication.class);
} }
} }

View File

@@ -33,7 +33,9 @@ public class DsRequestProcessor extends DsProcessor {
*/ */
@Override @Override
public String doDetermineDatasource(MethodInvocation invocation, String key) { public String doDetermineDatasource(MethodInvocation invocation, String key) {
HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest(); HttpServletRequest request = ((ServletRequestAttributes) Objects
.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
return request.getParameter(key.substring(9)); return request.getParameter(key.substring(9));
} }
} }

View File

@@ -13,17 +13,18 @@ import org.springframework.context.annotation.Configuration;
/** /**
* @author Hccake * @author Hccake
* @version 1.0 * @version 1.0
* @date 2020/6/15 17:37 * @date 2020/6/15 17:37 动态数据源加载
* 动态数据源加载
*/ */
@Configuration @Configuration
@RequiredArgsConstructor @RequiredArgsConstructor
public class DynamicDataSourceConfiguration { public class DynamicDataSourceConfiguration {
private final StringEncryptor stringEncryptor; private final StringEncryptor stringEncryptor;
/** /**
* 默认JDBC驱动类 * 默认JDBC驱动类
*/ */
public static final String DEFAULT_JDBC_DRIVER = "com.mysql.cj.jdbc.Driver" ; public static final String DEFAULT_JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
/** /**
* JDBC 动态数据源提供者 * JDBC 动态数据源提供者
@@ -34,18 +35,13 @@ public class DynamicDataSourceConfiguration {
public DynamicJdbcDataSourceProvider dynamicDataSourceProvider(DataSourceProperties dataSourceProperties) { public DynamicJdbcDataSourceProvider dynamicDataSourceProvider(DataSourceProperties dataSourceProperties) {
// 这里由于 dynamic-datasource-spring-boot-starter 的问题,必须填写 // 这里由于 dynamic-datasource-spring-boot-starter 的问题,必须填写
String driverClassName = dataSourceProperties.getDriverClassName(); String driverClassName = dataSourceProperties.getDriverClassName();
if(driverClassName == null){ if (driverClassName == null) {
driverClassName = DEFAULT_JDBC_DRIVER; driverClassName = DEFAULT_JDBC_DRIVER;
} }
return new DynamicJdbcDataSourceProvider( return new DynamicJdbcDataSourceProvider(stringEncryptor, driverClassName, dataSourceProperties.getUrl(),
stringEncryptor, dataSourceProperties.getUsername(), dataSourceProperties.getPassword());
driverClassName,
dataSourceProperties.getUrl(),
dataSourceProperties.getUsername(),
dataSourceProperties.getPassword());
} }
@Bean @Bean
public DsProcessor dsProcessor() { public DsProcessor dsProcessor() {
DsRequestProcessor requestProcessor = new DsRequestProcessor(); DsRequestProcessor requestProcessor = new DsRequestProcessor();

View File

@@ -17,11 +17,15 @@ import java.util.Map;
* @date 2020/6/15 17:46 * @date 2020/6/15 17:46
*/ */
public class DynamicJdbcDataSourceProvider extends AbstractJdbcDataSourceProvider { public class DynamicJdbcDataSourceProvider extends AbstractJdbcDataSourceProvider {
public static final String QUERY_DS_SQL = "select * from gen_data_source_config" ;
public static final String QUERY_DS_SQL = "select * from gen_data_source_config";
private final DataSourceProperty masterDataSourceProperty; private final DataSourceProperty masterDataSourceProperty;
private final StringEncryptor stringEncryptor; private final StringEncryptor stringEncryptor;
public DynamicJdbcDataSourceProvider(StringEncryptor stringEncryptor, String driverClassName, String url, String username, String password) { public DynamicJdbcDataSourceProvider(StringEncryptor stringEncryptor, String driverClassName, String url,
String username, String password) {
super(driverClassName, url, username, password); super(driverClassName, url, username, password);
this.stringEncryptor = stringEncryptor; this.stringEncryptor = stringEncryptor;
this.masterDataSourceProperty = new DataSourceProperty(); this.masterDataSourceProperty = new DataSourceProperty();
@@ -51,4 +55,5 @@ public class DynamicJdbcDataSourceProvider extends AbstractJdbcDataSourceProvide
return map; return map;
} }
} }

View File

@@ -18,12 +18,12 @@ import java.util.regex.Pattern;
/** /**
* @author Hccake * @author Hccake
* @version 1.0 * @version 1.0
* @date 2020/6/18 13:37 * @date 2020/6/18 13:37 前端页面请求404问题
* 前端页面请求404问题
*/ */
@Slf4j @Slf4j
@Configuration @Configuration
public class SpaRedirectFilterConfiguration { public class SpaRedirectFilterConfiguration {
private final static AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher(); private final static AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();
@Bean @Bean
@@ -39,28 +39,36 @@ public class SpaRedirectFilterConfiguration {
private OncePerRequestFilter createRedirectFilter() { private OncePerRequestFilter createRedirectFilter() {
return new OncePerRequestFilter() { return new OncePerRequestFilter() {
// Forwards all routes except '/index.html', '/200.html', '/favicon.ico', '/sw.js' '/api/', '/api/**' // Forwards all routes except '/index.html', '/200.html', '/favicon.ico',
// '/sw.js' '/api/', '/api/**'
private final String REGEX = "(?!/actuator|/_nuxt|/static|/index\\.html|/200\\.html|/favicon\\.ico|/sw\\.js).*$"; private final String REGEX = "(?!/actuator|/_nuxt|/static|/index\\.html|/200\\.html|/favicon\\.ico|/sw\\.js).*$";
private final Pattern pattern = Pattern.compile(REGEX); private final Pattern pattern = Pattern.compile(REGEX);
@Override @Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws ServletException, IOException { protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws ServletException, IOException {
String requestUri = req.getRequestURI(); String requestUri = req.getRequestURI();
if (pattern.matcher(requestUri).matches() && !"/".equals(requestUri)) { if (pattern.matcher(requestUri).matches() && !"/".equals(requestUri)) {
RequestDispatcher rd; RequestDispatcher rd;
if(SpaRedirectFilterConfiguration.ANT_PATH_MATCHER.match("/api/**", requestUri)){ if (SpaRedirectFilterConfiguration.ANT_PATH_MATCHER.match("/api/**", requestUri)) {
log.info("URL {} access the backend, redirecting...", requestUri); log.info("URL {} access the backend, redirecting...", requestUri);
rd = req.getRequestDispatcher(requestUri.substring(4)); rd = req.getRequestDispatcher(requestUri.substring(4));
}else { }
else {
// Delegate/Forward to `/` if `pattern` matches and it is not `/` // Delegate/Forward to `/` if `pattern` matches and it is not `/`
// Required because of 'mode: history'usage in frontend routing, see README for further details // Required because of 'mode: history'usage in frontend routing,
// see README for further details
log.info("URL {} entered directly into the Browser, redirecting...", requestUri); log.info("URL {} entered directly into the Browser, redirecting...", requestUri);
rd = req.getRequestDispatcher("/"); rd = req.getRequestDispatcher("/");
} }
rd.forward(req, res); rd.forward(req, res);
} else { }
else {
chain.doFilter(req, res); chain.doFilter(req, res);
} }
} }
}; };
} }
} }

View File

@@ -3,12 +3,12 @@ package com.hccake.ballcat.codegen.constant;
/** /**
* @author Hccake * @author Hccake
* @version 1.0 * @version 1.0
* @date 2020/6/15 17:53 * @date 2020/6/15 17:53 配置数据源使用的常量
* 配置数据源使用的常量
*/ */
public final class DataSourceConstants { public final class DataSourceConstants {
private DataSourceConstants(){}
private DataSourceConstants() {
}
/** /**
* 默认数据源名称master * 默认数据源名称master

View File

@@ -6,12 +6,12 @@ import lombok.RequiredArgsConstructor;
/** /**
* @author Hccake * @author Hccake
* @version 1.0 * @version 1.0
* @date 2020/6/23 14:36 * @date 2020/6/23 14:36 模板目录项类型
* 模板目录项类型
*/ */
@Getter @Getter
@RequiredArgsConstructor @RequiredArgsConstructor
public enum DirectoryEntryRemoveModeEnum { public enum DirectoryEntryRemoveModeEnum {
/** /**
* 保留子节点(子节点上移) * 保留子节点(子节点上移)
*/ */
@@ -22,4 +22,5 @@ public enum DirectoryEntryRemoveModeEnum {
REMOVE_CHILD_NODE(2); REMOVE_CHILD_NODE(2);
private final Integer type; private final Integer type;
} }

View File

@@ -6,12 +6,12 @@ import lombok.RequiredArgsConstructor;
/** /**
* @author Hccake * @author Hccake
* @version 1.0 * @version 1.0
* @date 2020/6/23 14:36 * @date 2020/6/23 14:36 模板目录项类型
* 模板目录项类型
*/ */
@Getter @Getter
@RequiredArgsConstructor @RequiredArgsConstructor
public enum DirectoryEntryTypeEnum { public enum DirectoryEntryTypeEnum {
/** /**
* 文件夹 * 文件夹
*/ */
@@ -22,4 +22,5 @@ public enum DirectoryEntryTypeEnum {
FILE(2); FILE(2);
private final Integer type; private final Integer type;
} }

View File

@@ -17,7 +17,6 @@ import org.springframework.web.bind.annotation.*;
import java.util.List; import java.util.List;
/** /**
* 数据源 * 数据源
* *
@@ -26,82 +25,78 @@ import java.util.List;
*/ */
@RestController @RestController
@RequiredArgsConstructor @RequiredArgsConstructor
@RequestMapping("/gen/datasource-config" ) @RequestMapping("/gen/datasource-config")
@Api(value = "datasource-config", tags = "数据源管理") @Api(value = "datasource-config", tags = "数据源管理")
public class DataSourceConfigController { public class DataSourceConfigController {
private final DataSourceConfigService dataSourceConfigService; private final DataSourceConfigService dataSourceConfigService;
/** /**
* 分页查询 * 分页查询
* @param page 分页对象 * @param page 分页对象
* @param dataSourceConfigQO 数据源 * @param dataSourceConfigQO 数据源
* @return R * @return R
*/ */
@ApiOperation(value = "分页查询", notes = "分页查询") @ApiOperation(value = "分页查询", notes = "分页查询")
@GetMapping("/page" ) @GetMapping("/page")
//@PreAuthorize("@per.hasPermission('gen:datasourceconfig:read')" ) // @PreAuthorize("@per.hasPermission('gen:datasourceconfig:read')" )
public R<IPage<DataSourceConfigVO>> getDataSourceConfigPage( public R<IPage<DataSourceConfigVO>> getDataSourceConfigPage(Page<?> page, DataSourceConfigQO dataSourceConfigQO) {
Page<?> page, DataSourceConfigQO dataSourceConfigQO) { return R.ok(dataSourceConfigService.selectPageVo(page, dataSourceConfigQO));
return R.ok(dataSourceConfigService.selectPageVo(page, dataSourceConfigQO)); }
}
/**
* 通过id查询数据源
* @param id id
* @return R
*/
@ApiOperation(value = "通过id查询", notes = "通过id查询")
@GetMapping("/{id}")
// @PreAuthorize("@per.hasPermission('gen:datasourceconfig:read')" )
public R<DataSourceConfig> getById(@PathVariable("id") Integer id) {
return R.ok(dataSourceConfigService.getById(id));
}
/** /**
* 通过id查询数据源 * 新增数据源
* @param id id * @param dataSourceConfigDTO 数据源
* @return R * @return R
*/ */
@ApiOperation(value = "通过id查询", notes = "通过id查询") @ApiOperation(value = "新增数据源", notes = "新增数据源")
@GetMapping("/{id}" ) // @CreateOperationLogging(msg = "新增数据源" )
// @PreAuthorize("@per.hasPermission('gen:datasourceconfig:read')" ) @PostMapping
public R<DataSourceConfig> getById(@PathVariable("id" ) Integer id) { // @PreAuthorize("@per.hasPermission('gen:datasourcecofig:add')" )
return R.ok(dataSourceConfigService.getById(id)); public R save(@RequestBody DataSourceConfigDTO dataSourceConfigDTO) {
} return dataSourceConfigService.save(dataSourceConfigDTO) ? R.ok()
: R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "新增数据源失败");
/** }
* 新增数据源
* @param dataSourceConfigDTO 数据源
* @return R
*/
@ApiOperation(value = "新增数据源", notes = "新增数据源")
//@CreateOperationLogging(msg = "新增数据源" )
@PostMapping
// @PreAuthorize("@per.hasPermission('gen:datasourcecofig:add')" )
public R save(@RequestBody DataSourceConfigDTO dataSourceConfigDTO) {
return dataSourceConfigService.save(dataSourceConfigDTO) ?
R.ok() : R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "新增数据源失败");
}
/**
* 修改数据源
* @param dataSourceConfigDTO 数据源
* @return R
*/
@ApiOperation(value = "修改数据源", notes = "修改数据源")
//@UpdateOperationLogging(msg = "修改数据源" )
@PutMapping
// @PreAuthorize("@per.hasPermission('gen:datasourceconfig:edit')" )
public R updateById(@RequestBody DataSourceConfigDTO dataSourceConfigDTO) {
return dataSourceConfigService.update(dataSourceConfigDTO) ?
R.ok() : R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "修改数据源失败");
}
/**
* 通过id删除数据源
* @param id id
* @return R
*/
@ApiOperation(value = "通过id删除数据源", notes = "通过id删除数据源")
//@DeleteOperationLogging(msg = "通过id删除数据源" )
@DeleteMapping("/{id}" )
// @PreAuthorize("@per.hasPermission('gen:datasourceconfig:del')" )
public R removeById(@PathVariable Integer id) {
return dataSourceConfigService.removeById(id) ?
R.ok() : R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "通过id删除数据源失败");
}
/**
* 修改数据源
* @param dataSourceConfigDTO 数据源
* @return R
*/
@ApiOperation(value = "修改数据源", notes = "修改数据源")
// @UpdateOperationLogging(msg = "修改数据源" )
@PutMapping
// @PreAuthorize("@per.hasPermission('gen:datasourceconfig:edit')" )
public R updateById(@RequestBody DataSourceConfigDTO dataSourceConfigDTO) {
return dataSourceConfigService.update(dataSourceConfigDTO) ? R.ok()
: R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "修改数据源失败");
}
/**
* 通过id删除数据源
* @param id id
* @return R
*/
@ApiOperation(value = "通过id删除数据源", notes = "通过id删除数据源")
// @DeleteOperationLogging(msg = "通过id删除数据源" )
@DeleteMapping("/{id}")
// @PreAuthorize("@per.hasPermission('gen:datasourceconfig:del')" )
public R removeById(@PathVariable Integer id) {
return dataSourceConfigService.removeById(id) ? R.ok()
: R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "通过id删除数据源失败");
}
/** /**
* 获取selectData数据 * 获取selectData数据

View File

@@ -30,9 +30,10 @@ import java.util.Map;
@RequestMapping @RequestMapping
@RequiredArgsConstructor @RequiredArgsConstructor
public class GenerateController { public class GenerateController {
private final GeneratorService generatorService;
private final TableInfoService tableInfoService;
private final GeneratorService generatorService;
private final TableInfoService tableInfoService;
/** /**
* 表信息分页查询 * 表信息分页查询
@@ -41,35 +42,32 @@ public class GenerateController {
* @return R * @return R
*/ */
@ApiOperation(value = "表信息分页查询", notes = "表信息分页查询") @ApiOperation(value = "表信息分页查询", notes = "表信息分页查询")
@GetMapping("/table-info/page" ) @GetMapping("/table-info/page")
public R<IPage<TableInfo>> getDataSourceConfigPage( public R<IPage<TableInfo>> getDataSourceConfigPage(Page<?> page, TableInfoQO tableInfoQO) {
Page<?> page, TableInfoQO tableInfoQO) {
return R.ok(tableInfoService.selectPageVo(page, tableInfoQO)); return R.ok(tableInfoService.selectPageVo(page, tableInfoQO));
} }
/**
/** * 生成代码
* 生成代码 */
*/ @SneakyThrows
@SneakyThrows @PostMapping("/generate")
@PostMapping("/generate") public void generatorCode(@RequestBody GeneratorOptionDTO generatorOptionDTO, HttpServletResponse response) {
public void generatorCode(
@RequestBody GeneratorOptionDTO generatorOptionDTO,
HttpServletResponse response) {
// TODO 待前端写好,暂时先写死 // TODO 待前端写好,暂时先写死
Map<String, String> map = new HashMap<>(4); Map<String, String> map = new HashMap<>(4);
map.put("moduleName", "gen"); map.put("moduleName", "gen");
map.put("packageName", "com.hccake.ballcat"); map.put("packageName", "com.hccake.ballcat");
map.put("author", "hccake"); map.put("author", "hccake");
generatorOptionDTO.setGenProperties(map); generatorOptionDTO.setGenProperties(map);
generatorOptionDTO.setTemplateGroupId(1); generatorOptionDTO.setTemplateGroupId(1);
byte[] data = generatorService.generatorCode(generatorOptionDTO); byte[] data = generatorService.generatorCode(generatorOptionDTO);
response.reset(); response.reset();
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"ballcat.zip\""); response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"ballcat.zip\"");
response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length)); response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
response.setContentType("application/octet-stream; charset=UTF-8"); response.setContentType("application/octet-stream; charset=UTF-8");
IoUtil.write(response.getOutputStream(), Boolean.TRUE, data);
}
IoUtil.write(response.getOutputStream(), Boolean.TRUE, data);
}
} }

View File

@@ -12,7 +12,6 @@ import org.springframework.web.bind.annotation.*;
import java.util.List; import java.util.List;
/** /**
* 模板文件目录项 * 模板文件目录项
* *
@@ -24,90 +23,77 @@ import java.util.List;
@RequestMapping("/gen/template/directory-entry") @RequestMapping("/gen/template/directory-entry")
@Api(value = "/gen/template/directory-entry", tags = "模板文件目录项管理") @Api(value = "/gen/template/directory-entry", tags = "模板文件目录项管理")
public class TemplateDirectoryEntryController { public class TemplateDirectoryEntryController {
private final TemplateDirectoryEntryService templateDirectoryEntryService; private final TemplateDirectoryEntryService templateDirectoryEntryService;
/** /**
* 模板组的文件目录 * 模板组的文件目录
*
* @param templateGroupId 模板组ID * @param templateGroupId 模板组ID
* @return R * @return R
*/ */
@ApiOperation(value = "指定模板组的文件目录项", notes = "指定模板组的文件目录项") @ApiOperation(value = "指定模板组的文件目录项", notes = "指定模板组的文件目录项")
@GetMapping("/list/{templateGroupId}") @GetMapping("/list/{templateGroupId}")
//@PreAuthorize("@per.hasPermission('codegen:templatedirectoryentry:read')" ) // @PreAuthorize("@per.hasPermission('codegen:templatedirectoryentry:read')" )
public R<List<TemplateDirectoryEntryVO>> getTemplateDirectoryEntryPage(@PathVariable Integer templateGroupId) { public R<List<TemplateDirectoryEntryVO>> getTemplateDirectoryEntryPage(@PathVariable Integer templateGroupId) {
return R.ok(templateDirectoryEntryService.queryDirectoryEntry(templateGroupId)); return R.ok(templateDirectoryEntryService.queryDirectoryEntry(templateGroupId));
} }
/** /**
* 移动目录项 * 移动目录项
* @param entryId 被移动的目录项ID * @param entryId 被移动的目录项ID
* @param horizontalMove 是否移动到目标目录平级,否则移动到其内部 * @param horizontalMove 是否移动到目标目录平级,否则移动到其内部
* @param targetEntryId 目标目录项ID * @param targetEntryId 目标目录项ID
* @return R * @return R
*/ */
@ApiOperation(value = "移动目录项", notes = "移动目录项") @ApiOperation(value = "移动目录项", notes = "移动目录项")
@PatchMapping("/{entryId}/position") @PatchMapping("/{entryId}/position")
public R<?> move( public R<?> move(@PathVariable Integer entryId, @RequestParam boolean horizontalMove,
@PathVariable Integer entryId, @RequestParam Integer targetEntryId) {
@RequestParam boolean horizontalMove, return templateDirectoryEntryService.move(horizontalMove, entryId, targetEntryId) ? R.ok()
@RequestParam Integer targetEntryId : R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "移动目录项失败");
) {
return templateDirectoryEntryService.move(horizontalMove, entryId, targetEntryId)?
R.ok(): R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "移动目录项失败");
} }
/** /**
* 重命名目录项 * 重命名目录项
* @param entryId 目录项ID * @param entryId 目录项ID
* @param name 名称 * @param name 名称
* @return R * @return R
*/ */
@ApiOperation(value = "重命名目录项", notes = "重命名目录项") @ApiOperation(value = "重命名目录项", notes = "重命名目录项")
@PatchMapping("/{entryId}/name") @PatchMapping("/{entryId}/name")
public R<?> rename(@PathVariable Integer entryId, @RequestParam String name) { public R<?> rename(@PathVariable Integer entryId, @RequestParam String name) {
return templateDirectoryEntryService.rename(entryId, name)? return templateDirectoryEntryService.rename(entryId, name) ? R.ok()
R.ok(): R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "重命名目录项"); : R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "重命名目录项");
} }
/** /**
* 新增模板文件目录项 * 新增模板文件目录项
*
* @param templateDirectoryCreateDTO 模板文件目录项 * @param templateDirectoryCreateDTO 模板文件目录项
* @return R * @return R
*/ */
@ApiOperation(value = "新增模板文件目录项", notes = "新增模板文件目录项") @ApiOperation(value = "新增模板文件目录项", notes = "新增模板文件目录项")
// @CreateOperationLogging(msg = "新增模板文件目录项" ) // @CreateOperationLogging(msg = "新增模板文件目录项" )
@PostMapping @PostMapping
//@PreAuthorize("@per.hasPermission('codegen:templatedirectoryentry:add')" ) // @PreAuthorize("@per.hasPermission('codegen:templatedirectoryentry:add')" )
public R<?> save(@RequestBody TemplateDirectoryCreateDTO templateDirectoryCreateDTO) { public R<?> save(@RequestBody TemplateDirectoryCreateDTO templateDirectoryCreateDTO) {
return templateDirectoryEntryService.createEntry(templateDirectoryCreateDTO) ? return templateDirectoryEntryService.createEntry(templateDirectoryCreateDTO) ? R.ok()
R.ok() : R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "新增模板文件目录项失败"); : R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "新增模板文件目录项失败");
} }
/** /**
* 通过id删除模板文件目录项 * 通过id删除模板文件目录项
*
* @param id id * @param id id
* @param mode 删除模式, * @param mode 删除模式, 1只删除本身将子节点上移 2. 删除自身及其所有子节点
* 1只删除本身将子节点上移
* 2. 删除自身及其所有子节点
*
* @return R * @return R
*/ */
@ApiOperation(value = "通过id删除模板文件目录项", notes = "通过id删除模板文件目录项") @ApiOperation(value = "通过id删除模板文件目录项", notes = "通过id删除模板文件目录项")
//@DeleteOperationLogging(msg = "通过id删除模板文件目录项" ) // @DeleteOperationLogging(msg = "通过id删除模板文件目录项" )
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
//@PreAuthorize("@per.hasPermission('codegen:templatedirectoryentry:del')" ) // @PreAuthorize("@per.hasPermission('codegen:templatedirectoryentry:del')" )
public R<?> removeById(@PathVariable Integer id, public R<?> removeById(@PathVariable Integer id, @RequestParam Integer mode) {
@RequestParam Integer mode) { return templateDirectoryEntryService.removeEntry(id, mode) ? R.ok()
return templateDirectoryEntryService.removeEntry(id, mode) ? : R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "通过id删除模板文件目录项失败");
R.ok() : R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "通过id删除模板文件目录项失败");
} }
} }

View File

@@ -13,7 +13,6 @@ import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
/** /**
* 模板组 * 模板组
* *
@@ -22,79 +21,77 @@ import org.springframework.web.bind.annotation.*;
*/ */
@RestController @RestController
@RequiredArgsConstructor @RequiredArgsConstructor
@RequestMapping("/gen/template/group" ) @RequestMapping("/gen/template/group")
@Api(value = "/template/group", tags = "模板组管理") @Api(value = "/template/group", tags = "模板组管理")
public class TemplateGroupController { public class TemplateGroupController {
private final TemplateGroupService templateGroupService; private final TemplateGroupService templateGroupService;
/** /**
* 分页查询 * 分页查询
* @param page 分页对象 * @param page 分页对象
* @param templateGroupQO 模板组 * @param templateGroupQO 模板组
* @return R * @return R
*/ */
@ApiOperation(value = "分页查询", notes = "分页查询") @ApiOperation(value = "分页查询", notes = "分页查询")
@GetMapping("/page" ) @GetMapping("/page")
//@PreAuthorize("@per.hasPermission('codegen:templategroup:read')" ) // @PreAuthorize("@per.hasPermission('codegen:templategroup:read')" )
public R<IPage<TemplateGroupVO>> getTemplateGroupPage( public R<IPage<TemplateGroupVO>> getTemplateGroupPage(Page<?> page, TemplateGroupQO templateGroupQO) {
Page<?> page, TemplateGroupQO templateGroupQO) { return R.ok(templateGroupService.selectPageVo(page, templateGroupQO));
return R.ok(templateGroupService.selectPageVo(page, templateGroupQO)); }
}
/**
* 通过id查询模板组
* @param id id
* @return R
*/
@ApiOperation(value = "通过id查询", notes = "通过id查询")
@GetMapping("/{id}")
// @PreAuthorize("@per.hasPermission('codegen:templategroup:read')" )
public R<TemplateGroup> getById(@PathVariable("id") Integer id) {
return R.ok(templateGroupService.getById(id));
}
/** /**
* 通过id查询模板组 * 新增模板组
* @param id id * @param templateGroup 模板组
* @return R * @return R
*/ */
@ApiOperation(value = "通过id查询", notes = "通过id查询") @ApiOperation(value = "新增模板组", notes = "新增模板组")
@GetMapping("/{id}" ) // @CreateOperationLogging(msg = "新增模板组" )
//@PreAuthorize("@per.hasPermission('codegen:templategroup:read')" ) @PostMapping
public R<TemplateGroup> getById(@PathVariable("id" ) Integer id) { // @PreAuthorize("@per.hasPermission('codegen:templategroup:add')" )
return R.ok(templateGroupService.getById(id)); public R save(@RequestBody TemplateGroup templateGroup) {
} return templateGroupService.save(templateGroup) ? R.ok()
: R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "新增模板组失败");
}
/** /**
* 新增模板组 * 修改模板组
* @param templateGroup 模板组 * @param templateGroup 模板组
* @return R * @return R
*/ */
@ApiOperation(value = "新增模板组", notes = "新增模板组") @ApiOperation(value = "修改模板组", notes = "修改模板组")
//@CreateOperationLogging(msg = "新增模板组" ) // @UpdateOperationLogging(msg = "修改模板组" )
@PostMapping @PutMapping
//@PreAuthorize("@per.hasPermission('codegen:templategroup:add')" ) // @PreAuthorize("@per.hasPermission('codegen:templategroup:edit')" )
public R save(@RequestBody TemplateGroup templateGroup) { public R updateById(@RequestBody TemplateGroup templateGroup) {
return templateGroupService.save(templateGroup) ? return templateGroupService.updateById(templateGroup) ? R.ok()
R.ok() : R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "新增模板组失败"); : R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "修改模板组失败");
} }
/** /**
* 修改模板组 * 通过id删除模板组
* @param templateGroup 模板组 * @param id id
* @return R * @return R
*/ */
@ApiOperation(value = "修改模板组", notes = "修改模板组") @ApiOperation(value = "通过id删除模板组", notes = "通过id删除模板组")
// @UpdateOperationLogging(msg = "修改模板组" ) // @DeleteOperationLogging(msg = "通过id删除模板组" )
@PutMapping @DeleteMapping("/{id}")
//@PreAuthorize("@per.hasPermission('codegen:templategroup:edit')" ) // @PreAuthorize("@per.hasPermission('codegen:templategroup:del')" )
public R updateById(@RequestBody TemplateGroup templateGroup) { public R removeById(@PathVariable Integer id) {
return templateGroupService.updateById(templateGroup) ? return templateGroupService.removeById(id) ? R.ok()
R.ok() : R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "修改模板组失败"); : R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "通过id删除模板组失败");
} }
/**
* 通过id删除模板组
* @param id id
* @return R
*/
@ApiOperation(value = "通过id删除模板组", notes = "通过id删除模板组")
//@DeleteOperationLogging(msg = "通过id删除模板组" )
@DeleteMapping("/{id}" )
//@PreAuthorize("@per.hasPermission('codegen:templategroup:del')" )
public R removeById(@PathVariable Integer id) {
return templateGroupService.removeById(id) ?
R.ok() : R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "通过id删除模板组失败");
}
} }

Some files were not shown because too many files have changed in this diff Show More