feat:
- Change Mybatis to JPA - Change groupId
This commit is contained in:
14
src/main/java/com/dlp/admin/DlpAdminBackendApplication.java
Normal file
14
src/main/java/com/dlp/admin/DlpAdminBackendApplication.java
Normal file
@@ -0,0 +1,14 @@
|
||||
package com.dlp.admin;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
|
||||
|
||||
@SpringBootApplication(exclude = {SecurityAutoConfiguration.class})
|
||||
public class DlpAdminBackendApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(DlpAdminBackendApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
55
src/main/java/com/dlp/admin/config/JwtFilter.java
Normal file
55
src/main/java/com/dlp/admin/config/JwtFilter.java
Normal file
@@ -0,0 +1,55 @@
|
||||
package com.dlp.admin.config;
|
||||
|
||||
import com.dlp.admin.entity.dto.user.TokenClaims;
|
||||
import com.dlp.admin.service.UserServ;
|
||||
import com.dlp.admin.util.JwtUtil;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Objects;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class JwtFilter extends OncePerRequestFilter {
|
||||
|
||||
private final AuthenticationManager authenticationManager;
|
||||
private final UserServ userServ;
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException {
|
||||
String token = getJwtFromRequest(request);
|
||||
if (Objects.isNull(token)) {
|
||||
filterChain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
|
||||
TokenClaims claims = JwtUtil.parseValidToken(token);
|
||||
UserDetails userDetails = userServ.loadUserByUsername(claims.getUsername());
|
||||
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
|
||||
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
|
||||
private String getJwtFromRequest(HttpServletRequest request) {
|
||||
String bearerToken = request.getHeader("Authorization");
|
||||
if (StringUtils.isBlank(bearerToken) || !bearerToken.startsWith("Bearer ")) {
|
||||
return null;
|
||||
}
|
||||
return bearerToken.substring(7);
|
||||
}
|
||||
|
||||
}
|
||||
20
src/main/java/com/dlp/admin/config/OpenApiConf.java
Normal file
20
src/main/java/com/dlp/admin/config/OpenApiConf.java
Normal file
@@ -0,0 +1,20 @@
|
||||
package com.dlp.admin.config;
|
||||
|
||||
import io.swagger.v3.oas.models.OpenAPI;
|
||||
import io.swagger.v3.oas.models.info.Info;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class OpenApiConf {
|
||||
|
||||
@Bean
|
||||
public OpenAPI springOpenAPI() {
|
||||
return new OpenAPI()
|
||||
.info(new Info()
|
||||
.title("DLP Admin")
|
||||
.description("DLP Admin APIs")
|
||||
.version("0.0.1"));
|
||||
}
|
||||
|
||||
}
|
||||
80
src/main/java/com/dlp/admin/config/SecurityConf.java
Normal file
80
src/main/java/com/dlp/admin/config/SecurityConf.java
Normal file
@@ -0,0 +1,80 @@
|
||||
package com.dlp.admin.config;
|
||||
|
||||
|
||||
import com.dlp.admin.entity.pojo.user.SysRole;
|
||||
import com.dlp.admin.repository.user.SysRoleRepo;
|
||||
import jakarta.transaction.Transactional;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.config.Customizer;
|
||||
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.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@RequiredArgsConstructor
|
||||
public class SecurityConf {
|
||||
|
||||
private final SecurityDataService securityDataService;
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http, JwtFilter jwtFilter) throws Exception {
|
||||
http
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests((authorizeHttpRequests) -> {
|
||||
//TODO: Lazy load problem
|
||||
securityDataService.fetchAllRoles().forEach(role -> {
|
||||
role.getResources().forEach(resource -> {
|
||||
authorizeHttpRequests.requestMatchers(
|
||||
HttpMethod.valueOf(resource.getRequestMethod().name()),
|
||||
resource.getResource()
|
||||
).hasAuthority(role.getRole());
|
||||
});
|
||||
});
|
||||
authorizeHttpRequests.anyRequest().permitAll();
|
||||
})
|
||||
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.httpBasic(Customizer.withDefaults());
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration)
|
||||
throws Exception {
|
||||
return authenticationConfiguration.getAuthenticationManager();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
static class SecurityDataService {
|
||||
|
||||
private final SysRoleRepo roleRepo;
|
||||
|
||||
@Transactional
|
||||
public List<SysRole> fetchAllRoles() {
|
||||
return roleRepo.findAll().stream().filter(role -> !role.getResources().isEmpty()).toList();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
16
src/main/java/com/dlp/admin/controller/ExceptionCtrl.java
Normal file
16
src/main/java/com/dlp/admin/controller/ExceptionCtrl.java
Normal file
@@ -0,0 +1,16 @@
|
||||
package com.dlp.admin.controller;
|
||||
|
||||
import com.dlp.admin.entity.exception.UsernameOrPasswordExcp;
|
||||
import com.dlp.admin.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());
|
||||
}
|
||||
|
||||
}
|
||||
102
src/main/java/com/dlp/admin/controller/UserCtrl.java
Normal file
102
src/main/java/com/dlp/admin/controller/UserCtrl.java
Normal file
@@ -0,0 +1,102 @@
|
||||
package com.dlp.admin.controller;
|
||||
|
||||
import com.dlp.admin.entity.pojo.user.SysResource;
|
||||
import com.dlp.admin.entity.pojo.user.SysRole;
|
||||
import com.dlp.admin.entity.req.user.*;
|
||||
import com.dlp.admin.entity.resp.PageResp;
|
||||
import com.dlp.admin.entity.resp.Resp;
|
||||
import com.dlp.admin.entity.resp.user.GetTagResp;
|
||||
import com.dlp.admin.entity.resp.user.GetUserResp;
|
||||
import com.dlp.admin.entity.resp.user.LoginResp;
|
||||
import com.dlp.admin.repository.user.SysRoleRepo;
|
||||
import com.dlp.admin.service.UserServ;
|
||||
import com.dlp.admin.util.RedisUtil;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/user")
|
||||
@AllArgsConstructor
|
||||
public class UserCtrl {
|
||||
|
||||
private final RedisUtil redisUtil;
|
||||
private final UserServ userServ;
|
||||
private final SysRoleRepo sysRoleRepo;
|
||||
|
||||
@PostMapping("/login")
|
||||
@Operation(summary = "登录接口")
|
||||
public Resp<LoginResp> login(@RequestBody LoginReq req) {
|
||||
return Resp.success(userServ.login(req));
|
||||
}
|
||||
|
||||
@PostMapping("/list")
|
||||
@Operation(summary = "搜索用户")
|
||||
public Resp<PageResp<GetUserResp>> listUser(@RequestBody ListUserReq req) {
|
||||
return Resp.success(null);
|
||||
}
|
||||
|
||||
@PostMapping("/add")
|
||||
@Operation(summary = "增加用户")
|
||||
public Resp<Object> addUser(@RequestBody AddUserReq req) {
|
||||
return Resp.success();
|
||||
}
|
||||
|
||||
@PostMapping("/get/{id}")
|
||||
@Operation(summary = "获取用户")
|
||||
public Resp<GetUserResp> getUser(@PathVariable("id") Long id) {
|
||||
return Resp.success(null);
|
||||
}
|
||||
|
||||
@PostMapping("/update")
|
||||
@Operation(summary = "更新用户")
|
||||
public Resp<Object> updateUser(@RequestBody UpdateUserReq req) {
|
||||
return Resp.success();
|
||||
}
|
||||
|
||||
@PostMapping("/delete/{id}")
|
||||
@Operation(summary = "删除用户")
|
||||
public Resp<Object> deleteUser(@PathVariable Long id) {
|
||||
return Resp.success();
|
||||
}
|
||||
|
||||
@PostMapping("/resetPwd/{id}")
|
||||
@Operation(summary = "重置密码")
|
||||
public Resp<Object> resetPwd(@PathVariable Long id) {
|
||||
return Resp.success();
|
||||
}
|
||||
|
||||
@PostMapping("/tag/add")
|
||||
@Operation(summary = "增加用户标签")
|
||||
private Resp<Object> addUserTag(@RequestBody AddUserTagReq req) {
|
||||
return Resp.success();
|
||||
}
|
||||
|
||||
@PostMapping("/tag/delete/{id}")
|
||||
@Operation(summary = "删除用户标签")
|
||||
private Resp<Object> deleteUserTag(@PathVariable Long id) {
|
||||
return Resp.success();
|
||||
}
|
||||
|
||||
@GetMapping("/tag/list")
|
||||
@Operation(summary = "获取所有用户标签")
|
||||
private Resp<List<GetTagResp>> listUserTag() {
|
||||
return Resp.success(null);
|
||||
}
|
||||
|
||||
@GetMapping("/test")
|
||||
private Resp<Object> test() {
|
||||
SysResource resource = new SysResource();
|
||||
resource.setResource("/user/test");
|
||||
resource.setRequestMethod(RequestMethod.GET);
|
||||
List<SysResource> resources = List.of(resource);
|
||||
// return Resp.success(sysResourceMapper.batchInsert(resources));
|
||||
// return Resp.success(sysRoleMapper.selectRoleIdsByUserId(List.of(1L, 2L)));
|
||||
List<SysRole> roles = sysRoleRepo.findAll();
|
||||
roles.stream().forEach(role -> role.getResources().stream().forEach(resource1 -> System.out.println(resource1.getResource())));
|
||||
return Resp.success();
|
||||
}
|
||||
|
||||
}
|
||||
11
src/main/java/com/dlp/admin/entity/ApiDescription.java
Normal file
11
src/main/java/com/dlp/admin/entity/ApiDescription.java
Normal file
@@ -0,0 +1,11 @@
|
||||
package com.dlp.admin.entity;
|
||||
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
@Documented
|
||||
public @interface ApiDescription {
|
||||
String value();
|
||||
}
|
||||
21
src/main/java/com/dlp/admin/entity/converter/SystemConv.java
Normal file
21
src/main/java/com/dlp/admin/entity/converter/SystemConv.java
Normal file
@@ -0,0 +1,21 @@
|
||||
package com.dlp.admin.entity.converter;
|
||||
|
||||
import com.dlp.admin.entity.pojo.user.SysResource;
|
||||
import com.dlp.admin.entity.dto.system.ApiInfo;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Mapper(componentModel = "spring")
|
||||
public interface SystemConv {
|
||||
|
||||
@Mapping(target = "id", ignore = true)
|
||||
@Mapping(target = "updatedAt", ignore = true)
|
||||
@Mapping(target = "resource", source = "uri")
|
||||
@Mapping(target = "createdAt", ignore = true)
|
||||
SysResource ApiInfoDto2Pojo(ApiInfo apiInfo);
|
||||
|
||||
List<SysResource> ApiInfosDto2Pojo(List<ApiInfo> apiInfos);
|
||||
|
||||
}
|
||||
26
src/main/java/com/dlp/admin/entity/converter/UserConv.java
Normal file
26
src/main/java/com/dlp/admin/entity/converter/UserConv.java
Normal file
@@ -0,0 +1,26 @@
|
||||
package com.dlp.admin.entity.converter;
|
||||
|
||||
import com.dlp.admin.entity.dto.user.CustomUserDetails;
|
||||
import com.dlp.admin.entity.dto.user.TokenClaims;
|
||||
import com.dlp.admin.entity.pojo.user.SysUser;
|
||||
import com.dlp.admin.entity.req.user.AddUserReq;
|
||||
import org.mapstruct.InheritInverseConfiguration;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
|
||||
@Mapper(componentModel = "spring")
|
||||
public interface UserConv {
|
||||
|
||||
@InheritInverseConfiguration
|
||||
SysUser RegisterReq2Pojo(AddUserReq req, String password);
|
||||
|
||||
@Mapping(target = "roles", expression = "java(user.getRoles().stream().map(com.dlp.admin.entity.pojo.user.SysRole::getRole).toList())")
|
||||
@Mapping(target = "orgId", expression = "java(user.getOrg().getId())")
|
||||
TokenClaims ClaimsPojo2Dto(SysUser user);
|
||||
|
||||
@Mapping(target = "orgId", expression = "java(user.getOrg().getId())")
|
||||
@Mapping(target = "authorities", ignore = true)
|
||||
@Mapping(target = "roles", expression = "java(user.getRoles().stream().map(com.dlp.admin.entity.pojo.user.SysRole::getRole).toList())")
|
||||
CustomUserDetails UserDetailsPojo2Dto(SysUser user);
|
||||
|
||||
}
|
||||
4
src/main/java/com/dlp/admin/entity/dto/Pair.java
Normal file
4
src/main/java/com/dlp/admin/entity/dto/Pair.java
Normal file
@@ -0,0 +1,4 @@
|
||||
package com.dlp.admin.entity.dto;
|
||||
|
||||
public record Pair<T1, T2>(T1 v1, T2 v2) {
|
||||
}
|
||||
4
src/main/java/com/dlp/admin/entity/dto/Tuple.java
Normal file
4
src/main/java/com/dlp/admin/entity/dto/Tuple.java
Normal file
@@ -0,0 +1,4 @@
|
||||
package com.dlp.admin.entity.dto;
|
||||
|
||||
public record Tuple<T1, T2, T3>(T1 v1, T2 v2, T3 v3) {
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.dlp.admin.entity.dto.system;
|
||||
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
|
||||
public record ApiInfo(String uri, RequestMethod requestMethod, String description) {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.dlp.admin.entity.dto.user;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class CustomUserDetails implements UserDetails {
|
||||
|
||||
private Long id;
|
||||
private String username;
|
||||
private String password;
|
||||
private List<String> roles;
|
||||
private Long orgId;
|
||||
|
||||
@Override
|
||||
@JsonIgnore
|
||||
public Collection<? extends GrantedAuthority> getAuthorities() {
|
||||
return roles.stream().map(SimpleGrantedAuthority::new).toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
@JsonIgnore
|
||||
public boolean isAccountNonExpired() {
|
||||
return UserDetails.super.isAccountNonExpired();
|
||||
}
|
||||
|
||||
@Override
|
||||
@JsonIgnore
|
||||
public boolean isAccountNonLocked() {
|
||||
return UserDetails.super.isAccountNonLocked();
|
||||
}
|
||||
|
||||
@Override
|
||||
@JsonIgnore
|
||||
public boolean isCredentialsNonExpired() {
|
||||
return UserDetails.super.isCredentialsNonExpired();
|
||||
}
|
||||
|
||||
@Override
|
||||
@JsonIgnore
|
||||
public boolean isEnabled() {
|
||||
return UserDetails.super.isEnabled();
|
||||
}
|
||||
}
|
||||
38
src/main/java/com/dlp/admin/entity/dto/user/TokenClaims.java
Normal file
38
src/main/java/com/dlp/admin/entity/dto/user/TokenClaims.java
Normal file
@@ -0,0 +1,38 @@
|
||||
package com.dlp.admin.entity.dto.user;
|
||||
|
||||
import com.auth0.jwt.interfaces.Claim;
|
||||
import com.dlp.admin.util.ConvertUtil;
|
||||
import lombok.Data;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Data
|
||||
public class TokenClaims {
|
||||
|
||||
private Long id;
|
||||
private String username;
|
||||
private List<String> roles;
|
||||
private Long orgId;
|
||||
|
||||
public Map<String, Object> toMap() {
|
||||
return ConvertUtil.toMap(this, Object.class);
|
||||
}
|
||||
|
||||
public static TokenClaims fromClaimMap(Map<String, Claim> map) {
|
||||
TokenClaims claims = new TokenClaims();
|
||||
for (Field field : claims.getClass().getDeclaredFields()) {
|
||||
field.setAccessible(true);
|
||||
try {
|
||||
field.set(claims, map.get(field.getName()).as(field.getType()));
|
||||
} catch (IllegalAccessException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return claims;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJyYWluYnVzIiwiZXhwIjoxNzIwNDM2MjE3LCJpYXQiOjE3MTc4NDQyMTcsImlzcyI6IkRMUCJ9._rINYg-YW8WpvRycXr4JLEpYu17Hm5__9pxuGTyn4iA
|
||||
15
src/main/java/com/dlp/admin/entity/enums/ExceptionEnum.java
Normal file
15
src/main/java/com/dlp/admin/entity/enums/ExceptionEnum.java
Normal file
@@ -0,0 +1,15 @@
|
||||
package com.dlp.admin.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/dlp/admin/entity/enums/OrgTypeEnum.java
Normal file
15
src/main/java/com/dlp/admin/entity/enums/OrgTypeEnum.java
Normal file
@@ -0,0 +1,15 @@
|
||||
package com.dlp.admin.entity.enums;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
public enum OrgTypeEnum {
|
||||
COMPANY("公司"), DEPARTMENT("部门"), USER_GROUP("用户组");
|
||||
|
||||
private final String desc;
|
||||
|
||||
OrgTypeEnum(String desc) {
|
||||
this.desc = desc;
|
||||
}
|
||||
|
||||
}
|
||||
10
src/main/java/com/dlp/admin/entity/enums/RoleEnum.java
Normal file
10
src/main/java/com/dlp/admin/entity/enums/RoleEnum.java
Normal file
@@ -0,0 +1,10 @@
|
||||
package com.dlp.admin.entity.enums;
|
||||
|
||||
public enum RoleEnum {
|
||||
// system admin
|
||||
SUPER_ADMIN,
|
||||
// department admin
|
||||
DEPART_ADMIN,
|
||||
// user
|
||||
USER
|
||||
}
|
||||
11
src/main/java/com/dlp/admin/entity/enums/UserStatusEnum.java
Normal file
11
src/main/java/com/dlp/admin/entity/enums/UserStatusEnum.java
Normal file
@@ -0,0 +1,11 @@
|
||||
package com.dlp.admin.entity.enums;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public enum UserStatusEnum {
|
||||
ACTIVATED("激活"), UNACTIVATED("未激活"), DISABLED("禁用");
|
||||
private final String desc;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.dlp.admin.entity.exception;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
public class OrgNotExistExcp extends RuntimeException {
|
||||
private final int code;
|
||||
private final String message;
|
||||
|
||||
public OrgNotExistExcp() {
|
||||
this.code = 40003;
|
||||
this.message = "组织不存在";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.dlp.admin.entity.exception;
|
||||
|
||||
import com.dlp.admin.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.dlp.admin.entity.exception;
|
||||
|
||||
import com.dlp.admin.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();
|
||||
}
|
||||
|
||||
}
|
||||
49
src/main/java/com/dlp/admin/entity/pojo/user/SysOrg.java
Normal file
49
src/main/java/com/dlp/admin/entity/pojo/user/SysOrg.java
Normal file
@@ -0,0 +1,49 @@
|
||||
package com.dlp.admin.entity.pojo.user;
|
||||
|
||||
import com.dlp.admin.entity.enums.OrgTypeEnum;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
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.repository.config.EnableJpaAuditing;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@Entity
|
||||
@EnableJpaAuditing
|
||||
public class SysOrg {
|
||||
|
||||
@Id
|
||||
private Long id;
|
||||
|
||||
private String org;
|
||||
|
||||
private OrgTypeEnum type;
|
||||
|
||||
private String fullPathName;
|
||||
|
||||
private String fullPath;
|
||||
|
||||
private Long parentId;
|
||||
|
||||
private String region;
|
||||
|
||||
private String area;
|
||||
|
||||
@CreatedDate
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@LastModifiedDate
|
||||
private LocalDateTime updatedAt;
|
||||
|
||||
@CreatedBy
|
||||
private Long createdBy;
|
||||
|
||||
@LastModifiedBy
|
||||
private Long updatedBy;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.dlp.admin.entity.pojo.user;
|
||||
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.Data;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@Entity
|
||||
public class SysResource {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String resource;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
private RequestMethod requestMethod;
|
||||
|
||||
private String description;
|
||||
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
private LocalDateTime updatedAt;
|
||||
|
||||
}
|
||||
31
src/main/java/com/dlp/admin/entity/pojo/user/SysRole.java
Normal file
31
src/main/java/com/dlp/admin/entity/pojo/user/SysRole.java
Normal file
@@ -0,0 +1,31 @@
|
||||
package com.dlp.admin.entity.pojo.user;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@Entity
|
||||
public class SysRole {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String role;
|
||||
|
||||
private String description;
|
||||
|
||||
@ManyToMany
|
||||
private List<SysResource> resources;
|
||||
|
||||
private Long createdBy;
|
||||
|
||||
private Long updatedBy;
|
||||
|
||||
private Long createdAt;
|
||||
|
||||
private Long updatedAt;
|
||||
|
||||
}
|
||||
42
src/main/java/com/dlp/admin/entity/pojo/user/SysUser.java
Normal file
42
src/main/java/com/dlp/admin/entity/pojo/user/SysUser.java
Normal file
@@ -0,0 +1,42 @@
|
||||
package com.dlp.admin.entity.pojo.user;
|
||||
|
||||
import com.dlp.admin.entity.enums.UserStatusEnum;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@Entity
|
||||
public class SysUser {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String username;
|
||||
|
||||
private String password;
|
||||
|
||||
private String email;
|
||||
|
||||
@ManyToMany
|
||||
private List<SysRole> roles;
|
||||
|
||||
@ManyToOne
|
||||
private SysOrg org;
|
||||
|
||||
private UserStatusEnum status;
|
||||
|
||||
private Long createBy;
|
||||
|
||||
private Long updateBy;
|
||||
|
||||
private LocalDateTime createAt;
|
||||
|
||||
private LocalDateTime updateAt;
|
||||
|
||||
private Integer isDeleted;
|
||||
|
||||
}
|
||||
9
src/main/java/com/dlp/admin/entity/req/PageReq.java
Normal file
9
src/main/java/com/dlp/admin/entity/req/PageReq.java
Normal file
@@ -0,0 +1,9 @@
|
||||
package com.dlp.admin.entity.req;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class PageReq {
|
||||
private Integer pageCurrent = 1;
|
||||
private Integer pageSize = 10;
|
||||
}
|
||||
37
src/main/java/com/dlp/admin/entity/req/user/AddUserReq.java
Normal file
37
src/main/java/com/dlp/admin/entity/req/user/AddUserReq.java
Normal file
@@ -0,0 +1,37 @@
|
||||
package com.dlp.admin.entity.req.user;
|
||||
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class AddUserReq {
|
||||
|
||||
@Pattern(regexp = "^[a-zA-Z0-9_-]{4,16}$", message = "用户名格式不正确")
|
||||
private String username;
|
||||
|
||||
@Pattern(regexp = "^[\\u4E00-\\u9FA5]{2,4}$", message = "姓名格式不正确")
|
||||
private String realName;
|
||||
|
||||
@Email(message = "邮箱格式不正确")
|
||||
private String email;
|
||||
|
||||
@NotNull
|
||||
private Long orgId;
|
||||
|
||||
@NotNull
|
||||
private String region;
|
||||
|
||||
@Pattern(regexp = "^1(3\\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\\d|9[0-35-9])\\d{8}$", message = "手机号格式不正确")
|
||||
private String mobile;
|
||||
|
||||
@Pattern(regexp = "0\\d{2,3}-\\d{7,8}$", message = "座机号格式不正确")
|
||||
private String phone;
|
||||
|
||||
private String remark;
|
||||
|
||||
private Long tagId;
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.dlp.admin.entity.req.user;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class AddUserTagReq {
|
||||
private String tag;
|
||||
private String remark;
|
||||
}
|
||||
14
src/main/java/com/dlp/admin/entity/req/user/ListUserReq.java
Normal file
14
src/main/java/com/dlp/admin/entity/req/user/ListUserReq.java
Normal file
@@ -0,0 +1,14 @@
|
||||
package com.dlp.admin.entity.req.user;
|
||||
|
||||
import com.dlp.admin.entity.req.PageReq;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class ListUserReq extends PageReq {
|
||||
private String username;
|
||||
private String email;
|
||||
private String region;
|
||||
private Long orgId;
|
||||
}
|
||||
15
src/main/java/com/dlp/admin/entity/req/user/LoginReq.java
Normal file
15
src/main/java/com/dlp/admin/entity/req/user/LoginReq.java
Normal file
@@ -0,0 +1,15 @@
|
||||
package com.dlp.admin.entity.req.user;
|
||||
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class LoginReq {
|
||||
|
||||
@Pattern(regexp = "^[a-zA-Z0-9_-]{4,16}$", message = "用户名格式不正确")
|
||||
private String username;
|
||||
|
||||
@Pattern(regexp = "^[a-zA-Z0-9_-]{8,16}$", message = "密码格式不正确")
|
||||
private String password;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.dlp.admin.entity.req.user;
|
||||
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class UpdateUserReq {
|
||||
|
||||
@NotNull
|
||||
private Long id;
|
||||
|
||||
@Pattern(regexp = "^[a-zA-Z0-9_-]{4,16}$", message = "用户名格式不正确")
|
||||
private String username;
|
||||
|
||||
@Pattern(regexp = "^[\\u4E00-\\u9FA5]{2,4}$", message = "姓名格式不正确")
|
||||
private String realName;
|
||||
|
||||
@Email(message = "邮箱格式不正确")
|
||||
private String email;
|
||||
|
||||
@NotNull
|
||||
private Long orgId;
|
||||
|
||||
@NotNull
|
||||
private String region;
|
||||
|
||||
@Pattern(regexp = "^1(3\\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\\d|9[0-35-9])\\d{8}$", message = "手机号格式不正确")
|
||||
private String mobile;
|
||||
|
||||
@Pattern(regexp = "0\\d{2,3}-\\d{7,8}$", message = "座机号格式不正确")
|
||||
private String phone;
|
||||
|
||||
private String remark;
|
||||
|
||||
}
|
||||
13
src/main/java/com/dlp/admin/entity/resp/PageResp.java
Normal file
13
src/main/java/com/dlp/admin/entity/resp/PageResp.java
Normal file
@@ -0,0 +1,13 @@
|
||||
package com.dlp.admin.entity.resp;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class PageResp<T> {
|
||||
private List<T> list;
|
||||
private Long total;
|
||||
private Long pageSize;
|
||||
private Long current;
|
||||
}
|
||||
32
src/main/java/com/dlp/admin/entity/resp/Resp.java
Normal file
32
src/main/java/com/dlp/admin/entity/resp/Resp.java
Normal file
@@ -0,0 +1,32 @@
|
||||
package com.dlp.admin.entity.resp;
|
||||
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public class Resp<T> {
|
||||
private int code;
|
||||
private String msg;
|
||||
private T data;
|
||||
|
||||
public static <T> Resp<T> success(T data) {
|
||||
return new Resp<>(200, "success", data);
|
||||
}
|
||||
|
||||
|
||||
public static Resp<Object> success() {
|
||||
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) {
|
||||
return new Resp<>(400, msg, null);
|
||||
}
|
||||
}
|
||||
10
src/main/java/com/dlp/admin/entity/resp/user/GetTagResp.java
Normal file
10
src/main/java/com/dlp/admin/entity/resp/user/GetTagResp.java
Normal file
@@ -0,0 +1,10 @@
|
||||
package com.dlp.admin.entity.resp.user;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class GetTagResp {
|
||||
private Long id;
|
||||
private String tag;
|
||||
private String remark;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.dlp.admin.entity.resp.user;
|
||||
|
||||
import com.dlp.admin.entity.enums.UserStatusEnum;
|
||||
import com.dlp.admin.entity.pojo.user.SysOrg;
|
||||
import com.dlp.admin.entity.pojo.user.SysRole;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class GetUserResp {
|
||||
|
||||
private Long id;
|
||||
|
||||
private String username;
|
||||
|
||||
private String email;
|
||||
|
||||
private List<SysRole> roles;
|
||||
|
||||
private SysOrg org;
|
||||
|
||||
@Schema(description = "未定字段格式")
|
||||
private List<Object> tags;
|
||||
|
||||
private UserStatusEnum status;
|
||||
|
||||
private Long createBy;
|
||||
|
||||
private Long updateBy;
|
||||
|
||||
private LocalDateTime createAt;
|
||||
|
||||
private LocalDateTime updateAt;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.dlp.admin.entity.resp.user;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class LoginResp {
|
||||
private String token;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.dlp.admin.repository.user;
|
||||
|
||||
import com.dlp.admin.entity.pojo.user.SysOrg;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface SysOrgRepo extends JpaRepository<SysOrg, Long> {
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.dlp.admin.repository.user;
|
||||
|
||||
import com.dlp.admin.entity.pojo.user.SysResource;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface SysResourceRepo extends JpaRepository<SysResource, Long> {
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.dlp.admin.repository.user;
|
||||
|
||||
import com.dlp.admin.entity.pojo.user.SysRole;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface SysRoleRepo extends JpaRepository<SysRole, Long> {
|
||||
}
|
||||
10
src/main/java/com/dlp/admin/repository/user/SysUserRepo.java
Normal file
10
src/main/java/com/dlp/admin/repository/user/SysUserRepo.java
Normal file
@@ -0,0 +1,10 @@
|
||||
package com.dlp.admin.repository.user;
|
||||
|
||||
import com.dlp.admin.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);
|
||||
}
|
||||
55
src/main/java/com/dlp/admin/service/SystemServ.java
Normal file
55
src/main/java/com/dlp/admin/service/SystemServ.java
Normal file
@@ -0,0 +1,55 @@
|
||||
package com.dlp.admin.service;
|
||||
|
||||
import com.dlp.admin.entity.converter.SystemConv;
|
||||
import com.dlp.admin.entity.dto.system.ApiInfo;
|
||||
|
||||
import com.dlp.admin.entity.pojo.user.SysResource;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
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.*;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class SystemServ {
|
||||
|
||||
private final ApplicationContext applicationContext;
|
||||
private final SystemConv systemConv;
|
||||
|
||||
public List<ApiInfo> getSystemApis() {
|
||||
|
||||
RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
|
||||
Map<RequestMappingInfo, HandlerMethod> methodMap = mapping.getHandlerMethods();
|
||||
|
||||
|
||||
List<ApiInfo> apiInfos = new LinkedList<>();
|
||||
methodMap.forEach((info, func) -> {
|
||||
if (Objects.isNull(info.getPathPatternsCondition())) {
|
||||
return;
|
||||
}
|
||||
|
||||
Set<PathPattern> patterns = info.getPathPatternsCondition().getPatterns();
|
||||
Set<RequestMethod> methods = info.getMethodsCondition().getMethods();
|
||||
Optional<Operation> desc = Optional.ofNullable(func.getMethod().getAnnotation(Operation.class));
|
||||
for (PathPattern url : patterns) {
|
||||
for (RequestMethod method : methods) {
|
||||
apiInfos.add(new ApiInfo(url.getPatternString(), method, desc.map(Operation::summary).orElse(null)));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return apiInfos;
|
||||
}
|
||||
|
||||
public void initResources() {
|
||||
List<SysResource> resources = systemConv.ApiInfosDto2Pojo(getSystemApis());
|
||||
}
|
||||
|
||||
}
|
||||
109
src/main/java/com/dlp/admin/service/UserServ.java
Normal file
109
src/main/java/com/dlp/admin/service/UserServ.java
Normal file
@@ -0,0 +1,109 @@
|
||||
package com.dlp.admin.service;
|
||||
|
||||
import com.dlp.admin.entity.converter.UserConv;
|
||||
import com.dlp.admin.entity.dto.user.CustomUserDetails;
|
||||
import com.dlp.admin.entity.dto.user.TokenClaims;
|
||||
import com.dlp.admin.entity.enums.UserStatusEnum;
|
||||
import com.dlp.admin.entity.exception.OrgNotExistExcp;
|
||||
import com.dlp.admin.entity.exception.UserDisabledExcp;
|
||||
import com.dlp.admin.entity.exception.UsernameOrPasswordExcp;
|
||||
import com.dlp.admin.entity.pojo.user.SysOrg;
|
||||
import com.dlp.admin.entity.pojo.user.SysUser;
|
||||
import com.dlp.admin.entity.req.user.LoginReq;
|
||||
import com.dlp.admin.entity.resp.user.LoginResp;
|
||||
import com.dlp.admin.repository.user.SysUserRepo;
|
||||
import com.dlp.admin.util.AuthUtil;
|
||||
import com.dlp.admin.util.JwtUtil;
|
||||
import com.dlp.admin.util.RedisUtil;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class UserServ implements UserDetailsService {
|
||||
|
||||
private final UserConv userConv;
|
||||
private final SysUserRepo userRepo;
|
||||
|
||||
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;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final AuthUtil authUtil;
|
||||
|
||||
public SysUser getUserByUsername(String username) {
|
||||
Optional<SysUser> user = userRepo.findByUsername(username);
|
||||
if (user.isEmpty()) {
|
||||
throw new UsernameNotFoundException("用户不存在");
|
||||
}
|
||||
return user.get();
|
||||
}
|
||||
|
||||
public LoginResp login(LoginReq req) {
|
||||
Optional<SysUser> userOpt = userRepo.findByUsername(req.getUsername());
|
||||
SysUser user = validUserAvailable(userOpt);
|
||||
validPassword(req.getPassword(), user.getPassword());
|
||||
TokenClaims claims = userConv.ClaimsPojo2Dto(user);
|
||||
LoginResp resp = new LoginResp();
|
||||
resp.setToken(JwtUtil.generateToken(claims));
|
||||
return resp;
|
||||
}
|
||||
//
|
||||
// public Object listUser() {
|
||||
// Long orgId = authUtil.getUserDetails().getOrgId();
|
||||
// List<Long> subOrgIds = userDao.listOrgWithSubOrg(orgId).stream().map(SysOrg::getId).toList();
|
||||
// return userDao.listUserByOrgIds(subOrgIds);
|
||||
// }
|
||||
|
||||
@Override
|
||||
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
||||
// 读缓存
|
||||
Optional<CustomUserDetails> userDetailsOpt = loadUserDetailsFromRedis(username);
|
||||
if (userDetailsOpt.isPresent()) {
|
||||
return userDetailsOpt.get();
|
||||
}
|
||||
|
||||
// 读数据库
|
||||
Optional<SysUser> userOpt = userRepo.findByUsername(username);
|
||||
SysUser user = validUserAvailable(userOpt);
|
||||
CustomUserDetails userDetails = userConv.UserDetailsPojo2Dto(user);
|
||||
|
||||
// 写缓存
|
||||
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);
|
||||
}
|
||||
|
||||
private void validPassword(String rawPassword, String encodedPassword) {
|
||||
if (!passwordEncoder.matches(rawPassword, encodedPassword)) {
|
||||
throw new UsernameOrPasswordExcp();
|
||||
}
|
||||
}
|
||||
|
||||
private SysUser validUserAvailable(Optional<SysUser> userOpt) {
|
||||
if (userOpt.isEmpty()) {
|
||||
throw new UsernameOrPasswordExcp();
|
||||
}
|
||||
if (userOpt.get().getStatus() == UserStatusEnum.DISABLED) {
|
||||
throw new UserDisabledExcp();
|
||||
}
|
||||
return userOpt.get();
|
||||
}
|
||||
|
||||
private SysOrg validOrgAvailable(Optional<SysOrg> orgOpt) {
|
||||
if (orgOpt.isEmpty()) {
|
||||
throw new OrgNotExistExcp();
|
||||
}
|
||||
return orgOpt.get();
|
||||
}
|
||||
}
|
||||
12
src/main/java/com/dlp/admin/util/AuthUtil.java
Normal file
12
src/main/java/com/dlp/admin/util/AuthUtil.java
Normal file
@@ -0,0 +1,12 @@
|
||||
package com.dlp.admin.util;
|
||||
|
||||
import com.dlp.admin.entity.dto.user.CustomUserDetails;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class AuthUtil {
|
||||
public CustomUserDetails getUserDetails() {
|
||||
return (CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
|
||||
}
|
||||
}
|
||||
30
src/main/java/com/dlp/admin/util/ConvertUtil.java
Normal file
30
src/main/java/com/dlp/admin/util/ConvertUtil.java
Normal file
@@ -0,0 +1,30 @@
|
||||
package com.dlp.admin.util;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.type.MapType;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class ConvertUtil {
|
||||
|
||||
private static final ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();
|
||||
|
||||
public static <T, V> Map<String, V> toMap(T source, Class<V> vClass) {
|
||||
MapType mapType = mapper.getTypeFactory().constructMapType(HashMap.class, String.class, vClass);
|
||||
return mapper.convertValue(source, mapType);
|
||||
}
|
||||
|
||||
public static <T> T fromMap(Map<String, ?> map, Class<T> 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);
|
||||
}
|
||||
}
|
||||
42
src/main/java/com/dlp/admin/util/JwtUtil.java
Normal file
42
src/main/java/com/dlp/admin/util/JwtUtil.java
Normal file
@@ -0,0 +1,42 @@
|
||||
package com.dlp.admin.util;
|
||||
|
||||
import com.auth0.jwt.JWT;
|
||||
import com.auth0.jwt.JWTCreator;
|
||||
import com.auth0.jwt.JWTVerifier;
|
||||
import com.auth0.jwt.algorithms.Algorithm;
|
||||
import com.auth0.jwt.exceptions.JWTVerificationException;
|
||||
import com.auth0.jwt.interfaces.DecodedJWT;
|
||||
import com.dlp.admin.entity.dto.user.TokenClaims;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public class JwtUtil {
|
||||
|
||||
private static final long TOKEN_ALIVE_TIME = 30 * 24 * 60 * 60;
|
||||
|
||||
private static final String SECRET = "2b44b0b00fd822d8ce753e54dac3dc4e06c2725f7db930f3b9924468b53194dbccdbe23d7baa5ef5fbc414ca4b2e64700bad60c5a7c45eaba56880985582fba4";
|
||||
|
||||
public static TokenClaims parseValidToken(String token) throws JWTVerificationException {
|
||||
JWTVerifier verifier = JWT.require(algorithm()).withIssuer("DLP").build();
|
||||
DecodedJWT decodedJWT = verifier.verify(token);
|
||||
return TokenClaims.fromClaimMap(decodedJWT.getClaims());
|
||||
}
|
||||
|
||||
public static String generateToken(TokenClaims claims) {
|
||||
JWTCreator.Builder builder = JWT.create();
|
||||
return builder.withPayload(claims.toMap())
|
||||
.withExpiresAt(Instant.now().plusSeconds(TOKEN_ALIVE_TIME))
|
||||
.withIssuedAt(Instant.now())
|
||||
.withIssuer("DLP")
|
||||
.sign(algorithm());
|
||||
}
|
||||
|
||||
private static Algorithm algorithm() {
|
||||
return Algorithm.HMAC256(SECRET);
|
||||
}
|
||||
|
||||
public static boolean needRenew(Instant expiresAt, long renewTime) {
|
||||
return expiresAt.minusSeconds(renewTime).isBefore(Instant.now());
|
||||
}
|
||||
|
||||
}
|
||||
67
src/main/java/com/dlp/admin/util/RedisUtil.java
Normal file
67
src/main/java/com/dlp/admin/util/RedisUtil.java
Normal file
@@ -0,0 +1,67 @@
|
||||
package com.dlp.admin.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);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user