mirror of
https://github.com/ccmjga/zhilu-admin
synced 2026-03-18 16:13:44 +08:00
init
This commit is contained in:
12
backend/src/main/java/com/zl/mjga/ApplicationService.java
Normal file
12
backend/src/main/java/com/zl/mjga/ApplicationService.java
Normal 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);
|
||||
}
|
||||
}
|
||||
45
backend/src/main/java/com/zl/mjga/config/CorsConfig.java
Normal file
45
backend/src/main/java/com/zl/mjga/config/CorsConfig.java
Normal 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;
|
||||
}
|
||||
}
|
||||
79
backend/src/main/java/com/zl/mjga/config/QuartzConfig.java
Normal file
79
backend/src/main/java/com/zl/mjga/config/QuartzConfig.java
Normal 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;
|
||||
}
|
||||
}
|
||||
31
backend/src/main/java/com/zl/mjga/config/cache/CacheConfig.java
vendored
Normal file
31
backend/src/main/java/com/zl/mjga/config/cache/CacheConfig.java
vendored
Normal 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());
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
79
backend/src/main/java/com/zl/mjga/config/security/Jwt.java
Normal file
79
backend/src/main/java/com/zl/mjga/config/security/Jwt.java
Normal 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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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()));
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
129
backend/src/main/java/com/zl/mjga/dto/PageRequestDto.java
Normal file
129
backend/src/main/java/com/zl/mjga/dto/PageRequestDto.java
Normal 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();
|
||||
}
|
||||
}
|
||||
22
backend/src/main/java/com/zl/mjga/dto/PageResponseDto.java
Normal file
22
backend/src/main/java/com/zl/mjga/dto/PageResponseDto.java
Normal 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);
|
||||
}
|
||||
}
|
||||
@@ -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) {}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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) {}
|
||||
@@ -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) {}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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) {}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.zl.mjga.dto.scheduler;
|
||||
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
|
||||
public record JobKeyDto(@NotEmpty String name, @NotEmpty String group) {}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.zl.mjga.dto.scheduler;
|
||||
|
||||
public record QueryDto(String name) {}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.zl.mjga.dto.scheduler;
|
||||
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
|
||||
public record TriggerKeyDto(@NotEmpty String name, @NotEmpty String group) {}
|
||||
16
backend/src/main/java/com/zl/mjga/dto/sign/SignInDto.java
Normal file
16
backend/src/main/java/com/zl/mjga/dto/sign/SignInDto.java
Normal 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;
|
||||
}
|
||||
15
backend/src/main/java/com/zl/mjga/dto/sign/SignUpDto.java
Normal file
15
backend/src/main/java/com/zl/mjga/dto/sign/SignUpDto.java
Normal 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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
17
backend/src/main/java/com/zl/mjga/dto/urp/RoleDto.java
Normal file
17
backend/src/main/java/com/zl/mjga/dto/urp/RoleDto.java
Normal 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<>();
|
||||
}
|
||||
18
backend/src/main/java/com/zl/mjga/dto/urp/RoleQueryDto.java
Normal file
18
backend/src/main/java/com/zl/mjga/dto/urp/RoleQueryDto.java
Normal 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;
|
||||
}
|
||||
15
backend/src/main/java/com/zl/mjga/dto/urp/RoleUpsertDto.java
Normal file
15
backend/src/main/java/com/zl/mjga/dto/urp/RoleUpsertDto.java
Normal 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;
|
||||
}
|
||||
10
backend/src/main/java/com/zl/mjga/dto/urp/UserQueryDto.java
Normal file
10
backend/src/main/java/com/zl/mjga/dto/urp/UserQueryDto.java
Normal file
@@ -0,0 +1,10 @@
|
||||
package com.zl.mjga.dto.urp;
|
||||
|
||||
import lombok.*;
|
||||
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@Data
|
||||
public class UserQueryDto {
|
||||
private String username;
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
17
backend/src/main/java/com/zl/mjga/dto/urp/UserUpsertDto.java
Normal file
17
backend/src/main/java/com/zl/mjga/dto/urp/UserUpsertDto.java
Normal 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;
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
19
backend/src/main/java/com/zl/mjga/job/DataBackupJob.java
Normal file
19
backend/src/main/java/com/zl/mjga/job/DataBackupJob.java
Normal 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()));
|
||||
}
|
||||
}
|
||||
19
backend/src/main/java/com/zl/mjga/job/EmailJob.java
Normal file
19
backend/src/main/java/com/zl/mjga/job/EmailJob.java
Normal 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()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.zl.mjga.model.urp;
|
||||
|
||||
public enum BindState {
|
||||
BIND,
|
||||
UNBIND,
|
||||
ALL;
|
||||
}
|
||||
12
backend/src/main/java/com/zl/mjga/model/urp/EPermission.java
Normal file
12
backend/src/main/java/com/zl/mjga/model/urp/EPermission.java
Normal file
@@ -0,0 +1,12 @@
|
||||
package com.zl.mjga.model.urp;
|
||||
|
||||
public enum EPermission {
|
||||
READ_POSITION_PERMISSION,
|
||||
WRITE_POSITION_PERMISSION,
|
||||
READ_DEPARTMENT_PERMISSION,
|
||||
WRITE_DEPARTMENT_PERMISSION,
|
||||
READ_SCHEDULER_PERMISSION,
|
||||
WRITE_SCHEDULER_PERMISSION,
|
||||
WRITE_USER_ROLE_PERMISSION,
|
||||
READ_USER_ROLE_PERMISSION
|
||||
}
|
||||
6
backend/src/main/java/com/zl/mjga/model/urp/ERole.java
Normal file
6
backend/src/main/java/com/zl/mjga/model/urp/ERole.java
Normal file
@@ -0,0 +1,6 @@
|
||||
package com.zl.mjga.model.urp;
|
||||
|
||||
public enum ERole {
|
||||
ADMIN,
|
||||
GENERAL
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.zl.mjga.model.urp;
|
||||
|
||||
public enum SchedulerType {
|
||||
CRON,
|
||||
SIMPLE,
|
||||
CALENDAR,
|
||||
DAILY
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.zl.mjga.repository;
|
||||
|
||||
import static org.jooq.generated.mjga.Tables.*;
|
||||
import static org.jooq.impl.DSL.noCondition;
|
||||
import static org.jooq.impl.DSL.noField;
|
||||
|
||||
import com.zl.mjga.dto.PageRequestDto;
|
||||
import com.zl.mjga.dto.department.DepartmentQueryDto;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.jooq.*;
|
||||
import org.jooq.Record;
|
||||
import org.jooq.generated.mjga.tables.Department;
|
||||
import org.jooq.generated.mjga.tables.daos.DepartmentDao;
|
||||
import org.jooq.impl.DSL;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public class DepartmentRepository extends DepartmentDao {
|
||||
|
||||
@Autowired
|
||||
public DepartmentRepository(Configuration configuration) {
|
||||
super(configuration);
|
||||
}
|
||||
|
||||
public Result<Record> pageFetchBy(
|
||||
PageRequestDto pageRequestDto, DepartmentQueryDto departmentQueryDto) {
|
||||
Department parent = DEPARTMENT.as("parent");
|
||||
return ctx()
|
||||
.select(
|
||||
DEPARTMENT.asterisk(),
|
||||
parent.NAME.as("parent_name"),
|
||||
departmentQueryDto.getUserId() != null
|
||||
? DSL.when(
|
||||
DEPARTMENT.ID.in(selectUsersDepartment(departmentQueryDto.getUserId())),
|
||||
true)
|
||||
.otherwise(false)
|
||||
.as("is_bound")
|
||||
: noField(),
|
||||
DSL.count().over().as("total_department").convertFrom(Long::valueOf))
|
||||
.from(DEPARTMENT)
|
||||
.leftJoin(parent)
|
||||
.on(parent.ID.eq(DEPARTMENT.PARENT_ID))
|
||||
.where(
|
||||
switch (departmentQueryDto.getBindState()) {
|
||||
case BIND -> DEPARTMENT.ID.in(selectUsersDepartment(departmentQueryDto.getUserId()));
|
||||
case UNBIND ->
|
||||
DEPARTMENT.ID.notIn(selectUsersDepartment(departmentQueryDto.getUserId()));
|
||||
case ALL -> noCondition();
|
||||
})
|
||||
.and(
|
||||
StringUtils.isNotEmpty(departmentQueryDto.getName())
|
||||
? DEPARTMENT.NAME.like("%" + departmentQueryDto.getName() + "%")
|
||||
: noCondition())
|
||||
.orderBy(pageRequestDto.getSortFields())
|
||||
.limit(pageRequestDto.getSize())
|
||||
.offset(pageRequestDto.getOffset())
|
||||
.fetch();
|
||||
}
|
||||
|
||||
private SelectConditionStep<Record1<Long>> selectUsersDepartment(Long userId) {
|
||||
return DSL.select(USER.department().ID)
|
||||
.from(USER)
|
||||
.innerJoin(USER.department())
|
||||
.where(USER.ID.eq(userId));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package com.zl.mjga.repository;
|
||||
|
||||
import static org.jooq.generated.mjga.tables.Permission.PERMISSION;
|
||||
import static org.jooq.generated.mjga.tables.Role.ROLE;
|
||||
import static org.jooq.impl.DSL.*;
|
||||
import static org.jooq.impl.DSL.noField;
|
||||
|
||||
import com.zl.mjga.dto.PageRequestDto;
|
||||
import com.zl.mjga.dto.urp.PermissionQueryDto;
|
||||
import java.util.List;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.jooq.*;
|
||||
import org.jooq.Record;
|
||||
import org.jooq.generated.mjga.tables.daos.PermissionDao;
|
||||
import org.jooq.generated.mjga.tables.pojos.Permission;
|
||||
import org.jooq.impl.DSL;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public class PermissionRepository extends PermissionDao {
|
||||
|
||||
@Autowired
|
||||
public PermissionRepository(Configuration configuration) {
|
||||
super(configuration);
|
||||
}
|
||||
|
||||
public Result<Record> pageFetchBy(
|
||||
PageRequestDto pageRequestDto, PermissionQueryDto permissionQueryDto) {
|
||||
return ctx()
|
||||
.select(
|
||||
asterisk(),
|
||||
permissionQueryDto.getRoleId() != null
|
||||
? when(
|
||||
PERMISSION.ID.in(selectRolesPermissionIds(permissionQueryDto.getRoleId())),
|
||||
true)
|
||||
.otherwise(false)
|
||||
.as("is_bound")
|
||||
: noField(),
|
||||
DSL.count().over().as("total_permission"))
|
||||
.from(PERMISSION)
|
||||
.where(
|
||||
switch (permissionQueryDto.getBindState()) {
|
||||
case BIND ->
|
||||
PERMISSION.ID.in(selectRolesPermissionIds(permissionQueryDto.getRoleId()));
|
||||
case UNBIND ->
|
||||
PERMISSION.ID.notIn(selectRolesPermissionIds(permissionQueryDto.getRoleId()));
|
||||
case ALL -> noCondition();
|
||||
})
|
||||
.and(
|
||||
permissionQueryDto.getPermissionId() == null
|
||||
? noCondition()
|
||||
: PERMISSION.ID.eq(permissionQueryDto.getPermissionId()))
|
||||
.and(
|
||||
StringUtils.isEmpty(permissionQueryDto.getPermissionName())
|
||||
? noCondition()
|
||||
: PERMISSION.NAME.like("%" + permissionQueryDto.getPermissionName() + "%"))
|
||||
.and(
|
||||
StringUtils.isEmpty(permissionQueryDto.getPermissionName())
|
||||
? noCondition()
|
||||
: PERMISSION.CODE.eq(permissionQueryDto.getPermissionCode()))
|
||||
.orderBy(pageRequestDto.getSortFields())
|
||||
.limit(pageRequestDto.getSize())
|
||||
.offset(pageRequestDto.getOffset())
|
||||
.fetch();
|
||||
}
|
||||
|
||||
private SelectConditionStep<Record1<Long>> selectRolesPermissionIds(Long roleId) {
|
||||
return DSL.select(ROLE.permission().ID)
|
||||
.from(ROLE)
|
||||
.leftJoin(ROLE.permission())
|
||||
.where(ROLE.ID.eq(roleId));
|
||||
}
|
||||
|
||||
public List<Permission> selectByPermissionIdIn(List<Long> permissionIdList) {
|
||||
return ctx()
|
||||
.selectFrom(PERMISSION)
|
||||
.where(PERMISSION.ID.in(permissionIdList))
|
||||
.fetchInto(Permission.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.zl.mjga.repository;
|
||||
|
||||
import static org.jooq.generated.mjga.Tables.*;
|
||||
import static org.jooq.impl.DSL.noCondition;
|
||||
import static org.jooq.impl.DSL.noField;
|
||||
|
||||
import com.zl.mjga.dto.PageRequestDto;
|
||||
import com.zl.mjga.dto.position.PositionQueryDto;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.jooq.*;
|
||||
import org.jooq.Record;
|
||||
import org.jooq.generated.mjga.tables.daos.PositionDao;
|
||||
import org.jooq.impl.DSL;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public class PositionRepository extends PositionDao {
|
||||
|
||||
@Autowired
|
||||
public PositionRepository(Configuration configuration) {
|
||||
super(configuration);
|
||||
}
|
||||
|
||||
public Result<Record> pageFetchBy(
|
||||
PageRequestDto pageRequestDto, PositionQueryDto positionQueryDto) {
|
||||
return ctx()
|
||||
.select(
|
||||
POSITION.asterisk(),
|
||||
positionQueryDto.getUserId() != null
|
||||
? DSL.when(POSITION.ID.in(selectUsersPosition(positionQueryDto.getUserId())), true)
|
||||
.otherwise(false)
|
||||
.as("is_bound")
|
||||
: noField(),
|
||||
DSL.count().over().as("total_position").convertFrom(Long::valueOf))
|
||||
.from(POSITION)
|
||||
.where(
|
||||
switch (positionQueryDto.getBindState()) {
|
||||
case BIND -> POSITION.ID.in(selectUsersPosition(positionQueryDto.getUserId()));
|
||||
case UNBIND -> POSITION.ID.notIn(selectUsersPosition(positionQueryDto.getUserId()));
|
||||
case ALL -> noCondition();
|
||||
})
|
||||
.and(
|
||||
StringUtils.isNotEmpty(positionQueryDto.getName())
|
||||
? POSITION.NAME.like("%" + positionQueryDto.getName() + "%")
|
||||
: noCondition())
|
||||
.orderBy(pageRequestDto.getSortFields())
|
||||
.limit(pageRequestDto.getSize())
|
||||
.offset(pageRequestDto.getOffset())
|
||||
.fetch();
|
||||
}
|
||||
|
||||
private SelectConditionStep<Record1<Long>> selectUsersPosition(Long userId) {
|
||||
return ctx()
|
||||
.select(USER.position().ID)
|
||||
.from(USER)
|
||||
.innerJoin(USER.position())
|
||||
.where(USER.ID.eq(userId));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.zl.mjga.repository;
|
||||
|
||||
import static org.jooq.generated.public_.Tables.*;
|
||||
import static org.jooq.impl.DSL.noCondition;
|
||||
|
||||
import com.zl.mjga.dto.PageRequestDto;
|
||||
import com.zl.mjga.dto.scheduler.QueryDto;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.jooq.*;
|
||||
import org.jooq.Record;
|
||||
import org.jooq.generated.public_.tables.daos.QrtzJobDetailsDao;
|
||||
import org.jooq.impl.DSL;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public class QrtzJobRepository extends QrtzJobDetailsDao {
|
||||
|
||||
@Autowired
|
||||
public QrtzJobRepository(Configuration configuration) {
|
||||
super(configuration);
|
||||
}
|
||||
|
||||
public Result<Record> fetchPageWithJobAndTriggerBy(
|
||||
PageRequestDto pageRequestDto, QueryDto queryDto) {
|
||||
return ctx()
|
||||
.select(
|
||||
QRTZ_JOB_DETAILS.asterisk(),
|
||||
QRTZ_JOB_DETAILS.qrtzTriggers().asterisk(),
|
||||
QRTZ_JOB_DETAILS.qrtzTriggers().qrtzCronTriggers().asterisk(),
|
||||
QRTZ_JOB_DETAILS.qrtzTriggers().qrtzSimpleTriggers().asterisk(),
|
||||
DSL.count().over().as("total_job"))
|
||||
.from(QRTZ_JOB_DETAILS)
|
||||
.leftJoin(QRTZ_JOB_DETAILS.qrtzTriggers())
|
||||
.leftJoin(QRTZ_JOB_DETAILS.qrtzTriggers().qrtzCronTriggers())
|
||||
.leftJoin(QRTZ_JOB_DETAILS.qrtzTriggers().qrtzSimpleTriggers())
|
||||
.where(
|
||||
StringUtils.isNotEmpty(queryDto.name())
|
||||
? QRTZ_JOB_DETAILS.SCHED_NAME.eq(queryDto.name())
|
||||
: noCondition())
|
||||
.orderBy(pageRequestDto.getSortFields())
|
||||
.limit(pageRequestDto.getSize())
|
||||
.offset(pageRequestDto.getOffset())
|
||||
.fetch();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.zl.mjga.repository;
|
||||
|
||||
import static org.jooq.generated.mjga.tables.RolePermissionMap.ROLE_PERMISSION_MAP;
|
||||
|
||||
import java.util.List;
|
||||
import org.jooq.Configuration;
|
||||
import org.jooq.generated.mjga.tables.daos.RolePermissionMapDao;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Repository
|
||||
public class RolePermissionMapRepository extends RolePermissionMapDao {
|
||||
|
||||
@Autowired
|
||||
public RolePermissionMapRepository(Configuration configuration) {
|
||||
super(configuration);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteByRoleId(Long roleId) {
|
||||
ctx().deleteFrom(ROLE_PERMISSION_MAP).where(ROLE_PERMISSION_MAP.ROLE_ID.eq(roleId)).execute();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteBy(Long roleId, List<Long> permissionIdList) {
|
||||
ctx()
|
||||
.deleteFrom(ROLE_PERMISSION_MAP)
|
||||
.where(ROLE_PERMISSION_MAP.ROLE_ID.eq(roleId))
|
||||
.and(ROLE_PERMISSION_MAP.PERMISSION_ID.in(permissionIdList))
|
||||
.execute();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.zl.mjga.repository;
|
||||
|
||||
import static org.jooq.generated.mjga.Tables.USER;
|
||||
import static org.jooq.generated.mjga.tables.Role.ROLE;
|
||||
import static org.jooq.impl.DSL.*;
|
||||
|
||||
import com.zl.mjga.dto.PageRequestDto;
|
||||
import com.zl.mjga.dto.urp.RoleQueryDto;
|
||||
import java.util.List;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.jooq.*;
|
||||
import org.jooq.Record;
|
||||
import org.jooq.generated.mjga.tables.daos.RoleDao;
|
||||
import org.jooq.generated.mjga.tables.pojos.Permission;
|
||||
import org.jooq.generated.mjga.tables.pojos.Role;
|
||||
import org.jooq.impl.DSL;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public class RoleRepository extends RoleDao {
|
||||
|
||||
@Autowired
|
||||
public RoleRepository(Configuration configuration) {
|
||||
super(configuration);
|
||||
}
|
||||
|
||||
public List<Role> selectByRoleCodeIn(List<String> roleCodeList) {
|
||||
return ctx().selectFrom(ROLE).where(ROLE.CODE.in(roleCodeList)).fetchInto(Role.class);
|
||||
}
|
||||
|
||||
public List<Role> selectByRoleIdIn(List<Long> roleIdList) {
|
||||
return ctx().selectFrom(ROLE).where(ROLE.ID.in(roleIdList)).fetchInto(Role.class);
|
||||
}
|
||||
|
||||
public Result<Record> pageFetchBy(PageRequestDto pageRequestDto, RoleQueryDto roleQueryDto) {
|
||||
return ctx()
|
||||
.select(
|
||||
asterisk(),
|
||||
roleQueryDto.getUserId() != null
|
||||
? when(ROLE.ID.in(selectUsersRoleIds(roleQueryDto.getUserId())), true)
|
||||
.otherwise(false)
|
||||
.as("is_bound")
|
||||
: noField(),
|
||||
multiset(select(ROLE.permission().asterisk()).from(ROLE.permission()))
|
||||
.convertFrom(r -> r.into(Permission.class))
|
||||
.as("permissions"),
|
||||
DSL.count(ROLE.ID).over().as("total_role"))
|
||||
.from(ROLE)
|
||||
.where(
|
||||
switch (roleQueryDto.getBindState()) {
|
||||
case BIND -> ROLE.ID.in(selectUsersRoleIds(roleQueryDto.getUserId()));
|
||||
case UNBIND -> ROLE.ID.notIn(selectUsersRoleIds(roleQueryDto.getUserId()));
|
||||
case ALL -> noCondition();
|
||||
})
|
||||
.and(
|
||||
roleQueryDto.getRoleId() == null ? noCondition() : ROLE.ID.eq(roleQueryDto.getRoleId()))
|
||||
.and(
|
||||
StringUtils.isEmpty(roleQueryDto.getRoleName())
|
||||
? noCondition()
|
||||
: ROLE.NAME.like("%" + roleQueryDto.getRoleName() + "%"))
|
||||
.and(
|
||||
StringUtils.isEmpty(roleQueryDto.getRoleCode())
|
||||
? noCondition()
|
||||
: ROLE.CODE.eq(roleQueryDto.getRoleCode()))
|
||||
.orderBy(pageRequestDto.getSortFields())
|
||||
.limit(pageRequestDto.getSize())
|
||||
.offset(pageRequestDto.getOffset())
|
||||
.fetch();
|
||||
}
|
||||
|
||||
private SelectConditionStep<Record1<Long>> selectUsersRoleIds(Long userId) {
|
||||
return DSL.select(USER.role().ID).from(USER).innerJoin(USER.role()).where(USER.ID.eq(userId));
|
||||
}
|
||||
|
||||
public Result<Record> fetchUniqueRoleWithPermission(Long roleId) {
|
||||
return ctx()
|
||||
.select(ROLE.asterisk(), ROLE.permission().asterisk())
|
||||
.from(ROLE, ROLE.permission())
|
||||
.where(ROLE.ID.eq(roleId))
|
||||
.orderBy(ROLE.ID)
|
||||
.fetch();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.zl.mjga.repository;
|
||||
|
||||
import org.jooq.Configuration;
|
||||
import org.jooq.generated.mjga.tables.daos.UserDepartmentMapDao;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public class UserDepartmentMapRepository extends UserDepartmentMapDao {
|
||||
@Autowired
|
||||
public UserDepartmentMapRepository(Configuration configuration) {
|
||||
super(configuration);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.zl.mjga.repository;
|
||||
|
||||
import org.jooq.Configuration;
|
||||
import org.jooq.generated.mjga.tables.daos.UserPositionMapDao;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public class UserPositionMapRepository extends UserPositionMapDao {
|
||||
@Autowired
|
||||
public UserPositionMapRepository(Configuration configuration) {
|
||||
super(configuration);
|
||||
}
|
||||
}
|
||||
151
backend/src/main/java/com/zl/mjga/repository/UserRepository.java
Normal file
151
backend/src/main/java/com/zl/mjga/repository/UserRepository.java
Normal file
@@ -0,0 +1,151 @@
|
||||
package com.zl.mjga.repository;
|
||||
|
||||
import static org.jooq.generated.mjga.Tables.*;
|
||||
import static org.jooq.generated.mjga.tables.User.USER;
|
||||
import static org.jooq.impl.DSL.*;
|
||||
|
||||
import com.zl.mjga.dto.PageRequestDto;
|
||||
import com.zl.mjga.dto.urp.PermissionRespDto;
|
||||
import com.zl.mjga.dto.urp.RoleDto;
|
||||
import com.zl.mjga.dto.urp.UserQueryDto;
|
||||
import com.zl.mjga.dto.urp.UserRolePermissionDto;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.jooq.*;
|
||||
import org.jooq.Record;
|
||||
import org.jooq.generated.mjga.tables.daos.*;
|
||||
import org.jooq.generated.mjga.tables.pojos.User;
|
||||
import org.jooq.impl.DSL;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Repository
|
||||
public class UserRepository extends UserDao {
|
||||
|
||||
@Autowired
|
||||
public UserRepository(Configuration configuration) {
|
||||
super(configuration);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void mergeWithoutNullFieldBy(User user) {
|
||||
ctx()
|
||||
.mergeInto(USER)
|
||||
.using(
|
||||
select(
|
||||
value(user.getId()).as("id"),
|
||||
value(user.getUsername()).as("username"),
|
||||
value(user.getPassword()).as("password"),
|
||||
value(user.getEnable()).as("enable"))
|
||||
.asTable("newUser"))
|
||||
.on(USER.ID.eq(DSL.field(DSL.name("newUser", "id"), Long.class)))
|
||||
.whenMatchedThenUpdate()
|
||||
.set(USER.USERNAME, DSL.field(DSL.name("newUser", "username"), String.class))
|
||||
.set(
|
||||
USER.PASSWORD,
|
||||
StringUtils.isNotEmpty(user.getPassword())
|
||||
? DSL.field(DSL.name("newUser", "password"), String.class)
|
||||
: USER.PASSWORD)
|
||||
.set(USER.ENABLE, DSL.field(DSL.name("newUser", "enable"), Boolean.class))
|
||||
.whenNotMatchedThenInsert(USER.USERNAME, USER.PASSWORD, USER.ENABLE)
|
||||
.values(
|
||||
DSL.field(DSL.name("newUser", "username"), String.class),
|
||||
DSL.field(DSL.name("newUser", "password"), String.class),
|
||||
DSL.field(DSL.name("newUser", "enable"), Boolean.class))
|
||||
.execute();
|
||||
}
|
||||
|
||||
public Result<Record> pageFetchBy(PageRequestDto pageRequestDto, UserQueryDto userQueryDto) {
|
||||
return ctx()
|
||||
.select(asterisk(), DSL.count().over().as("total_user"))
|
||||
.from(USER)
|
||||
.where(
|
||||
userQueryDto.getUsername() != null
|
||||
? USER.USERNAME.like("%" + userQueryDto.getUsername() + "%")
|
||||
: noCondition())
|
||||
.orderBy(pageRequestDto.getSortFields())
|
||||
.limit(pageRequestDto.getSize())
|
||||
.offset(pageRequestDto.getOffset())
|
||||
.fetch();
|
||||
}
|
||||
|
||||
public UserRolePermissionDto fetchUniqueUserDtoWithNestedRolePermissionBy(Long userId) {
|
||||
return ctx()
|
||||
.select(
|
||||
USER.asterisk(),
|
||||
multiset(
|
||||
select(
|
||||
USER.role().asterisk(),
|
||||
multiset(
|
||||
select(USER.role().permission().asterisk())
|
||||
.from(USER.role().permission()))
|
||||
.convertFrom(
|
||||
r -> r.map((record) -> record.into(PermissionRespDto.class)))
|
||||
.as("permissions"))
|
||||
.from(USER.role()))
|
||||
.convertFrom(r -> r.map((record) -> record.into(RoleDto.class)))
|
||||
.as("roles"))
|
||||
.from(USER)
|
||||
.where(USER.ID.eq(userId))
|
||||
.fetchOneInto(UserRolePermissionDto.class);
|
||||
}
|
||||
|
||||
// public UserRolePermissionDto fetchUniqueUserDtoWithNestedRolePermissionBy(Long roleId) {
|
||||
// return ctx()
|
||||
// .select(
|
||||
// USER.asterisk(),
|
||||
// multiset(
|
||||
// select(
|
||||
// ROLE.asterisk(),
|
||||
// multiset(
|
||||
// select(PERMISSION.asterisk())
|
||||
// .from(ROLE_PERMISSION_MAP)
|
||||
// .leftJoin(PERMISSION)
|
||||
// .on(ROLE_PERMISSION_MAP.PERMISSION_ID.eq(PERMISSION.ID))
|
||||
// .where(ROLE_PERMISSION_MAP.ROLE_ID.eq(ROLE.ID)))
|
||||
// .convertFrom(
|
||||
// r -> r.map((record) ->
|
||||
// record.into(PermissionRespDto.class)))
|
||||
// .as("permissions"))
|
||||
// .from(USER_ROLE_MAP)
|
||||
// .leftJoin(ROLE)
|
||||
// .on(USER_ROLE_MAP.ROLE_ID.eq(ROLE.ID))
|
||||
// .where(USER.ID.eq(USER_ROLE_MAP.USER_ID)))
|
||||
// .convertFrom(r -> r.map((record) -> record.into(RoleDto.class)))
|
||||
// .as("roles"))
|
||||
// .from(USER)
|
||||
// .where(USER.ID.eq(roleId))
|
||||
// .fetchOneInto(UserRolePermissionDto.class);
|
||||
// }
|
||||
|
||||
public Result<Record> fetchUniqueUserWithRolePermissionBy(Long userId) {
|
||||
return ctx()
|
||||
.select(USER.asterisk(), USER.role().asterisk(), USER.role().permission().asterisk())
|
||||
.from(USER)
|
||||
.leftJoin(USER.role())
|
||||
.leftJoin(USER.role().permission())
|
||||
.where(USER.ID.eq(userId))
|
||||
.fetch();
|
||||
}
|
||||
|
||||
// public Result<Record> fetchUniqueUserWithRolePermissionBy(Long roleId) {
|
||||
// return ctx()
|
||||
// .select()
|
||||
// .from(USER)
|
||||
// .leftJoin(USER_ROLE_MAP)
|
||||
// .on(USER.ID.eq(USER_ROLE_MAP.USER_ID))
|
||||
// .leftJoin(ROLE)
|
||||
// .on(USER_ROLE_MAP.ROLE_ID.eq(ROLE.ID))
|
||||
// .leftJoin(ROLE_PERMISSION_MAP)
|
||||
// .on(ROLE.ID.eq(ROLE_PERMISSION_MAP.ROLE_ID))
|
||||
// .leftJoin(PERMISSION)
|
||||
// .on(ROLE_PERMISSION_MAP.PERMISSION_ID.eq(PERMISSION.ID))
|
||||
// .where(USER.ID.eq(roleId))
|
||||
// .fetch();
|
||||
// }
|
||||
|
||||
@Transactional
|
||||
public void deleteByUsername(String username) {
|
||||
ctx().delete(USER).where(USER.USERNAME.eq(username)).execute();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.zl.mjga.repository;
|
||||
|
||||
import static org.jooq.generated.mjga.tables.UserRoleMap.USER_ROLE_MAP;
|
||||
|
||||
import java.util.List;
|
||||
import org.jooq.Configuration;
|
||||
import org.jooq.generated.mjga.tables.daos.UserRoleMapDao;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Repository
|
||||
public class UserRoleMapRepository extends UserRoleMapDao {
|
||||
|
||||
@Autowired
|
||||
public UserRoleMapRepository(Configuration configuration) {
|
||||
super(configuration);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteByUserId(Long userId) {
|
||||
ctx().deleteFrom(USER_ROLE_MAP).where(USER_ROLE_MAP.USER_ID.eq(userId)).execute();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteBy(Long userId, List<Long> roleIdList) {
|
||||
ctx()
|
||||
.deleteFrom(USER_ROLE_MAP)
|
||||
.where(USER_ROLE_MAP.USER_ID.eq(userId))
|
||||
.and(USER_ROLE_MAP.ROLE_ID.in(roleIdList))
|
||||
.execute();
|
||||
}
|
||||
}
|
||||
28
backend/src/main/java/com/zl/mjga/service/CacheService.java
Normal file
28
backend/src/main/java/com/zl/mjga/service/CacheService.java
Normal file
@@ -0,0 +1,28 @@
|
||||
package com.zl.mjga.service;
|
||||
|
||||
import com.zl.mjga.config.cache.CacheConfig;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.cache.annotation.CacheEvict;
|
||||
import org.springframework.cache.annotation.CachePut;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class CacheService {
|
||||
@Cacheable(value = CacheConfig.VERIFY_CODE, key = "{#identify}", unless = "#result == null")
|
||||
public String getVerifyCodeBy(String identify) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@CachePut(value = CacheConfig.VERIFY_CODE, key = "{#identify}")
|
||||
public String upsertVerifyCodeBy(String identify, String value) {
|
||||
return value;
|
||||
}
|
||||
|
||||
@CacheEvict(value = CacheConfig.VERIFY_CODE, key = "{#identify}")
|
||||
public void removeVerifyCodeBy(String identify) {}
|
||||
|
||||
@CacheEvict(value = CacheConfig.VERIFY_CODE, allEntries = true)
|
||||
public void clearAllVerifyCode() {}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.zl.mjga.service;
|
||||
|
||||
import static org.jooq.generated.mjga.tables.Department.DEPARTMENT;
|
||||
|
||||
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 java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.jooq.Record;
|
||||
import org.jooq.Result;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class DepartmentService {
|
||||
|
||||
private final DepartmentRepository departmentRepository;
|
||||
|
||||
public PageResponseDto<List<DepartmentRespDto>> pageQueryDepartment(
|
||||
PageRequestDto pageRequestDto, DepartmentQueryDto departmentQueryDto) {
|
||||
Result<Record> records = departmentRepository.pageFetchBy(pageRequestDto, departmentQueryDto);
|
||||
if (records.isEmpty()) {
|
||||
return PageResponseDto.empty();
|
||||
}
|
||||
List<DepartmentRespDto> departments =
|
||||
records.map(
|
||||
record -> {
|
||||
return DepartmentRespDto.builder()
|
||||
.id(record.getValue(DEPARTMENT.ID))
|
||||
.name(record.getValue(DEPARTMENT.NAME))
|
||||
.parentId(record.getValue(DEPARTMENT.PARENT_ID))
|
||||
.isBound(
|
||||
record.field("is_bound") != null
|
||||
? record.get("is_bound", Boolean.class)
|
||||
: null)
|
||||
.parentName(record.get("parent_name", String.class))
|
||||
.build();
|
||||
});
|
||||
Long totalDepartment = records.get(0).getValue("total_department", Long.class);
|
||||
return new PageResponseDto<>(totalDepartment, departments);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
package com.zl.mjga.service;
|
||||
|
||||
import static org.jooq.generated.mjga.tables.Permission.PERMISSION;
|
||||
import static org.jooq.generated.mjga.tables.Role.ROLE;
|
||||
import static org.jooq.generated.mjga.tables.User.USER;
|
||||
|
||||
import com.zl.mjga.dto.PageRequestDto;
|
||||
import com.zl.mjga.dto.PageResponseDto;
|
||||
import com.zl.mjga.dto.department.DepartmentBindDto;
|
||||
import com.zl.mjga.dto.position.PositionBindDto;
|
||||
import com.zl.mjga.dto.urp.*;
|
||||
import com.zl.mjga.exception.BusinessException;
|
||||
import com.zl.mjga.model.urp.ERole;
|
||||
import com.zl.mjga.repository.*;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.collections4.CollectionUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.jooq.Record;
|
||||
import org.jooq.Result;
|
||||
import org.jooq.generated.mjga.tables.pojos.*;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class IdentityAccessService {
|
||||
|
||||
private final UserRepository userRepository;
|
||||
private final RoleRepository roleRepository;
|
||||
private final UserRoleMapRepository userRoleMapRepository;
|
||||
private final PermissionRepository permissionRepository;
|
||||
private final RolePermissionMapRepository rolePermissionMapRepository;
|
||||
private final UserDepartmentMapRepository userDepartmentMapRepository;
|
||||
private final UserPositionMapRepository userPositionMapRepository;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
public void upsertUser(UserUpsertDto userUpsertDto) {
|
||||
User user = new User();
|
||||
BeanUtils.copyProperties(userUpsertDto, user);
|
||||
if (StringUtils.isNotEmpty(userUpsertDto.getPassword())) {
|
||||
user.setPassword(passwordEncoder.encode(userUpsertDto.getPassword()));
|
||||
}
|
||||
userRepository.mergeWithoutNullFieldBy(user);
|
||||
}
|
||||
|
||||
public void upsertRole(RoleUpsertDto roleUpsertDto) {
|
||||
Role role = new Role();
|
||||
BeanUtils.copyProperties(roleUpsertDto, role);
|
||||
roleRepository.merge(role);
|
||||
}
|
||||
|
||||
public void upsertPermission(PermissionUpsertDto permissionUpsertDto) {
|
||||
Permission permission = new Permission();
|
||||
BeanUtils.copyProperties(permissionUpsertDto, permission);
|
||||
permissionRepository.merge(permission);
|
||||
}
|
||||
|
||||
public PageResponseDto<List<UserRolePermissionDto>> pageQueryUser(
|
||||
PageRequestDto pageRequestDto, UserQueryDto userQueryDto) {
|
||||
Result<Record> userRecords = userRepository.pageFetchBy(pageRequestDto, userQueryDto);
|
||||
if (userRecords.isEmpty()) {
|
||||
return PageResponseDto.empty();
|
||||
}
|
||||
List<UserRolePermissionDto> userRolePermissionDtoList =
|
||||
userRecords.stream()
|
||||
.map((record) -> queryUniqueUserWithRolePermission(record.getValue(USER.ID)))
|
||||
.toList();
|
||||
return new PageResponseDto<>(
|
||||
userRecords.get(0).getValue("total_user", Integer.class), userRolePermissionDtoList);
|
||||
}
|
||||
|
||||
public @Nullable UserRolePermissionDto queryUniqueUserWithRolePermission(Long userId) {
|
||||
return userRepository.fetchUniqueUserDtoWithNestedRolePermissionBy(userId);
|
||||
}
|
||||
|
||||
public PageResponseDto<List<RoleDto>> pageQueryRole(
|
||||
PageRequestDto pageRequestDto, RoleQueryDto roleQueryDto) {
|
||||
Result<Record> roleRecords = roleRepository.pageFetchBy(pageRequestDto, roleQueryDto);
|
||||
if (roleRecords.isEmpty()) {
|
||||
return PageResponseDto.empty();
|
||||
}
|
||||
List<RoleDto> roleDtoList =
|
||||
roleRecords.stream()
|
||||
.map(
|
||||
record -> {
|
||||
return RoleDto.builder()
|
||||
.id(record.getValue("id", Long.class))
|
||||
.code(record.getValue("code", String.class))
|
||||
.name(record.getValue("name", String.class))
|
||||
.isBound(
|
||||
record.field("is_bound", Boolean.class) != null
|
||||
? record.getValue("is_bound", Boolean.class)
|
||||
: null)
|
||||
.permissions(record.getValue("permissions", List.class))
|
||||
.build();
|
||||
})
|
||||
.toList();
|
||||
return new PageResponseDto<>(
|
||||
roleRecords.get(0).getValue("total_role", Integer.class), roleDtoList);
|
||||
}
|
||||
|
||||
public @Nullable RoleDto queryUniqueRoleWithPermission(Long roleId) {
|
||||
Result<Record> roleWithPermissionRecords = roleRepository.fetchUniqueRoleWithPermission(roleId);
|
||||
if (roleWithPermissionRecords.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
RoleDto roleDto = createRbacDtoRolePart(roleWithPermissionRecords);
|
||||
setCurrentRolePermission(roleDto, roleWithPermissionRecords);
|
||||
return roleDto;
|
||||
}
|
||||
|
||||
public PageResponseDto<List<PermissionRespDto>> pageQueryPermission(
|
||||
PageRequestDto pageRequestDto, PermissionQueryDto permissionQueryDto) {
|
||||
Result<Record> permissionRecords =
|
||||
permissionRepository.pageFetchBy(pageRequestDto, permissionQueryDto);
|
||||
if (permissionRecords.isEmpty()) {
|
||||
return PageResponseDto.empty();
|
||||
}
|
||||
List<PermissionRespDto> permissionRespDtoList =
|
||||
permissionRecords.stream()
|
||||
.map(
|
||||
record ->
|
||||
PermissionRespDto.builder()
|
||||
.id(record.getValue("id", Long.class))
|
||||
.name(record.getValue("name", String.class))
|
||||
.code(record.getValue("code", String.class))
|
||||
.isBound(
|
||||
record.field("is_bound", Boolean.class) != null
|
||||
? record.getValue("is_bound", Boolean.class)
|
||||
: null)
|
||||
.build())
|
||||
.toList();
|
||||
return new PageResponseDto<>(
|
||||
permissionRecords.get(0).getValue("total_permission", Integer.class),
|
||||
permissionRespDtoList);
|
||||
}
|
||||
|
||||
public void bindPermissionBy(Long roleId, List<Long> permissionIdList) {
|
||||
List<RolePermissionMap> permissionMapList =
|
||||
permissionIdList.stream()
|
||||
.map(
|
||||
(permissionId -> {
|
||||
RolePermissionMap rolePermissionMap = new RolePermissionMap();
|
||||
rolePermissionMap.setRoleId(roleId);
|
||||
rolePermissionMap.setPermissionId(permissionId);
|
||||
return rolePermissionMap;
|
||||
}))
|
||||
.collect(Collectors.toList());
|
||||
rolePermissionMapRepository.merge(permissionMapList);
|
||||
}
|
||||
|
||||
public void unBindPermissionBy(Long roleId, List<Long> permissionIdList) {
|
||||
if (CollectionUtils.isEmpty(permissionIdList)) {
|
||||
return;
|
||||
}
|
||||
rolePermissionMapRepository.deleteBy(roleId, permissionIdList);
|
||||
}
|
||||
|
||||
public void unBindRoleToUser(Long userId, List<Long> roleIdList) {
|
||||
if (CollectionUtils.isEmpty(roleIdList)) {
|
||||
return;
|
||||
}
|
||||
List<Role> roles = roleRepository.selectByRoleIdIn(roleIdList);
|
||||
if (CollectionUtils.isEmpty(roles)) {
|
||||
throw new BusinessException("unbind role not exist");
|
||||
}
|
||||
userRoleMapRepository.deleteBy(userId, roleIdList);
|
||||
}
|
||||
|
||||
public void bindRoleToUser(Long userId, List<Long> roleIdList) {
|
||||
List<UserRoleMap> userRoleMapList =
|
||||
roleIdList.stream()
|
||||
.map(
|
||||
(roleId -> {
|
||||
UserRoleMap userRoleMap = new UserRoleMap();
|
||||
userRoleMap.setUserId(userId);
|
||||
userRoleMap.setRoleId(roleId);
|
||||
return userRoleMap;
|
||||
}))
|
||||
.collect(Collectors.toList());
|
||||
userRoleMapRepository.merge(userRoleMapList);
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Throwable.class)
|
||||
public void bindRoleModuleToUser(Long userId, List<ERole> eRoleList) {
|
||||
bindRoleToUser(
|
||||
userId,
|
||||
roleRepository
|
||||
.selectByRoleCodeIn(eRoleList.stream().map(Enum::name).collect(Collectors.toList()))
|
||||
.stream()
|
||||
.map(Role::getId)
|
||||
.toList());
|
||||
}
|
||||
|
||||
private void setCurrentRolePermission(RoleDto roleDto, List<Record> roleResult) {
|
||||
if (roleResult.get(0).getValue(PERMISSION.ID) != null) {
|
||||
roleResult.forEach(
|
||||
(record) -> {
|
||||
PermissionRespDto permissionRespDto = createRbacDtoPermissionPart(record);
|
||||
roleDto.getPermissions().add(permissionRespDto);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private PermissionRespDto createRbacDtoPermissionPart(Record record) {
|
||||
PermissionRespDto permissionRespDto = new PermissionRespDto();
|
||||
permissionRespDto.setId(record.getValue(PERMISSION.ID));
|
||||
permissionRespDto.setCode(record.getValue(PERMISSION.CODE));
|
||||
permissionRespDto.setName(record.getValue(PERMISSION.NAME));
|
||||
return permissionRespDto;
|
||||
}
|
||||
|
||||
private RoleDto createRbacDtoRolePart(List<Record> roleResult) {
|
||||
RoleDto roleDto = new RoleDto();
|
||||
roleDto.setId(roleResult.get(0).getValue(ROLE.ID));
|
||||
roleDto.setCode(roleResult.get(0).getValue(ROLE.CODE));
|
||||
roleDto.setName(roleResult.get(0).getValue(ROLE.NAME));
|
||||
return roleDto;
|
||||
}
|
||||
|
||||
public boolean isRoleDuplicate(String roleCode, String name) {
|
||||
return roleRepository.fetchOneByCode(roleCode) != null
|
||||
|| roleRepository.fetchOneByName(name) != null;
|
||||
}
|
||||
|
||||
public boolean isUsernameDuplicate(String username) {
|
||||
return userRepository.fetchOneByUsername(username) != null;
|
||||
}
|
||||
|
||||
public boolean isPermissionDuplicate(String code, String name) {
|
||||
return permissionRepository.fetchOneByCode(code) != null
|
||||
|| permissionRepository.fetchOneByName(name) != null;
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Throwable.class)
|
||||
public void bindDepartmentBy(DepartmentBindDto departmentBindDto) {
|
||||
List<UserDepartmentMap> userDepartmentMaps =
|
||||
departmentBindDto.departmentIds().stream()
|
||||
.map(
|
||||
(departmentId) -> {
|
||||
UserDepartmentMap userDepartmentMap = new UserDepartmentMap();
|
||||
userDepartmentMap.setUserId(departmentBindDto.userId());
|
||||
userDepartmentMap.setDepartmentId(departmentId);
|
||||
return userDepartmentMap;
|
||||
})
|
||||
.toList();
|
||||
userDepartmentMapRepository.merge(userDepartmentMaps);
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Throwable.class)
|
||||
public void unBindDepartmentBy(DepartmentBindDto departmentBindDto) {
|
||||
for (Long departmentId : departmentBindDto.departmentIds()) {
|
||||
UserDepartmentMap userDepartmentMap = new UserDepartmentMap();
|
||||
userDepartmentMap.setUserId(departmentBindDto.userId());
|
||||
userDepartmentMap.setDepartmentId(departmentId);
|
||||
userDepartmentMapRepository.delete(userDepartmentMap);
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Throwable.class)
|
||||
public void bindPositionBy(PositionBindDto positionBindDto) {
|
||||
List<UserPositionMap> userPositionMaps =
|
||||
positionBindDto.positionIds().stream()
|
||||
.map(
|
||||
(positionId) -> {
|
||||
UserPositionMap userPositionMap = new UserPositionMap();
|
||||
userPositionMap.setUserId(positionBindDto.userId());
|
||||
userPositionMap.setPositionId(positionId);
|
||||
return userPositionMap;
|
||||
})
|
||||
.toList();
|
||||
userPositionMapRepository.merge(userPositionMaps);
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Throwable.class)
|
||||
public void unBindPositionBy(PositionBindDto positionBindDto) {
|
||||
for (Long positionId : positionBindDto.positionIds()) {
|
||||
UserPositionMap userPositionMap = new UserPositionMap();
|
||||
userPositionMap.setUserId(positionBindDto.userId());
|
||||
userPositionMap.setPositionId(positionId);
|
||||
userPositionMapRepository.delete(userPositionMap);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.zl.mjga.service;
|
||||
|
||||
import static org.jooq.generated.mjga.tables.Position.POSITION;
|
||||
|
||||
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 java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.jooq.Record;
|
||||
import org.jooq.Result;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class PositionService {
|
||||
|
||||
private final PositionRepository positionRepository;
|
||||
|
||||
public PageResponseDto<List<PositionRespDto>> pageQueryPosition(
|
||||
PageRequestDto pageRequestDto, PositionQueryDto positionQueryDto) {
|
||||
Result<Record> records = positionRepository.pageFetchBy(pageRequestDto, positionQueryDto);
|
||||
if (records.isEmpty()) {
|
||||
return PageResponseDto.empty();
|
||||
}
|
||||
List<PositionRespDto> positions =
|
||||
records.map(
|
||||
record ->
|
||||
PositionRespDto.builder()
|
||||
.id(record.getValue(POSITION.ID))
|
||||
.name(record.getValue(POSITION.NAME))
|
||||
.isBound(
|
||||
record.field("is_bound", Boolean.class) != null
|
||||
? record.getValue("is_bound", Boolean.class)
|
||||
: null)
|
||||
.build());
|
||||
Long totalPosition = records.get(0).getValue("total_position", Long.class);
|
||||
return new PageResponseDto<>(totalPosition, positions);
|
||||
}
|
||||
}
|
||||
103
backend/src/main/java/com/zl/mjga/service/SchedulerService.java
Normal file
103
backend/src/main/java/com/zl/mjga/service/SchedulerService.java
Normal file
@@ -0,0 +1,103 @@
|
||||
package com.zl.mjga.service;
|
||||
|
||||
import static org.jooq.generated.public_.Tables.*;
|
||||
import static org.quartz.TriggerBuilder.newTrigger;
|
||||
|
||||
import com.zl.mjga.dto.PageRequestDto;
|
||||
import com.zl.mjga.dto.PageResponseDto;
|
||||
import com.zl.mjga.dto.scheduler.JobTriggerDto;
|
||||
import com.zl.mjga.dto.scheduler.QueryDto;
|
||||
import com.zl.mjga.repository.QrtzJobRepository;
|
||||
import jakarta.annotation.Resource;
|
||||
import java.time.Instant;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.jooq.Record;
|
||||
import org.jooq.Result;
|
||||
import org.quartz.*;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class SchedulerService {
|
||||
|
||||
@Resource(name = "emailJobSchedulerFactory")
|
||||
private Scheduler emailJobScheduler;
|
||||
|
||||
@Resource(name = "dataBackupSchedulerFactory")
|
||||
private Scheduler dataBackupScheduler;
|
||||
|
||||
private final QrtzJobRepository qrtzJobRepository;
|
||||
|
||||
public PageResponseDto<List<JobTriggerDto>> getJobWithTriggerBy(
|
||||
PageRequestDto pageRequestDto, QueryDto queryDto) {
|
||||
Result<Record> records =
|
||||
qrtzJobRepository.fetchPageWithJobAndTriggerBy(pageRequestDto, queryDto);
|
||||
if (records.isEmpty()) {
|
||||
return PageResponseDto.empty();
|
||||
}
|
||||
List<JobTriggerDto> jobTriggerDtoList =
|
||||
records.map(
|
||||
record -> {
|
||||
JobTriggerDto jobTriggerDto = new JobTriggerDto();
|
||||
jobTriggerDto.setName(record.getValue(QRTZ_JOB_DETAILS.JOB_NAME));
|
||||
jobTriggerDto.setGroup(record.getValue(QRTZ_JOB_DETAILS.JOB_GROUP));
|
||||
jobTriggerDto.setClassName(record.getValue(QRTZ_JOB_DETAILS.JOB_CLASS_NAME));
|
||||
jobTriggerDto.setTriggerName(record.getValue(QRTZ_TRIGGERS.TRIGGER_NAME));
|
||||
jobTriggerDto.setTriggerGroup(record.getValue(QRTZ_TRIGGERS.TRIGGER_GROUP));
|
||||
jobTriggerDto.setCronExpression(record.getValue(QRTZ_CRON_TRIGGERS.CRON_EXPRESSION));
|
||||
jobTriggerDto.setStartTime(record.getValue(QRTZ_TRIGGERS.START_TIME));
|
||||
jobTriggerDto.setEndTime(record.getValue(QRTZ_TRIGGERS.END_TIME));
|
||||
jobTriggerDto.setNextFireTime(record.getValue(QRTZ_TRIGGERS.NEXT_FIRE_TIME));
|
||||
jobTriggerDto.setPreviousFireTime(record.getValue(QRTZ_TRIGGERS.PREV_FIRE_TIME));
|
||||
jobTriggerDto.setSchedulerType(record.getValue(QRTZ_TRIGGERS.TRIGGER_TYPE));
|
||||
jobTriggerDto.setTriggerState(record.getValue(QRTZ_TRIGGERS.TRIGGER_STATE));
|
||||
return jobTriggerDto;
|
||||
});
|
||||
return new PageResponseDto<>(
|
||||
records.get(0).getValue("total_job", Integer.class), jobTriggerDtoList);
|
||||
}
|
||||
|
||||
public void resumeTrigger(TriggerKey triggerKey) throws SchedulerException {
|
||||
emailJobScheduler.resumeTrigger(triggerKey);
|
||||
dataBackupScheduler.resumeTrigger(triggerKey);
|
||||
}
|
||||
|
||||
public void pauseTrigger(TriggerKey triggerKey) throws SchedulerException {
|
||||
emailJobScheduler.pauseTrigger(triggerKey);
|
||||
dataBackupScheduler.pauseTrigger(triggerKey);
|
||||
}
|
||||
|
||||
public void triggerJob(JobKey jobKey, Date startAt) throws SchedulerException {
|
||||
JobDetail jobDetail = emailJobScheduler.getJobDetail(jobKey);
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
Trigger dayLaterTrigger =
|
||||
newTrigger()
|
||||
.withIdentity(
|
||||
String.format(
|
||||
"%s-%s-%s", "trigger", authentication.getName(), Instant.now().toEpochMilli()),
|
||||
"job-management")
|
||||
.startAt(startAt)
|
||||
.build();
|
||||
emailJobScheduler.scheduleJob(jobDetail, dayLaterTrigger);
|
||||
}
|
||||
|
||||
public void updateCronTrigger(TriggerKey triggerKey, String cron) throws SchedulerException {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
Trigger newTrigger =
|
||||
TriggerBuilder.newTrigger()
|
||||
.withIdentity(
|
||||
String.format(
|
||||
"%s-%s-%s",
|
||||
"cronTrigger", authentication.getName(), Instant.now().toEpochMilli()),
|
||||
"job-management")
|
||||
.withSchedule(CronScheduleBuilder.cronSchedule(cron))
|
||||
.build();
|
||||
dataBackupScheduler.rescheduleJob(triggerKey, newTrigger);
|
||||
}
|
||||
}
|
||||
51
backend/src/main/java/com/zl/mjga/service/SignService.java
Normal file
51
backend/src/main/java/com/zl/mjga/service/SignService.java
Normal file
@@ -0,0 +1,51 @@
|
||||
package com.zl.mjga.service;
|
||||
|
||||
import com.zl.mjga.dto.sign.SignInDto;
|
||||
import com.zl.mjga.dto.sign.SignUpDto;
|
||||
import com.zl.mjga.exception.BusinessException;
|
||||
import com.zl.mjga.model.urp.ERole;
|
||||
import com.zl.mjga.repository.UserRepository;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.jooq.generated.mjga.tables.pojos.User;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class SignService {
|
||||
|
||||
private final UserRepository userRepository;
|
||||
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
private final IdentityAccessService identityAccessService;
|
||||
|
||||
public Long signIn(SignInDto signInDto) {
|
||||
User user = userRepository.fetchOneByUsername(signInDto.getUsername());
|
||||
if (user == null) {
|
||||
throw new BusinessException(String.format("%s user not found", signInDto.getUsername()));
|
||||
}
|
||||
if (!passwordEncoder.matches(signInDto.getPassword(), user.getPassword())) {
|
||||
throw new BusinessException("password invalid");
|
||||
}
|
||||
return user.getId();
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Throwable.class)
|
||||
public void signUp(SignUpDto signUpDto) {
|
||||
if (identityAccessService.isUsernameDuplicate(signUpDto.getUsername())) {
|
||||
throw new BusinessException(
|
||||
String.format("username %s already exist", signUpDto.getUsername()));
|
||||
}
|
||||
User user = new User();
|
||||
user.setUsername(signUpDto.getUsername());
|
||||
user.setPassword(passwordEncoder.encode(signUpDto.getPassword()));
|
||||
userRepository.insert(user);
|
||||
User insertUser = userRepository.fetchOneByUsername(signUpDto.getUsername());
|
||||
identityAccessService.bindRoleModuleToUser(insertUser.getId(), List.of(ERole.GENERAL));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user