feat: change JPA to Mybatis
This commit is contained in:
46
pom.xml
46
pom.xml
@@ -23,12 +23,10 @@
|
|||||||
<open-api.version>2.5.0</open-api.version>
|
<open-api.version>2.5.0</open-api.version>
|
||||||
<jedis.version>5.1.3</jedis.version>
|
<jedis.version>5.1.3</jedis.version>
|
||||||
<jwt.version>4.4.0</jwt.version>
|
<jwt.version>4.4.0</jwt.version>
|
||||||
|
<mybatis-plus.version>3.5.6</mybatis-plus.version>
|
||||||
</properties>
|
</properties>
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-web</artifactId>
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
@@ -45,6 +43,16 @@
|
|||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-data-redis</artifactId>
|
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<!-- <dependency>-->
|
||||||
|
<!-- <groupId>org.springframework.boot</groupId>-->
|
||||||
|
<!-- <artifactId>spring-boot-starter-data-jpa</artifactId>-->
|
||||||
|
<!-- </dependency>-->
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.baomidou</groupId>
|
||||||
|
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
|
||||||
|
<version>${mybatis-plus.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.mysql</groupId>
|
<groupId>com.mysql</groupId>
|
||||||
@@ -75,11 +83,11 @@
|
|||||||
<version>${commons-lang3.version}</version>
|
<version>${commons-lang3.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<!-- <dependency>-->
|
||||||
<groupId>org.springdoc</groupId>
|
<!-- <groupId>org.springdoc</groupId>-->
|
||||||
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
|
<!-- <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>-->
|
||||||
<version>${open-api.version}</version>
|
<!-- <version>${open-api.version}</version>-->
|
||||||
</dependency>
|
<!-- </dependency>-->
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>redis.clients</groupId>
|
<groupId>redis.clients</groupId>
|
||||||
@@ -93,6 +101,19 @@
|
|||||||
<version>${jwt.version}</version>
|
<version>${jwt.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.fasterxml.jackson.core</groupId>
|
||||||
|
<artifactId>jackson-databind</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||||
|
<artifactId>jackson-datatype-jsr310</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<!-- <dependency>-->
|
||||||
|
<!-- <groupId>com.fasterxml.jackson.datatype</groupId>-->
|
||||||
|
<!-- <artifactId>jackson-datatype-hibernate6</artifactId>-->
|
||||||
|
<!-- </dependency>-->
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@@ -139,4 +160,11 @@
|
|||||||
|
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
<repositories>
|
||||||
|
<repository>
|
||||||
|
<id>maven_central</id>
|
||||||
|
<name>Maven Central</name>
|
||||||
|
<url>https://repo.maven.apache.org/maven2/</url>
|
||||||
|
</repository>
|
||||||
|
</repositories>
|
||||||
</project>
|
</project>
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
package com.rainbus.dlp;
|
package com.rainbus.dlp;
|
||||||
|
|
||||||
|
import org.mybatis.spring.annotation.MapperScan;
|
||||||
import org.springframework.boot.SpringApplication;
|
import org.springframework.boot.SpringApplication;
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
|
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
|
||||||
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
|
|
||||||
|
|
||||||
@EnableJpaAuditing
|
|
||||||
@SpringBootApplication(exclude = {SecurityAutoConfiguration.class})
|
@SpringBootApplication(exclude = {SecurityAutoConfiguration.class})
|
||||||
|
@MapperScan("com.rainbus.dlp.repository.mapper")
|
||||||
public class DlpAdminBackendApplication {
|
public class DlpAdminBackendApplication {
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
package com.rainbus.dlp.config;
|
package com.rainbus.dlp.config;
|
||||||
|
|
||||||
import com.rainbus.dlp.entity.dto.user.CustomUserDetails;
|
|
||||||
import com.rainbus.dlp.entity.dto.user.TokenClaims;
|
import com.rainbus.dlp.entity.dto.user.TokenClaims;
|
||||||
import com.rainbus.dlp.service.UserServ;
|
import com.rainbus.dlp.service.UserServ;
|
||||||
import com.rainbus.dlp.util.JwtUtil;
|
import com.rainbus.dlp.util.JwtUtil;
|
||||||
@@ -13,11 +12,9 @@ import org.apache.commons.lang3.StringUtils;
|
|||||||
import org.springframework.lang.NonNull;
|
import org.springframework.lang.NonNull;
|
||||||
import org.springframework.security.authentication.AuthenticationManager;
|
import org.springframework.security.authentication.AuthenticationManager;
|
||||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||||
import org.springframework.security.core.Authentication;
|
|
||||||
import org.springframework.security.core.GrantedAuthority;
|
import org.springframework.security.core.GrantedAuthority;
|
||||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||||
import org.springframework.security.core.context.SecurityContextHolder;
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
import org.springframework.security.core.userdetails.User;
|
|
||||||
import org.springframework.security.core.userdetails.UserDetails;
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
|
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
@@ -42,10 +39,10 @@ public class JwtFilter extends OncePerRequestFilter {
|
|||||||
filterChain.doFilter(request, response);
|
filterChain.doFilter(request, response);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
TokenClaims claims = JwtUtil.parseValidToken(token);
|
TokenClaims claims = JwtUtil.parseValidToken(token);
|
||||||
UserDetails userDetails = userServ.loadUserByUsername(claims.getUsername());
|
UserDetails userDetails = userServ.loadUserByUsername(claims.getUsername());
|
||||||
List<GrantedAuthority> authorities = claims.getRoles().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
|
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
|
||||||
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, authorities);
|
|
||||||
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
|
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
|
||||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||||
filterChain.doFilter(request, response);
|
filterChain.doFilter(request, response);
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package com.rainbus.dlp.config;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
|
||||||
|
import com.rainbus.dlp.entity.dto.user.CustomUserDetails;
|
||||||
|
import org.apache.ibatis.reflection.MetaObject;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class MybatisMetaObjectHandler implements MetaObjectHandler {
|
||||||
|
@Override
|
||||||
|
public void insertFill(MetaObject metaObject) {
|
||||||
|
if (metaObject.hasSetter("createAt")) {
|
||||||
|
this.fillStrategy(metaObject, "createAt", LocalDateTime.now());
|
||||||
|
}
|
||||||
|
if (metaObject.hasSetter("updateAt")) {
|
||||||
|
this.fillStrategy(metaObject, "updateAt", LocalDateTime.now());
|
||||||
|
}
|
||||||
|
if (metaObject.hasSetter("createBy")) {
|
||||||
|
this.fillStrategy(metaObject, "createBy", this.getCurrentUserId());
|
||||||
|
}
|
||||||
|
if (metaObject.hasSetter("updateBy")) {
|
||||||
|
this.fillStrategy(metaObject, "updateBy", this.getCurrentUserId());
|
||||||
|
}
|
||||||
|
if (metaObject.hasSetter("isDeleted")) {
|
||||||
|
this.fillStrategy(metaObject, "isDeleted", false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void updateFill(MetaObject metaObject) {
|
||||||
|
if (metaObject.hasSetter("updateAt")) {
|
||||||
|
this.fillStrategy(metaObject, "updateAt", LocalDateTime.now());
|
||||||
|
}
|
||||||
|
if (metaObject.hasSetter("updateBy")) {
|
||||||
|
this.fillStrategy(metaObject, "updateBy", this.getCurrentUserId());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Long getCurrentUserId() {
|
||||||
|
CustomUserDetails userDetails = (CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
|
||||||
|
return userDetails.getId();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -2,36 +2,29 @@ package com.rainbus.dlp.config;
|
|||||||
|
|
||||||
|
|
||||||
import com.rainbus.dlp.entity.pojo.user.SysRole;
|
import com.rainbus.dlp.entity.pojo.user.SysRole;
|
||||||
import com.rainbus.dlp.repository.user.SysRoleRepo;
|
|
||||||
import com.rainbus.dlp.service.UserServ;
|
import com.rainbus.dlp.service.UserServ;
|
||||||
import lombok.AllArgsConstructor;
|
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.http.HttpMethod;
|
import org.springframework.http.HttpMethod;
|
||||||
import org.springframework.security.authentication.AuthenticationManager;
|
import org.springframework.security.authentication.AuthenticationManager;
|
||||||
import org.springframework.security.authentication.AuthenticationProvider;
|
|
||||||
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
|
|
||||||
import org.springframework.security.config.Customizer;
|
import org.springframework.security.config.Customizer;
|
||||||
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
|
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
|
||||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||||
import org.springframework.security.config.annotation.web.configurers.AuthorizeHttpRequestsConfigurer;
|
|
||||||
import org.springframework.security.config.annotation.web.configurers.SessionManagementConfigurer;
|
|
||||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
import org.springframework.security.web.SecurityFilterChain;
|
import org.springframework.security.web.SecurityFilterChain;
|
||||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||||
import org.springframework.web.bind.annotation.RequestMethod;
|
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
@EnableWebSecurity
|
@EnableWebSecurity
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class SecurityConfig {
|
public class SecurityConf {
|
||||||
|
|
||||||
private final UserServ userServ;
|
private final UserServ userServ;
|
||||||
|
|
||||||
@@ -41,7 +34,7 @@ public class SecurityConfig {
|
|||||||
.csrf(AbstractHttpConfigurer::disable)
|
.csrf(AbstractHttpConfigurer::disable)
|
||||||
.sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
.sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||||
.authorizeHttpRequests((authorizeHttpRequests) -> {
|
.authorizeHttpRequests((authorizeHttpRequests) -> {
|
||||||
userServ.getAllRoles().forEach(role -> {
|
userServ.listRoleResource().forEach(role -> {
|
||||||
role.getResources().forEach(resource -> {
|
role.getResources().forEach(resource -> {
|
||||||
authorizeHttpRequests.requestMatchers(
|
authorizeHttpRequests.requestMatchers(
|
||||||
HttpMethod.valueOf(resource.getRequestMethod().name()),
|
HttpMethod.valueOf(resource.getRequestMethod().name()),
|
||||||
16
src/main/java/com/rainbus/dlp/controller/ExceptionCtrl.java
Normal file
16
src/main/java/com/rainbus/dlp/controller/ExceptionCtrl.java
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
package com.rainbus.dlp.controller;
|
||||||
|
|
||||||
|
import com.rainbus.dlp.entity.exception.UsernameOrPasswordExcp;
|
||||||
|
import com.rainbus.dlp.entity.resp.Resp;
|
||||||
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||||
|
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||||
|
|
||||||
|
@RestControllerAdvice
|
||||||
|
public class ExceptionCtrl {
|
||||||
|
|
||||||
|
@ExceptionHandler(UsernameOrPasswordExcp.class)
|
||||||
|
public Resp<Object> handler(UsernameOrPasswordExcp e) {
|
||||||
|
return Resp.fail(e.getCode(), e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,60 +1,66 @@
|
|||||||
package com.rainbus.dlp.controller;
|
package com.rainbus.dlp.controller;
|
||||||
|
|
||||||
import com.rainbus.dlp.entity.dto.user.TokenClaims;
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
import com.rainbus.dlp.entity.mapper.UserConv;
|
import com.rainbus.dlp.entity.converter.UserConv;
|
||||||
import com.rainbus.dlp.entity.pojo.user.SysUser;
|
import com.rainbus.dlp.entity.pojo.user.SysUser;
|
||||||
import com.rainbus.dlp.entity.req.user.RegisterReq;
|
import com.rainbus.dlp.entity.req.user.RegisterReq;
|
||||||
import com.rainbus.dlp.entity.resp.Resp;
|
import com.rainbus.dlp.entity.resp.Resp;
|
||||||
import com.rainbus.dlp.repository.user.SysUserRepo;
|
import com.rainbus.dlp.repository.mapper.user.SysRoleMapper;
|
||||||
import com.rainbus.dlp.util.JwtUtil;
|
import com.rainbus.dlp.repository.mapper.user.SysUserMapper;
|
||||||
|
import com.rainbus.dlp.service.SystemServ;
|
||||||
|
import com.rainbus.dlp.util.RedisUtil;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import org.springframework.security.authentication.AuthenticationManager;
|
import org.springframework.security.authentication.AuthenticationManager;
|
||||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
|
||||||
import org.springframework.security.core.Authentication;
|
|
||||||
import org.springframework.security.core.context.SecurityContextHolder;
|
|
||||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
import org.springframework.validation.annotation.Validated;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/user")
|
@RequestMapping("/user")
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
public class UserCtrl {
|
public class UserCtrl {
|
||||||
|
|
||||||
private final SysUserRepo userRepo;
|
|
||||||
private final UserConv userConv;
|
private final UserConv userConv;
|
||||||
private final AuthenticationManager authenticationManager;
|
private final AuthenticationManager authenticationManager;
|
||||||
private final PasswordEncoder passwordEncoder;
|
private final PasswordEncoder passwordEncoder;
|
||||||
|
private final RedisUtil redisUtil;
|
||||||
|
private final SystemServ systemServ;
|
||||||
|
private final SysUserMapper sysUserMapper;
|
||||||
|
private final SysRoleMapper sysRoleMapper;
|
||||||
|
|
||||||
@PostMapping("/register")
|
@PostMapping("/addUser")
|
||||||
public Resp<Object> register(@RequestBody RegisterReq req) {
|
public Resp<Object> addUser(@RequestBody @Validated RegisterReq req) {
|
||||||
req.setPassword(passwordEncoder.encode(req.getPassword()));
|
// userRepo.save(userConv.RegisterReq2Pojo(req, defaultPwd(req.getUsername())));
|
||||||
userRepo.save(userConv.RegisterReq2Pojo(req));
|
|
||||||
return Resp.success();
|
return Resp.success();
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/login")
|
@PostMapping("/login")
|
||||||
public Resp<Object> login(@RequestBody RegisterReq req) {
|
public Resp<Object> login(@RequestBody RegisterReq req) {
|
||||||
SysUser user = userRepo.findByUsername(req.getUsername()).orElse(null);
|
// SysUser user = userRepo.findByUsername(req.getUsername()).orElse(null);
|
||||||
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(req.getUsername(), req.getPassword()));
|
// Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(req.getUsername(), req.getPassword()));
|
||||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
// SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||||
if (user == null) {
|
// if (user == null) {
|
||||||
return Resp.fail("user not exist");
|
// return Resp.fail("user not exist");
|
||||||
}
|
// }
|
||||||
if (!passwordEncoder.matches(req.getPassword(), user.getPassword())) {
|
// if (!passwordEncoder.matches(req.getPassword(), user.getPassword())) {
|
||||||
return Resp.fail("password error");
|
// return Resp.fail("password error");
|
||||||
}
|
// }
|
||||||
return Resp.success(JwtUtil.generateToken(userConv.ClaimsPojo2Dto(user)));
|
// return Resp.success(JwtUtil.generateToken(userConv.ClaimsPojo2Dto(user)));
|
||||||
|
return Resp.success();
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("token")
|
@PostMapping("/test")
|
||||||
public Resp<Object> token() {
|
public Resp<Object> test() throws JsonProcessingException {
|
||||||
TokenClaims claims = new TokenClaims();
|
return Resp.success(redisUtil.get("user", SysUser.class));
|
||||||
claims.setUsername("rainbus");
|
}
|
||||||
claims.setId(1L);
|
|
||||||
claims.setRoles(List.of("USER"));
|
@GetMapping("/test2")
|
||||||
return Resp.success(JwtUtil.generateToken(claims));
|
public Resp<Object> test2() {
|
||||||
|
return Resp.success(sysRoleMapper.selectAllRoleResource());
|
||||||
|
}
|
||||||
|
|
||||||
|
private String defaultPwd(String username) {
|
||||||
|
return passwordEncoder.encode("Dlp" + username);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.rainbus.dlp.entity.mapper;
|
package com.rainbus.dlp.entity.converter;
|
||||||
|
|
||||||
|
import com.rainbus.dlp.entity.dto.user.CustomUserDetails;
|
||||||
import com.rainbus.dlp.entity.dto.user.TokenClaims;
|
import com.rainbus.dlp.entity.dto.user.TokenClaims;
|
||||||
import com.rainbus.dlp.entity.pojo.user.SysUser;
|
import com.rainbus.dlp.entity.pojo.user.SysUser;
|
||||||
import com.rainbus.dlp.entity.req.user.RegisterReq;
|
import com.rainbus.dlp.entity.req.user.RegisterReq;
|
||||||
@@ -11,9 +12,13 @@ import org.mapstruct.Mapping;
|
|||||||
public interface UserConv {
|
public interface UserConv {
|
||||||
|
|
||||||
@InheritInverseConfiguration
|
@InheritInverseConfiguration
|
||||||
SysUser RegisterReq2Pojo(RegisterReq req);
|
SysUser RegisterReq2Pojo(RegisterReq req, String password);
|
||||||
|
|
||||||
@Mapping(target = "roles", expression = "java(user.getRoles().stream().map(com.rainbus.dlp.entity.pojo.user.SysRole::getRole).toList())")
|
@Mapping(target = "roles", expression = "java(user.getRoles().stream().map(com.rainbus.dlp.entity.pojo.user.SysRole::getRole).toList())")
|
||||||
TokenClaims ClaimsPojo2Dto(SysUser user);
|
TokenClaims ClaimsPojo2Dto(SysUser user);
|
||||||
|
|
||||||
|
@Mapping(target = "authorities", ignore = true)
|
||||||
|
@Mapping(target = "roles", expression = "java(user.getRoles().stream().map(com.rainbus.dlp.entity.pojo.user.SysRole::getRole).toList())")
|
||||||
|
CustomUserDetails UserPojo2UserDetails(SysUser user);
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -1,37 +1,56 @@
|
|||||||
package com.rainbus.dlp.entity.dto.user;
|
package com.rainbus.dlp.entity.dto.user;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||||
|
import com.rainbus.dlp.entity.enums.UserStatusEnum;
|
||||||
|
import com.rainbus.dlp.entity.pojo.user.SysOrg;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
import org.springframework.security.core.GrantedAuthority;
|
||||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||||
import org.springframework.security.core.userdetails.UserDetails;
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
@Getter
|
@Data
|
||||||
|
@NoArgsConstructor
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
public class CustomUserDetails implements UserDetails {
|
public class CustomUserDetails implements UserDetails {
|
||||||
|
|
||||||
|
private Long id;
|
||||||
private String username;
|
private String username;
|
||||||
private String password;
|
private String password;
|
||||||
private List<SimpleGrantedAuthority> authorities;
|
private List<String> roles;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@JsonIgnore
|
||||||
|
public Collection<? extends GrantedAuthority> getAuthorities() {
|
||||||
|
return roles.stream().map(SimpleGrantedAuthority::new).toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@JsonIgnore
|
||||||
public boolean isAccountNonExpired() {
|
public boolean isAccountNonExpired() {
|
||||||
return UserDetails.super.isAccountNonExpired();
|
return UserDetails.super.isAccountNonExpired();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@JsonIgnore
|
||||||
public boolean isAccountNonLocked() {
|
public boolean isAccountNonLocked() {
|
||||||
return UserDetails.super.isAccountNonLocked();
|
return UserDetails.super.isAccountNonLocked();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@JsonIgnore
|
||||||
public boolean isCredentialsNonExpired() {
|
public boolean isCredentialsNonExpired() {
|
||||||
return UserDetails.super.isCredentialsNonExpired();
|
return UserDetails.super.isCredentialsNonExpired();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@JsonIgnore
|
||||||
public boolean isEnabled() {
|
public boolean isEnabled() {
|
||||||
return UserDetails.super.isEnabled();
|
return UserDetails.super.isEnabled();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package com.rainbus.dlp.entity.enums;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Getter;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@AllArgsConstructor
|
||||||
|
public enum ExceptionEnum {
|
||||||
|
USERNAME_OR_PASSWORD_ERROR(40001, "用户名或密码错误"),
|
||||||
|
USER_DISABLED(40002, "用户当前无法使用");
|
||||||
|
|
||||||
|
|
||||||
|
private final int code;
|
||||||
|
private final String message;
|
||||||
|
}
|
||||||
15
src/main/java/com/rainbus/dlp/entity/enums/OrgTypeEnum.java
Normal file
15
src/main/java/com/rainbus/dlp/entity/enums/OrgTypeEnum.java
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
package com.rainbus.dlp.entity.enums;
|
||||||
|
|
||||||
|
import lombok.Getter;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
public enum OrgTypeEnum {
|
||||||
|
COMPANY("公司"), DEPARTMENT("部门"), USER_GROUP("用户组");
|
||||||
|
|
||||||
|
private final String desc;
|
||||||
|
|
||||||
|
OrgTypeEnum(String desc) {
|
||||||
|
this.desc = desc;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package com.rainbus.dlp.entity.enums;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Getter;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@AllArgsConstructor
|
||||||
|
public enum UserStatusEnum {
|
||||||
|
ACTIVATED("激活"), UNACTIVATED("未激活"), DISABLED("禁用");
|
||||||
|
private final String desc;
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package com.rainbus.dlp.entity.exception;
|
||||||
|
|
||||||
|
import com.rainbus.dlp.entity.enums.ExceptionEnum;
|
||||||
|
import lombok.Getter;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
public class UserDisabledExcp extends RuntimeException {
|
||||||
|
private final int code;
|
||||||
|
private final String message;
|
||||||
|
|
||||||
|
public UserDisabledExcp() {
|
||||||
|
this.code = ExceptionEnum.USER_DISABLED.getCode();
|
||||||
|
this.message = ExceptionEnum.USER_DISABLED.getMessage();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package com.rainbus.dlp.entity.exception;
|
||||||
|
|
||||||
|
import com.rainbus.dlp.entity.enums.ExceptionEnum;
|
||||||
|
import lombok.Getter;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
public class UsernameOrPasswordExcp extends RuntimeException {
|
||||||
|
private final int code;
|
||||||
|
private final String message;
|
||||||
|
|
||||||
|
public UsernameOrPasswordExcp() {
|
||||||
|
this.code = ExceptionEnum.USERNAME_OR_PASSWORD_ERROR.getCode();
|
||||||
|
this.message = ExceptionEnum.USERNAME_OR_PASSWORD_ERROR.getMessage();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
35
src/main/java/com/rainbus/dlp/entity/pojo/user/SysOrg.java
Normal file
35
src/main/java/com/rainbus/dlp/entity/pojo/user/SysOrg.java
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
package com.rainbus.dlp.entity.pojo.user;
|
||||||
|
|
||||||
|
import com.rainbus.dlp.entity.enums.OrgTypeEnum;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public class SysOrg {
|
||||||
|
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
private String org;
|
||||||
|
|
||||||
|
private OrgTypeEnum type;
|
||||||
|
|
||||||
|
private String fullPathName;
|
||||||
|
|
||||||
|
private String fullPath;
|
||||||
|
|
||||||
|
private Long parentId;
|
||||||
|
|
||||||
|
private String region;
|
||||||
|
|
||||||
|
private String area;
|
||||||
|
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
|
||||||
|
private LocalDateTime updatedAt;
|
||||||
|
|
||||||
|
private Long createdBy;
|
||||||
|
|
||||||
|
private Long updatedBy;
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,44 +1,28 @@
|
|||||||
package com.rainbus.dlp.entity.pojo.user;
|
package com.rainbus.dlp.entity.pojo.user;
|
||||||
|
|
||||||
|
|
||||||
import jakarta.persistence.*;
|
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
import org.springframework.data.annotation.CreatedBy;
|
|
||||||
import org.springframework.data.annotation.CreatedDate;
|
|
||||||
import org.springframework.data.annotation.LastModifiedBy;
|
|
||||||
import org.springframework.data.annotation.LastModifiedDate;
|
|
||||||
import org.springframework.web.bind.annotation.RequestMethod;
|
import org.springframework.web.bind.annotation.RequestMethod;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
@Entity
|
|
||||||
public class SysResource {
|
public class SysResource {
|
||||||
|
|
||||||
@Id
|
|
||||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
|
||||||
private Long id;
|
private Long id;
|
||||||
|
|
||||||
@Column
|
|
||||||
private String resource;
|
private String resource;
|
||||||
|
|
||||||
@Column
|
|
||||||
@Enumerated(EnumType.STRING)
|
|
||||||
private RequestMethod requestMethod;
|
private RequestMethod requestMethod;
|
||||||
|
|
||||||
@Column
|
|
||||||
private String description;
|
private String description;
|
||||||
|
|
||||||
@CreatedBy
|
|
||||||
private Long createdBy;
|
private Long createdBy;
|
||||||
|
|
||||||
@LastModifiedBy
|
|
||||||
private Long updatedBy;
|
private Long updatedBy;
|
||||||
|
|
||||||
@CreatedDate
|
|
||||||
private LocalDateTime createdAt;
|
private LocalDateTime createdAt;
|
||||||
|
|
||||||
@LastModifiedDate
|
|
||||||
private LocalDateTime updatedAt;
|
private LocalDateTime updatedAt;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,49 +1,26 @@
|
|||||||
package com.rainbus.dlp.entity.pojo.user;
|
package com.rainbus.dlp.entity.pojo.user;
|
||||||
|
|
||||||
import com.rainbus.dlp.entity.enums.RoleEnum;
|
|
||||||
import jakarta.persistence.*;
|
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
import org.hibernate.annotations.Comment;
|
|
||||||
import org.springframework.data.annotation.CreatedBy;
|
|
||||||
import org.springframework.data.annotation.CreatedDate;
|
|
||||||
import org.springframework.data.annotation.LastModifiedBy;
|
|
||||||
import org.springframework.data.annotation.LastModifiedDate;
|
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
@Entity
|
|
||||||
public class SysRole {
|
public class SysRole {
|
||||||
|
|
||||||
@Id
|
|
||||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
|
||||||
@Comment("id")
|
|
||||||
private Long id;
|
private Long id;
|
||||||
|
|
||||||
@Comment("角色")
|
|
||||||
private String role;
|
private String role;
|
||||||
|
|
||||||
@Column
|
|
||||||
@Comment("描述")
|
|
||||||
private String description;
|
private String description;
|
||||||
|
|
||||||
@OneToMany(fetch = FetchType.EAGER)
|
|
||||||
private List<SysResource> resources;
|
private List<SysResource> resources;
|
||||||
|
|
||||||
@CreatedBy
|
|
||||||
@Comment("创建人")
|
|
||||||
private Long createdBy;
|
private Long createdBy;
|
||||||
|
|
||||||
@LastModifiedBy
|
|
||||||
@Comment("更新人")
|
|
||||||
private Long updatedBy;
|
private Long updatedBy;
|
||||||
|
|
||||||
@CreatedDate
|
|
||||||
@Comment("创建时间")
|
|
||||||
private Long createdAt;
|
private Long createdAt;
|
||||||
|
|
||||||
@LastModifiedDate
|
|
||||||
@Comment("更新时间")
|
|
||||||
private Long updatedAt;
|
private Long updatedAt;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,50 +1,37 @@
|
|||||||
package com.rainbus.dlp.entity.pojo.user;
|
package com.rainbus.dlp.entity.pojo.user;
|
||||||
|
|
||||||
import com.rainbus.dlp.entity.enums.RoleEnum;
|
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||||
import jakarta.persistence.*;
|
import com.rainbus.dlp.entity.enums.UserStatusEnum;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
import org.springframework.data.annotation.CreatedBy;
|
|
||||||
import org.springframework.data.annotation.CreatedDate;
|
|
||||||
import org.springframework.data.annotation.LastModifiedBy;
|
|
||||||
import org.springframework.data.annotation.LastModifiedDate;
|
|
||||||
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
@Entity
|
|
||||||
//@SQLRestriction("is_deleted = 0")
|
|
||||||
@EntityListeners(value = AuditingEntityListener.class)
|
|
||||||
//@SQLDelete(sql = "update `user` set is_deleted = 1 where id = ?")
|
|
||||||
public class SysUser {
|
public class SysUser {
|
||||||
|
|
||||||
@Id
|
|
||||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
|
||||||
private Long id;
|
private Long id;
|
||||||
|
|
||||||
@Column
|
|
||||||
private String username;
|
private String username;
|
||||||
|
|
||||||
@Column
|
|
||||||
private String password;
|
private String password;
|
||||||
|
|
||||||
@OneToMany(fetch = FetchType.EAGER)
|
private String email;
|
||||||
|
|
||||||
private List<SysRole> roles;
|
private List<SysRole> roles;
|
||||||
|
|
||||||
@CreatedBy
|
private SysOrg org;
|
||||||
|
|
||||||
|
private UserStatusEnum status;
|
||||||
|
|
||||||
private Long createBy;
|
private Long createBy;
|
||||||
|
|
||||||
@LastModifiedBy
|
|
||||||
private Long updateBy;
|
private Long updateBy;
|
||||||
|
|
||||||
@CreatedDate
|
|
||||||
private LocalDateTime createAt;
|
private LocalDateTime createAt;
|
||||||
|
|
||||||
@LastModifiedDate
|
|
||||||
private LocalDateTime updateAt;
|
private LocalDateTime updateAt;
|
||||||
|
|
||||||
@Column
|
|
||||||
private Integer isDeleted;
|
private Integer isDeleted;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,16 @@
|
|||||||
package com.rainbus.dlp.entity.req.user;
|
package com.rainbus.dlp.entity.req.user;
|
||||||
|
|
||||||
|
import jakarta.validation.constraints.Email;
|
||||||
|
import jakarta.validation.constraints.Pattern;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
public class RegisterReq {
|
public class RegisterReq {
|
||||||
|
|
||||||
|
@Pattern(regexp = "^[a-zA-Z0-9_-]{4,16}$", message = "用户名格式不正确")
|
||||||
private String username;
|
private String username;
|
||||||
|
|
||||||
private String password;
|
@Email(message = "邮箱格式不正确")
|
||||||
|
private String email;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,6 +20,12 @@ public class Resp<T> {
|
|||||||
return new Resp<>(200, "success", null);
|
return new Resp<>(200, "success", null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
public static Resp<Object> fail(int code, String msg) {
|
||||||
|
return new Resp<>(code, msg, null);
|
||||||
|
}
|
||||||
|
|
||||||
public static Resp<Object> fail(String msg) {
|
public static Resp<Object> fail(String msg) {
|
||||||
return new Resp<>(400, msg, null);
|
return new Resp<>(400, msg, null);
|
||||||
}
|
}
|
||||||
|
|||||||
36
src/main/java/com/rainbus/dlp/repository/dao/UserDao.java
Normal file
36
src/main/java/com/rainbus/dlp/repository/dao/UserDao.java
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
package com.rainbus.dlp.repository.dao;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.rainbus.dlp.entity.pojo.user.SysRole;
|
||||||
|
import com.rainbus.dlp.entity.pojo.user.SysUser;
|
||||||
|
import com.rainbus.dlp.repository.mapper.user.SysRoleMapper;
|
||||||
|
import com.rainbus.dlp.repository.mapper.user.SysUserMapper;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class UserDao {
|
||||||
|
|
||||||
|
private final SysUserMapper userMapper;
|
||||||
|
private final SysRoleMapper roleMapper;
|
||||||
|
|
||||||
|
public Optional<SysUser> findUserByUsername(String username) {
|
||||||
|
LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<SysUser>()
|
||||||
|
.eq(SysUser::getUsername, username);
|
||||||
|
return Optional.ofNullable(userMapper.selectOne(wrapper));
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<SysUser> findUserRoleOrgByUsername(String username) {
|
||||||
|
return Optional.ofNullable(userMapper.selectUserRoleOrgByUsername(username));
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<SysRole> listRoleResource() {
|
||||||
|
return roleMapper.selectAllRoleResource();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package com.rainbus.dlp.repository.mapper.user;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.rainbus.dlp.entity.pojo.user.SysOrg;
|
||||||
|
|
||||||
|
public interface SysOrgMapper extends BaseMapper<SysOrg> {
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package com.rainbus.dlp.repository.mapper.user;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.Wrapper;
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.rainbus.dlp.entity.pojo.user.SysResource;
|
||||||
|
import org.apache.ibatis.annotations.Select;
|
||||||
|
import org.mapstruct.Mapping;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public interface SysResourceMapper extends BaseMapper<SysResource> {
|
||||||
|
|
||||||
|
@Select("""
|
||||||
|
select * from sys_resource sr
|
||||||
|
left join sys_role_resources srr
|
||||||
|
on sr.id = srr.resources_id
|
||||||
|
where srr.sys_role_id = #{roleId}
|
||||||
|
""")
|
||||||
|
List<SysResource> selectListByRoleId(Long roleId);
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package com.rainbus.dlp.repository.mapper.user;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.rainbus.dlp.entity.pojo.user.SysRole;
|
||||||
|
import org.apache.ibatis.annotations.*;
|
||||||
|
|
||||||
|
import javax.management.relation.Role;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public interface SysRoleMapper extends BaseMapper<SysRole> {
|
||||||
|
|
||||||
|
@Select("""
|
||||||
|
select * from sys_role sr
|
||||||
|
left join sys_user_roles sur
|
||||||
|
on sr.id = sur.roles_id
|
||||||
|
where sur.sys_user_id = #{userId}
|
||||||
|
""")
|
||||||
|
List<SysRole> selectListByUserId(Long userId);
|
||||||
|
|
||||||
|
@Select("""
|
||||||
|
select * from sys_role where id = 4
|
||||||
|
""")
|
||||||
|
@Results(
|
||||||
|
@Result(
|
||||||
|
property = "resources",
|
||||||
|
column = "id",
|
||||||
|
many = @Many(
|
||||||
|
select = "com.rainbus.dlp.repository.mapper.user.SysResourceMapper.selectListByRoleId"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
List<SysRole> selectAllRoleResource();
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package com.rainbus.dlp.repository.mapper.user;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.rainbus.dlp.entity.pojo.user.SysUser;
|
||||||
|
import org.apache.ibatis.annotations.*;
|
||||||
|
|
||||||
|
public interface SysUserMapper extends BaseMapper<SysUser> {
|
||||||
|
@Select("""
|
||||||
|
select * from sys_user where username = #{username}
|
||||||
|
""")
|
||||||
|
@Results({
|
||||||
|
@Result(column = "id", property = "id"),
|
||||||
|
@Result(
|
||||||
|
column = "id",
|
||||||
|
property = "roles",
|
||||||
|
many = @Many(
|
||||||
|
select = "com.rainbus.dlp.repository.mapper.user.SysRoleMapper.selectListByUserId"
|
||||||
|
)
|
||||||
|
),
|
||||||
|
@Result(
|
||||||
|
column = "org_id",
|
||||||
|
property = "org",
|
||||||
|
one = @One(
|
||||||
|
select = "com.rainbus.dlp.repository.mapper.user.SysOrgMapper.selectById"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
})
|
||||||
|
SysUser selectUserRoleOrgByUsername(@Param("username") String username);
|
||||||
|
}
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
package com.rainbus.dlp.repository.user;
|
|
||||||
|
|
||||||
import com.rainbus.dlp.entity.pojo.user.SysResource;
|
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
|
||||||
|
|
||||||
public interface SysResourceRepo extends JpaRepository<SysResource, Long> {
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
package com.rainbus.dlp.repository.user;
|
|
||||||
|
|
||||||
import com.rainbus.dlp.entity.pojo.user.SysRole;
|
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
|
||||||
|
|
||||||
public interface SysRoleRepo extends JpaRepository<SysRole, Long> {
|
|
||||||
}
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
package com.rainbus.dlp.repository.user;
|
|
||||||
|
|
||||||
import com.rainbus.dlp.entity.pojo.user.SysUser;
|
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
|
||||||
|
|
||||||
import java.util.Optional;
|
|
||||||
|
|
||||||
public interface SysUserRepo extends JpaRepository<SysUser, Long> {
|
|
||||||
|
|
||||||
Optional<SysUser> findByUsername(String username);
|
|
||||||
|
|
||||||
}
|
|
||||||
47
src/main/java/com/rainbus/dlp/service/SystemServ.java
Normal file
47
src/main/java/com/rainbus/dlp/service/SystemServ.java
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
package com.rainbus.dlp.service;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.context.ApplicationContext;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMethod;
|
||||||
|
import org.springframework.web.method.HandlerMethod;
|
||||||
|
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
|
||||||
|
import org.springframework.web.util.pattern.PathPattern;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class SystemServ {
|
||||||
|
|
||||||
|
private final ApplicationContext applicationContext;
|
||||||
|
|
||||||
|
public record ApiInfo(String url, RequestMethod method) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<ApiInfo> getSystemApis() {
|
||||||
|
List<ApiInfo> apiInfos = new ArrayList<>();
|
||||||
|
|
||||||
|
RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
|
||||||
|
Map<RequestMappingInfo, HandlerMethod> methodMap = mapping.getHandlerMethods();
|
||||||
|
|
||||||
|
for (RequestMappingInfo info : methodMap.keySet()) {
|
||||||
|
if (Objects.isNull(info.getPathPatternsCondition())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
Set<PathPattern> patterns = info.getPathPatternsCondition().getPatterns();
|
||||||
|
Set<RequestMethod> methods = info.getMethodsCondition().getMethods();
|
||||||
|
for (PathPattern url : patterns) {
|
||||||
|
for (RequestMethod method : methods) {
|
||||||
|
apiInfos.add(new ApiInfo(url.getPatternString(), method));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiInfos;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,44 +1,77 @@
|
|||||||
package com.rainbus.dlp.service;
|
package com.rainbus.dlp.service;
|
||||||
|
|
||||||
|
import com.rainbus.dlp.entity.converter.UserConv;
|
||||||
import com.rainbus.dlp.entity.dto.user.CustomUserDetails;
|
import com.rainbus.dlp.entity.dto.user.CustomUserDetails;
|
||||||
|
import com.rainbus.dlp.entity.enums.UserStatusEnum;
|
||||||
|
import com.rainbus.dlp.entity.exception.UserDisabledExcp;
|
||||||
import com.rainbus.dlp.entity.pojo.user.SysRole;
|
import com.rainbus.dlp.entity.pojo.user.SysRole;
|
||||||
import com.rainbus.dlp.entity.pojo.user.SysUser;
|
import com.rainbus.dlp.entity.pojo.user.SysUser;
|
||||||
import com.rainbus.dlp.repository.user.SysResourceRepo;
|
import com.rainbus.dlp.repository.dao.UserDao;
|
||||||
import com.rainbus.dlp.repository.user.SysRoleRepo;
|
import com.rainbus.dlp.util.RedisUtil;
|
||||||
import com.rainbus.dlp.repository.user.SysUserRepo;
|
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import org.springframework.security.core.GrantedAuthority;
|
|
||||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
|
||||||
import org.springframework.security.core.userdetails.UserDetails;
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.validation.SimpleErrors;
|
|
||||||
|
|
||||||
|
import javax.management.relation.Role;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.stream.Collectors;
|
import java.util.Optional;
|
||||||
|
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
public class UserServ implements UserDetailsService {
|
public class UserServ implements UserDetailsService {
|
||||||
|
|
||||||
private final SysUserRepo userRepo;
|
private final UserConv userConv;
|
||||||
private final SysRoleRepo roleRepo;
|
private final UserDao userDao;
|
||||||
private final SysResourceRepo resourceRepo;
|
|
||||||
|
public static final String REDIS_USER_DETAILS = "user_details_%s";
|
||||||
|
public static final long REDIS_USER_DETAILS_EXPIRE = 1 * 60 * 60;
|
||||||
|
private final RedisUtil redisUtil;
|
||||||
|
|
||||||
public SysUser getUserByUsername(String username) {
|
public SysUser getUserByUsername(String username) {
|
||||||
return userRepo.findByUsername(username).orElse(null);
|
Optional<SysUser> user = userDao.findUserByUsername(username);
|
||||||
|
if (user.isEmpty()) {
|
||||||
|
throw new UsernameNotFoundException("用户不存在");
|
||||||
|
}
|
||||||
|
return user.get();
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<SysRole> getAllRoles() {
|
public List<SysRole> listRoleResource() {
|
||||||
return roleRepo.findAll();
|
return userDao.listRoleResource();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// public List<SysRole> getAllRoles() {
|
||||||
|
// return roleRepo.findAll();
|
||||||
|
// }
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
||||||
SysUser user = userRepo.findByUsername(username).orElseThrow(() -> new UsernameNotFoundException("user not exist"));
|
// 读缓存
|
||||||
List<SimpleGrantedAuthority> authorities = user.getRoles().stream().map(role -> new SimpleGrantedAuthority(role.getRole())).toList();
|
Optional<CustomUserDetails> userDetailsOpt = loadUserDetailsFromRedis(username);
|
||||||
return new CustomUserDetails(user.getUsername(), user.getPassword(), authorities);
|
if (userDetailsOpt.isPresent()) {
|
||||||
|
return userDetailsOpt.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 读数据库
|
||||||
|
Optional<SysUser> user = userDao.findUserRoleOrgByUsername(username);
|
||||||
|
if (user.isEmpty()) {
|
||||||
|
throw new UsernameNotFoundException("用户不存在");
|
||||||
|
}
|
||||||
|
if (user.get().getStatus() == UserStatusEnum.DISABLED) {
|
||||||
|
throw new UserDisabledExcp();
|
||||||
|
}
|
||||||
|
CustomUserDetails userDetails = userConv.UserPojo2UserDetails(user.get());
|
||||||
|
|
||||||
|
// 写缓存
|
||||||
|
redisUtil.setex(RedisUtil.parseKey(REDIS_USER_DETAILS, username), userDetails, REDIS_USER_DETAILS_EXPIRE);
|
||||||
|
|
||||||
|
return userDetails;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private Optional<CustomUserDetails> loadUserDetailsFromRedis(String username) {
|
||||||
|
return redisUtil.get(RedisUtil.parseKey(REDIS_USER_DETAILS, username), CustomUserDetails.class);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.rainbus.dlp.util;
|
package com.rainbus.dlp.util;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import com.fasterxml.jackson.databind.type.MapType;
|
import com.fasterxml.jackson.databind.type.MapType;
|
||||||
|
|
||||||
@@ -8,7 +9,7 @@ import java.util.Map;
|
|||||||
|
|
||||||
public class ConvertUtil {
|
public class ConvertUtil {
|
||||||
|
|
||||||
private static final ObjectMapper mapper = new ObjectMapper();
|
private static final ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();
|
||||||
|
|
||||||
public static <T, V> Map<String, V> toMap(T source, Class<V> vClass) {
|
public static <T, V> Map<String, V> toMap(T source, Class<V> vClass) {
|
||||||
MapType mapType = mapper.getTypeFactory().constructMapType(HashMap.class, String.class, vClass);
|
MapType mapType = mapper.getTypeFactory().constructMapType(HashMap.class, String.class, vClass);
|
||||||
@@ -19,4 +20,11 @@ public class ConvertUtil {
|
|||||||
return mapper.convertValue(map, tClass);
|
return mapper.convertValue(map, tClass);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static <T> T fromJsonStr(String jsonStr, Class<T> tClass) throws JsonProcessingException {
|
||||||
|
return mapper.readValue(jsonStr, tClass);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <V> String toJsonStr(V value) throws JsonProcessingException {
|
||||||
|
return mapper.writeValueAsString(value);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
67
src/main/java/com/rainbus/dlp/util/RedisUtil.java
Normal file
67
src/main/java/com/rainbus/dlp/util/RedisUtil.java
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
package com.rainbus.dlp.util;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import org.springframework.data.redis.core.RedisTemplate;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class RedisUtil {
|
||||||
|
|
||||||
|
private final RedisTemplate<String, String> redisTemplate;
|
||||||
|
|
||||||
|
public boolean set(String key, String value) {
|
||||||
|
redisTemplate.opsForValue().set(key, value);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public <V> boolean set(String key, V value) {
|
||||||
|
try {
|
||||||
|
set(key, ConvertUtil.toJsonStr(value));
|
||||||
|
} catch (JsonProcessingException e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<String> get(String key) {
|
||||||
|
return Optional.ofNullable(redisTemplate.opsForValue().get(key));
|
||||||
|
}
|
||||||
|
|
||||||
|
public <V> Optional<V> get(String key, Class<V> vClass) {
|
||||||
|
return get(key).map(s -> {
|
||||||
|
try {
|
||||||
|
return ConvertUtil.fromJsonStr(s, vClass);
|
||||||
|
} catch (JsonProcessingException e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public void delete(String key) {
|
||||||
|
redisTemplate.delete(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean setex(String key, String value, long timeout) {
|
||||||
|
redisTemplate.opsForValue().set(key, value, Duration.ofSeconds(timeout));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public <V> boolean setex(String key, V value, long timeout) {
|
||||||
|
try {
|
||||||
|
setex(key, ConvertUtil.toJsonStr(value), timeout);
|
||||||
|
} catch (JsonProcessingException e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String parseKey(String pattern, Object... args) {
|
||||||
|
return String.format(pattern, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -7,10 +7,7 @@ spring:
|
|||||||
username: root
|
username: root
|
||||||
password: 13291004986@lm
|
password: 13291004986@lm
|
||||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||||
jpa:
|
|
||||||
hibernate:
|
|
||||||
ddl-auto: update
|
|
||||||
show-sql: true
|
|
||||||
|
|
||||||
data:
|
data:
|
||||||
redis:
|
redis:
|
||||||
@@ -19,3 +16,10 @@ spring:
|
|||||||
password: 13291004986
|
password: 13291004986
|
||||||
timeout: 10000
|
timeout: 10000
|
||||||
database: 0
|
database: 0
|
||||||
|
logging:
|
||||||
|
level:
|
||||||
|
com:
|
||||||
|
rainbus:
|
||||||
|
dlp:
|
||||||
|
repository:
|
||||||
|
mapper: debug
|
||||||
|
|||||||
Reference in New Issue
Block a user