This commit is contained in:
Chuck1sn
2025-05-14 10:16:48 +08:00
commit 3cd59337e7
220 changed files with 23768 additions and 0 deletions

View File

@@ -0,0 +1,12 @@
package com.zl.mjga;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages = {"com.zl.mjga", "org.jooq.generated"})
public class ApplicationService {
public static void main(String[] args) {
SpringApplication.run(ApplicationService.class, args);
}
}

View File

@@ -0,0 +1,45 @@
package com.zl.mjga.config;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Value("${cors.allowedOrigins}")
private String allowedOrigins;
@Value("${cors.allowedMethods}")
private String allowedMethods;
@Value("${cors.allowedHeaders}")
private String allowedHeaders;
@Value("${cors.allowedExposeHeaders}")
private String allowedExposeHeaders;
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList(allowedOrigins.split(",")));
configuration.setAllowedMethods(Arrays.asList(allowedMethods.split(",")));
configuration.setAllowedHeaders(Arrays.asList(allowedHeaders.split(",")));
configuration.setExposedHeaders(Arrays.asList(allowedExposeHeaders.split(",")));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}

View File

@@ -0,0 +1,79 @@
package com.zl.mjga.config;
import com.zl.mjga.job.DataBackupJob;
import java.util.Map;
import java.util.Properties;
import javax.sql.DataSource;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Trigger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
@Configuration
public class QuartzConfig {
@Value("${spring.flyway.default-schema}")
private String defaultSchema;
@Bean("emailJobSchedulerFactory")
public SchedulerFactoryBean emailJobSchedulerFactory(DataSource dataSource) {
SchedulerFactoryBean schedulerFactory = new SchedulerFactoryBean();
schedulerFactory.setSchedulerName("email-scheduler");
schedulerFactory.setDataSource(dataSource);
Properties props = getCommonProps();
props.setProperty("org.quartz.threadPool.threadCount", "10");
schedulerFactory.setQuartzProperties(props);
return schedulerFactory;
}
@Bean("dataBackupJobDetail")
public JobDetailFactoryBean dataBackupJobDetail() {
JobDetailFactoryBean factory = new JobDetailFactoryBean();
factory.setJobClass(DataBackupJob.class);
factory.setJobDataMap(new JobDataMap(Map.of("roleId", "Gh2mxa")));
factory.setName("data-backup-job");
factory.setGroup("batch-service");
factory.setDurability(true);
return factory;
}
@Bean("dataBackupSchedulerFactory")
public SchedulerFactoryBean dataBackupSchedulerFactory(
Trigger dataBackupTrigger, JobDetail dataBackupJobDetail, DataSource dataSource) {
SchedulerFactoryBean schedulerFactory = new SchedulerFactoryBean();
schedulerFactory.setSchedulerName("data-backup-scheduler");
Properties props = getCommonProps();
props.setProperty("org.quartz.threadPool.threadCount", "10");
schedulerFactory.setQuartzProperties(props);
schedulerFactory.setJobDetails(dataBackupJobDetail);
schedulerFactory.setTriggers(dataBackupTrigger);
schedulerFactory.setDataSource(dataSource);
return schedulerFactory;
}
private Properties getCommonProps() {
Properties props = new Properties();
props.setProperty(
"org.quartz.jobStore.class",
"org.springframework.scheduling.quartz.LocalDataSourceJobStore");
props.setProperty(
"org.quartz.jobStore.driverDelegateClass",
"org.quartz.impl.jdbcjobstore.PostgreSQLDelegate");
props.setProperty("org.quartz.jobStore.tablePrefix", String.format("%s.qrtz_", defaultSchema));
return props;
}
@Bean("dataBackupTrigger")
public CronTriggerFactoryBean dataBackupTrigger(JobDetail dataBackupJobDetail) {
CronTriggerFactoryBean factory = new CronTriggerFactoryBean();
factory.setJobDetail(dataBackupJobDetail);
factory.setCronExpression("0 0/5 * * * ?");
return factory;
}
}

View File

@@ -0,0 +1,31 @@
package com.zl.mjga.config.cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@EnableCaching
@Configuration
public class CacheConfig {
public static final String VERIFY_CODE = "verifyCode";
@Bean
public CacheManager cacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
cacheManager.setCaches(List.of(verifyCodeCache()));
return cacheManager;
}
private CaffeineCache verifyCodeCache() {
return new CaffeineCache(
VERIFY_CODE,
Caffeine.newBuilder().maximumSize(1000).expireAfterWrite(60, TimeUnit.SECONDS).build());
}
}

View File

@@ -0,0 +1,30 @@
package com.zl.mjga.config.security;
import jakarta.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.security.web.firewall.HttpFirewall;
import org.springframework.security.web.firewall.RequestRejectedHandler;
import org.springframework.security.web.firewall.StrictHttpFirewall;
@Configuration
public class HttpFireWallConfig {
@Bean
public HttpFirewall getHttpFirewall() {
return new StrictHttpFirewall();
}
@Bean
public RequestRejectedHandler requestRejectedHandler() {
return (request, response, requestRejectedException) -> {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.setContentType(MediaType.TEXT_PLAIN_VALUE);
try (PrintWriter writer = response.getWriter()) {
writer.write(requestRejectedException.getMessage());
}
};
}
}

View File

@@ -0,0 +1,79 @@
package com.zl.mjga.config.security;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Slf4j
@Component
@Getter
public class Jwt {
private final String secret;
private final int expirationMin;
private final JWTVerifier verifier;
public Jwt(
@Value("${jwt.secret}") String secret, @Value("${jwt.expiration-min}") int expirationMin) {
this.verifier = JWT.require(Algorithm.HMAC256(secret)).build();
this.secret = secret;
this.expirationMin = expirationMin;
}
public String getSubject(String token) {
return JWT.decode(token).getSubject();
}
public Boolean verify(String token) {
try {
verifier.verify(token);
return Boolean.TRUE;
} catch (JWTVerificationException e) {
return Boolean.FALSE;
}
}
public String extract(HttpServletRequest request) {
String authorization = request.getHeader("Authorization");
if (StringUtils.isNotEmpty(authorization) && authorization.startsWith("Bearer")) {
return authorization.substring(7);
} else {
return null;
}
}
public String create(String userIdentify) {
return JWT.create()
.withSubject(String.valueOf(userIdentify))
.withIssuedAt(new Date())
.withExpiresAt(
Date.from(
LocalDateTime.now()
.plusMinutes(expirationMin)
.atZone(ZoneId.systemDefault())
.toInstant()))
.sign(Algorithm.HMAC256(secret));
}
public void makeToken(
HttpServletRequest request, HttpServletResponse response, String userIdentify) {
response.addHeader("Authorization", String.format("Bearer %s", create(userIdentify)));
}
public void removeToken(HttpServletRequest request, HttpServletResponse response) {
response.addHeader("Authorization", null);
}
}

View File

@@ -0,0 +1,44 @@
package com.zl.mjga.config.security;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;
@Slf4j
@Setter
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final Jwt jwt;
private final UserDetailsServiceImpl userDetailsService;
@Override
protected void doFilterInternal(
HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String token = jwt.extract(request);
if (StringUtils.isNotEmpty(token) && jwt.verify(token)) {
try {
UserDetails userDetails = userDetailsService.loadUserByUsername(jwt.getSubject(token));
JwtAuthenticationToken authenticated =
JwtAuthenticationToken.authenticated(userDetails, token, userDetails.getAuthorities());
authenticated.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authenticated);
} catch (Exception e) {
log.error("jwt with invalid user id {}", jwt.getSubject(token), e);
}
}
filterChain.doFilter(request, response);
}
}

View File

@@ -0,0 +1,57 @@
package com.zl.mjga.config.security;
import java.io.Serial;
import java.util.Collection;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.core.userdetails.UserDetails;
@Setter
@Getter
@ToString
public class JwtAuthenticationToken extends AbstractAuthenticationToken {
@Serial private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private final Object principal;
private String credentials;
public JwtAuthenticationToken(Object principal, String credentials) {
super(null);
this.principal = principal;
this.credentials = credentials;
super.setAuthenticated(false);
}
public JwtAuthenticationToken(
Object principal, String credentials, Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.principal = principal;
this.credentials = credentials;
super.setAuthenticated(true);
}
public static JwtAuthenticationToken unauthenticated(String userIdentify, String token) {
return new JwtAuthenticationToken(userIdentify, token);
}
public static JwtAuthenticationToken authenticated(
UserDetails principal, String token, Collection<? extends GrantedAuthority> authorities) {
return new JwtAuthenticationToken(principal, token, authorities);
}
@Override
public String getCredentials() {
return this.credentials;
}
@Override
public Object getPrincipal() {
return this.principal;
}
}

View File

@@ -0,0 +1,14 @@
package com.zl.mjga.config.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class PasswordEncoderConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}

View File

@@ -0,0 +1,28 @@
package com.zl.mjga.config.security;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
public class RestfulAuthenticationEntryPointHandler
implements AccessDeniedHandler, AuthenticationEntryPoint {
@Override
public void commence(
HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
@Override
public void handle(
HttpServletRequest request,
HttpServletResponse response,
AccessDeniedException accessDeniedException) {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
}
}

View File

@@ -0,0 +1,38 @@
package com.zl.mjga.config.security;
import com.zl.mjga.dto.urp.UserRolePermissionDto;
import com.zl.mjga.service.IdentityAccessService;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {
private final IdentityAccessService identityAccessService;
@Override
public UserDetails loadUserByUsername(String id) throws UsernameNotFoundException {
UserRolePermissionDto userRolePermissionDto =
identityAccessService.queryUniqueUserWithRolePermission(Long.valueOf(id));
if (userRolePermissionDto == null) {
throw new UsernameNotFoundException(String.format("uid %s user not found", id));
}
return new User(
userRolePermissionDto.getUsername(),
userRolePermissionDto.getPassword(),
userRolePermissionDto.getEnable(),
true,
true,
true,
userRolePermissionDto.getPermissions().stream()
.map((permission) -> new SimpleGrantedAuthority(permission.getCode()))
.collect(Collectors.toSet()));
}
}

View File

@@ -0,0 +1,77 @@
package com.zl.mjga.config.security;
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.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
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.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.*;
import org.springframework.web.cors.CorsConfigurationSource;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
@RequiredArgsConstructor
public class WebSecurityConfig {
private final UserDetailsServiceImpl userDetailsService;
private final Jwt jwt;
private final CorsConfigurationSource corsConfigurationSource;
@Bean
public AuthenticationManager authenticationManager(
AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
@Bean
public RequestMatcher publicEndPointMatcher() {
return new OrRequestMatcher(
new AntPathRequestMatcher("/auth/sign-in", HttpMethod.POST.name()),
new AntPathRequestMatcher("/auth/sign-up", HttpMethod.POST.name()),
new AntPathRequestMatcher("/v3/api-docs/**", HttpMethod.GET.name()),
new AntPathRequestMatcher("/swagger-ui/**", HttpMethod.GET.name()),
new AntPathRequestMatcher("/swagger-ui.html", HttpMethod.GET.name()),
new AntPathRequestMatcher("/error"));
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
RestfulAuthenticationEntryPointHandler restfulAuthenticationEntryPointHandler =
new RestfulAuthenticationEntryPointHandler();
/*
<Stateless API CSRF protection>
http.csrf(csrf -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()))
*/
http.cors(corsConfigurer -> corsConfigurer.configurationSource(corsConfigurationSource));
http.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(
authorize ->
authorize
.requestMatchers(publicEndPointMatcher())
.permitAll()
.anyRequest()
.authenticated())
.exceptionHandling(
(exceptionHandling) ->
exceptionHandling
.accessDeniedHandler(restfulAuthenticationEntryPointHandler)
.authenticationEntryPoint(restfulAuthenticationEntryPointHandler))
.sessionManagement(
session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.addFilterAt(
new JwtAuthenticationFilter(jwt, userDetailsService),
UsernamePasswordAuthenticationFilter.class);
return http.build();
}
}

View File

@@ -0,0 +1,51 @@
package com.zl.mjga.controller;
import com.zl.mjga.dto.PageRequestDto;
import com.zl.mjga.dto.PageResponseDto;
import com.zl.mjga.dto.department.DepartmentQueryDto;
import com.zl.mjga.dto.department.DepartmentRespDto;
import com.zl.mjga.repository.DepartmentRepository;
import com.zl.mjga.service.DepartmentService;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.jooq.generated.mjga.tables.pojos.Department;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
@SuppressWarnings("PMD.AvoidDuplicateLiterals")
@RestController
@RequestMapping("/department")
@RequiredArgsConstructor
public class DepartmentController {
private final DepartmentService departmentService;
private final DepartmentRepository departmentRepository;
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).READ_DEPARTMENT_PERMISSION)")
@GetMapping("/page-query")
@ResponseStatus(HttpStatus.OK)
PageResponseDto<List<DepartmentRespDto>> pageQueryDepartments(
@ModelAttribute PageRequestDto pageRequestDto,
@ModelAttribute DepartmentQueryDto departmentQueryDto) {
return departmentService.pageQueryDepartment(pageRequestDto, departmentQueryDto);
}
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).READ_DEPARTMENT_PERMISSION)")
@GetMapping("/query")
List<Department> queryDepartments() {
return departmentRepository.findAll();
}
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).WRITE_DEPARTMENT_PERMISSION)")
@DeleteMapping()
void deleteDepartment(@RequestParam Long id) {
departmentRepository.deleteById(id);
}
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).WRITE_DEPARTMENT_PERMISSION)")
@PostMapping()
void upsertDepartment(@RequestBody Department department) {
departmentRepository.merge(department);
}
}

View File

@@ -0,0 +1,177 @@
package com.zl.mjga.controller;
import com.zl.mjga.dto.PageRequestDto;
import com.zl.mjga.dto.PageResponseDto;
import com.zl.mjga.dto.department.DepartmentBindDto;
import com.zl.mjga.dto.permission.PermissionBindDto;
import com.zl.mjga.dto.position.PositionBindDto;
import com.zl.mjga.dto.role.RoleBindDto;
import com.zl.mjga.dto.urp.*;
import com.zl.mjga.repository.RoleRepository;
import com.zl.mjga.repository.UserRepository;
import com.zl.mjga.service.IdentityAccessService;
import jakarta.validation.Valid;
import java.security.Principal;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.jooq.generated.mjga.tables.pojos.User;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
@SuppressWarnings("PMD.AvoidDuplicateLiterals")
@RestController
@RequestMapping("/iam")
@RequiredArgsConstructor
public class IdentityAccessController {
private final IdentityAccessService identityAccessService;
private final UserRepository userRepository;
private final RoleRepository roleRepository;
@GetMapping("/me")
UserRolePermissionDto currentUser(Principal principal) {
String name = principal.getName();
User user = userRepository.fetchOneByUsername(name);
return identityAccessService.queryUniqueUserWithRolePermission(user.getId());
}
@PostMapping("/me")
void upsertMe(Principal principal, @RequestBody UserUpsertDto userUpsertDto) {
String name = principal.getName();
User user = userRepository.fetchOneByUsername(name);
userUpsertDto.setId(user.getId());
identityAccessService.upsertUser(userUpsertDto);
}
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).WRITE_USER_ROLE_PERMISSION)")
@PostMapping("/user")
void upsertUser(@RequestBody UserUpsertDto userUpsertDto) {
identityAccessService.upsertUser(userUpsertDto);
}
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).READ_USER_ROLE_PERMISSION)")
@GetMapping("/user")
UserRolePermissionDto queryUserWithRolePermission(@RequestParam Long userId) {
return identityAccessService.queryUniqueUserWithRolePermission(userId);
}
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).WRITE_USER_ROLE_PERMISSION)")
@DeleteMapping("/user")
void deleteUser(@RequestParam Long userId) {
userRepository.deleteById(userId);
}
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).WRITE_USER_ROLE_PERMISSION)")
@PostMapping("/role")
void upsertRole(@RequestBody RoleUpsertDto roleUpsertDto) {
identityAccessService.upsertRole(roleUpsertDto);
}
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).WRITE_USER_ROLE_PERMISSION)")
@DeleteMapping("/role")
void deleteRole(@RequestParam Long roleId) {
roleRepository.deleteById(roleId);
}
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).WRITE_USER_ROLE_PERMISSION)")
@GetMapping("/role")
RoleDto queryRoleWithPermission(@RequestParam Long roleId) {
return identityAccessService.queryUniqueRoleWithPermission(roleId);
}
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).WRITE_USER_ROLE_PERMISSION)")
@PostMapping("/permission")
void upsertPermission(@RequestBody PermissionUpsertDto permissionUpsertDto) {
identityAccessService.upsertPermission(permissionUpsertDto);
}
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).WRITE_USER_ROLE_PERMISSION)")
@DeleteMapping("/permission")
void deletePermission(@RequestParam Long permissionId) {
roleRepository.deleteById(permissionId);
}
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).READ_USER_ROLE_PERMISSION)")
@GetMapping("/users")
@ResponseStatus(HttpStatus.OK)
PageResponseDto<List<UserRolePermissionDto>> queryUsers(
@ModelAttribute PageRequestDto pageRequestDto, @ModelAttribute UserQueryDto userQueryDto) {
return identityAccessService.pageQueryUser(pageRequestDto, userQueryDto);
}
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).READ_USER_ROLE_PERMISSION)")
@GetMapping("/roles")
@ResponseStatus(HttpStatus.OK)
PageResponseDto<List<RoleDto>> queryRoles(
@ModelAttribute PageRequestDto pageRequestDto, @ModelAttribute RoleQueryDto roleQueryDto) {
return identityAccessService.pageQueryRole(pageRequestDto, roleQueryDto);
}
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).READ_USER_ROLE_PERMISSION)")
@GetMapping("/permissions")
@ResponseStatus(HttpStatus.OK)
PageResponseDto<List<PermissionRespDto>> queryPermissions(
@ModelAttribute PageRequestDto pageRequestDto,
@ModelAttribute PermissionQueryDto permissionQueryDto) {
return identityAccessService.pageQueryPermission(pageRequestDto, permissionQueryDto);
}
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).WRITE_USER_ROLE_PERMISSION)")
@PostMapping("/role/bind")
@ResponseStatus(HttpStatus.OK)
void bindRoleBy(@RequestBody @Valid RoleBindDto roleBindDto) {
identityAccessService.bindRoleToUser(roleBindDto.userId(), roleBindDto.roleIds());
}
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).WRITE_USER_ROLE_PERMISSION)")
@PostMapping("/role/unbind")
@ResponseStatus(HttpStatus.OK)
void unBindRoleBy(@RequestBody @Valid RoleBindDto roleBindDto) {
identityAccessService.unBindRoleToUser(roleBindDto.userId(), roleBindDto.roleIds());
}
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).WRITE_USER_ROLE_PERMISSION)")
@PostMapping("/permission/bind")
@ResponseStatus(HttpStatus.OK)
void bindPermissionBy(@RequestBody @Valid PermissionBindDto permissionBindDto) {
identityAccessService.bindPermissionBy(
permissionBindDto.roleId(), permissionBindDto.permissionIds());
}
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).WRITE_USER_ROLE_PERMISSION)")
@PostMapping("/permission/unbind")
@ResponseStatus(HttpStatus.OK)
void unBindPermissionBy(@RequestBody @Valid PermissionBindDto permissionBindDto) {
identityAccessService.unBindPermissionBy(
permissionBindDto.roleId(), permissionBindDto.permissionIds());
}
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).WRITE_DEPARTMENT_PERMISSION)")
@PostMapping("/department/bind")
@ResponseStatus(HttpStatus.OK)
public void bindDepartmentBy(@RequestBody @Valid DepartmentBindDto departmentBindDto) {
identityAccessService.bindDepartmentBy(departmentBindDto);
}
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).WRITE_DEPARTMENT_PERMISSION)")
@PostMapping("/department/unbind")
@ResponseStatus(HttpStatus.OK)
public void unBindDepartmentBy(@RequestBody @Valid DepartmentBindDto departmentBindDto) {
identityAccessService.unBindDepartmentBy(departmentBindDto);
}
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).WRITE_DEPARTMENT_PERMISSION)")
@PostMapping("/position/bind")
@ResponseStatus(HttpStatus.OK)
public void bindPositionBy(@RequestBody @Valid PositionBindDto positionBindDto) {
identityAccessService.bindPositionBy(positionBindDto);
}
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).WRITE_DEPARTMENT_PERMISSION)")
@PostMapping("/position/unbind")
@ResponseStatus(HttpStatus.OK)
public void unBindPositionBy(@RequestBody @Valid PositionBindDto positionBindDto) {
identityAccessService.unBindPositionBy(positionBindDto);
}
}

View File

@@ -0,0 +1,51 @@
package com.zl.mjga.controller;
import com.zl.mjga.dto.PageRequestDto;
import com.zl.mjga.dto.PageResponseDto;
import com.zl.mjga.dto.position.PositionQueryDto;
import com.zl.mjga.dto.position.PositionRespDto;
import com.zl.mjga.repository.PositionRepository;
import com.zl.mjga.service.PositionService;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.jooq.generated.mjga.tables.pojos.Position;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
@SuppressWarnings("PMD.AvoidDuplicateLiterals")
@RestController
@RequestMapping("/position")
@RequiredArgsConstructor
public class PositionController {
private final PositionService positionService;
private final PositionRepository positionRepository;
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).READ_POSITION_PERMISSION)")
@GetMapping("/page-query")
@ResponseStatus(HttpStatus.OK)
PageResponseDto<List<PositionRespDto>> pageQueryPositions(
@ModelAttribute PageRequestDto pageRequestDto,
@ModelAttribute PositionQueryDto positionQueryDto) {
return positionService.pageQueryPosition(pageRequestDto, positionQueryDto);
}
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).READ_POSITION_PERMISSION)")
@GetMapping("/query")
List<Position> queryPositions() {
return positionRepository.findAll();
}
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).WRITE_POSITION_PERMISSION)")
@DeleteMapping()
void deletePosition(@RequestParam Long id) {
positionRepository.deleteById(id);
}
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).WRITE_POSITION_PERMISSION)")
@PostMapping()
void upsertPosition(@RequestBody Position position) {
positionRepository.merge(position);
}
}

View File

@@ -0,0 +1,58 @@
package com.zl.mjga.controller;
import com.zl.mjga.dto.PageRequestDto;
import com.zl.mjga.dto.PageResponseDto;
import com.zl.mjga.dto.scheduler.JobKeyDto;
import com.zl.mjga.dto.scheduler.JobTriggerDto;
import com.zl.mjga.dto.scheduler.QueryDto;
import com.zl.mjga.dto.scheduler.TriggerKeyDto;
import com.zl.mjga.service.SchedulerService;
import java.util.Date;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.quartz.JobKey;
import org.quartz.SchedulerException;
import org.quartz.TriggerKey;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/scheduler")
@RequiredArgsConstructor
public class SchedulerController {
private final SchedulerService schedulerService;
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).READ_SCHEDULER_PERMISSION)")
@GetMapping("/page-query")
public PageResponseDto<List<JobTriggerDto>> pageQuery(
@ModelAttribute PageRequestDto pageRequestDto, @ModelAttribute QueryDto queryDto) {
return schedulerService.getJobWithTriggerBy(pageRequestDto, queryDto);
}
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).WRITE_SCHEDULER_PERMISSION)")
@PostMapping("/trigger/resume")
public void resumeTrigger(@RequestBody TriggerKeyDto triggerKey) throws SchedulerException {
schedulerService.resumeTrigger(new TriggerKey(triggerKey.name(), triggerKey.group()));
}
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).WRITE_SCHEDULER_PERMISSION)")
@PostMapping("/trigger/pause")
public void pauseTrigger(@RequestBody TriggerKeyDto triggerKey) throws SchedulerException {
schedulerService.pauseTrigger(new TriggerKey(triggerKey.name(), triggerKey.group()));
}
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).WRITE_SCHEDULER_PERMISSION)")
@PostMapping("/job/trigger")
public void triggerJob(@RequestBody JobKeyDto jobKeyDto, @RequestParam Long startAt)
throws SchedulerException {
schedulerService.triggerJob(new JobKey(jobKeyDto.name(), jobKeyDto.group()), new Date(startAt));
}
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).WRITE_SCHEDULER_PERMISSION)")
@PutMapping("/job/update")
public void updateJob(@RequestBody TriggerKeyDto triggerKey, @RequestParam String cron)
throws SchedulerException {
schedulerService.updateCronTrigger(new TriggerKey(triggerKey.name(), triggerKey.group()), cron);
}
}

View File

@@ -0,0 +1,43 @@
package com.zl.mjga.controller;
import com.zl.mjga.config.security.Jwt;
import com.zl.mjga.dto.sign.SignInDto;
import com.zl.mjga.dto.sign.SignUpDto;
import com.zl.mjga.service.SignService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class SignController {
private final SignService signService;
private final Jwt jwt;
@ResponseStatus(HttpStatus.OK)
@PostMapping("/sign-in")
void signIn(
HttpServletRequest request,
HttpServletResponse response,
@RequestBody @Valid SignInDto signInDto) {
jwt.makeToken(request, response, String.valueOf(signService.signIn(signInDto)));
}
@ResponseStatus(HttpStatus.CREATED)
@PostMapping("/sign-up")
void signUp(@RequestBody @Valid SignUpDto signUpDto) {
signService.signUp(signUpDto);
}
@ResponseStatus(HttpStatus.OK)
@PostMapping("/sign-out")
void signOut(HttpServletRequest request, HttpServletResponse response) {
jwt.removeToken(request, response);
}
}

View File

@@ -0,0 +1,129 @@
package com.zl.mjga.dto;
import static org.jooq.impl.DSL.field;
import static org.jooq.impl.DSL.name;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.*;
import org.apache.commons.lang3.StringUtils;
import org.jooq.SortField;
import org.jooq.SortOrder;
@Data
@NoArgsConstructor
public class PageRequestDto {
public static final String REGEX = "^[a-zA-Z][a-zA-Z0-9_]*$";
public static final String SPACE = " ";
private long page;
private long size;
private Map<String, Direction> sortBy = new HashMap<>();
public PageRequestDto(int page, int size) {
checkPageAndSize(page, size);
this.page = page;
this.size = size;
}
public PageRequestDto(int page, int size, Map<String, Direction> sortBy) {
checkPageAndSize(page, size);
this.page = page;
this.size = size;
this.sortBy = sortBy;
}
@AllArgsConstructor
@Getter
public enum Direction {
ASC("ASC"),
DESC("DESC");
private final String keyword;
public static Direction fromString(String value) {
try {
return Direction.valueOf(value.toUpperCase(Locale.US));
} catch (Exception e) {
throw new IllegalArgumentException(
String.format(
"Invalid value '%s' for orders given; Has to be either 'desc' or 'asc' (case"
+ " insensitive)",
value),
e);
}
}
}
public static PageRequestDto of(int page, int size) {
return new PageRequestDto(page, size);
}
public static PageRequestDto of(int page, int size, Map<String, Direction> sortBy) {
return new PageRequestDto(page, size, sortBy);
}
public List<SortField<Object>> getSortFields() {
return sortBy.entrySet().stream()
.map(
(entry) ->
field(name(entry.getKey())).sort(SortOrder.valueOf(entry.getValue().getKeyword())))
.toList();
}
private void checkPageAndSize(int page, int size) {
if (page < 0) {
throw new IllegalArgumentException("Page index must not be less than zero");
}
if (size < 1) {
throw new IllegalArgumentException("Page size must not be less than one");
}
}
public long getOffset() {
if (page == 0) {
return 0;
} else {
return (page - 1) * size;
}
}
public void setSortBy(String sortBy) {
this.sortBy = convertSortBy(sortBy);
}
private Map<String, Direction> convertSortBy(String sortBy) {
Map<String, Direction> result = new HashMap<>();
if (StringUtils.isEmpty(sortBy)) {
return result;
}
for (String fieldSpaceDirection : sortBy.split(",")) {
String[] fieldDirectionArray = fieldSpaceDirection.split(SPACE);
if (fieldDirectionArray.length != 2) {
throw new IllegalArgumentException(
String.format(
"Invalid sortBy field format %s. The expect format is [col1 asc,col2 desc]",
sortBy));
}
String field = fieldDirectionArray[0];
if (!verifySortField(field)) {
throw new IllegalArgumentException(
String.format("Invalid Sort field %s. Sort field must match %s", sortBy, REGEX));
}
String direction = fieldDirectionArray[1];
result.put(field, Direction.fromString(direction));
}
return result;
}
private static boolean verifySortField(String sortField) {
Pattern pattern = Pattern.compile(REGEX);
Matcher matcher = pattern.matcher(sortField);
return matcher.matches();
}
}

View File

@@ -0,0 +1,22 @@
package com.zl.mjga.dto;
import jakarta.annotation.Nullable;
import lombok.*;
@Data
public class PageResponseDto<T> {
private long total;
private T data;
public PageResponseDto(long total, @Nullable T data) {
if (total < 0) {
throw new IllegalArgumentException("total must not be less than zero");
}
this.total = total;
this.data = data;
}
public static <T> PageResponseDto<T> empty() {
return new PageResponseDto<>(0, null);
}
}

View File

@@ -0,0 +1,6 @@
package com.zl.mjga.dto.department;
import jakarta.validation.constraints.NotNull;
import java.util.List;
public record DepartmentBindDto(@NotNull Long userId, @NotNull List<Long> departmentIds) {}

View File

@@ -0,0 +1,16 @@
package com.zl.mjga.dto.department;
import com.zl.mjga.model.urp.BindState;
import lombok.*;
@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class DepartmentQueryDto {
private Long userId;
private String name;
private Boolean enable;
private BindState bindState = BindState.ALL;
}

View File

@@ -0,0 +1,20 @@
package com.zl.mjga.dto.department;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class DepartmentRespDto {
@NotNull private Long id;
@NotEmpty private String name;
private Long parentId;
private String parentName;
private Boolean isBound;
}

View File

@@ -0,0 +1,17 @@
package com.zl.mjga.dto.department;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.*;
@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class DepartmentUpsertDto {
private Long id;
@NotEmpty private String name;
private Long parentId;
@NotNull private Boolean enable;
}

View File

@@ -0,0 +1,8 @@
package com.zl.mjga.dto.permission;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import java.util.List;
public record PermissionBindDto(
@NotNull Long roleId, @NotEmpty(message = "权限不能为空") List<Long> permissionIds) {}

View File

@@ -0,0 +1,6 @@
package com.zl.mjga.dto.position;
import jakarta.validation.constraints.NotNull;
import java.util.List;
public record PositionBindDto(@NotNull Long userId, @NotNull List<Long> positionIds) {}

View File

@@ -0,0 +1,15 @@
package com.zl.mjga.dto.position;
import com.zl.mjga.model.urp.BindState;
import lombok.*;
@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class PositionQueryDto {
private Long userId;
private String name;
private BindState bindState = BindState.ALL;
}

View File

@@ -0,0 +1,19 @@
package com.zl.mjga.dto.position;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class PositionRespDto {
@NotNull private Long id;
@NotEmpty private String name;
private Long parentId;
private Boolean isBound;
}

View File

@@ -0,0 +1,17 @@
package com.zl.mjga.dto.position;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.*;
@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class PositionUpsertDto {
private Long id;
@NotEmpty private String name;
private Long parentId;
@NotNull private Boolean enable;
}

View File

@@ -0,0 +1,8 @@
package com.zl.mjga.dto.role;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import java.util.List;
public record RoleBindDto(
@NotNull(message = "用户不能为空") Long userId, @NotEmpty(message = "角色不能为空") List<Long> roleIds) {}

View File

@@ -0,0 +1,5 @@
package com.zl.mjga.dto.scheduler;
import jakarta.validation.constraints.NotEmpty;
public record JobKeyDto(@NotEmpty String name, @NotEmpty String group) {}

View File

@@ -0,0 +1,26 @@
package com.zl.mjga.dto.scheduler;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class JobTriggerDto {
private String name;
private String group;
private String className;
private Map jobDataMap;
private String triggerName;
private String triggerGroup;
private String schedulerType;
private String cronExpression;
private long startTime;
private long endTime;
private long nextFireTime;
private long previousFireTime;
private String triggerState;
private Map triggerJobDataMap;
}

View File

@@ -0,0 +1,3 @@
package com.zl.mjga.dto.scheduler;
public record QueryDto(String name) {}

View File

@@ -0,0 +1,21 @@
package com.zl.mjga.dto.scheduler;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TriggerDto {
private String name;
private String group;
private String schedulerType;
private String cronExpression;
private long startTime;
private long endTime;
private long nextFireTime;
private long previousFireTime;
private Map jobDataMap;
}

View File

@@ -0,0 +1,5 @@
package com.zl.mjga.dto.scheduler;
import jakarta.validation.constraints.NotEmpty;
public record TriggerKeyDto(@NotEmpty String name, @NotEmpty String group) {}

View File

@@ -0,0 +1,16 @@
package com.zl.mjga.dto.sign;
import jakarta.validation.constraints.NotEmpty;
import lombok.*;
@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class SignInDto {
@NotEmpty private String username;
@NotEmpty private String password;
}

View File

@@ -0,0 +1,15 @@
package com.zl.mjga.dto.sign;
import jakarta.validation.constraints.NotEmpty;
import lombok.*;
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class SignUpDto {
@NotEmpty private String username;
@NotEmpty private String password;
}

View File

@@ -0,0 +1,18 @@
package com.zl.mjga.dto.urp;
import com.zl.mjga.model.urp.BindState;
import java.util.List;
import lombok.*;
@AllArgsConstructor
@NoArgsConstructor
@Data
public class PermissionQueryDto {
private Long roleId;
private Long permissionId;
private String permissionCode;
private String permissionName;
private List<Long> permissionIdList;
private BindState bindState = BindState.ALL;
}

View File

@@ -0,0 +1,14 @@
package com.zl.mjga.dto.urp;
import lombok.*;
@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
public class PermissionRespDto {
private Long id;
private String code;
private String name;
private Boolean isBound;
}

View File

@@ -0,0 +1,15 @@
package com.zl.mjga.dto.urp;
import jakarta.validation.constraints.NotEmpty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@AllArgsConstructor
@NoArgsConstructor
@Data
public class PermissionUpsertDto {
private Long id;
@NotEmpty private String code;
@NotEmpty private String name;
}

View File

@@ -0,0 +1,17 @@
package com.zl.mjga.dto.urp;
import java.util.LinkedList;
import java.util.List;
import lombok.*;
@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
public class RoleDto {
private Long id;
private String code;
private String name;
private Boolean isBound;
@Builder.Default List<PermissionRespDto> permissions = new LinkedList<>();
}

View File

@@ -0,0 +1,18 @@
package com.zl.mjga.dto.urp;
import com.zl.mjga.model.urp.BindState;
import java.util.List;
import lombok.*;
@AllArgsConstructor
@NoArgsConstructor
@Data
public class RoleQueryDto {
private Long userId;
private Long roleId;
private String roleCode;
private String roleName;
private List<Long> roleIdList;
private BindState bindState = BindState.ALL;
}

View File

@@ -0,0 +1,15 @@
package com.zl.mjga.dto.urp;
import jakarta.validation.constraints.NotEmpty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@AllArgsConstructor
@NoArgsConstructor
@Data
public class RoleUpsertDto {
private Long id;
@NotEmpty private String code;
@NotEmpty private String name;
}

View File

@@ -0,0 +1,10 @@
package com.zl.mjga.dto.urp;
import lombok.*;
@AllArgsConstructor
@NoArgsConstructor
@Data
public class UserQueryDto {
private String username;
}

View File

@@ -0,0 +1,34 @@
package com.zl.mjga.dto.urp;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.OffsetDateTime;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.*;
@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
public class UserRolePermissionDto {
private Long id;
private String username;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String password;
private Boolean enable;
@Builder.Default private List<RoleDto> roles = new LinkedList<>();
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
private OffsetDateTime createTime;
public Set<PermissionRespDto> getPermissions() {
return roles.stream()
.flatMap((roleDto) -> roleDto.getPermissions().stream())
.collect(Collectors.toSet());
}
}

View File

@@ -0,0 +1,17 @@
package com.zl.mjga.dto.urp;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@AllArgsConstructor
@NoArgsConstructor
@Data
public class UserUpsertDto {
private Long id;
@NotEmpty private String username;
private String password;
@NotNull private Boolean enable;
}

View File

@@ -0,0 +1,25 @@
package com.zl.mjga.exception;
public class BusinessException extends RuntimeException {
@java.io.Serial private static final long serialVersionUID = -2119302295305964305L;
public BusinessException() {}
public BusinessException(String message) {
super(message);
}
public BusinessException(String message, Throwable cause) {
super(message, cause);
}
public BusinessException(Throwable cause) {
super(cause);
}
public BusinessException(
String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}

View File

@@ -0,0 +1,90 @@
package com.zl.mjga.exception;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.lang.Nullable;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.firewall.RequestRejectedException;
import org.springframework.web.ErrorResponseException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = {BusinessException.class})
public ResponseEntity<Object> handleBusinessException(BusinessException ex, WebRequest request) {
log.error("Business Error Handled ===> ", ex);
ErrorResponseException errorResponseException =
new ErrorResponseException(
HttpStatus.INTERNAL_SERVER_ERROR,
ProblemDetail.forStatusAndDetail(HttpStatus.INTERNAL_SERVER_ERROR, ex.getMessage()),
ex.getCause());
return handleExceptionInternal(
errorResponseException,
errorResponseException.getBody(),
errorResponseException.getHeaders(),
errorResponseException.getStatusCode(),
request);
}
@SuppressWarnings("NullableProblems")
@Override
@Nullable public ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatusCode status,
WebRequest request) {
log.error("MethodArgumentNotValidException Handled ===> ", ex);
ErrorResponseException errorResponseException =
new ErrorResponseException(
status, ProblemDetail.forStatusAndDetail(status, ex.getMessage()), ex.getCause());
return handleExceptionInternal(
errorResponseException,
errorResponseException.getBody(),
errorResponseException.getHeaders(),
errorResponseException.getStatusCode(),
request);
}
@ExceptionHandler(value = {RequestRejectedException.class})
public ResponseEntity<Object> handleRequestRejectedException(
RequestRejectedException ex, WebRequest request) {
log.error("RequestRejectedException Handled ===> ", ex);
ErrorResponseException errorResponseException =
new ErrorResponseException(
HttpStatus.BAD_REQUEST,
ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, ex.getMessage()),
ex.getCause());
return handleExceptionInternal(
errorResponseException,
errorResponseException.getBody(),
errorResponseException.getHeaders(),
errorResponseException.getStatusCode(),
request);
}
@ExceptionHandler(value = {AccessDeniedException.class})
public ResponseEntity<Object> handleAccessDenied(AccessDeniedException ex) {
throw ex;
}
@ExceptionHandler(value = {Throwable.class})
public ResponseEntity<Object> handleException(Throwable ex, WebRequest request) {
log.error("System Error Handled ===> ", ex);
ErrorResponseException errorResponseException =
new ErrorResponseException(
HttpStatus.INTERNAL_SERVER_ERROR,
ProblemDetail.forStatusAndDetail(HttpStatus.INTERNAL_SERVER_ERROR, "System Error"),
ex.getCause());
return handleExceptionInternal(
errorResponseException,
errorResponseException.getBody(),
errorResponseException.getHeaders(),
errorResponseException.getStatusCode(),
request);
}
}

View File

@@ -0,0 +1,19 @@
package com.zl.mjga.job;
import java.text.MessageFormat;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
@Slf4j
public class DataBackupJob implements Job {
@Override
public void execute(JobExecutionContext context) {
String userId = context.getJobDetail().getJobDataMap().getString("roleId");
log.info(
MessageFormat.format(
"Job execute: JobName {0} Param {1} Thread: {2}",
getClass(), userId, Thread.currentThread().getName()));
}
}

View File

@@ -0,0 +1,19 @@
package com.zl.mjga.job;
import java.text.MessageFormat;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
@Slf4j
public class EmailJob implements Job {
@Override
public void execute(JobExecutionContext context) {
String userEmail = context.getJobDetail().getJobDataMap().getString("userEmail");
log.info(
MessageFormat.format(
"Job execute: JobName {0} Param {1} Thread: {2}",
getClass(), userEmail, Thread.currentThread().getName()));
}
}

View File

@@ -0,0 +1,7 @@
package com.zl.mjga.model.urp;
public enum BindState {
BIND,
UNBIND,
ALL;
}

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